code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
Highcharts JS v5.0.13 (2017-07-27)
(c) 2009-2017 Highsoft AS
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?module.exports=a:a(Highcharts)})(function(a){a.theme={colors:["#FDD089","#FF7F79","#A0446E","#251535"],colorAxis:{maxColor:"#60042E",minColor:"#FDD089"},plotOptions:{map:{nullColor:"#fefefc"}},navigator:{series:{color:"#FF7F79",lineColor:"#A0446E"}}};a.setOptions(a.theme)});
| ChrisCioffi/ChrisCioffi.github.io | portfolio/Highcharts-5.0.13/code/themes/sunset.js | JavaScript | mit | 438 |
/*! lazysizes - v1.2.3-rc1 */
!function(a){"use strict";var b,c,d,e;a.addEventListener&&(b=a.lazySizes&&lazySizes.cfg||a.lazySizesConfig||{},c=b.lazyClass||"lazyload",d=function(){var b,d;if("string"==typeof c&&(c=document.getElementsByClassName(c)),a.lazySizes)for(b=0,d=c.length;d>b;b++)lazySizes.loader.unveil(c[b])},addEventListener("beforeprint",d,!1),!("onbeforeprint"in a)&&a.matchMedia&&(e=matchMedia("print"))&&e.addListener&&e.addListener(function(){e.matches&&d()}))}(window); | ristoman/lazysizes | plugins/print/ls.print.min.js | JavaScript | mit | 487 |
/**
@file PhysicsFrame.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2002-07-09
@edited 2006-01-25
*/
#include "G3D/platform.h"
#include "G3D/PhysicsFrame.h"
#include "G3D/BinaryInput.h"
#include "G3D/BinaryOutput.h"
namespace G3D {
PhysicsFrame::PhysicsFrame() {
translation = Vector3::zero();
rotation = Quat();
}
PhysicsFrame::PhysicsFrame(
const CoordinateFrame& coordinateFrame) {
translation = coordinateFrame.translation;
rotation = Quat(coordinateFrame.rotation);
}
PhysicsFrame PhysicsFrame::operator*(const PhysicsFrame& other) const {
PhysicsFrame result;
result.rotation = rotation * other.rotation;
result.translation = translation + rotation.toRotationMatrix() * other.translation;
return result;
}
CoordinateFrame PhysicsFrame::toCoordinateFrame() const {
CoordinateFrame f;
f.translation = translation;
f.rotation = rotation.toRotationMatrix();
return f;
}
PhysicsFrame PhysicsFrame::lerp(
const PhysicsFrame& other,
float alpha) const {
PhysicsFrame result;
result.translation = translation.lerp(other.translation, alpha);
result.rotation = rotation.slerp(other.rotation, alpha);
return result;
}
void PhysicsFrame::deserialize(class BinaryInput& b) {
translation.deserialize(b);
rotation.deserialize(b);
}
void PhysicsFrame::serialize(class BinaryOutput& b) const {
translation.serialize(b);
rotation.serialize(b);
}
}; // namespace
| AsherBond/MondocosmOS | mangos/dep/src/g3dlite/PhysicsFrame.cpp | C++ | agpl-3.0 | 1,542 |
/*
HISTORY
02-Aug-10 L-05-28 $$1 pdeshmuk Created.
*/
function deleteItemsInSimpRep ()
{
if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
/*--------------------------------------------------------------------*\
Get the current assembly
\*--------------------------------------------------------------------*/
var session = pfcGetProESession ();
var assembly = session.CurrentModel;
if (assembly.Type != pfcCreate ("pfcModelType").MDL_ASSEMBLY)
throw new Error (0, "Current model is not an assembly");
/*--------------------------------------------------------------------*\
Get the current active simprep.
\*--------------------------------------------------------------------*/
var simp_rep = assembly.GetActiveSimpRep();
/*--------------------------------------------------------------------*\
Get the current number of items
\*--------------------------------------------------------------------*/
var simp_rep_instructions = simp_rep.GetInstructions();
var number_items = simp_rep_instructions.Items.Count;
document.getElementById("numItems").value = number_items;
/*--------------------------------------------------------------------*\
Deleting items
\*--------------------------------------------------------------------*/
var simp_rep_instructions_item = simp_rep_instructions.Items.Item(number_items-1);
simp_rep_instructions_item.Action = null;
simp_rep.SetInstructions(simp_rep_instructions);
number_items = simp_rep.GetInstructions().Items.Count;
document.getElementById("numItems").value = number_items;
return;
}
function addItemsInSimpRep ()
{
if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
/*--------------------------------------------------------------------*\
Get the current assembly
\*--------------------------------------------------------------------*/
var session = pfcGetProESession ();
var assembly = session.CurrentModel;
if (assembly.Type != pfcCreate ("pfcModelType").MDL_ASSEMBLY)
throw new Error (0, "Current model is not an assembly");
/*--------------------------------------------------------------------*\
Get the current active simprep.
\*--------------------------------------------------------------------*/
var simp_rep = assembly.GetActiveSimpRep();
/*--------------------------------------------------------------------*\
Get the current number of items
\*--------------------------------------------------------------------*/
var simp_rep_instructions = simp_rep.GetInstructions();
var number_items = simp_rep_instructions.Items.Count;
document.getElementById("numItems").value = number_items;
/*--------------------------------------------------------------------*\
Add an item
\*--------------------------------------------------------------------*/
var item_path = pfcCreate ("intseq");
/*--------------------------------------------------------------------*\
Prompt for selection.
\*--------------------------------------------------------------------*/
selOptions = pfcCreate ("pfcSelectionOptions").Create ("feature");
selOptions.MaxNumSels = parseInt (1);
var selections = void null;
try {
selections = session.Select (selOptions, void null);
}
catch (err) {
/*--------------------------------------------------------------------*\
Handle the situation where the user didn't make selections, but picked
elsewhere instead.
\*--------------------------------------------------------------------*/
if (pfcGetExceptionType (err) == "pfcXToolkitUserAbort" ||
pfcGetExceptionType (err) == "pfcXToolkitPickAbove")
return (void null);
else
throw err;
}
if (selections.Count == 0)
return (void null);
var selection = selections.Item(0);
var componentpath = selection.Path;
var intseqIds = componentpath.ComponentIds;
item_path.Append(intseqIds.Item(0));
simp_rep_comp_item_path = pfcCreate("pfcSimpRepCompItemPath").Create(item_path);
simp_rep_item = pfcCreate("pfcSimpRepItem").Create(simp_rep_comp_item_path);
simp_rep_action = pfcCreate("pfcSimpRepExclude").Create();
simp_rep_item.Action = simp_rep_action;
simp_rep_instructions.Items.Append(simp_rep_item);
simp_rep.SetInstructions(simp_rep_instructions);
simp_rep_instructions = simp_rep.GetInstructions();
number_items = simp_rep_instructions.Items.Count;
document.getElementById("numItems").value = number_items;
return;
}
| 2014c2g12/c2g12 | wsgi/wsgi/static/weblink/examples/jscript/pfcSimpRepExamples.js | JavaScript | gpl-2.0 | 4,660 |
/**
* A date picker component which shows a Date Picker on the screen. This class extends from {@link Ext.picker.Picker}
* and {@link Ext.Sheet} so it is a popup.
*
* This component has no required configurations.
*
* ## Examples
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date');
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* You may want to adjust the {@link #yearFrom} and {@link #yearTo} properties:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* yearFrom: 2000,
* yearTo : 2015
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* You can set the value of the {@link Ext.picker.Date} to the current date using `new Date()`:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* value: new Date()
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* And you can hide the titles from each of the slots by using the {@link #useTitles} configuration:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* useTitles: false
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*/
Ext.define('Ext.picker.Date', {
extend: 'Ext.picker.Picker',
xtype: 'datepicker',
alternateClassName: 'Ext.DatePicker',
requires: ['Ext.DateExtras', 'Ext.util.InputBlocker'],
/**
* @event change
* Fired when the value of this picker has changed and the done button is pressed.
* @param {Ext.picker.Date} this This Picker
* @param {Date} value The date value
*/
config: {
/**
* @cfg {Number} yearFrom
* The start year for the date picker. If {@link #yearFrom} is greater than
* {@link #yearTo} then the order of years will be reversed.
* @accessor
*/
yearFrom: 1980,
/**
* @cfg {Number} [yearTo=new Date().getFullYear()]
* The last year for the date picker. If {@link #yearFrom} is greater than
* {@link #yearTo} then the order of years will be reversed.
* @accessor
*/
yearTo: new Date().getFullYear(),
/**
* @cfg {String} monthText
* The label to show for the month column.
* @accessor
*/
monthText: 'Month',
/**
* @cfg {String} dayText
* The label to show for the day column.
* @accessor
*/
dayText: 'Day',
/**
* @cfg {String} yearText
* The label to show for the year column.
* @accessor
*/
yearText: 'Year',
/**
* @cfg {Array} slotOrder
* An array of strings that specifies the order of the slots.
* @accessor
*/
slotOrder: ['month', 'day', 'year'],
/**
* @cfg {Object/Date} value
* Default value for the field and the internal {@link Ext.picker.Date} component. Accepts an object of 'year',
* 'month' and 'day' values, all of which should be numbers, or a {@link Date}.
*
* Examples:
*
* - `{year: 1989, day: 1, month: 5}` = 1st May 1989
* - `new Date()` = current date
* @accessor
*/
/**
* @cfg {Array} slots
* @hide
* @accessor
*/
/**
* @cfg {String/Mixed} doneButton
* Can be either:
*
* - A {String} text to be used on the Done button.
* - An {Object} as config for {@link Ext.Button}.
* - `false` or `null` to hide it.
* @accessor
*/
doneButton: true
},
platformConfig: [{
theme: ['Windows'],
doneButton: {
iconCls: 'check2',
ui: 'round',
text: ''
}
}],
initialize: function() {
this.callParent();
this.on({
scope: this,
delegate: '> slot',
slotpick: this.onSlotPick
});
this.on({
scope: this,
show: this.onSlotPick
});
},
setValue: function(value, animated) {
if (Ext.isDate(value)) {
value = {
day : value.getDate(),
month: value.getMonth() + 1,
year : value.getFullYear()
};
}
this.callParent([value, animated]);
this.onSlotPick();
},
getValue: function(useDom) {
var values = {},
items = this.getItems().items,
ln = items.length,
daysInMonth, day, month, year, item, i;
for (i = 0; i < ln; i++) {
item = items[i];
if (item instanceof Ext.picker.Slot) {
values[item.getName()] = item.getValue(useDom);
}
}
//if all the slots return null, we should not return a date
if (values.year === null && values.month === null && values.day === null) {
return null;
}
year = Ext.isNumber(values.year) ? values.year : 1;
month = Ext.isNumber(values.month) ? values.month : 1;
day = Ext.isNumber(values.day) ? values.day : 1;
if (month && year && month && day) {
daysInMonth = this.getDaysInMonth(month, year);
}
day = (daysInMonth) ? Math.min(day, daysInMonth): day;
return new Date(year, month - 1, day);
},
/**
* Updates the yearFrom configuration
*/
updateYearFrom: function() {
if (this.initialized) {
this.createSlots();
}
},
/**
* Updates the yearTo configuration
*/
updateYearTo: function() {
if (this.initialized) {
this.createSlots();
}
},
/**
* Updates the monthText configuration
*/
updateMonthText: function(newMonthText, oldMonthText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if ((typeof item.title == "string" && item.title == oldMonthText) || (item.title.html == oldMonthText)) {
item.setTitle(newMonthText);
}
}
}
},
/**
* Updates the {@link #dayText} configuration.
*/
updateDayText: function(newDayText, oldDayText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if ((typeof item.title == "string" && item.title == oldDayText) || (item.title.html == oldDayText)) {
item.setTitle(newDayText);
}
}
}
},
/**
* Updates the yearText configuration
*/
updateYearText: function(yearText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if (item.title == this.yearText) {
item.setTitle(yearText);
}
}
}
},
// @private
constructor: function() {
this.callParent(arguments);
this.createSlots();
},
/**
* Generates all slots for all years specified by this component, and then sets them on the component
* @private
*/
createSlots: function() {
var me = this,
slotOrder = me.getSlotOrder(),
yearsFrom = me.getYearFrom(),
yearsTo = me.getYearTo(),
years = [],
days = [],
months = [],
reverse = yearsFrom > yearsTo,
ln, i, daysInMonth;
while (yearsFrom) {
years.push({
text : yearsFrom,
value : yearsFrom
});
if (yearsFrom === yearsTo) {
break;
}
if (reverse) {
yearsFrom--;
} else {
yearsFrom++;
}
}
daysInMonth = me.getDaysInMonth(1, new Date().getFullYear());
for (i = 0; i < daysInMonth; i++) {
days.push({
text : i + 1,
value : i + 1
});
}
for (i = 0, ln = Ext.Date.monthNames.length; i < ln; i++) {
months.push({
text : Ext.Date.monthNames[i],
value : i + 1
});
}
var slots = [];
slotOrder.forEach(function (item) {
slots.push(me.createSlot(item, days, months, years));
});
me.setSlots(slots);
},
/**
* Returns a slot config for a specified date.
* @private
*/
createSlot: function(name, days, months, years) {
switch (name) {
case 'year':
return {
name: 'year',
align: 'center',
data: years,
title: this.getYearText(),
flex: 3
};
case 'month':
return {
name: name,
align: 'right',
data: months,
title: this.getMonthText(),
flex: 4
};
case 'day':
return {
name: 'day',
align: 'center',
data: days,
title: this.getDayText(),
flex: 2
};
}
},
onSlotPick: function() {
var value = this.getValue(true),
slot = this.getDaySlot(),
year = value.getFullYear(),
month = value.getMonth(),
days = [],
daysInMonth, i;
if (!value || !Ext.isDate(value) || !slot) {
return;
}
this.callParent(arguments);
//get the new days of the month for this new date
daysInMonth = this.getDaysInMonth(month + 1, year);
for (i = 0; i < daysInMonth; i++) {
days.push({
text: i + 1,
value: i + 1
});
}
// We don't need to update the slot days unless it has changed
if (slot.getStore().getCount() == days.length) {
return;
}
slot.getStore().setData(days);
// Now we have the correct amount of days for the day slot, lets update it
var store = slot.getStore(),
viewItems = slot.getViewItems(),
valueField = slot.getValueField(),
index, item;
index = store.find(valueField, value.getDate());
if (index == -1) {
return;
}
item = Ext.get(viewItems[index]);
slot.selectedIndex = index;
slot.scrollToItem(item);
slot.setValue(slot.getValue(true));
},
getDaySlot: function() {
var innerItems = this.getInnerItems(),
ln = innerItems.length,
i, slot;
if (this.daySlot) {
return this.daySlot;
}
for (i = 0; i < ln; i++) {
slot = innerItems[i];
if (slot.isSlot && slot.getName() == "day") {
this.daySlot = slot;
return slot;
}
}
return null;
},
// @private
getDaysInMonth: function(month, year) {
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return month == 2 && this.isLeapYear(year) ? 29 : daysInMonth[month-1];
},
// @private
isLeapYear: function(year) {
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
},
onDoneButtonTap: function() {
var oldValue = this._value,
newValue = this.getValue(true),
testValue = newValue;
if (Ext.isDate(newValue)) {
testValue = newValue.toDateString();
}
if (Ext.isDate(oldValue)) {
oldValue = oldValue.toDateString();
}
if (testValue != oldValue) {
this.fireEvent('change', this, newValue);
}
this.hide();
Ext.util.InputBlocker.unblockInputs();
}
}); | appcodechile/Rockola | webapp/touch/src/picker/Date.js | JavaScript | mit | 12,879 |
function acosh (arg) {
// http://kevin.vanzonneveld.net
// + original by: Onno Marsman
// * example 1: acosh(8723321.4);
// * returns 1: 16.674657798418625
return Math.log(arg + Math.sqrt(arg * arg - 1));
}
| montanaflynn/phpjs | functions/math/acosh.js | JavaScript | mit | 227 |
// @target: ES3
// @sourcemap: true
interface I {}
var x = 0; | progre/TypeScript | tests/cases/compiler/sourceMap-InterfacePrecedingVariableDeclaration1.ts | TypeScript | apache-2.0 | 66 |
#!/bin/bash
# This script:
# - assumes there are 2 network interfaces connected to $PUBLIC_SUBNET and $PRIVATE_SUBNET respectively
# - finds IP addresses from those interfaces using `ip` command
# - exports the IPs as variables
function getIpForSubnet {
if [ -z $1 ]; then
echo Subnet parameter undefined
exit 1
else
ip r | grep $1 | sed 's/.*src\ \([^\ ]*\).*/\1/'
fi
}
if [ -z $PUBLIC_SUBNET ]; then
PUBLIC_IP=0.0.0.0
echo PUBLIC_SUBNET undefined. PUBLIC_IP defaults to $PUBLIC_IP
else
export PUBLIC_IP=`getIpForSubnet $PUBLIC_SUBNET`
fi
if [ -z $PRIVATE_SUBNET ]; then
PRIVATE_IP=127.0.0.1
echo PRIVATE_SUBNET undefined. PRIVATE_IP defaults to $PRIVATE_IP
else
export PRIVATE_IP=`getIpForSubnet $PRIVATE_SUBNET`
fi
echo Routing table:
ip r
echo PUBLIC_SUBNET=$PUBLIC_SUBNET
echo PRIVATE_SUBNET=$PRIVATE_SUBNET
echo PUBLIC_IP=$PUBLIC_IP
echo PRIVATE_IP=$PRIVATE_IP
| thomasdarimont/keycloak | testsuite/performance/load-balancer/wildfly-modcluster/src/main/scripts/get-ips.sh | Shell | apache-2.0 | 934 |
package opts
import (
"fmt"
"testing"
)
func TestParseHost(t *testing.T) {
invalid := []string{
"anything",
"something with spaces",
"://",
"unknown://",
"tcp://:port",
"tcp://invalid",
"tcp://invalid:port",
}
valid := map[string]string{
"": DefaultHost,
" ": DefaultHost,
" ": DefaultHost,
"fd://": "fd://",
"fd://something": "fd://something",
"tcp://host:": fmt.Sprintf("tcp://host:%d", DefaultHTTPPort),
"tcp://": DefaultTCPHost,
"tcp://:2375": fmt.Sprintf("tcp://%s:2375", DefaultHTTPHost),
"tcp://:2376": fmt.Sprintf("tcp://%s:2376", DefaultHTTPHost),
"tcp://0.0.0.0:8080": "tcp://0.0.0.0:8080",
"tcp://192.168.0.0:12000": "tcp://192.168.0.0:12000",
"tcp://192.168:8080": "tcp://192.168:8080",
"tcp://0.0.0.0:1234567890": "tcp://0.0.0.0:1234567890", // yeah it's valid :P
" tcp://:7777/path ": fmt.Sprintf("tcp://%s:7777/path", DefaultHTTPHost),
"tcp://docker.com:2375": "tcp://docker.com:2375",
"unix://": "unix://" + DefaultUnixSocket,
"unix://path/to/socket": "unix://path/to/socket",
"npipe://": "npipe://" + DefaultNamedPipe,
"npipe:////./pipe/foo": "npipe:////./pipe/foo",
}
for _, value := range invalid {
if _, err := ParseHost(false, value); err == nil {
t.Errorf("Expected an error for %v, got [nil]", value)
}
}
for value, expected := range valid {
if actual, err := ParseHost(false, value); err != nil || actual != expected {
t.Errorf("Expected for %v [%v], got [%v, %v]", value, expected, actual, err)
}
}
}
func TestParseDockerDaemonHost(t *testing.T) {
invalids := map[string]string{
"0.0.0.0": "Invalid bind address format: 0.0.0.0",
"tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d",
"tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path",
"udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1",
"udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375",
"tcp://unix:///run/docker.sock": "Invalid bind address format: unix",
" tcp://:7777/path ": "Invalid bind address format: tcp://:7777/path ",
"tcp": "Invalid bind address format: tcp",
"unix": "Invalid bind address format: unix",
"fd": "Invalid bind address format: fd",
"": "Invalid bind address format: ",
}
valids := map[string]string{
"0.0.0.1:": "tcp://0.0.0.1:2375",
"0.0.0.1:5555": "tcp://0.0.0.1:5555",
"0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path",
"[::1]:": "tcp://[::1]:2375",
"[::1]:5555/path": "tcp://[::1]:5555/path",
"[0:0:0:0:0:0:0:1]:": "tcp://[0:0:0:0:0:0:0:1]:2375",
"[0:0:0:0:0:0:0:1]:5555/path": "tcp://[0:0:0:0:0:0:0:1]:5555/path",
":6666": fmt.Sprintf("tcp://%s:6666", DefaultHTTPHost),
":6666/path": fmt.Sprintf("tcp://%s:6666/path", DefaultHTTPHost),
"tcp://": DefaultTCPHost,
"tcp://:7777": fmt.Sprintf("tcp://%s:7777", DefaultHTTPHost),
"tcp://:7777/path": fmt.Sprintf("tcp://%s:7777/path", DefaultHTTPHost),
"unix:///run/docker.sock": "unix:///run/docker.sock",
"unix://": "unix://" + DefaultUnixSocket,
"fd://": "fd://",
"fd://something": "fd://something",
"localhost:": "tcp://localhost:2375",
"localhost:5555": "tcp://localhost:5555",
"localhost:5555/path": "tcp://localhost:5555/path",
}
for invalidAddr, expectedError := range invalids {
if addr, err := parseDockerDaemonHost(invalidAddr); err == nil || err.Error() != expectedError {
t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr)
}
}
for validAddr, expectedAddr := range valids {
if addr, err := parseDockerDaemonHost(validAddr); err != nil || addr != expectedAddr {
t.Errorf("%v -> expected %v, got (%v) addr (%v)", validAddr, expectedAddr, err, addr)
}
}
}
func TestParseTCP(t *testing.T) {
var (
defaultHTTPHost = "tcp://127.0.0.1:2376"
)
invalids := map[string]string{
"0.0.0.0": "Invalid bind address format: 0.0.0.0",
"tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d",
"tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path",
"udp://127.0.0.1": "Invalid proto, expected tcp: udp://127.0.0.1",
"udp://127.0.0.1:2375": "Invalid proto, expected tcp: udp://127.0.0.1:2375",
}
valids := map[string]string{
"": defaultHTTPHost,
"tcp://": defaultHTTPHost,
"0.0.0.1:": "tcp://0.0.0.1:2376",
"0.0.0.1:5555": "tcp://0.0.0.1:5555",
"0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path",
":6666": "tcp://127.0.0.1:6666",
":6666/path": "tcp://127.0.0.1:6666/path",
"tcp://:7777": "tcp://127.0.0.1:7777",
"tcp://:7777/path": "tcp://127.0.0.1:7777/path",
"[::1]:": "tcp://[::1]:2376",
"[::1]:5555": "tcp://[::1]:5555",
"[::1]:5555/path": "tcp://[::1]:5555/path",
"[0:0:0:0:0:0:0:1]:": "tcp://[0:0:0:0:0:0:0:1]:2376",
"[0:0:0:0:0:0:0:1]:5555": "tcp://[0:0:0:0:0:0:0:1]:5555",
"[0:0:0:0:0:0:0:1]:5555/path": "tcp://[0:0:0:0:0:0:0:1]:5555/path",
"localhost:": "tcp://localhost:2376",
"localhost:5555": "tcp://localhost:5555",
"localhost:5555/path": "tcp://localhost:5555/path",
}
for invalidAddr, expectedError := range invalids {
if addr, err := parseTCPAddr(invalidAddr, defaultHTTPHost); err == nil || err.Error() != expectedError {
t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr)
}
}
for validAddr, expectedAddr := range valids {
if addr, err := parseTCPAddr(validAddr, defaultHTTPHost); err != nil || addr != expectedAddr {
t.Errorf("%v -> expected %v, got %v and addr %v", validAddr, expectedAddr, err, addr)
}
}
}
func TestParseInvalidUnixAddrInvalid(t *testing.T) {
if _, err := parseSimpleProtoAddr("unix", "tcp://127.0.0.1", "unix:///var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" {
t.Fatalf("Expected an error, got %v", err)
}
if _, err := parseSimpleProtoAddr("unix", "unix://tcp://127.0.0.1", "/var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" {
t.Fatalf("Expected an error, got %v", err)
}
if v, err := parseSimpleProtoAddr("unix", "", "/var/run/docker.sock"); err != nil || v != "unix:///var/run/docker.sock" {
t.Fatalf("Expected an %v, got %v", v, "unix:///var/run/docker.sock")
}
}
| BradErz/kops | vendor/github.com/docker/docker/opts/hosts_test.go | GO | apache-2.0 | 7,120 |
/*
* Copyright 2009 Jerome Glisse.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
*/
/*
* Authors:
* Jerome Glisse <glisse@freedesktop.org>
* Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
* Dave Airlie
*/
#include <ttm/ttm_bo_api.h>
#include <ttm/ttm_bo_driver.h>
#include <ttm/ttm_placement.h>
#include <ttm/ttm_module.h>
#include <ttm/ttm_page_alloc.h>
#include <drm/drmP.h>
#include <drm/radeon_drm.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include "radeon_reg.h"
#include "radeon.h"
#define DRM_FILE_PAGE_OFFSET (0x100000000ULL >> PAGE_SHIFT)
static int radeon_ttm_debugfs_init(struct radeon_device *rdev);
static struct radeon_device *radeon_get_rdev(struct ttm_bo_device *bdev)
{
struct radeon_mman *mman;
struct radeon_device *rdev;
mman = container_of(bdev, struct radeon_mman, bdev);
rdev = container_of(mman, struct radeon_device, mman);
return rdev;
}
/*
* Global memory.
*/
static int radeon_ttm_mem_global_init(struct drm_global_reference *ref)
{
return ttm_mem_global_init(ref->object);
}
static void radeon_ttm_mem_global_release(struct drm_global_reference *ref)
{
ttm_mem_global_release(ref->object);
}
static int radeon_ttm_global_init(struct radeon_device *rdev)
{
struct drm_global_reference *global_ref;
int r;
rdev->mman.mem_global_referenced = false;
global_ref = &rdev->mman.mem_global_ref;
global_ref->global_type = DRM_GLOBAL_TTM_MEM;
global_ref->size = sizeof(struct ttm_mem_global);
global_ref->init = &radeon_ttm_mem_global_init;
global_ref->release = &radeon_ttm_mem_global_release;
r = drm_global_item_ref(global_ref);
if (r != 0) {
DRM_ERROR("Failed setting up TTM memory accounting "
"subsystem.\n");
return r;
}
rdev->mman.bo_global_ref.mem_glob =
rdev->mman.mem_global_ref.object;
global_ref = &rdev->mman.bo_global_ref.ref;
global_ref->global_type = DRM_GLOBAL_TTM_BO;
global_ref->size = sizeof(struct ttm_bo_global);
global_ref->init = &ttm_bo_global_init;
global_ref->release = &ttm_bo_global_release;
r = drm_global_item_ref(global_ref);
if (r != 0) {
DRM_ERROR("Failed setting up TTM BO subsystem.\n");
drm_global_item_unref(&rdev->mman.mem_global_ref);
return r;
}
rdev->mman.mem_global_referenced = true;
return 0;
}
static void radeon_ttm_global_fini(struct radeon_device *rdev)
{
if (rdev->mman.mem_global_referenced) {
drm_global_item_unref(&rdev->mman.bo_global_ref.ref);
drm_global_item_unref(&rdev->mman.mem_global_ref);
rdev->mman.mem_global_referenced = false;
}
}
struct ttm_backend *radeon_ttm_backend_create(struct radeon_device *rdev);
static struct ttm_backend*
radeon_create_ttm_backend_entry(struct ttm_bo_device *bdev)
{
struct radeon_device *rdev;
rdev = radeon_get_rdev(bdev);
#if __OS_HAS_AGP
if (rdev->flags & RADEON_IS_AGP) {
return ttm_agp_backend_init(bdev, rdev->ddev->agp->bridge);
} else
#endif
{
return radeon_ttm_backend_create(rdev);
}
}
static int radeon_invalidate_caches(struct ttm_bo_device *bdev, uint32_t flags)
{
return 0;
}
static int radeon_init_mem_type(struct ttm_bo_device *bdev, uint32_t type,
struct ttm_mem_type_manager *man)
{
struct radeon_device *rdev;
rdev = radeon_get_rdev(bdev);
switch (type) {
case TTM_PL_SYSTEM:
/* System memory */
man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
man->available_caching = TTM_PL_MASK_CACHING;
man->default_caching = TTM_PL_FLAG_CACHED;
break;
case TTM_PL_TT:
man->func = &ttm_bo_manager_func;
man->gpu_offset = rdev->mc.gtt_start;
man->available_caching = TTM_PL_MASK_CACHING;
man->default_caching = TTM_PL_FLAG_CACHED;
man->flags = TTM_MEMTYPE_FLAG_MAPPABLE | TTM_MEMTYPE_FLAG_CMA;
#if __OS_HAS_AGP
if (rdev->flags & RADEON_IS_AGP) {
if (!(drm_core_has_AGP(rdev->ddev) && rdev->ddev->agp)) {
DRM_ERROR("AGP is not enabled for memory type %u\n",
(unsigned)type);
return -EINVAL;
}
if (!rdev->ddev->agp->cant_use_aperture)
man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
man->available_caching = TTM_PL_FLAG_UNCACHED |
TTM_PL_FLAG_WC;
man->default_caching = TTM_PL_FLAG_WC;
}
#endif
break;
case TTM_PL_VRAM:
/* "On-card" video ram */
man->func = &ttm_bo_manager_func;
man->gpu_offset = rdev->mc.vram_start;
man->flags = TTM_MEMTYPE_FLAG_FIXED |
TTM_MEMTYPE_FLAG_MAPPABLE;
man->available_caching = TTM_PL_FLAG_UNCACHED | TTM_PL_FLAG_WC;
man->default_caching = TTM_PL_FLAG_WC;
break;
default:
DRM_ERROR("Unsupported memory type %u\n", (unsigned)type);
return -EINVAL;
}
return 0;
}
static void radeon_evict_flags(struct ttm_buffer_object *bo,
struct ttm_placement *placement)
{
struct radeon_bo *rbo;
static u32 placements = TTM_PL_MASK_CACHING | TTM_PL_FLAG_SYSTEM;
if (!radeon_ttm_bo_is_radeon_bo(bo)) {
placement->fpfn = 0;
placement->lpfn = 0;
placement->placement = &placements;
placement->busy_placement = &placements;
placement->num_placement = 1;
placement->num_busy_placement = 1;
return;
}
rbo = container_of(bo, struct radeon_bo, tbo);
switch (bo->mem.mem_type) {
case TTM_PL_VRAM:
if (rbo->rdev->cp.ready == false)
radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_CPU);
else
radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_GTT);
break;
case TTM_PL_TT:
default:
radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_CPU);
}
*placement = rbo->placement;
}
static int radeon_verify_access(struct ttm_buffer_object *bo, struct file *filp)
{
return 0;
}
static void radeon_move_null(struct ttm_buffer_object *bo,
struct ttm_mem_reg *new_mem)
{
struct ttm_mem_reg *old_mem = &bo->mem;
BUG_ON(old_mem->mm_node != NULL);
*old_mem = *new_mem;
new_mem->mm_node = NULL;
}
static int radeon_move_blit(struct ttm_buffer_object *bo,
bool evict, int no_wait_reserve, bool no_wait_gpu,
struct ttm_mem_reg *new_mem,
struct ttm_mem_reg *old_mem)
{
struct radeon_device *rdev;
uint64_t old_start, new_start;
struct radeon_fence *fence;
int r;
rdev = radeon_get_rdev(bo->bdev);
r = radeon_fence_create(rdev, &fence);
if (unlikely(r)) {
return r;
}
old_start = old_mem->start << PAGE_SHIFT;
new_start = new_mem->start << PAGE_SHIFT;
switch (old_mem->mem_type) {
case TTM_PL_VRAM:
old_start += rdev->mc.vram_start;
break;
case TTM_PL_TT:
old_start += rdev->mc.gtt_start;
break;
default:
DRM_ERROR("Unknown placement %d\n", old_mem->mem_type);
return -EINVAL;
}
switch (new_mem->mem_type) {
case TTM_PL_VRAM:
new_start += rdev->mc.vram_start;
break;
case TTM_PL_TT:
new_start += rdev->mc.gtt_start;
break;
default:
DRM_ERROR("Unknown placement %d\n", old_mem->mem_type);
return -EINVAL;
}
if (!rdev->cp.ready) {
DRM_ERROR("Trying to move memory with CP turned off.\n");
return -EINVAL;
}
r = radeon_copy(rdev, old_start, new_start, new_mem->num_pages, fence);
/* FIXME: handle copy error */
r = ttm_bo_move_accel_cleanup(bo, (void *)fence, NULL,
evict, no_wait_reserve, no_wait_gpu, new_mem);
radeon_fence_unref(&fence);
return r;
}
static int radeon_move_vram_ram(struct ttm_buffer_object *bo,
bool evict, bool interruptible,
bool no_wait_reserve, bool no_wait_gpu,
struct ttm_mem_reg *new_mem)
{
struct radeon_device *rdev;
struct ttm_mem_reg *old_mem = &bo->mem;
struct ttm_mem_reg tmp_mem;
u32 placements;
struct ttm_placement placement;
int r;
rdev = radeon_get_rdev(bo->bdev);
tmp_mem = *new_mem;
tmp_mem.mm_node = NULL;
placement.fpfn = 0;
placement.lpfn = 0;
placement.num_placement = 1;
placement.placement = &placements;
placement.num_busy_placement = 1;
placement.busy_placement = &placements;
placements = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
r = ttm_bo_mem_space(bo, &placement, &tmp_mem,
interruptible, no_wait_reserve, no_wait_gpu);
if (unlikely(r)) {
return r;
}
r = ttm_tt_set_placement_caching(bo->ttm, tmp_mem.placement);
if (unlikely(r)) {
goto out_cleanup;
}
r = ttm_tt_bind(bo->ttm, &tmp_mem);
if (unlikely(r)) {
goto out_cleanup;
}
r = radeon_move_blit(bo, true, no_wait_reserve, no_wait_gpu, &tmp_mem, old_mem);
if (unlikely(r)) {
goto out_cleanup;
}
r = ttm_bo_move_ttm(bo, true, no_wait_reserve, no_wait_gpu, new_mem);
out_cleanup:
ttm_bo_mem_put(bo, &tmp_mem);
return r;
}
static int radeon_move_ram_vram(struct ttm_buffer_object *bo,
bool evict, bool interruptible,
bool no_wait_reserve, bool no_wait_gpu,
struct ttm_mem_reg *new_mem)
{
struct radeon_device *rdev;
struct ttm_mem_reg *old_mem = &bo->mem;
struct ttm_mem_reg tmp_mem;
struct ttm_placement placement;
u32 placements;
int r;
rdev = radeon_get_rdev(bo->bdev);
tmp_mem = *new_mem;
tmp_mem.mm_node = NULL;
placement.fpfn = 0;
placement.lpfn = 0;
placement.num_placement = 1;
placement.placement = &placements;
placement.num_busy_placement = 1;
placement.busy_placement = &placements;
placements = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
r = ttm_bo_mem_space(bo, &placement, &tmp_mem, interruptible, no_wait_reserve, no_wait_gpu);
if (unlikely(r)) {
return r;
}
r = ttm_bo_move_ttm(bo, true, no_wait_reserve, no_wait_gpu, &tmp_mem);
if (unlikely(r)) {
goto out_cleanup;
}
r = radeon_move_blit(bo, true, no_wait_reserve, no_wait_gpu, new_mem, old_mem);
if (unlikely(r)) {
goto out_cleanup;
}
out_cleanup:
ttm_bo_mem_put(bo, &tmp_mem);
return r;
}
static int radeon_bo_move(struct ttm_buffer_object *bo,
bool evict, bool interruptible,
bool no_wait_reserve, bool no_wait_gpu,
struct ttm_mem_reg *new_mem)
{
struct radeon_device *rdev;
struct ttm_mem_reg *old_mem = &bo->mem;
int r;
rdev = radeon_get_rdev(bo->bdev);
if (old_mem->mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
radeon_move_null(bo, new_mem);
return 0;
}
if ((old_mem->mem_type == TTM_PL_TT &&
new_mem->mem_type == TTM_PL_SYSTEM) ||
(old_mem->mem_type == TTM_PL_SYSTEM &&
new_mem->mem_type == TTM_PL_TT)) {
/* bind is enough */
radeon_move_null(bo, new_mem);
return 0;
}
if (!rdev->cp.ready || rdev->asic->copy == NULL) {
/* use memcpy */
goto memcpy;
}
if (old_mem->mem_type == TTM_PL_VRAM &&
new_mem->mem_type == TTM_PL_SYSTEM) {
r = radeon_move_vram_ram(bo, evict, interruptible,
no_wait_reserve, no_wait_gpu, new_mem);
} else if (old_mem->mem_type == TTM_PL_SYSTEM &&
new_mem->mem_type == TTM_PL_VRAM) {
r = radeon_move_ram_vram(bo, evict, interruptible,
no_wait_reserve, no_wait_gpu, new_mem);
} else {
r = radeon_move_blit(bo, evict, no_wait_reserve, no_wait_gpu, new_mem, old_mem);
}
if (r) {
memcpy:
r = ttm_bo_move_memcpy(bo, evict, no_wait_reserve, no_wait_gpu, new_mem);
}
return r;
}
static int radeon_ttm_io_mem_reserve(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
{
struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
struct radeon_device *rdev = radeon_get_rdev(bdev);
mem->bus.addr = NULL;
mem->bus.offset = 0;
mem->bus.size = mem->num_pages << PAGE_SHIFT;
mem->bus.base = 0;
mem->bus.is_iomem = false;
if (!(man->flags & TTM_MEMTYPE_FLAG_MAPPABLE))
return -EINVAL;
switch (mem->mem_type) {
case TTM_PL_SYSTEM:
/* system memory */
return 0;
case TTM_PL_TT:
#if __OS_HAS_AGP
if (rdev->flags & RADEON_IS_AGP) {
/* RADEON_IS_AGP is set only if AGP is active */
mem->bus.offset = mem->start << PAGE_SHIFT;
mem->bus.base = rdev->mc.agp_base;
mem->bus.is_iomem = !rdev->ddev->agp->cant_use_aperture;
}
#endif
break;
case TTM_PL_VRAM:
mem->bus.offset = mem->start << PAGE_SHIFT;
/* check if it's visible */
if ((mem->bus.offset + mem->bus.size) > rdev->mc.visible_vram_size)
return -EINVAL;
mem->bus.base = rdev->mc.aper_base;
mem->bus.is_iomem = true;
break;
default:
return -EINVAL;
}
return 0;
}
static void radeon_ttm_io_mem_free(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
{
}
static int radeon_sync_obj_wait(void *sync_obj, void *sync_arg,
bool lazy, bool interruptible)
{
return radeon_fence_wait((struct radeon_fence *)sync_obj, interruptible);
}
static int radeon_sync_obj_flush(void *sync_obj, void *sync_arg)
{
return 0;
}
static void radeon_sync_obj_unref(void **sync_obj)
{
radeon_fence_unref((struct radeon_fence **)sync_obj);
}
static void *radeon_sync_obj_ref(void *sync_obj)
{
return radeon_fence_ref((struct radeon_fence *)sync_obj);
}
static bool radeon_sync_obj_signaled(void *sync_obj, void *sync_arg)
{
return radeon_fence_signaled((struct radeon_fence *)sync_obj);
}
static struct ttm_bo_driver radeon_bo_driver = {
.create_ttm_backend_entry = &radeon_create_ttm_backend_entry,
.invalidate_caches = &radeon_invalidate_caches,
.init_mem_type = &radeon_init_mem_type,
.evict_flags = &radeon_evict_flags,
.move = &radeon_bo_move,
.verify_access = &radeon_verify_access,
.sync_obj_signaled = &radeon_sync_obj_signaled,
.sync_obj_wait = &radeon_sync_obj_wait,
.sync_obj_flush = &radeon_sync_obj_flush,
.sync_obj_unref = &radeon_sync_obj_unref,
.sync_obj_ref = &radeon_sync_obj_ref,
.move_notify = &radeon_bo_move_notify,
.fault_reserve_notify = &radeon_bo_fault_reserve_notify,
.io_mem_reserve = &radeon_ttm_io_mem_reserve,
.io_mem_free = &radeon_ttm_io_mem_free,
};
int radeon_ttm_init(struct radeon_device *rdev)
{
int r;
r = radeon_ttm_global_init(rdev);
if (r) {
return r;
}
/* No others user of address space so set it to 0 */
r = ttm_bo_device_init(&rdev->mman.bdev,
rdev->mman.bo_global_ref.ref.object,
&radeon_bo_driver, DRM_FILE_PAGE_OFFSET,
rdev->need_dma32);
if (r) {
DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
return r;
}
rdev->mman.initialized = true;
r = ttm_bo_init_mm(&rdev->mman.bdev, TTM_PL_VRAM,
rdev->mc.real_vram_size >> PAGE_SHIFT);
if (r) {
DRM_ERROR("Failed initializing VRAM heap.\n");
return r;
}
r = radeon_bo_create(rdev, NULL, 256 * 1024, PAGE_SIZE, true,
RADEON_GEM_DOMAIN_VRAM,
&rdev->stollen_vga_memory);
if (r) {
return r;
}
r = radeon_bo_reserve(rdev->stollen_vga_memory, false);
if (r)
return r;
r = radeon_bo_pin(rdev->stollen_vga_memory, RADEON_GEM_DOMAIN_VRAM, NULL);
radeon_bo_unreserve(rdev->stollen_vga_memory);
if (r) {
radeon_bo_unref(&rdev->stollen_vga_memory);
return r;
}
DRM_INFO("radeon: %uM of VRAM memory ready\n",
(unsigned)rdev->mc.real_vram_size / (1024 * 1024));
r = ttm_bo_init_mm(&rdev->mman.bdev, TTM_PL_TT,
rdev->mc.gtt_size >> PAGE_SHIFT);
if (r) {
DRM_ERROR("Failed initializing GTT heap.\n");
return r;
}
DRM_INFO("radeon: %uM of GTT memory ready.\n",
(unsigned)(rdev->mc.gtt_size / (1024 * 1024)));
if (unlikely(rdev->mman.bdev.dev_mapping == NULL)) {
rdev->mman.bdev.dev_mapping = rdev->ddev->dev_mapping;
}
r = radeon_ttm_debugfs_init(rdev);
if (r) {
DRM_ERROR("Failed to init debugfs\n");
return r;
}
return 0;
}
void radeon_ttm_fini(struct radeon_device *rdev)
{
int r;
if (!rdev->mman.initialized)
return;
if (rdev->stollen_vga_memory) {
r = radeon_bo_reserve(rdev->stollen_vga_memory, false);
if (r == 0) {
radeon_bo_unpin(rdev->stollen_vga_memory);
radeon_bo_unreserve(rdev->stollen_vga_memory);
}
radeon_bo_unref(&rdev->stollen_vga_memory);
}
ttm_bo_clean_mm(&rdev->mman.bdev, TTM_PL_VRAM);
ttm_bo_clean_mm(&rdev->mman.bdev, TTM_PL_TT);
ttm_bo_device_release(&rdev->mman.bdev);
radeon_gart_fini(rdev);
radeon_ttm_global_fini(rdev);
rdev->mman.initialized = false;
DRM_INFO("radeon: ttm finalized\n");
}
/* this should only be called at bootup or when userspace
* isn't running */
void radeon_ttm_set_active_vram_size(struct radeon_device *rdev, u64 size)
{
struct ttm_mem_type_manager *man;
if (!rdev->mman.initialized)
return;
man = &rdev->mman.bdev.man[TTM_PL_VRAM];
/* this just adjusts TTM size idea, which sets lpfn to the correct value */
man->size = size >> PAGE_SHIFT;
}
static struct vm_operations_struct radeon_ttm_vm_ops;
static const struct vm_operations_struct *ttm_vm_ops = NULL;
static int radeon_ttm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct ttm_buffer_object *bo;
struct radeon_device *rdev;
int r;
bo = (struct ttm_buffer_object *)vma->vm_private_data;
if (bo == NULL) {
return VM_FAULT_NOPAGE;
}
rdev = radeon_get_rdev(bo->bdev);
mutex_lock(&rdev->vram_mutex);
r = ttm_vm_ops->fault(vma, vmf);
mutex_unlock(&rdev->vram_mutex);
return r;
}
int radeon_mmap(struct file *filp, struct vm_area_struct *vma)
{
struct drm_file *file_priv;
struct radeon_device *rdev;
int r;
if (unlikely(vma->vm_pgoff < DRM_FILE_PAGE_OFFSET)) {
return drm_mmap(filp, vma);
}
file_priv = filp->private_data;
rdev = file_priv->minor->dev->dev_private;
if (rdev == NULL) {
return -EINVAL;
}
r = ttm_bo_mmap(filp, vma, &rdev->mman.bdev);
if (unlikely(r != 0)) {
return r;
}
if (unlikely(ttm_vm_ops == NULL)) {
ttm_vm_ops = vma->vm_ops;
radeon_ttm_vm_ops = *ttm_vm_ops;
radeon_ttm_vm_ops.fault = &radeon_ttm_fault;
}
vma->vm_ops = &radeon_ttm_vm_ops;
return 0;
}
/*
* TTM backend functions.
*/
struct radeon_ttm_backend {
struct ttm_backend backend;
struct radeon_device *rdev;
unsigned long num_pages;
struct page **pages;
struct page *dummy_read_page;
bool populated;
bool bound;
unsigned offset;
};
static int radeon_ttm_backend_populate(struct ttm_backend *backend,
unsigned long num_pages,
struct page **pages,
struct page *dummy_read_page)
{
struct radeon_ttm_backend *gtt;
gtt = container_of(backend, struct radeon_ttm_backend, backend);
gtt->pages = pages;
gtt->num_pages = num_pages;
gtt->dummy_read_page = dummy_read_page;
gtt->populated = true;
return 0;
}
static void radeon_ttm_backend_clear(struct ttm_backend *backend)
{
struct radeon_ttm_backend *gtt;
gtt = container_of(backend, struct radeon_ttm_backend, backend);
gtt->pages = NULL;
gtt->num_pages = 0;
gtt->dummy_read_page = NULL;
gtt->populated = false;
gtt->bound = false;
}
static int radeon_ttm_backend_bind(struct ttm_backend *backend,
struct ttm_mem_reg *bo_mem)
{
struct radeon_ttm_backend *gtt;
int r;
gtt = container_of(backend, struct radeon_ttm_backend, backend);
gtt->offset = bo_mem->start << PAGE_SHIFT;
if (!gtt->num_pages) {
WARN(1, "nothing to bind %lu pages for mreg %p back %p!\n",
gtt->num_pages, bo_mem, backend);
}
r = radeon_gart_bind(gtt->rdev, gtt->offset,
gtt->num_pages, gtt->pages);
if (r) {
DRM_ERROR("failed to bind %lu pages at 0x%08X\n",
gtt->num_pages, gtt->offset);
return r;
}
gtt->bound = true;
return 0;
}
static int radeon_ttm_backend_unbind(struct ttm_backend *backend)
{
struct radeon_ttm_backend *gtt;
gtt = container_of(backend, struct radeon_ttm_backend, backend);
radeon_gart_unbind(gtt->rdev, gtt->offset, gtt->num_pages);
gtt->bound = false;
return 0;
}
static void radeon_ttm_backend_destroy(struct ttm_backend *backend)
{
struct radeon_ttm_backend *gtt;
gtt = container_of(backend, struct radeon_ttm_backend, backend);
if (gtt->bound) {
radeon_ttm_backend_unbind(backend);
}
kfree(gtt);
}
static struct ttm_backend_func radeon_backend_func = {
.populate = &radeon_ttm_backend_populate,
.clear = &radeon_ttm_backend_clear,
.bind = &radeon_ttm_backend_bind,
.unbind = &radeon_ttm_backend_unbind,
.destroy = &radeon_ttm_backend_destroy,
};
struct ttm_backend *radeon_ttm_backend_create(struct radeon_device *rdev)
{
struct radeon_ttm_backend *gtt;
gtt = kzalloc(sizeof(struct radeon_ttm_backend), GFP_KERNEL);
if (gtt == NULL) {
return NULL;
}
gtt->backend.bdev = &rdev->mman.bdev;
gtt->backend.flags = 0;
gtt->backend.func = &radeon_backend_func;
gtt->rdev = rdev;
gtt->pages = NULL;
gtt->num_pages = 0;
gtt->dummy_read_page = NULL;
gtt->populated = false;
gtt->bound = false;
return >t->backend;
}
#define RADEON_DEBUGFS_MEM_TYPES 2
#if defined(CONFIG_DEBUG_FS)
static int radeon_mm_dump_table(struct seq_file *m, void *data)
{
struct drm_info_node *node = (struct drm_info_node *)m->private;
struct drm_mm *mm = (struct drm_mm *)node->info_ent->data;
struct drm_device *dev = node->minor->dev;
struct radeon_device *rdev = dev->dev_private;
int ret;
struct ttm_bo_global *glob = rdev->mman.bdev.glob;
spin_lock(&glob->lru_lock);
ret = drm_mm_dump_table(m, mm);
spin_unlock(&glob->lru_lock);
return ret;
}
#endif
static int radeon_ttm_debugfs_init(struct radeon_device *rdev)
{
#if defined(CONFIG_DEBUG_FS)
static struct drm_info_list radeon_mem_types_list[RADEON_DEBUGFS_MEM_TYPES+1];
static char radeon_mem_types_names[RADEON_DEBUGFS_MEM_TYPES+1][32];
unsigned i;
for (i = 0; i < RADEON_DEBUGFS_MEM_TYPES; i++) {
if (i == 0)
sprintf(radeon_mem_types_names[i], "radeon_vram_mm");
else
sprintf(radeon_mem_types_names[i], "radeon_gtt_mm");
radeon_mem_types_list[i].name = radeon_mem_types_names[i];
radeon_mem_types_list[i].show = &radeon_mm_dump_table;
radeon_mem_types_list[i].driver_features = 0;
if (i == 0)
radeon_mem_types_list[i].data = rdev->mman.bdev.man[TTM_PL_VRAM].priv;
else
radeon_mem_types_list[i].data = rdev->mman.bdev.man[TTM_PL_TT].priv;
}
/* Add ttm page pool to debugfs */
sprintf(radeon_mem_types_names[i], "ttm_page_pool");
radeon_mem_types_list[i].name = radeon_mem_types_names[i];
radeon_mem_types_list[i].show = &ttm_page_alloc_debugfs;
radeon_mem_types_list[i].driver_features = 0;
radeon_mem_types_list[i].data = NULL;
return radeon_debugfs_add_files(rdev, radeon_mem_types_list, RADEON_DEBUGFS_MEM_TYPES+1);
#endif
return 0;
}
| NooNameR/k3_bravo | drivers3/gpu2/drm/radeon/radeon_ttm.c | C | gpl-2.0 | 22,598 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @version
*/
public class RedeliveryOnExceptionBlockedDelayTest extends ContextTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(RedeliveryOnExceptionBlockedDelayTest.class);
private static volatile int attempt;
public void testRedelivery() throws Exception {
MockEndpoint before = getMockEndpoint("mock:result");
before.expectedBodiesReceived("Hello World", "Hello Camel");
// we use blocked redelivery delay so the messages arrive in the same order
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedBodiesReceived("Hello World", "Hello Camel");
template.sendBody("seda:start", "World");
template.sendBody("seda:start", "Camel");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// will by default block
onException(IllegalArgumentException.class)
.maximumRedeliveries(5).redeliveryDelay(2000);
from("seda:start")
.to("log:before")
.to("mock:before")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
LOG.info("Processing at attempt " + attempt + " " + exchange);
String body = exchange.getIn().getBody(String.class);
if (body.contains("World")) {
if (++attempt <= 2) {
LOG.info("Processing failed will thrown an exception");
throw new IllegalArgumentException("Damn");
}
}
exchange.getIn().setBody("Hello " + body);
LOG.info("Processing at attempt " + attempt + " complete " + exchange);
}
})
.to("log:after")
.to("mock:result");
}
};
}
}
| mohanaraosv/camel | camel-core/src/test/java/org/apache/camel/processor/RedeliveryOnExceptionBlockedDelayTest.java | Java | apache-2.0 | 3,369 |
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('router', function (Y, NAME) {
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
@module app
@submodule router
@since 3.4.0
**/
var HistoryHash = Y.HistoryHash,
QS = Y.QueryString,
YArray = Y.Array,
YLang = Y.Lang,
YObject = Y.Object,
win = Y.config.win,
// Holds all the active router instances. This supports the static
// `dispatch()` method which causes all routers to dispatch.
instances = [],
// We have to queue up pushState calls to avoid race conditions, since the
// popstate event doesn't actually provide any info on what URL it's
// associated with.
saveQueue = [],
/**
Fired when the router is ready to begin dispatching to route handlers.
You shouldn't need to wait for this event unless you plan to implement some
kind of custom dispatching logic. It's used internally in order to avoid
dispatching to an initial route if a browser history change occurs first.
@event ready
@param {Boolean} dispatched `true` if routes have already been dispatched
(most likely due to a history change).
@fireOnce
**/
EVT_READY = 'ready';
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
This makes it easy to wire up route handlers for different application states
while providing full back/forward navigation support and bookmarkable, shareable
URLs.
@class Router
@param {Object} [config] Config properties.
@param {Boolean} [config.html5] Overrides the default capability detection
and forces this router to use (`true`) or not use (`false`) HTML5
history.
@param {String} [config.root=''] Root path from which all routes should be
evaluated.
@param {Array} [config.routes=[]] Array of route definition objects.
@constructor
@extends Base
@since 3.4.0
**/
function Router() {
Router.superclass.constructor.apply(this, arguments);
}
Y.Router = Y.extend(Router, Y.Base, {
// -- Protected Properties -------------------------------------------------
/**
Whether or not `_dispatch()` has been called since this router was
instantiated.
@property _dispatched
@type Boolean
@default undefined
@protected
**/
/**
Whether or not we're currently in the process of dispatching to routes.
@property _dispatching
@type Boolean
@default undefined
@protected
**/
/**
History event handle for the `history:change` or `hashchange` event
subscription.
@property _historyEvents
@type EventHandle
@protected
**/
/**
Cached copy of the `html5` attribute for internal use.
@property _html5
@type Boolean
@protected
**/
/**
Map which holds the registered param handlers in the form:
`name` -> RegExp | Function.
@property _params
@type Object
@protected
@since 3.12.0
**/
/**
Whether or not the `ready` event has fired yet.
@property _ready
@type Boolean
@default undefined
@protected
**/
/**
Regex used to break up a URL string around the URL's path.
Subpattern captures:
1. Origin, everything before the URL's path-part.
2. The URL's path-part.
3. The URL's query.
4. The URL's hash fragment.
@property _regexURL
@type RegExp
@protected
@since 3.5.0
**/
_regexURL: /^((?:[^\/#?:]+:\/\/|\/\/)[^\/]*)?([^?#]*)(\?[^#]*)?(#.*)?$/,
/**
Regex used to match parameter placeholders in route paths.
Subpattern captures:
1. Parameter prefix character. Either a `:` for subpath parameters that
should only match a single level of a path, or `*` for splat parameters
that should match any number of path levels.
2. Parameter name, if specified, otherwise it is a wildcard match.
@property _regexPathParam
@type RegExp
@protected
**/
_regexPathParam: /([:*])([\w\-]+)?/g,
/**
Regex that matches and captures the query portion of a URL, minus the
preceding `?` character, and discarding the hash portion of the URL if any.
@property _regexUrlQuery
@type RegExp
@protected
**/
_regexUrlQuery: /\?([^#]*).*$/,
/**
Regex that matches everything before the path portion of a URL (the origin).
This will be used to strip this part of the URL from a string when we
only want the path.
@property _regexUrlOrigin
@type RegExp
@protected
**/
_regexUrlOrigin: /^(?:[^\/#?:]+:\/\/|\/\/)[^\/]*/,
/**
Collection of registered routes.
@property _routes
@type Array
@protected
**/
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
var self = this;
self._html5 = self.get('html5');
self._params = {};
self._routes = [];
self._url = self._getURL();
// Necessary because setters don't run on init.
self._setRoutes(config && config.routes ? config.routes :
self.get('routes'));
// Set up a history instance or hashchange listener.
if (self._html5) {
self._history = new Y.HistoryHTML5({force: true});
self._historyEvents =
Y.after('history:change', self._afterHistoryChange, self);
} else {
self._historyEvents =
Y.on('hashchange', self._afterHistoryChange, win, self);
}
// Fire a `ready` event once we're ready to route. We wait first for all
// subclass initializers to finish, then for window.onload, and then an
// additional 20ms to allow the browser to fire a useless initial
// `popstate` event if it wants to (and Chrome always wants to).
self.publish(EVT_READY, {
defaultFn : self._defReadyFn,
fireOnce : true,
preventable: false
});
self.once('initializedChange', function () {
Y.once('load', function () {
setTimeout(function () {
self.fire(EVT_READY, {dispatched: !!self._dispatched});
}, 20);
});
});
// Store this router in the collection of all active router instances.
instances.push(this);
},
destructor: function () {
var instanceIndex = YArray.indexOf(instances, this);
// Remove this router from the collection of active router instances.
if (instanceIndex > -1) {
instances.splice(instanceIndex, 1);
}
if (this._historyEvents) {
this._historyEvents.detach();
}
},
// -- Public Methods -------------------------------------------------------
/**
Dispatches to the first route handler that matches the current URL, if any.
If `dispatch()` is called before the `ready` event has fired, it will
automatically wait for the `ready` event before dispatching. Otherwise it
will dispatch immediately.
@method dispatch
@chainable
**/
dispatch: function () {
this.once(EVT_READY, function () {
var req, res;
this._ready = true;
if (!this.upgrade()) {
req = this._getRequest('dispatch');
res = this._getResponse(req);
this._dispatch(req, res);
}
});
return this;
},
/**
Gets the current route path.
@method getPath
@return {String} Current route path.
**/
getPath: function () {
return this._getPath();
},
/**
Returns `true` if this router has at least one route that matches the
specified URL, `false` otherwise. This also checks that any named `param`
handlers also accept app param values in the `url`.
This method enforces the same-origin security constraint on the specified
`url`; any URL which is not from the same origin as the current URL will
always return `false`.
@method hasRoute
@param {String} url URL to match.
@return {Boolean} `true` if there's at least one matching route, `false`
otherwise.
**/
hasRoute: function (url) {
var path, routePath, routes;
if (!this._hasSameOrigin(url)) {
return false;
}
if (!this._html5) {
url = this._upgradeURL(url);
}
// Get just the path portion of the specified `url`. The `match()`
// method does some special checking that the `path` is within the root.
path = this.removeQuery(url.replace(this._regexUrlOrigin, ''));
routes = this.match(path);
if (!routes.length) {
return false;
}
routePath = this.removeRoot(path);
// Check that there's at least one route whose param handlers also
// accept all the param values.
return !!YArray.filter(routes, function (route) {
// Get the param values for the route and path to see whether the
// param handlers accept or reject the param values. Include any
// route whose named param handlers accept *all* param values. This
// will return `false` if a param handler rejects a param value.
return this._getParamValues(route, routePath);
}, this).length;
},
/**
Returns an array of route objects that match the specified URL path.
If this router has a `root`, then the specified `path` _must_ be
semantically within the `root` path to match any routes.
This method is called internally to determine which routes match the current
path whenever the URL changes. You may override it if you want to customize
the route matching logic, although this usually shouldn't be necessary.
Each returned route object has the following properties:
* `callback`: A function or a string representing the name of a function
this router that should be executed when the route is triggered.
* `keys`: An array of strings representing the named parameters defined in
the route's path specification, if any.
* `path`: The route's path specification, which may be either a string or
a regex.
* `regex`: A regular expression version of the route's path specification.
This regex is used to determine whether the route matches a given path.
@example
router.route('/foo', function () {});
router.match('/foo');
// => [{callback: ..., keys: [], path: '/foo', regex: ...}]
@method match
@param {String} path URL path to match. This should be an absolute path that
starts with a slash: "/".
@return {Object[]} Array of route objects that match the specified path.
**/
match: function (path) {
var root = this.get('root');
if (root) {
// The `path` must be semantically within this router's `root` path
// or mount point, if it's not then no routes should be considered a
// match.
if (!this._pathHasRoot(root, path)) {
return [];
}
// Remove this router's `root` from the `path` before checking the
// routes for any matches.
path = this.removeRoot(path);
}
return YArray.filter(this._routes, function (route) {
return path.search(route.regex) > -1;
});
},
/**
Adds a handler for a route param specified by _name_.
Param handlers can be registered via this method and are used to
validate/format values of named params in routes before dispatching to the
route's handler functions. Using param handlers allows routes to defined
using string paths which allows for `req.params` to use named params, but
still applying extra validation or formatting to the param values parsed
from the URL.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped. All
other return values will be used in place of the original param value parsed
from the URL.
@example
router.param('postId', function (value) {
return parseInt(value, 10);
});
router.param('username', /^\w+$/);
router.route('/posts/:postId', function (req) {
});
router.route('/users/:username', function (req) {
// `req.params.username` is an array because the result of calling
// `exec()` on the regex is assigned as the param's value.
});
router.route('*', function () {
});
// URLs which match routes:
router.save('/posts/1'); // => "Post: 1"
router.save('/users/ericf'); // => "User: ericf"
// URLs which do not match routes because params fail validation:
router.save('/posts/a'); // => "Catch-all no routes matched!"
router.save('/users/ericf,rgrove'); // => "Catch-all no routes matched!"
@method param
@param {String} name Name of the param used in route paths.
@param {Function|RegExp} handler Function to invoke or regular expression to
`exec()` during route dispatching whose return value is used as the new
param value. Values of `false`, `null`, `undefined`, or `NaN` will cause
the current route to not match and be skipped. When a function is
specified, it will be invoked in the context of this instance with the
following parameters:
@param {String} handler.value The current param value parsed from the URL.
@param {String} handler.name The name of the param.
@chainable
@since 3.12.0
**/
param: function (name, handler) {
this._params[name] = handler;
return this;
},
/**
Removes the `root` URL from the front of _url_ (if it's there) and returns
the result. The returned path will always have a leading `/`.
@method removeRoot
@param {String} url URL.
@return {String} Rootless path.
**/
removeRoot: function (url) {
var root = this.get('root'),
path;
// Strip out the non-path part of the URL, if any (e.g.
// "http://foo.com"), so that we're left with just the path.
url = url.replace(this._regexUrlOrigin, '');
// Return the host-less URL if there's no `root` path to further remove.
if (!root) {
return url;
}
path = this.removeQuery(url);
// Remove the `root` from the `url` if it's the same or its path is
// semantically within the root path.
if (path === root || this._pathHasRoot(root, path)) {
url = url.substring(root.length);
}
return url.charAt(0) === '/' ? url : '/' + url;
},
/**
Removes a query string from the end of the _url_ (if one exists) and returns
the result.
@method removeQuery
@param {String} url URL.
@return {String} Queryless path.
**/
removeQuery: function (url) {
return url.replace(/\?.*$/, '');
},
/**
Replaces the current browser history entry with a new one, and dispatches to
the first matching route handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.replace('/path/');
// New URL: http://example.com/path/
router.replace('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.replace('/');
// New URL: http://example.com/
@method replace
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see save()
**/
replace: function (url) {
return this._queue(url, true);
},
/**
Adds a route handler for the specified `route`.
The `route` parameter may be a string or regular expression to represent a
URL path, or a route object. If it's a string (which is most common), it may
contain named parameters: `:param` will match any single part of a URL path
(not including `/` characters), and `*param` will match any number of parts
of a URL path (including `/` characters). These named parameters will be
made available as keys on the `req.params` object that's passed to route
handlers.
If the `route` parameter is a regex, all pattern matches will be made
available as numbered keys on `req.params`, starting with `0` for the full
match, then `1` for the first subpattern match, and so on.
Alternatively, an object can be provided to represent the route and it may
contain a `path` property which is a string or regular expression which
causes the route to be process as described above. If the route object
already contains a `regex` or `regexp` property, the route will be
considered fully-processed and will be associated with any `callacks`
specified on the object and those specified as parameters to this method.
**Note:** Any additional data contained on the route object will be
preserved.
Here's a set of sample routes along with URL paths that they match:
* Route: `/photos/:tag/:page`
* URL: `/photos/kittens/1`, params: `{tag: 'kittens', page: '1'}`
* URL: `/photos/puppies/2`, params: `{tag: 'puppies', page: '2'}`
* Route: `/file/*path`
* URL: `/file/foo/bar/baz.txt`, params: `{path: 'foo/bar/baz.txt'}`
* URL: `/file/foo`, params: `{path: 'foo'}`
**Middleware**: Routes also support an arbitrary number of callback
functions. This allows you to easily reuse parts of your route-handling code
with different route. This method is liberal in how it processes the
specified `callbacks`, you can specify them as separate arguments, or as
arrays, or both.
If multiple route match a given URL, they will be executed in the order they
were added. The first route that was added will be the first to be executed.
**Passing Control**: Invoking the `next()` function within a route callback
will pass control to the next callback function (if any) or route handler
(if any). If a value is passed to `next()`, it's assumed to be an error,
therefore stopping the dispatch chain, unless that value is: `"route"`,
which is special case and dispatching will skip to the next route handler.
This allows middleware to skip any remaining middleware for a particular
route.
@example
router.route('/photos/:tag/:page', function (req, res, next) {
});
// Using middleware.
router.findUser = function (req, res, next) {
req.user = this.get('users').findById(req.params.user);
next();
};
router.route('/users/:user', 'findUser', function (req, res, next) {
// The `findUser` middleware puts the `user` object on the `req`.
});
@method route
@param {String|RegExp|Object} route Route to match. May be a string or a
regular expression, or a route object.
@param {Array|Function|String} callbacks* Callback functions to call
whenever this route is triggered. These can be specified as separate
arguments, or in arrays, or both. If a callback is specified as a
string, the named function will be called on this router instance.
@param {Object} callbacks.req Request object containing information about
the request. It contains the following properties.
@param {Array|Object} callbacks.req.params Captured parameters matched
by the route path specification. If a string path was used and
contained named parameters, then this will be a key/value hash mapping
parameter names to their matched values. If a regex path was used,
this will be an array of subpattern matches starting at index 0 for
the full match, then 1 for the first subpattern match, and so on.
@param {String} callbacks.req.path The current URL path.
@param {Number} callbacks.req.pendingCallbacks Number of remaining
callbacks the route handler has after this one in the dispatch chain.
@param {Number} callbacks.req.pendingRoutes Number of matching routes
after this one in the dispatch chain.
@param {Object} callbacks.req.query Query hash representing the URL
query string, if any. Parameter names are keys, and are mapped to
parameter values.
@param {Object} callbacks.req.route Reference to the current route
object whose callbacks are being dispatched.
@param {Object} callbacks.req.router Reference to this router instance.
@param {String} callbacks.req.src What initiated the dispatch. In an
HTML5 browser, when the back/forward buttons are used, this property
will have a value of "popstate". When the `dispath()` method is
called, the `src` will be `"dispatch"`.
@param {String} callbacks.req.url The full URL.
@param {Object} callbacks.res Response object containing methods and
information that relate to responding to a request. It contains the
following properties.
@param {Object} callbacks.res.req Reference to the request object.
@param {Function} callbacks.next Function to pass control to the next
callback or the next matching route if no more callbacks (middleware)
exist for the current route handler. If you don't call this function,
then no further callbacks or route handlers will be executed, even if
there are more that match. If you do call this function, then the next
callback (if any) or matching route handler (if any) will be called.
All of these functions will receive the same `req` and `res` objects
that were passed to this route (so you can use these objects to pass
data along to subsequent callbacks and routes).
@param {String} [callbacks.next.err] Optional error which will stop the
dispatch chaining for this `req`, unless the value is `"route"`, which
is special cased to jump skip past any callbacks for the current route
and pass control the next route handler.
@chainable
**/
route: function (route, callbacks) {
// Grab callback functions from var-args.
callbacks = YArray(arguments, 1, true);
var keys, regex;
// Supports both the `route(path, callbacks)` and `route(config)` call
// signatures, allowing for fully-processed route configs to be passed.
if (typeof route === 'string' || YLang.isRegExp(route)) {
// Flatten `callbacks` into a single dimension array.
callbacks = YArray.flatten(callbacks);
keys = [];
regex = this._getRegex(route, keys);
route = {
callbacks: callbacks,
keys : keys,
path : route,
regex : regex
};
} else {
// Look for any configured `route.callbacks` and fallback to
// `route.callback` for back-compat, append var-arg `callbacks`,
// then flatten the entire collection to a single dimension array.
callbacks = YArray.flatten(
[route.callbacks || route.callback || []].concat(callbacks)
);
// Check for previously generated regex, also fallback to `regexp`
// for greater interop.
keys = route.keys;
regex = route.regex || route.regexp;
// Generates the route's regex if it doesn't already have one.
if (!regex) {
keys = [];
regex = this._getRegex(route.path, keys);
}
// Merge specified `route` config object with processed data.
route = Y.merge(route, {
callbacks: callbacks,
keys : keys,
path : route.path || regex,
regex : regex
});
}
this._routes.push(route);
return this;
},
/**
Saves a new browser history entry and dispatches to the first matching route
handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL and create a history entry.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.save('/path/');
// New URL: http://example.com/path/
router.save('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.save('/');
// New URL: http://example.com/
@method save
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see replace()
**/
save: function (url) {
return this._queue(url);
},
/**
Upgrades a hash-based URL to an HTML5 URL if necessary. In non-HTML5
browsers, this method is a noop.
@method upgrade
@return {Boolean} `true` if the URL was upgraded, `false` otherwise.
**/
upgrade: function () {
if (!this._html5) {
return false;
}
// Get the resolve hash path.
var hashPath = this._getHashPath();
if (hashPath) {
// This is an HTML5 browser and we have a hash-based path in the
// URL, so we need to upgrade the URL to a non-hash URL. This
// will trigger a `history:change` event, which will in turn
// trigger a dispatch.
this.once(EVT_READY, function () {
this.replace(hashPath);
});
return true;
}
return false;
},
// -- Protected Methods ----------------------------------------------------
/**
Wrapper around `decodeURIComponent` that also converts `+` chars into
spaces.
@method _decode
@param {String} string String to decode.
@return {String} Decoded string.
@protected
**/
_decode: function (string) {
return decodeURIComponent(string.replace(/\+/g, ' '));
},
/**
Shifts the topmost `_save()` call off the queue and executes it. Does
nothing if the queue is empty.
@method _dequeue
@chainable
@see _queue
@protected
**/
_dequeue: function () {
var self = this,
fn;
// If window.onload hasn't yet fired, wait until it has before
// dequeueing. This will ensure that we don't call pushState() before an
// initial popstate event has fired.
if (!YUI.Env.windowLoaded) {
Y.once('load', function () {
self._dequeue();
});
return this;
}
fn = saveQueue.shift();
return fn ? fn() : this;
},
/**
Dispatches to the first route handler that matches the specified _path_.
If called before the `ready` event has fired, the dispatch will be aborted.
This ensures normalized behavior between Chrome (which fires a `popstate`
event on every pageview) and other browsers (which do not).
@method _dispatch
@param {object} req Request object.
@param {String} res Response object.
@chainable
@protected
**/
_dispatch: function (req, res) {
var self = this,
routes = self.match(req.path),
callbacks = [],
routePath, paramValues;
self._dispatching = self._dispatched = true;
if (!routes || !routes.length) {
self._dispatching = false;
return self;
}
routePath = self.removeRoot(req.path);
function next(err) {
var callback, name, route;
if (err) {
// Special case "route" to skip to the next route handler
// avoiding any additional callbacks for the current route.
if (err === 'route') {
callbacks = [];
next();
} else {
Y.error(err);
}
} else if ((callback = callbacks.shift())) {
if (typeof callback === 'string') {
name = callback;
callback = self[name];
if (!callback) {
Y.error('Router: Callback not found: ' + name, null, 'router');
}
}
// Allow access to the number of remaining callbacks for the
// route.
req.pendingCallbacks = callbacks.length;
callback.call(self, req, res, next);
} else if ((route = routes.shift())) {
paramValues = self._getParamValues(route, routePath);
if (!paramValues) {
// Skip this route because one of the param handlers
// rejected a param value in the `routePath`.
next('route');
return;
}
// Expose the processed param values.
req.params = paramValues;
// Allow access to current route and the number of remaining
// routes for this request.
req.route = route;
req.pendingRoutes = routes.length;
// Make a copy of this route's `callbacks` so the original array
// is preserved.
callbacks = route.callbacks.concat();
// Execute this route's `callbacks`.
next();
}
}
next();
self._dispatching = false;
return self._dequeue();
},
/**
Returns the resolved path from the hash fragment, or an empty string if the
hash is not path-like.
@method _getHashPath
@param {String} [hash] Hash fragment to resolve into a path. By default this
will be the hash from the current URL.
@return {String} Current hash path, or an empty string if the hash is empty.
@protected
**/
_getHashPath: function (hash) {
hash || (hash = HistoryHash.getHash());
// Make sure the `hash` is path-like.
if (hash && hash.charAt(0) === '/') {
return this._joinURL(hash);
}
return '';
},
/**
Gets the location origin (i.e., protocol, host, and port) as a URL.
@example
http://example.com
@method _getOrigin
@return {String} Location origin (i.e., protocol, host, and port).
@protected
**/
_getOrigin: function () {
var location = Y.getLocation();
return location.origin || (location.protocol + '//' + location.host);
},
/**
Getter for the `params` attribute.
@method _getParams
@return {Object} Mapping of param handlers: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_getParams: function () {
return Y.merge(this._params);
},
/**
Gets the param values for the specified `route` and `path`, suitable to use
form `req.params`.
**Note:** This method will return `false` if a named param handler rejects a
param value.
@method _getParamValues
@param {Object} route The route to get param values for.
@param {String} path The route path (root removed) that provides the param
values.
@return {Boolean|Array|Object} The collection of processed param values.
Either a hash of `name` -> `value` for named params processed by this
router's param handlers, or an array of matches for a route with unnamed
params. If a named param handler rejects a value, then `false` will be
returned.
@protected
@since 3.16.0
**/
_getParamValues: function (route, path) {
var matches, paramsMatch, paramValues;
// Decode each of the path params so that the any URL-encoded path
// segments are decoded in the `req.params` object.
matches = YArray.map(route.regex.exec(path) || [], function (match) {
// Decode matches, or coerce `undefined` matches to an empty
// string to match expectations of working with `req.params`
// in the context of route dispatching, and normalize
// browser differences in their handling of regex NPCGs:
// https://github.com/yui/yui3/issues/1076
return (match && this._decode(match)) || '';
}, this);
// Simply return the array of decoded values when the route does *not*
// use named parameters.
if (matches.length - 1 !== route.keys.length) {
return matches;
}
// Remove the first "match" from the param values, because it's just the
// `path` processed by the route's regex, and map the values to the keys
// to create the name params collection.
paramValues = YArray.hash(route.keys, matches.slice(1));
// Pass each named param value to its handler, if there is one, for
// validation/processing. If a param value is rejected by a handler,
// then the params don't match and a falsy value is returned.
paramsMatch = YArray.every(route.keys, function (name) {
var paramHandler = this._params[name],
value = paramValues[name];
if (paramHandler && value && typeof value === 'string') {
// Check if `paramHandler` is a RegExp, because this
// is true in Android 2.3 and other browsers!
// `typeof /.*/ === 'function'`
value = YLang.isRegExp(paramHandler) ?
paramHandler.exec(value) :
paramHandler.call(this, value, name);
if (value !== false && YLang.isValue(value)) {
// Update the named param to the value from the handler.
paramValues[name] = value;
return true;
}
// Consider the param value as rejected by the handler.
return false;
}
return true;
}, this);
if (paramsMatch) {
return paramValues;
}
// Signal that a param value was rejected by a named param handler.
return false;
},
/**
Gets the current route path.
@method _getPath
@return {String} Current route path.
@protected
**/
_getPath: function () {
var path = (!this._html5 && this._getHashPath()) ||
Y.getLocation().pathname;
return this.removeQuery(path);
},
/**
Returns the current path root after popping off the last path segment,
making it useful for resolving other URL paths against.
The path root will always begin and end with a '/'.
@method _getPathRoot
@return {String} The URL's path root.
@protected
@since 3.5.0
**/
_getPathRoot: function () {
var slash = '/',
path = Y.getLocation().pathname,
segments;
if (path.charAt(path.length - 1) === slash) {
return path;
}
segments = path.split(slash);
segments.pop();
return segments.join(slash) + slash;
},
/**
Gets the current route query string.
@method _getQuery
@return {String} Current route query string.
@protected
**/
_getQuery: function () {
var location = Y.getLocation(),
hash, matches;
if (this._html5) {
return location.search.substring(1);
}
hash = HistoryHash.getHash();
matches = hash.match(this._regexUrlQuery);
return hash && matches ? matches[1] : location.search.substring(1);
},
/**
Creates a regular expression from the given route specification. If _path_
is already a regex, it will be returned unmodified.
@method _getRegex
@param {String|RegExp} path Route path specification.
@param {Array} keys Array reference to which route parameter names will be
added.
@return {RegExp} Route regex.
@protected
**/
_getRegex: function (path, keys) {
if (YLang.isRegExp(path)) {
return path;
}
// Special case for catchall paths.
if (path === '*') {
return (/.*/);
}
path = path.replace(this._regexPathParam, function (match, operator, key) {
// Only `*` operators are supported for key-less matches to allowing
// in-path wildcards like: '/foo/*'.
if (!key) {
return operator === '*' ? '.*' : match;
}
keys.push(key);
return operator === '*' ? '(.*?)' : '([^/#?]+)';
});
return new RegExp('^' + path + '$');
},
/**
Gets a request object that can be passed to a route handler.
@method _getRequest
@param {String} src What initiated the URL change and need for the request.
@return {Object} Request object.
@protected
**/
_getRequest: function (src) {
return {
path : this._getPath(),
query : this._parseQuery(this._getQuery()),
url : this._getURL(),
router: this,
src : src
};
},
/**
Gets a response object that can be passed to a route handler.
@method _getResponse
@param {Object} req Request object.
@return {Object} Response Object.
@protected
**/
_getResponse: function (req) {
return {req: req};
},
/**
Getter for the `routes` attribute.
@method _getRoutes
@return {Object[]} Array of route objects.
@protected
**/
_getRoutes: function () {
return this._routes.concat();
},
/**
Gets the current full URL.
@method _getURL
@return {String} URL.
@protected
**/
_getURL: function () {
var url = Y.getLocation().toString();
if (!this._html5) {
url = this._upgradeURL(url);
}
return url;
},
/**
Returns `true` when the specified `url` is from the same origin as the
current URL; i.e., the protocol, host, and port of the URLs are the same.
All host or path relative URLs are of the same origin. A scheme-relative URL
is first prefixed with the current scheme before being evaluated.
@method _hasSameOrigin
@param {String} url URL to compare origin with the current URL.
@return {Boolean} Whether the URL has the same origin of the current URL.
@protected
**/
_hasSameOrigin: function (url) {
var origin = ((url && url.match(this._regexUrlOrigin)) || [])[0];
// Prepend current scheme to scheme-relative URLs.
if (origin && origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return !origin || origin === this._getOrigin();
},
/**
Joins the `root` URL to the specified _url_, normalizing leading/trailing
`/` characters.
@example
router.set('root', '/foo');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
router.set('root', '/foo/');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
@method _joinURL
@param {String} url URL to append to the `root` URL.
@return {String} Joined URL.
@protected
**/
_joinURL: function (url) {
var root = this.get('root');
// Causes `url` to _always_ begin with a "/".
url = this.removeRoot(url);
if (url.charAt(0) === '/') {
url = url.substring(1);
}
return root && root.charAt(root.length - 1) === '/' ?
root + url :
root + '/' + url;
},
/**
Returns a normalized path, ridding it of any '..' segments and properly
handling leading and trailing slashes.
@method _normalizePath
@param {String} path URL path to normalize.
@return {String} Normalized path.
@protected
@since 3.5.0
**/
_normalizePath: function (path) {
var dots = '..',
slash = '/',
i, len, normalized, segments, segment, stack;
if (!path || path === slash) {
return slash;
}
segments = path.split(slash);
stack = [];
for (i = 0, len = segments.length; i < len; ++i) {
segment = segments[i];
if (segment === dots) {
stack.pop();
} else if (segment) {
stack.push(segment);
}
}
normalized = slash + stack.join(slash);
// Append trailing slash if necessary.
if (normalized !== slash && path.charAt(path.length - 1) === slash) {
normalized += slash;
}
return normalized;
},
/**
Parses a URL query string into a key/value hash. If `Y.QueryString.parse` is
available, this method will be an alias to that.
@method _parseQuery
@param {String} query Query string to parse.
@return {Object} Hash of key/value pairs for query parameters.
@protected
**/
_parseQuery: QS && QS.parse ? QS.parse : function (query) {
var decode = this._decode,
params = query.split('&'),
i = 0,
len = params.length,
result = {},
param;
for (; i < len; ++i) {
param = params[i].split('=');
if (param[0]) {
result[decode(param[0])] = decode(param[1] || '');
}
}
return result;
},
/**
Returns `true` when the specified `path` is semantically within the
specified `root` path.
If the `root` does not end with a trailing slash ("/"), one will be added
before the `path` is evaluated against the root path.
@example
this._pathHasRoot('/app', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/'); // => true
this._pathHasRoot('/app', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/app'); // => false
this._pathHasRoot('/app', '/app'); // => false
@method _pathHasRoot
@param {String} root Root path used to evaluate whether the specificed
`path` is semantically within. A trailing slash ("/") will be added if
it does not already end with one.
@param {String} path Path to evaluate for containing the specified `root`.
@return {Boolean} Whether or not the `path` is semantically within the
`root` path.
@protected
@since 3.13.0
**/
_pathHasRoot: function (root, path) {
var rootPath = root.charAt(root.length - 1) === '/' ? root : root + '/';
return path.indexOf(rootPath) === 0;
},
/**
Queues up a `_save()` call to run after all previously-queued calls have
finished.
This is necessary because if we make multiple `_save()` calls before the
first call gets dispatched, then both calls will dispatch to the last call's
URL.
All arguments passed to `_queue()` will be passed on to `_save()` when the
queued function is executed.
@method _queue
@chainable
@see _dequeue
@protected
**/
_queue: function () {
var args = arguments,
self = this;
saveQueue.push(function () {
if (self._html5) {
if (Y.UA.ios && Y.UA.ios < 5) {
// iOS <5 has buggy HTML5 history support, and needs to be
// synchronous.
self._save.apply(self, args);
} else {
// Wrapped in a timeout to ensure that _save() calls are
// always processed asynchronously. This ensures consistency
// between HTML5- and hash-based history.
setTimeout(function () {
self._save.apply(self, args);
}, 1);
}
} else {
self._dispatching = true; // otherwise we'll dequeue too quickly
self._save.apply(self, args);
}
return self;
});
return !this._dispatching ? this._dequeue() : this;
},
/**
Returns the normalized result of resolving the `path` against the current
path. Falsy values for `path` will return just the current path.
@method _resolvePath
@param {String} path URL path to resolve.
@return {String} Resolved path.
@protected
@since 3.5.0
**/
_resolvePath: function (path) {
if (!path) {
return Y.getLocation().pathname;
}
if (path.charAt(0) !== '/') {
path = this._getPathRoot() + path;
}
return this._normalizePath(path);
},
/**
Resolves the specified URL against the current URL.
This method resolves URLs like a browser does and will always return an
absolute URL. When the specified URL is already absolute, it is assumed to
be fully resolved and is simply returned as is. Scheme-relative URLs are
prefixed with the current protocol. Relative URLs are giving the current
URL's origin and are resolved and normalized against the current path root.
@method _resolveURL
@param {String} url URL to resolve.
@return {String} Resolved URL.
@protected
@since 3.5.0
**/
_resolveURL: function (url) {
var parts = url && url.match(this._regexURL),
origin, path, query, hash, resolved;
if (!parts) {
return Y.getLocation().toString();
}
origin = parts[1];
path = parts[2];
query = parts[3];
hash = parts[4];
// Absolute and scheme-relative URLs are assumed to be fully-resolved.
if (origin) {
// Prepend the current scheme for scheme-relative URLs.
if (origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return origin + (path || '/') + (query || '') + (hash || '');
}
// Will default to the current origin and current path.
resolved = this._getOrigin() + this._resolvePath(path);
// A path or query for the specified URL trumps the current URL's.
if (path || query) {
return resolved + (query || '') + (hash || '');
}
query = this._getQuery();
return resolved + (query ? ('?' + query) : '') + (hash || '');
},
/**
Saves a history entry using either `pushState()` or the location hash.
This method enforces the same-origin security constraint; attempting to save
a `url` that is not from the same origin as the current URL will result in
an error.
@method _save
@param {String} [url] URL for the history entry.
@param {Boolean} [replace=false] If `true`, the current history entry will
be replaced instead of a new one being added.
@chainable
@protected
**/
_save: function (url, replace) {
var urlIsString = typeof url === 'string',
currentPath, root, hash;
// Perform same-origin check on the specified URL.
if (urlIsString && !this._hasSameOrigin(url)) {
Y.error('Security error: The new URL must be of the same origin as the current URL.');
return this;
}
// Joins the `url` with the `root`.
if (urlIsString) {
url = this._joinURL(url);
}
// Force _ready to true to ensure that the history change is handled
// even if _save is called before the `ready` event fires.
this._ready = true;
if (this._html5) {
this._history[replace ? 'replace' : 'add'](null, {url: url});
} else {
currentPath = Y.getLocation().pathname;
root = this.get('root');
hash = HistoryHash.getHash();
if (!urlIsString) {
url = hash;
}
// Determine if the `root` already exists in the current location's
// `pathname`, and if it does then we can exclude it from the
// hash-based path. No need to duplicate the info in the URL.
if (root === currentPath || root === this._getPathRoot()) {
url = this.removeRoot(url);
}
// The `hashchange` event only fires when the new hash is actually
// different. This makes sure we'll always dequeue and dispatch
// _all_ router instances, mimicking the HTML5 behavior.
if (url === hash) {
Y.Router.dispatch();
} else {
HistoryHash[replace ? 'replaceHash' : 'setHash'](url);
}
}
return this;
},
/**
Setter for the `params` attribute.
@method _setParams
@param {Object} params Map in the form: `name` -> RegExp | Function.
@return {Object} The map of params: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_setParams: function (params) {
this._params = {};
YObject.each(params, function (regex, name) {
this.param(name, regex);
}, this);
return Y.merge(this._params);
},
/**
Setter for the `routes` attribute.
@method _setRoutes
@param {Object[]} routes Array of route objects.
@return {Object[]} Array of route objects.
@protected
**/
_setRoutes: function (routes) {
this._routes = [];
YArray.each(routes, function (route) {
this.route(route);
}, this);
return this._routes.concat();
},
/**
Upgrades a hash-based URL to a full-path URL, if necessary.
The specified `url` will be upgraded if its of the same origin as the
current URL and has a path-like hash. URLs that don't need upgrading will be
returned as-is.
@example
app._upgradeURL('http://example.com/#/foo/'); // => 'http://example.com/foo/';
@method _upgradeURL
@param {String} url The URL to upgrade from hash-based to full-path.
@return {String} The upgraded URL, or the specified URL untouched.
@protected
@since 3.5.0
**/
_upgradeURL: function (url) {
// We should not try to upgrade paths for external URLs.
if (!this._hasSameOrigin(url)) {
return url;
}
var hash = (url.match(/#(.*)$/) || [])[1] || '',
hashPrefix = Y.HistoryHash.hashPrefix,
hashPath;
// Strip any hash prefix, like hash-bangs.
if (hashPrefix && hash.indexOf(hashPrefix) === 0) {
hash = hash.replace(hashPrefix, '');
}
// If the hash looks like a URL path, assume it is, and upgrade it!
if (hash) {
hashPath = this._getHashPath(hash);
if (hashPath) {
return this._resolveURL(hashPath);
}
}
return url;
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles `history:change` and `hashchange` events.
@method _afterHistoryChange
@param {EventFacade} e
@protected
**/
_afterHistoryChange: function (e) {
var self = this,
src = e.src,
prevURL = self._url,
currentURL = self._getURL(),
req, res;
self._url = currentURL;
// Handles the awkwardness that is the `popstate` event. HTML5 browsers
// fire `popstate` right before they fire `hashchange`, and Chrome fires
// `popstate` on page load. If this router is not ready or the previous
// and current URLs only differ by their hash, then we want to ignore
// this `popstate` event.
if (src === 'popstate' &&
(!self._ready || prevURL.replace(/#.*$/, '') === currentURL.replace(/#.*$/, ''))) {
return;
}
req = self._getRequest(src);
res = self._getResponse(req);
self._dispatch(req, res);
},
// -- Default Event Handlers -----------------------------------------------
/**
Default handler for the `ready` event.
@method _defReadyFn
@param {EventFacade} e
@protected
**/
_defReadyFn: function (e) {
this._ready = true;
}
}, {
// -- Static Properties ----------------------------------------------------
NAME: 'router',
ATTRS: {
/**
Whether or not this browser is capable of using HTML5 history.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
**/
html5: {
// Android versions lower than 3.0 are buggy and don't update
// window.location after a pushState() call, so we fall back to
// hash-based history for them.
//
// See http://code.google.com/p/android/issues/detail?id=17471
valueFn: function () { return Y.Router.html5; },
writeOnce: 'initOnly'
},
/**
Map of params handlers in the form: `name` -> RegExp | Function.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped.
All other return values will be used in place of the original param
value parsed from the URL.
This attribute is intended to be used to set params at init time, or to
completely reset all params after init. To add params after init without
resetting all existing params, use the `param()` method.
@attribute params
@type Object
@default `{}`
@see param
@since 3.12.0
**/
params: {
value : {},
getter: '_getParams',
setter: '_setParams'
},
/**
Absolute root path from which all routes should be evaluated.
For example, if your router is running on a page at
`http://example.com/myapp/` and you add a route with the path `/`, your
route will never execute, because the path will always be preceded by
`/myapp`. Setting `root` to `/myapp` would cause all routes to be
evaluated relative to that root URL, so the `/` route would then execute
when the user browses to `http://example.com/myapp/`.
@example
router.set('root', '/myapp');
router.route('/foo', function () { ... });
// Updates the URL to: "/myapp/foo"
router.save('/foo');
@attribute root
@type String
@default `''`
**/
root: {
value: ''
},
/**
Array of route objects.
Each item in the array must be an object with the following properties
in order to be processed by the router:
* `path`: String or regex representing the path to match. See the docs
for the `route()` method for more details.
* `callbacks`: Function or a string representing the name of a
function on this router instance that should be called when the
route is triggered. An array of functions and/or strings may also be
provided. See the docs for the `route()` method for more details.
If a route object contains a `regex` or `regexp` property, or if its
`path` is a regular express, then the route will be considered to be
fully-processed. Any fully-processed routes may contain the following
properties:
* `regex`: The regular expression representing the path to match, this
property may also be named `regexp` for greater compatibility.
* `keys`: Array of named path parameters used to populate `req.params`
objects when dispatching to route handlers.
Any additional data contained on these route objects will be retained.
This is useful to store extra metadata about a route; e.g., a `name` to
give routes logical names.
This attribute is intended to be used to set routes at init time, or to
completely reset all routes after init. To add routes after init without
resetting all existing routes, use the `route()` method.
@attribute routes
@type Object[]
@default `[]`
@see route
**/
routes: {
value : [],
getter: '_getRoutes',
setter: '_setRoutes'
}
},
// Used as the default value for the `html5` attribute, and for testing.
html5: Y.HistoryBase.html5 && (!Y.UA.android || Y.UA.android >= 3),
// To make this testable.
_instances: instances,
/**
Dispatches to the first route handler that matches the specified `path` for
all active router instances.
This provides a mechanism to cause all active router instances to dispatch
to their route handlers without needing to change the URL or fire the
`history:change` or `hashchange` event.
@method dispatch
@static
@since 3.6.0
**/
dispatch: function () {
var i, len, router, req, res;
for (i = 0, len = instances.length; i < len; i += 1) {
router = instances[i];
if (router) {
req = router._getRequest('dispatch');
res = router._getResponse(req);
router._dispatch(req, res);
}
}
}
});
/**
The `Controller` class was deprecated in YUI 3.5.0 and is now an alias for the
`Router` class. Use that class instead. This alias will be removed in a future
version of YUI.
@class Controller
@constructor
@extends Base
@deprecated Use `Router` instead.
@see Router
**/
Y.Controller = Y.Router;
}, '3.16.0', {"optional": ["querystring-parse"], "requires": ["array-extras", "base-build", "history"]});
| vousk/jsdelivr | files/yui/3.16.0/router/router.js | JavaScript | mit | 59,499 |
## 2015-04-28 - Version 5.2.0
###Summary
This release adds several new features for expanded configuration, support for SSL Ciphers, several bugfixes, and improved tests.
####Features
- New parameters to class `rabbitmq`
- `ssl_ciphers`
- New parameters to class `rabbitmq::config`
- `interface`
- `ssl_interface`
- New parameters to type `rabbitmq_exchange`
- `internal`
- `auto_delete`
- `durable`
- Adds syncing with Modulesync
- Adds support for SSL Ciphers
- Adds `file_limit` support for RedHat platforms
####Bugfixes
- Will not create `rabbitmqadmin.conf` if admin is disabled
- Fixes `check_password`
- Fix to allow bindings and queues to be created when non-default management port is being used by rabbitmq. (MODULES-1856)
- `rabbitmq_policy` converts known parameters to integers
- Updates apt key for full fingerprint compliance.
- Adds a missing `routing_key` param to rabbitmqadmin absent binding call.
## 2015-03-10 - Version 5.1.0
###Summary
This release adds several features for greater flexibility in configuration of rabbitmq, includes a number of bug fixes, and bumps the minimum required version of puppetlabs-stdlib to 3.0.0.
####Changes to defaults
- The default environment variables in `rabbitmq::config` have been renamed from `RABBITMQ_NODE_PORT` and `RABBITMQ_NODE_IP_ADDRESS` to `NODE_PORT` and `NODE_IP_ADDRESS` (MODULES-1673)
####Features
- New parameters to class `rabbitmq`
- `file_limit`
- `interface`
- `ldap_other_bind`
- `ldap_config_variables`
- `ssl_interface`
- `ssl_versions`
- `rabbitmq_group`
- `rabbitmq_home`
- `rabbitmq_user`
- Add `rabbitmq_queue` and `rabbitmq_binding` types
- Update the providers to be able to retry commands
####Bugfixes
- Cleans up the formatting for rabbitmq.conf for readability
- Update tag splitting in the `rabbitmqctl` provider for `rabbitmq_user` to work with comma or space separated tags
- Do not enforce the source value for the yum provider (MODULES-1631)
- Fix conditional around `$pin`
- Remove broken SSL option in rabbitmqadmin.conf (MODULES-1691)
- Fix issues in `rabbitmq_user` with admin and no tags
- Fix issues in `rabbitmq_user` with tags not being sorted
- Fix broken check for existing exchanges in `rabbitmq_exchange`
## 2014-12-22 - Version 5.0.0
### Summary
This release fixes a longstanding security issue where the rabbitmq
erlang cookie was exposed as a fact by managing the cookie with a
provider. It also drops support for Puppet 2.7, adds many features
and fixes several bugs.
#### Backwards-incompatible Changes
- Removed the rabbitmq_erlang_cookie fact and replaced the logic to
manage that cookie with a provider.
- Dropped official support for Puppet 2.7 (EOL 9/30/2014
https://groups.google.com/forum/#!topic/puppet-users/QLguMcLraLE )
- Changed the default value of $rabbitmq::params::ldap_user_dn_pattern
to not contain a variable
- Removed deprecated parameters: $rabbitmq::cluster_disk_nodes,
$rabbitmq::server::manage_service, and
$rabbitmq::server::config_mirrored_queues
#### Features
- Add tcp_keepalive parameter to enable TCP keepalive
- Use https to download rabbitmqadmin tool when $rabbitmq::ssl is true
- Add key_content parameter for offline Debian package installations
- Use 16 character apt key to avoid potential collisions
- Add rabbitmq_policy type, including support for rabbitmq <3.2.0
- Add rabbitmq::ensure_repo parameter
- Add ability to change rabbitmq_user password
- Allow disk as a valid cluster node type
#### Bugfixes
- Avoid attempting to install rabbitmqadmin via a proxy (since it is
downloaded from localhost)
- Optimize check for RHEL GPG key
- Configure ssl_listener in stomp only if using ssl
- Use rpm as default package provider for RedHat, bringing the module in
line with the documented instructions to manage erlang separately and allowing
the default version and source parameters to become meaningful
- Configure cacertfile only if verify_none is not set
- Use -q flag for rabbitmqctl commands to avoid parsing inconsistent
debug output
- Use the -m flag for rabbitmqplugins commands, again to avoid parsing
inconsistent debug output
- Strip backslashes from the rabbitmqctl output to avoid parsing issues
- Fix limitation where version parameter was ignored
- Add /etc/rabbitmq/rabbitmqadmin.conf to fix rabbitmqadmin port usage
when ssl is on
- Fix linter errors and warnings
- Add, update, and fix tests
- Update docs
## 2014-08-20 - Version 4.1.0
### Summary
This release adds several new features, fixes bugs, and improves tests and
documentation.
#### Features
- Autorequire the rabbitmq-server service in the rabbitmq_vhost type
- Add credentials to rabbitmqadmin URL
- Added $ssl_only parameter to rabbitmq, rabbitmq::params, and
rabbitmq::config
- Added property tags to rabbitmq_user provider
#### Bugfixes
- Fix erroneous commas in rabbitmq::config
- Use correct ensure value for the rabbitmq_stomp rabbitmq_plugin
- Set HOME env variable to nil when leveraging rabbitmq to remove type error
from Python script
- Fix location for rabbitmq-plugins for RHEL
- Remove validation for package_source to allow it to be set to false
- Allow LDAP auth configuration without configuring stomp
- Added missing $ssl_verify and $ssl_fail_if_no_peer_cert to rabbitmq::config
## 2014-05-16 - Version 4.0.0
### Summary
This release includes many new features and bug fixes. With the exception of
erlang management this should be backwards compatible with 3.1.0.
#### Backwards-incompatible Changes
- erlang_manage was removed. You will need to manage erlang separately. See
the README for more information on how to configure this.
#### Features
- Improved SSL support
- Add LDAP support
- Add ability to manage RabbitMQ repositories
- Add ability to manage Erlang kernel configuration options
- Improved handling of user tags
- Use nanliu-staging module instead of hardcoded 'curl'
- Switch to yum or zypper provider instead of rpm
- Add ability to manage STOMP plugin installation.
- Allow empty permission fields
- Convert existing system tests to beaker acceptance tests.
#### Bugfixes
- exchanges no longer recreated on each puppet run if non-default vhost is used
- Allow port to be UNSET
- Re-added rabbitmq::server class
- Deprecated previously unused manage_service variable in favor of
service_manage
- Use correct key for rabbitmq apt::source
- config_mirrored_queues variable removed
- It previously did nothing, will now at least throw a warning if you try to
use it
- Remove unnecessary dependency on Class['rabbitmq::repo::rhel'] in
rabbitmq::install
## 2013-09-14 - Version 3.1.0
### Summary
This release focuses on a few small (but critical) bugfixes as well as extends
the amount of custom RabbitMQ configuration you can do with the module.
#### Features
- You can now change RabbitMQ 'Config Variables' via the parameter `config_variables`.
- You can now change RabbitMQ 'Environment Variables' via the parameter `environment_variables`.
- ArchLinux support added.
#### Fixes
- Make use of the user/password parameters in rabbitmq_exchange{}
- Correct the read/write parameter order on set_permissions/list_permissions as
they were reversed.
- Make the module pull down 3.1.5 by default.
## 2013-07-18 3.0.0
### Summary
This release heavily refactors the RabbitMQ and changes functionality in
several key ways. Please pay attention to the new README.md file for
details of how to interact with the class now. Puppet 3 and RHEL are
now fully supported. The default version of RabbitMQ has changed to
a 3.x release.
#### Bugfixes
- Improve travis testing options.
- Stop reimporting the GPG key on every run on RHEL and Debian.
- Fix documentation to make it clear you don't have to set provider => each time.
- Reference the standard rabbitmq port in the documentation instead of a custom port.
- Fixes to the README formatting.
#### Features
- Refactor the module to fix RHEL support. All interaction with the module
is now done through the main rabbitmq class.
- Add support for mirrored queues (Only on Debian family distributions currently)
- Add rabbitmq_exchange provider (using rabbitmqadmin)
- Add new `rabbitmq` class parameters:
- `manage_service`: Boolean to choose if Puppet should manage the service. (For pacemaker/HA setups)
- Add SuSE support.
#### Incompatible Changes
- Rabbitmq::server has been removed and is now rabbitmq::config. You should
not use this class directly, only via the main rabbitmq class.
## 2013-04-11 2.1.0
- remove puppetversion from rabbitmq.config template
- add cluster support
- escape resource names in regexp
## 2012-07-31 Jeff McCune <jeff@puppetlabs.com> 2.0.2
- Re-release 2.0.1 with $EDITOR droppings cleaned up
## 2012-05-03 2.0.0
- added support for new-style admin users
- added support for rabbitmq 2.7.1
## 2011-06-14 Dan Bode <dan@Puppetlabs.com> 2.0.0rc1
- Massive refactor:
- added native types for user/vhost/user_permissions
- added apt support for vendor packages
- added smoke tests
## 2011-04-08 Jeff McCune <jeff@puppetlabs.com> 1.0.4
- Update module for RabbitMQ 2.4.1 and rabbitmq-plugin-stomp package.
## 2011-03-24 1.0.3
- Initial release to the forge. Reviewed by Cody. Whitespace is good.
## 2011-03-22 1.0.2
- Whitespace only fix again... ack '\t' is my friend...
## 2011-03-22 1.0.1
- Whitespace only fix.
## 2011-03-22 1.0.0
- Initial Release. Manage the package, file and service.
| GodOfConquest/LoopAnime-Website | vagrant/puphpet/puppet/modules/rabbitmq/CHANGELOG.md | Markdown | mit | 9,444 |
/*
* Copyright 2011 Freescale Semiconductor, Inc.
* Copyright 2011 Linaro Ltd.
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <asm/page.h>
#include <asm/sizes.h>
#include <asm/mach/map.h>
#include "hardware.h"
#define IMX6Q_UART1_BASE_ADDR 0x02020000
#define IMX6Q_UART2_BASE_ADDR 0x021e8000
#define IMX6Q_UART3_BASE_ADDR 0x021ec000
#define IMX6Q_UART4_BASE_ADDR 0x021f0000
#define IMX6Q_UART5_BASE_ADDR 0x021f4000
/*
* IMX6Q_UART_BASE_ADDR is put in the middle to force the expansion
* of IMX6Q_UART##n##_BASE_ADDR.
*/
#define IMX6Q_UART_BASE_ADDR(n) IMX6Q_UART##n##_BASE_ADDR
#define IMX6Q_UART_BASE(n) IMX6Q_UART_BASE_ADDR(n)
#define IMX6Q_DEBUG_UART_BASE IMX6Q_UART_BASE(CONFIG_DEBUG_IMX6Q_UART_PORT)
static struct map_desc imx_lluart_desc = {
#ifdef CONFIG_DEBUG_IMX6Q_UART
.virtual = IMX_IO_P2V(IMX6Q_DEBUG_UART_BASE),
.pfn = __phys_to_pfn(IMX6Q_DEBUG_UART_BASE),
.length = 0x4000,
.type = MT_DEVICE,
#endif
};
void __init imx_lluart_map_io(void)
{
if (imx_lluart_desc.virtual)
iotable_init(&imx_lluart_desc, 1);
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/linux-source-3.8.0/arch/arm/mach-imx/lluart.c | C | gpl-2.0 | 1,321 |
/*
This file is part of Ext JS 3.4
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-04-03 15:07:25
*/
/**
* List compiled by mystix on the extjs.com forums.
* Thank you Mystix!
*/
/* Slovak Translation by Michal Thomka
* 14 April 2007
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">Nahrávam...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.GridPanel){
Ext.grid.GridPanel.prototype.ddText = "{0} označených riadkov";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "Zavrieť túto záložku";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "Hodnota v tomto poli je nesprávna";
}
if(Ext.LoadMask){
Ext.LoadMask.prototype.msg = "Nahrávam...";
}
Date.monthNames = [
"Január",
"Február",
"Marec",
"Apríl",
"Máj",
"Jún",
"Júl",
"August",
"September",
"Október",
"November",
"December"
];
Date.dayNames = [
"Nedeľa",
"Pondelok",
"Utorok",
"Streda",
"Štvrtok",
"Piatok",
"Sobota"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "OK",
cancel : "Zrušiť",
yes : "Áno",
no : "Nie"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "d.m.Y");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "Dnes",
minText : "Tento dátum je menší ako minimálny možný dátum",
maxText : "Tento dátum je väčší ako maximálny možný dátum",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : 'Ďalší Mesiac (Control+Doprava)',
prevText : 'Predch. Mesiac (Control+Doľava)',
monthYearText : 'Vyberte Mesiac (Control+Hore/Dole pre posun rokov)',
todayTip : "{0} (Medzerník)",
format : "d.m.Y"
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "Strana",
afterPageText : "z {0}",
firstText : "Prvá Strana",
prevText : "Predch. Strana",
nextText : "Ďalšia Strana",
lastText : "Posledná strana",
refreshText : "Obnoviť",
displayMsg : "Zobrazujem {0} - {1} z {2}",
emptyMsg : 'iadne dáta'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "Minimálna dĺžka pre toto pole je {0}",
maxLengthText : "Maximálna dĺžka pre toto pole je {0}",
blankText : "Toto pole je povinné",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "Minimálna hodnota pre toto pole je {0}",
maxText : "Maximálna hodnota pre toto pole je {0}",
nanText : "{0} je nesprávne číslo"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "Zablokované",
disabledDatesText : "Zablokované",
minText : "Dátum v tomto poli musí byť až po {0}",
maxText : "Dátum v tomto poli musí byť pred {0}",
invalidText : "{0} nie je správny dátum - musí byť vo formáte {1}",
format : "d.m.Y"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "Nahrávam...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : 'Toto pole musí byť e-mailová adresa vo formáte "user@example.com"',
urlText : 'Toto pole musí byť URL vo formáte "http:/'+'/www.example.com"',
alphaText : 'Toto pole može obsahovať iba písmená a znak _',
alphanumText : 'Toto pole može obsahovať iba písmená, čísla a znak _'
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "Zoradiť vzostupne",
sortDescText : "Zoradiť zostupne",
lockText : "Zamknúť stľpec",
unlockText : "Odomknúť stľpec",
columnsText : "Stľpce"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "Názov",
valueText : "Hodnota",
dateFormat : "d.m.Y"
});
}
if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "Potiahnite pre zmenu rozmeru",
collapsibleSplitTip : "Potiahnite pre zmenu rozmeru. Dvojklikom schováte."
});
}
| dinubalti/FirstSymfony | web/public/js/lib/ext-3.4.1/src/locale/ext-lang-sk.js | JavaScript | mit | 5,418 |
/* SPDX-License-Identifier: GPL-2.0 */
/*
* ATI Frame Buffer Device Driver Core Definitions
*/
#include <linux/spinlock.h>
#include <linux/wait.h>
/*
* Elements of the hardware specific atyfb_par structure
*/
struct crtc {
u32 vxres;
u32 vyres;
u32 xoffset;
u32 yoffset;
u32 bpp;
u32 h_tot_disp;
u32 h_sync_strt_wid;
u32 v_tot_disp;
u32 v_sync_strt_wid;
u32 vline_crnt_vline;
u32 off_pitch;
u32 gen_cntl;
u32 dp_pix_width; /* acceleration */
u32 dp_chain_mask; /* acceleration */
#ifdef CONFIG_FB_ATY_GENERIC_LCD
u32 horz_stretching;
u32 vert_stretching;
u32 ext_vert_stretch;
u32 shadow_h_tot_disp;
u32 shadow_h_sync_strt_wid;
u32 shadow_v_tot_disp;
u32 shadow_v_sync_strt_wid;
u32 lcd_gen_cntl;
u32 lcd_config_panel;
u32 lcd_index;
#endif
};
struct aty_interrupt {
wait_queue_head_t wait;
unsigned int count;
int pan_display;
};
struct pll_info {
int pll_max;
int pll_min;
int sclk, mclk, mclk_pm, xclk;
int ref_div;
int ref_clk;
int ecp_max;
};
typedef struct {
u16 unknown1;
u16 PCLK_min_freq;
u16 PCLK_max_freq;
u16 unknown2;
u16 ref_freq;
u16 ref_divider;
u16 unknown3;
u16 MCLK_pwd;
u16 MCLK_max_freq;
u16 XCLK_max_freq;
u16 SCLK_freq;
} __attribute__ ((packed)) PLL_BLOCK_MACH64;
struct pll_514 {
u8 m;
u8 n;
};
struct pll_18818 {
u32 program_bits;
u32 locationAddr;
u32 period_in_ps;
u32 post_divider;
};
struct pll_ct {
u8 pll_ref_div;
u8 pll_gen_cntl;
u8 mclk_fb_div;
u8 mclk_fb_mult; /* 2 ro 4 */
u8 sclk_fb_div;
u8 pll_vclk_cntl;
u8 vclk_post_div;
u8 vclk_fb_div;
u8 pll_ext_cntl;
u8 ext_vpll_cntl;
u8 spll_cntl2;
u32 dsp_config; /* Mach64 GTB DSP */
u32 dsp_on_off; /* Mach64 GTB DSP */
u32 dsp_loop_latency;
u32 fifo_size;
u32 xclkpagefaultdelay;
u32 xclkmaxrasdelay;
u8 xclk_ref_div;
u8 xclk_post_div;
u8 mclk_post_div_real;
u8 xclk_post_div_real;
u8 vclk_post_div_real;
u8 features;
#ifdef CONFIG_FB_ATY_GENERIC_LCD
u32 xres; /* use for LCD stretching/scaling */
#endif
};
/*
for pll_ct.features
*/
#define DONT_USE_SPLL 0x1
#define DONT_USE_XDLL 0x2
#define USE_CPUCLK 0x4
#define POWERDOWN_PLL 0x8
union aty_pll {
struct pll_ct ct;
struct pll_514 ibm514;
struct pll_18818 ics2595;
};
/*
* The hardware parameters for each card
*/
struct atyfb_par {
u32 pseudo_palette[16];
struct { u8 red, green, blue; } palette[256];
const struct aty_dac_ops *dac_ops;
const struct aty_pll_ops *pll_ops;
void __iomem *ati_regbase;
unsigned long clk_wr_offset; /* meaning overloaded, clock id by CT */
struct crtc crtc;
union aty_pll pll;
struct pll_info pll_limits;
u32 features;
u32 ref_clk_per;
u32 pll_per;
u32 mclk_per;
u32 xclk_per;
u8 bus_type;
u8 ram_type;
u8 mem_refresh_rate;
u16 pci_id;
u32 accel_flags;
int blitter_may_be_busy;
int asleep;
int lock_blank;
unsigned long res_start;
unsigned long res_size;
struct pci_dev *pdev;
#ifdef __sparc__
struct pci_mmap_map *mmap_map;
u8 mmaped;
#endif
int open;
#ifdef CONFIG_FB_ATY_GENERIC_LCD
unsigned long bios_base_phys;
unsigned long bios_base;
unsigned long lcd_table;
u16 lcd_width;
u16 lcd_height;
u32 lcd_pixclock;
u16 lcd_refreshrate;
u16 lcd_htotal;
u16 lcd_hdisp;
u16 lcd_hsync_dly;
u16 lcd_hsync_len;
u16 lcd_vtotal;
u16 lcd_vdisp;
u16 lcd_vsync_len;
u16 lcd_right_margin;
u16 lcd_lower_margin;
u16 lcd_hblank_len;
u16 lcd_vblank_len;
#endif
unsigned long aux_start; /* auxiliary aperture */
unsigned long aux_size;
struct aty_interrupt vblank;
unsigned long irq_flags;
unsigned int irq;
spinlock_t int_lock;
int wc_cookie;
u32 mem_cntl;
struct crtc saved_crtc;
union aty_pll saved_pll;
};
/*
* ATI Mach64 features
*/
#define M64_HAS(feature) ((par)->features & (M64F_##feature))
#define M64F_RESET_3D 0x00000001
#define M64F_MAGIC_FIFO 0x00000002
#define M64F_GTB_DSP 0x00000004
#define M64F_FIFO_32 0x00000008
#define M64F_SDRAM_MAGIC_PLL 0x00000010
#define M64F_MAGIC_POSTDIV 0x00000020
#define M64F_INTEGRATED 0x00000040
#define M64F_CT_BUS 0x00000080
#define M64F_VT_BUS 0x00000100
#define M64F_MOBIL_BUS 0x00000200
#define M64F_GX 0x00000400
#define M64F_CT 0x00000800
#define M64F_VT 0x00001000
#define M64F_GT 0x00002000
#define M64F_MAGIC_VRAM_SIZE 0x00004000
#define M64F_G3_PB_1_1 0x00008000
#define M64F_G3_PB_1024x768 0x00010000
#define M64F_EXTRA_BRIGHT 0x00020000
#define M64F_LT_LCD_REGS 0x00040000
#define M64F_XL_DLL 0x00080000
#define M64F_MFB_FORCE_4 0x00100000
#define M64F_HW_TRIPLE 0x00200000
#define M64F_XL_MEM 0x00400000
/*
* Register access
*/
static inline u32 aty_ld_le32(int regindex, const struct atyfb_par *par)
{
/* Hack for bloc 1, should be cleanly optimized by compiler */
if (regindex >= 0x400)
regindex -= 0x800;
#ifdef CONFIG_ATARI
return in_le32(par->ati_regbase + regindex);
#else
return readl(par->ati_regbase + regindex);
#endif
}
static inline void aty_st_le32(int regindex, u32 val, const struct atyfb_par *par)
{
/* Hack for bloc 1, should be cleanly optimized by compiler */
if (regindex >= 0x400)
regindex -= 0x800;
#ifdef CONFIG_ATARI
out_le32(par->ati_regbase + regindex, val);
#else
writel(val, par->ati_regbase + regindex);
#endif
}
static inline void aty_st_le16(int regindex, u16 val,
const struct atyfb_par *par)
{
/* Hack for bloc 1, should be cleanly optimized by compiler */
if (regindex >= 0x400)
regindex -= 0x800;
#ifdef CONFIG_ATARI
out_le16(par->ati_regbase + regindex, val);
#else
writel(val, par->ati_regbase + regindex);
#endif
}
static inline u8 aty_ld_8(int regindex, const struct atyfb_par *par)
{
/* Hack for bloc 1, should be cleanly optimized by compiler */
if (regindex >= 0x400)
regindex -= 0x800;
#ifdef CONFIG_ATARI
return in_8(par->ati_regbase + regindex);
#else
return readb(par->ati_regbase + regindex);
#endif
}
static inline void aty_st_8(int regindex, u8 val, const struct atyfb_par *par)
{
/* Hack for bloc 1, should be cleanly optimized by compiler */
if (regindex >= 0x400)
regindex -= 0x800;
#ifdef CONFIG_ATARI
out_8(par->ati_regbase + regindex, val);
#else
writeb(val, par->ati_regbase + regindex);
#endif
}
#if defined(CONFIG_PM) || defined(CONFIG_PMAC_BACKLIGHT) || \
defined (CONFIG_FB_ATY_GENERIC_LCD) || defined (CONFIG_FB_ATY_BACKLIGHT)
extern void aty_st_lcd(int index, u32 val, const struct atyfb_par *par);
extern u32 aty_ld_lcd(int index, const struct atyfb_par *par);
#endif
/*
* DAC operations
*/
struct aty_dac_ops {
int (*set_dac) (const struct fb_info * info,
const union aty_pll * pll, u32 bpp, u32 accel);
};
extern const struct aty_dac_ops aty_dac_ibm514; /* IBM RGB514 */
extern const struct aty_dac_ops aty_dac_ati68860b; /* ATI 68860-B */
extern const struct aty_dac_ops aty_dac_att21c498; /* AT&T 21C498 */
extern const struct aty_dac_ops aty_dac_unsupported; /* unsupported */
extern const struct aty_dac_ops aty_dac_ct; /* Integrated */
/*
* Clock operations
*/
struct aty_pll_ops {
int (*var_to_pll) (const struct fb_info * info, u32 vclk_per, u32 bpp, union aty_pll * pll);
u32 (*pll_to_var) (const struct fb_info * info, const union aty_pll * pll);
void (*set_pll) (const struct fb_info * info, const union aty_pll * pll);
void (*get_pll) (const struct fb_info *info, union aty_pll * pll);
int (*init_pll) (const struct fb_info * info, union aty_pll * pll);
void (*resume_pll)(const struct fb_info *info, union aty_pll *pll);
};
extern const struct aty_pll_ops aty_pll_ati18818_1; /* ATI 18818 */
extern const struct aty_pll_ops aty_pll_stg1703; /* STG 1703 */
extern const struct aty_pll_ops aty_pll_ch8398; /* Chrontel 8398 */
extern const struct aty_pll_ops aty_pll_att20c408; /* AT&T 20C408 */
extern const struct aty_pll_ops aty_pll_ibm514; /* IBM RGB514 */
extern const struct aty_pll_ops aty_pll_unsupported; /* unsupported */
extern const struct aty_pll_ops aty_pll_ct; /* Integrated */
extern void aty_set_pll_ct(const struct fb_info *info, const union aty_pll *pll);
extern u8 aty_ld_pll_ct(int offset, const struct atyfb_par *par);
/*
* Hardware cursor support
*/
extern int aty_init_cursor(struct fb_info *info);
/*
* Hardware acceleration
*/
static inline void wait_for_fifo(u16 entries, const struct atyfb_par *par)
{
while ((aty_ld_le32(FIFO_STAT, par) & 0xffff) >
((u32) (0x8000 >> entries)));
}
static inline void wait_for_idle(struct atyfb_par *par)
{
wait_for_fifo(16, par);
while ((aty_ld_le32(GUI_STAT, par) & 1) != 0);
par->blitter_may_be_busy = 0;
}
extern void aty_reset_engine(const struct atyfb_par *par);
extern void aty_init_engine(struct atyfb_par *par, struct fb_info *info);
extern u8 aty_ld_pll_ct(int offset, const struct atyfb_par *par);
void atyfb_copyarea(struct fb_info *info, const struct fb_copyarea *area);
void atyfb_fillrect(struct fb_info *info, const struct fb_fillrect *rect);
void atyfb_imageblit(struct fb_info *info, const struct fb_image *image);
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.14/drivers/video/fbdev/aty/atyfb.h | C | gpl-2.0 | 8,971 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
public enum SmoothingMode
{
Invalid = QualityMode.Invalid,
Default = QualityMode.Default,
HighSpeed = QualityMode.Low,
HighQuality = QualityMode.High,
None,
AntiAlias
}
}
| rubo/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/SmoothingMode.cs | C# | mit | 472 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
public enum InterpolationMode
{
Invalid = QualityMode.Invalid,
Default = QualityMode.Default,
Low = QualityMode.Low,
High = QualityMode.High,
Bilinear,
Bicubic,
NearestNeighbor,
HighQualityBilinear,
HighQualityBicubic
}
}
| nbarbettini/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/InterpolationMode.cs | C# | mit | 547 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* An implementation of a userlist which has been filtered and approved.
*
* @package core_privacy
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_privacy\local\request;
defined('MOODLE_INTERNAL') || die();
/**
* An implementation of a userlist which has been filtered and approved.
*
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class approved_userlist extends userlist_base {
/**
* Create a new approved userlist.
*
* @param \context $context The context.
* @param string $component the frankenstyle component name.
* @param \int[] $userids The list of userids present in this list.
*/
public function __construct(\context $context, string $component, array $userids) {
parent::__construct($context, $component);
$this->set_userids($userids);
}
/**
* Create an approved userlist from a userlist.
*
* @param userlist $userlist The source list
* @return approved_userlist The newly created approved userlist.
*/
public static function create_from_userlist(userlist $userlist) : approved_userlist {
$newlist = new static($userlist->get_context(), $userlist->get_component(), $userlist->get_userids());
return $newlist;
}
}
| reskit/moodle | privacy/classes/local/request/approved_userlist.php | PHP | gpl-3.0 | 2,170 |
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.View
* @since CakePHP(tm) v 0.2.9
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Router', 'Routing');
App::uses('Hash', 'Utility');
App::uses('Inflector', 'Utility');
/**
* Abstract base class for all other Helpers in CakePHP.
* Provides common methods and features.
*
* @package Cake.View
*/
class Helper extends Object {
/**
* Settings for this helper.
*
* @var array
*/
public $settings = array();
/**
* List of helpers used by this helper
*
* @var array
*/
public $helpers = array();
/**
* A helper lookup table used to lazy load helper objects.
*
* @var array
*/
protected $_helperMap = array();
/**
* The current theme name if any.
*
* @var string
*/
public $theme = null;
/**
* Request object
*
* @var CakeRequest
*/
public $request = null;
/**
* Plugin path
*
* @var string
*/
public $plugin = null;
/**
* Holds the fields array('field_name' => array('type' => 'string', 'length' => 100),
* primaryKey and validates array('field_name')
*
* @var array
*/
public $fieldset = array();
/**
* Holds tag templates.
*
* @var array
*/
public $tags = array();
/**
* Holds the content to be cleaned.
*
* @var mixed
*/
protected $_tainted = null;
/**
* Holds the cleaned content.
*
* @var mixed
*/
protected $_cleaned = null;
/**
* The View instance this helper is attached to
*
* @var View
*/
protected $_View;
/**
* A list of strings that should be treated as suffixes, or
* sub inputs for a parent input. This is used for date/time
* inputs primarily.
*
* @var array
*/
protected $_fieldSuffixes = array(
'year', 'month', 'day', 'hour', 'min', 'second', 'meridian'
);
/**
* The name of the current model entities are in scope of.
*
* @see Helper::setEntity()
* @var string
*/
protected $_modelScope;
/**
* The name of the current model association entities are in scope of.
*
* @see Helper::setEntity()
* @var string
*/
protected $_association;
/**
* The dot separated list of elements the current field entity is for.
*
* @see Helper::setEntity()
* @var string
*/
protected $_entityPath;
/**
* Minimized attributes
*
* @var array
*/
protected $_minimizedAttributes = array(
'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected',
'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize',
'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate'
);
/**
* Format to attribute
*
* @var string
*/
protected $_attributeFormat = '%s="%s"';
/**
* Format to attribute
*
* @var string
*/
protected $_minimizedAttributeFormat = '%s="%s"';
/**
* Default Constructor
*
* @param View $View The View this helper is being attached to.
* @param array $settings Configuration settings for the helper.
*/
public function __construct(View $View, $settings = array()) {
$this->_View = $View;
$this->request = $View->request;
if ($settings) {
$this->settings = Hash::merge($this->settings, $settings);
}
if (!empty($this->helpers)) {
$this->_helperMap = ObjectCollection::normalizeObjectArray($this->helpers);
}
}
/**
* Provide non fatal errors on missing method calls.
*
* @param string $method Method to invoke
* @param array $params Array of params for the method.
* @return void
*/
public function __call($method, $params) {
trigger_error(__d('cake_dev', 'Method %1$s::%2$s does not exist', get_class($this), $method), E_USER_WARNING);
}
/**
* Lazy loads helpers. Provides access to deprecated request properties as well.
*
* @param string $name Name of the property being accessed.
* @return mixed Helper or property found at $name
* @deprecated Accessing request properties through this method is deprecated and will be removed in 3.0.
*/
public function __get($name) {
if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
$settings = array('enabled' => false) + (array)$this->_helperMap[$name]['settings'];
$this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $settings);
}
if (isset($this->{$name})) {
return $this->{$name};
}
switch ($name) {
case 'base':
case 'here':
case 'webroot':
case 'data':
return $this->request->{$name};
case 'action':
return isset($this->request->params['action']) ? $this->request->params['action'] : '';
case 'params':
return $this->request;
}
}
/**
* Provides backwards compatibility access for setting values to the request object.
*
* @param string $name Name of the property being accessed.
* @param mixed $value Value to set.
* @return void
* @deprecated This method will be removed in 3.0
*/
public function __set($name, $value) {
switch ($name) {
case 'base':
case 'here':
case 'webroot':
case 'data':
$this->request->{$name} = $value;
return;
case 'action':
$this->request->params['action'] = $value;
return;
}
$this->{$name} = $value;
}
/**
* Finds URL for specified action.
*
* Returns a URL pointing at the provided parameters.
*
* @param string|array $url Either a relative string url like `/products/view/23` or
* an array of URL parameters. Using an array for URLs will allow you to leverage
* the reverse routing features of CakePHP.
* @param boolean $full If true, the full base URL will be prepended to the result
* @return string Full translated URL with base path.
* @link http://book.cakephp.org/2.0/en/views/helpers.html
*/
public function url($url = null, $full = false) {
return h(Router::url($url, $full));
}
/**
* Checks if a file exists when theme is used, if no file is found default location is returned
*
* @param string $file The file to create a webroot path to.
* @return string Web accessible path to file.
*/
public function webroot($file) {
$asset = explode('?', $file);
$asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
$webPath = "{$this->request->webroot}" . $asset[0];
$file = $asset[0];
if (!empty($this->theme)) {
$file = trim($file, '/');
$theme = $this->theme . '/';
if (DS === '\\') {
$file = str_replace('/', '\\', $file);
}
if (file_exists(Configure::read('App.www_root') . 'theme' . DS . $this->theme . DS . $file)) {
$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
} else {
$themePath = App::themePath($this->theme);
$path = $themePath . 'webroot' . DS . $file;
if (file_exists($path)) {
$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
}
}
}
if (strpos($webPath, '//') !== false) {
return str_replace('//', '/', $webPath . $asset[1]);
}
return $webPath . $asset[1];
}
/**
* Generate URL for given asset file. Depending on options passed provides full URL with domain name.
* Also calls Helper::assetTimestamp() to add timestamp to local files
*
* @param string|array $path Path string or URL array
* @param array $options Options array. Possible keys:
* `fullBase` Return full URL with domain name
* `pathPrefix` Path prefix for relative URLs
* `ext` Asset extension to append
* `plugin` False value will prevent parsing path as a plugin
* @return string Generated URL
*/
public function assetUrl($path, $options = array()) {
if (is_array($path)) {
return $this->url($path, !empty($options['fullBase']));
}
if (strpos($path, '://') !== false) {
return $path;
}
if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
list($plugin, $path) = $this->_View->pluginSplit($path, false);
}
if (!empty($options['pathPrefix']) && $path[0] !== '/') {
$path = $options['pathPrefix'] . $path;
}
if (
!empty($options['ext']) &&
strpos($path, '?') === false &&
substr($path, -strlen($options['ext'])) !== $options['ext']
) {
$path .= $options['ext'];
}
if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
return $path;
}
if (isset($plugin)) {
$path = Inflector::underscore($plugin) . '/' . $path;
}
$path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
if (!empty($options['fullBase'])) {
$path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
}
return $path;
}
/**
* Encodes a URL for use in HTML attributes.
*
* @param string $url The URL to encode.
* @return string The URL encoded for both URL & HTML contexts.
*/
protected function _encodeUrl($url) {
$path = parse_url($url, PHP_URL_PATH);
$parts = array_map('rawurldecode', explode('/', $path));
$parts = array_map('rawurlencode', $parts);
$encoded = implode('/', $parts);
return h(str_replace($path, $encoded, $url));
}
/**
* Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
* Configure. If Asset.timestamp is true and debug > 0, or Asset.timestamp === 'force'
* a timestamp will be added.
*
* @param string $path The file path to timestamp, the path must be inside WWW_ROOT
* @return string Path with a timestamp added, or not.
*/
public function assetTimestamp($path) {
$stamp = Configure::read('Asset.timestamp');
$timestampEnabled = $stamp === 'force' || ($stamp === true && Configure::read('debug') > 0);
if ($timestampEnabled && strpos($path, '?') === false) {
$filepath = preg_replace(
'/^' . preg_quote($this->request->webroot, '/') . '/',
'',
urldecode($path)
);
$webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
if (file_exists($webrootPath)) {
//@codingStandardsIgnoreStart
return $path . '?' . @filemtime($webrootPath);
//@codingStandardsIgnoreEnd
}
$segments = explode('/', ltrim($filepath, '/'));
if ($segments[0] === 'theme') {
$theme = $segments[1];
unset($segments[0], $segments[1]);
$themePath = App::themePath($theme) . 'webroot' . DS . implode(DS, $segments);
//@codingStandardsIgnoreStart
return $path . '?' . @filemtime($themePath);
//@codingStandardsIgnoreEnd
} else {
$plugin = Inflector::camelize($segments[0]);
if (CakePlugin::loaded($plugin)) {
unset($segments[0]);
$pluginPath = CakePlugin::path($plugin) . 'webroot' . DS . implode(DS, $segments);
//@codingStandardsIgnoreStart
return $path . '?' . @filemtime($pluginPath);
//@codingStandardsIgnoreEnd
}
}
}
return $path;
}
/**
* Used to remove harmful tags from content. Removes a number of well known XSS attacks
* from content. However, is not guaranteed to remove all possibilities. Escaping
* content is the best way to prevent all possible attacks.
*
* @param string|array $output Either an array of strings to clean or a single string to clean.
* @return string|array cleaned content for output
* @deprecated This method will be removed in 3.0
*/
public function clean($output) {
$this->_reset();
if (empty($output)) {
return null;
}
if (is_array($output)) {
foreach ($output as $key => $value) {
$return[$key] = $this->clean($value);
}
return $return;
}
$this->_tainted = $output;
$this->_clean();
return $this->_cleaned;
}
/**
* Returns a space-delimited string with items of the $options array. If a key
* of $options array happens to be one of those listed in `Helper::$_minimizedAttributes`
*
* And its value is one of:
*
* - '1' (string)
* - 1 (integer)
* - true (boolean)
* - 'true' (string)
*
* Then the value will be reset to be identical with key's name.
* If the value is not one of these 3, the parameter is not output.
*
* 'escape' is a special option in that it controls the conversion of
* attributes to their html-entity encoded equivalents. Set to false to disable html-encoding.
*
* If value for any option key is set to `null` or `false`, that option will be excluded from output.
*
* @param array $options Array of options.
* @param array $exclude Array of options to be excluded, the options here will not be part of the return.
* @param string $insertBefore String to be inserted before options.
* @param string $insertAfter String to be inserted after options.
* @return string Composed attributes.
* @deprecated This method will be moved to HtmlHelper in 3.0
*/
protected function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
if (!is_string($options)) {
$options = (array)$options + array('escape' => true);
if (!is_array($exclude)) {
$exclude = array();
}
$exclude = array('escape' => true) + array_flip($exclude);
$escape = $options['escape'];
$attributes = array();
foreach ($options as $key => $value) {
if (!isset($exclude[$key]) && $value !== false && $value !== null) {
$attributes[] = $this->_formatAttribute($key, $value, $escape);
}
}
$out = implode(' ', $attributes);
} else {
$out = $options;
}
return $out ? $insertBefore . $out . $insertAfter : '';
}
/**
* Formats an individual attribute, and returns the string value of the composed attribute.
* Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
*
* @param string $key The name of the attribute to create
* @param string $value The value of the attribute to create.
* @param boolean $escape Define if the value must be escaped
* @return string The composed attribute.
* @deprecated This method will be moved to HtmlHelper in 3.0
*/
protected function _formatAttribute($key, $value, $escape = true) {
if (is_array($value)) {
$value = implode(' ', $value);
}
if (is_numeric($key)) {
return sprintf($this->_minimizedAttributeFormat, $value, $value);
}
$truthy = array(1, '1', true, 'true', $key);
$isMinimized = in_array($key, $this->_minimizedAttributes);
if ($isMinimized && in_array($value, $truthy, true)) {
return sprintf($this->_minimizedAttributeFormat, $key, $key);
}
if ($isMinimized) {
return '';
}
return sprintf($this->_attributeFormat, $key, ($escape ? h($value) : $value));
}
/**
* Returns a string to be used as onclick handler for confirm dialogs.
*
* @param string $message Message to be displayed
* @param string $okCode Code to be executed after user chose 'OK'
* @param string $cancelCode Code to be executed after user chose 'Cancel'
* @param array $options Array of options
* @return string onclick JS code
*/
protected function _confirm($message, $okCode, $cancelCode = '', $options = array()) {
$message = json_encode($message);
$confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
if (isset($options['escape']) && $options['escape'] === false) {
$confirm = h($confirm);
}
return $confirm;
}
/**
* Sets this helper's model and field properties to the dot-separated value-pair in $entity.
*
* @param string $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
* @param boolean $setScope Sets the view scope to the model specified in $tagValue
* @return void
*/
public function setEntity($entity, $setScope = false) {
if ($entity === null) {
$this->_modelScope = false;
}
if ($setScope === true) {
$this->_modelScope = $entity;
}
$parts = array_values(Hash::filter(explode('.', $entity)));
if (empty($parts)) {
return;
}
$count = count($parts);
$lastPart = isset($parts[$count - 1]) ? $parts[$count - 1] : null;
// Either 'body' or 'date.month' type inputs.
if (
($count === 1 && $this->_modelScope && !$setScope) ||
(
$count === 2 &&
in_array($lastPart, $this->_fieldSuffixes) &&
$this->_modelScope &&
$parts[0] !== $this->_modelScope
)
) {
$entity = $this->_modelScope . '.' . $entity;
}
// 0.name, 0.created.month style inputs. Excludes inputs with the modelScope in them.
if (
$count >= 2 &&
is_numeric($parts[0]) &&
!is_numeric($parts[1]) &&
$this->_modelScope &&
strpos($entity, $this->_modelScope) === false
) {
$entity = $this->_modelScope . '.' . $entity;
}
$this->_association = null;
$isHabtm = (
isset($this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type']) &&
$this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type'] === 'multiple'
);
// habtm models are special
if ($count === 1 && $isHabtm) {
$this->_association = $parts[0];
$entity = $parts[0] . '.' . $parts[0];
} else {
// check for associated model.
$reversed = array_reverse($parts);
foreach ($reversed as $i => $part) {
if ($i > 0 && preg_match('/^[A-Z]/', $part)) {
$this->_association = $part;
break;
}
}
}
$this->_entityPath = $entity;
}
/**
* Returns the entity reference of the current context as an array of identity parts
*
* @return array An array containing the identity elements of an entity
*/
public function entity() {
return explode('.', $this->_entityPath);
}
/**
* Gets the currently-used model of the rendering context.
*
* @return string
*/
public function model() {
if ($this->_association) {
return $this->_association;
}
return $this->_modelScope;
}
/**
* Gets the currently-used model field of the rendering context.
* Strips off field suffixes such as year, month, day, hour, min, meridian
* when the current entity is longer than 2 elements.
*
* @return string
*/
public function field() {
$entity = $this->entity();
$count = count($entity);
$last = $entity[$count - 1];
if ($count > 2 && in_array($last, $this->_fieldSuffixes)) {
$last = isset($entity[$count - 2]) ? $entity[$count - 2] : null;
}
return $last;
}
/**
* Generates a DOM ID for the selected element, if one is not set.
* Uses the current View::entity() settings to generate a CamelCased id attribute.
*
* @param array|string $options Either an array of html attributes to add $id into, or a string
* with a view entity path to get a domId for.
* @param string $id The name of the 'id' attribute.
* @return mixed If $options was an array, an array will be returned with $id set. If a string
* was supplied, a string will be returned.
*/
public function domId($options = null, $id = 'id') {
if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
unset($options[$id]);
return $options;
} elseif (!is_array($options) && $options !== null) {
$this->setEntity($options);
return $this->domId();
}
$entity = $this->entity();
$model = array_shift($entity);
$dom = $model . implode('', array_map(array('Inflector', 'camelize'), $entity));
if (is_array($options) && !array_key_exists($id, $options)) {
$options[$id] = $dom;
} elseif ($options === null) {
return $dom;
}
return $options;
}
/**
* Gets the input field name for the current tag. Creates input name attributes
* using CakePHP's data[Model][field] formatting.
*
* @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
* If a string or null, will be used as the View entity.
* @param string $field Field name.
* @param string $key The name of the attribute to be set, defaults to 'name'
* @return mixed If an array was given for $options, an array with $key set will be returned.
* If a string was supplied a string will be returned.
*/
protected function _name($options = array(), $field = null, $key = 'name') {
if ($options === null) {
$options = array();
} elseif (is_string($options)) {
$field = $options;
$options = 0;
}
if (!empty($field)) {
$this->setEntity($field);
}
if (is_array($options) && array_key_exists($key, $options)) {
return $options;
}
switch ($field) {
case '_method':
$name = $field;
break;
default:
$name = 'data[' . implode('][', $this->entity()) . ']';
}
if (is_array($options)) {
$options[$key] = $name;
return $options;
}
return $name;
}
/**
* Gets the data for the current tag
*
* @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
* If a string or null, will be used as the View entity.
* @param string $field Field name.
* @param string $key The name of the attribute to be set, defaults to 'value'
* @return mixed If an array was given for $options, an array with $key set will be returned.
* If a string was supplied a string will be returned.
*/
public function value($options = array(), $field = null, $key = 'value') {
if ($options === null) {
$options = array();
} elseif (is_string($options)) {
$field = $options;
$options = 0;
}
if (is_array($options) && isset($options[$key])) {
return $options;
}
if (!empty($field)) {
$this->setEntity($field);
}
$result = null;
$data = $this->request->data;
$entity = $this->entity();
if (!empty($data) && is_array($data) && !empty($entity)) {
$result = Hash::get($data, implode('.', $entity));
}
$habtmKey = $this->field();
if (empty($result) && isset($data[$habtmKey][$habtmKey]) && is_array($data[$habtmKey])) {
$result = $data[$habtmKey][$habtmKey];
} elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) {
if (ClassRegistry::isKeySet($habtmKey)) {
$model = ClassRegistry::getObject($habtmKey);
$result = $this->_selectedArray($data[$habtmKey], $model->primaryKey);
}
}
if (is_array($options)) {
if ($result === null && isset($options['default'])) {
$result = $options['default'];
}
unset($options['default']);
}
if (is_array($options)) {
$options[$key] = $result;
return $options;
}
return $result;
}
/**
* Sets the defaults for an input tag. Will set the
* name, value, and id attributes for an array of html attributes.
*
* @param string $field The field name to initialize.
* @param array $options Array of options to use while initializing an input field.
* @return array Array options for the form input.
*/
protected function _initInputField($field, $options = array()) {
if ($field !== null) {
$this->setEntity($field);
}
$options = (array)$options;
$options = $this->_name($options);
$options = $this->value($options);
$options = $this->domId($options);
return $options;
}
/**
* Adds the given class to the element options
*
* @param array $options Array options/attributes to add a class to
* @param string $class The class name being added.
* @param string $key the key to use for class.
* @return array Array of options with $key set.
*/
public function addClass($options = array(), $class = null, $key = 'class') {
if (isset($options[$key]) && trim($options[$key])) {
$options[$key] .= ' ' . $class;
} else {
$options[$key] = $class;
}
return $options;
}
/**
* Returns a string generated by a helper method
*
* This method can be overridden in subclasses to do generalized output post-processing
*
* @param string $str String to be output.
* @return string
* @deprecated This method will be removed in future versions.
*/
public function output($str) {
return $str;
}
/**
* Before render callback. beforeRender is called before the view file is rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The view file that is going to be rendered
* @return void
*/
public function beforeRender($viewFile) {
}
/**
* After render callback. afterRender is called after the view file is rendered
* but before the layout has been rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The view file that was rendered.
* @return void
*/
public function afterRender($viewFile) {
}
/**
* Before layout callback. beforeLayout is called before the layout is rendered.
*
* Overridden in subclasses.
*
* @param string $layoutFile The layout about to be rendered.
* @return void
*/
public function beforeLayout($layoutFile) {
}
/**
* After layout callback. afterLayout is called after the layout has rendered.
*
* Overridden in subclasses.
*
* @param string $layoutFile The layout file that was rendered.
* @return void
*/
public function afterLayout($layoutFile) {
}
/**
* Before render file callback.
* Called before any view fragment is rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The file about to be rendered.
* @return void
*/
public function beforeRenderFile($viewFile) {
}
/**
* After render file callback.
* Called after any view fragment is rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The file just be rendered.
* @param string $content The content that was rendered.
* @return void
*/
public function afterRenderFile($viewFile, $content) {
}
/**
* Transforms a recordset from a hasAndBelongsToMany association to a list of selected
* options for a multiple select element
*
* @param string|array $data Data array or model name.
* @param string $key Field name.
* @return array
*/
protected function _selectedArray($data, $key = 'id') {
if (!is_array($data)) {
$model = $data;
if (!empty($this->request->data[$model][$model])) {
return $this->request->data[$model][$model];
}
if (!empty($this->request->data[$model])) {
$data = $this->request->data[$model];
}
}
$array = array();
if (!empty($data)) {
foreach ($data as $row) {
if (isset($row[$key])) {
$array[$row[$key]] = $row[$key];
}
}
}
return empty($array) ? null : $array;
}
/**
* Resets the vars used by Helper::clean() to null
*
* @return void
*/
protected function _reset() {
$this->_tainted = null;
$this->_cleaned = null;
}
/**
* Removes harmful content from output
*
* @return void
*/
protected function _clean() {
if (get_magic_quotes_gpc()) {
$this->_cleaned = stripslashes($this->_tainted);
} else {
$this->_cleaned = $this->_tainted;
}
$this->_cleaned = str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $this->_cleaned);
$this->_cleaned = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u', "$1;", $this->_cleaned);
$this->_cleaned = preg_replace('#(&\#x*)([0-9A-F]+);*#iu', "$1$2;", $this->_cleaned);
$this->_cleaned = html_entity_decode($this->_cleaned, ENT_COMPAT, "UTF-8");
$this->_cleaned = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>#iUu', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*)[\\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2nojavascript...', $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2novbscript...', $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=*([\'\"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#iUu', '$1=$2nomozbinding...', $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*data[\x00-\x20]*:#Uu', '$1=$2nodata...', $this->_cleaned);
$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*expression[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*behaviour[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*>#iUu', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#</*\w+:\w[^>]*>#i', "", $this->_cleaned);
do {
$oldstring = $this->_cleaned;
$this->_cleaned = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $this->_cleaned);
} while ($oldstring !== $this->_cleaned);
$this->_cleaned = str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $this->_cleaned);
}
}
| jones139/hdms | lib/Cake/View/Helper.php | PHP | gpl-3.0 | 28,454 |
#*********************************************************
#
# Copyright (c) Microsoft. All rights reserved.
# This code is licensed under the MIT License (MIT).
# This code is licensed under the MIT License (MIT).
# THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
# ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
# IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
# PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
#
#*********************************************************
param(
[switch]$Force = $false
)
$scriptPath = $(Split-Path $MyInvocation.MyCommand.Path)
$firewallRuleName = "StreamSocketSample - HTTP 443"
$requiredFeatures = "IIS-WebServer", "IIS-WebServerRole"
$settingsFile = "$scriptPath\StreamSocketSampleScriptSettings.xml"
$settings = @{"featuresToEnable"=""; "certificateThumbprint"=""}
# Check if running as Administrator.
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object System.Security.Principal.WindowsPrincipal($windowsIdentity)
$administratorRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($principal.IsInRole($administratorRole) -eq $false)
{
"Please run the script from elevated PowerShell."
return
}
# Check if the config file was created. If yes, user should first run RemoveServer.ps1.
if (Test-Path $settingsFile)
{
"The script has already been run. Please run RemoveServer.ps1 before running it again."
return
}
if(!$Force)
{
Write-Warning "This script will attempt to enable IIS and configure HTTPS."
Write-Warning "The script may interfere with any existing IIS configuration on this machine."
Write-Warning "Press N to abort if IIS is already configured on this PC."
$answer = Read-Host '[Y] Yes [N] No (default is "N")'
if ($answer -ne "Y")
{
Write-Host "Aborted by user."
return
}
}
# Get features that should be enabled.
$featuresToEnable = @()
Get-WindowsOptionalFeature -Online | ?{ $_.State -eq [Microsoft.Dism.Commands.FeatureState]::Disabled -and $requiredFeatures -contains $_.FeatureName } | %{ $featuresToEnable += $_.FeatureName }
# Save enabled features to the config file.
$settings.featuresToEnable = $featuresToEnable
$settings | Export-Clixml -Path $settingsFile
# Enable features.
if ($featuresToEnable.Count -gt 0)
{
"Enabling following features: $($featuresToEnable -join ", ")."
Enable-WindowsOptionalFeature -Online -FeatureName $featuresToEnable > $null
}
# Add firewall rule.
"Adding firewall rule `'$firewallRuleName`'."
New-NetFirewallRule -DisplayName $firewallRuleName -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow > $null
"Creating self-signed certificate."
$cert = New-SelfSignedCertificate -DnsName www.fabrikam.com -CertStoreLocation cert:\LocalMachine\My
$settings.certificateThumbprint = $cert.Thumbprint
$settings | Export-Clixml -Path $settingsFile
"Creating SSL IIS binding"
New-WebBinding -Name "Default Web Site" -IP "*" -Port 443 -Protocol https
"Removing all existing SSL bindings"
Remove-Item IIS:\SslBindings\*
"Assigning certificate to the binding"
cd IIS:\SslBindings
$cert | New-Item 0.0.0.0!443 | out-null
"Done: https://localhost should now display an invalid-certificate web-page."
cd $scriptPath
| oldnewthing/Windows-universal-samples | archived/StreamSocket/js/server/setupserver.ps1 | PowerShell | mit | 3,268 |
// (C) Copyright Edward Diener 2015
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#if !defined(BOOST_VMD_SEQ_TO_LIST_HPP)
#define BOOST_VMD_SEQ_TO_LIST_HPP
#include <boost/vmd/detail/setup.hpp>
#if BOOST_PP_VARIADICS
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/seq/to_list.hpp>
// #include <boost/vmd/identity.hpp>
#include <boost/vmd/is_empty.hpp>
/*
The succeeding comments in this file are in doxygen format.
*/
/** \file
*/
/** \def BOOST_VMD_SEQ_TO_LIST(seq)
\brief converts a seq to a list.
seq = seq to be converted.
If the seq is an empty seq it is converted to an empty list (BOOST_PP_NIL).
Otherwise the seq is converted to a list with the same number of elements as the seq.
*/
#if BOOST_VMD_MSVC
#define BOOST_VMD_SEQ_TO_LIST(seq) \
BOOST_PP_IIF \
( \
BOOST_VMD_IS_EMPTY(seq), \
BOOST_VMD_SEQ_TO_LIST_PE, \
BOOST_VMD_SEQ_TO_LIST_NPE \
) \
(seq) \
/**/
#define BOOST_VMD_SEQ_TO_LIST_PE(seq) BOOST_PP_NIL
/**/
#define BOOST_VMD_SEQ_TO_LIST_NPE(seq) BOOST_PP_SEQ_TO_LIST(seq)
/**/
#else
#define BOOST_VMD_SEQ_TO_LIST(seq) \
BOOST_PP_IIF \
( \
BOOST_VMD_IS_EMPTY(seq), \
BOOST_VMD_IDENTITY(BOOST_PP_NIL), \
BOOST_PP_SEQ_TO_LIST \
) \
(seq) \
/**/
#endif
#endif /* BOOST_PP_VARIADICS */
#endif /* BOOST_VMD_SEQ_TO_LIST_HPP */
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/boost/vmd/seq/to_list.hpp | C++ | gpl-3.0 | 1,572 |
/*
* User level driver support for input subsystem
*
* Heavily based on evdev.c by Vojtech Pavlik
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Aristeu Sergio Rozanski Filho <aris@cathedrallabs.org>
*
* Changes/Revisions:
* 0.4 01/09/2014 (Benjamin Tissoires <benjamin.tissoires@redhat.com>)
* - add UI_GET_SYSNAME ioctl
* 0.3 09/04/2006 (Anssi Hannula <anssi.hannula@gmail.com>)
* - updated ff support for the changes in kernel interface
* - added MODULE_VERSION
* 0.2 16/10/2004 (Micah Dowty <micah@navi.cx>)
* - added force feedback support
* - added UI_SET_PHYS
* 0.1 20/06/2002
* - first public version
*/
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/uinput.h>
#include <linux/input/mt.h>
#include "../input-compat.h"
static int uinput_dev_event(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
struct uinput_device *udev = input_get_drvdata(dev);
udev->buff[udev->head].type = type;
udev->buff[udev->head].code = code;
udev->buff[udev->head].value = value;
do_gettimeofday(&udev->buff[udev->head].time);
udev->head = (udev->head + 1) % UINPUT_BUFFER_SIZE;
wake_up_interruptible(&udev->waitq);
return 0;
}
/* Atomically allocate an ID for the given request. Returns 0 on success. */
static bool uinput_request_alloc_id(struct uinput_device *udev,
struct uinput_request *request)
{
unsigned int id;
bool reserved = false;
spin_lock(&udev->requests_lock);
for (id = 0; id < UINPUT_NUM_REQUESTS; id++) {
if (!udev->requests[id]) {
request->id = id;
udev->requests[id] = request;
reserved = true;
break;
}
}
spin_unlock(&udev->requests_lock);
return reserved;
}
static struct uinput_request *uinput_request_find(struct uinput_device *udev,
unsigned int id)
{
/* Find an input request, by ID. Returns NULL if the ID isn't valid. */
if (id >= UINPUT_NUM_REQUESTS)
return NULL;
return udev->requests[id];
}
static int uinput_request_reserve_slot(struct uinput_device *udev,
struct uinput_request *request)
{
/* Allocate slot. If none are available right away, wait. */
return wait_event_interruptible(udev->requests_waitq,
uinput_request_alloc_id(udev, request));
}
static void uinput_request_done(struct uinput_device *udev,
struct uinput_request *request)
{
/* Mark slot as available */
udev->requests[request->id] = NULL;
wake_up(&udev->requests_waitq);
complete(&request->done);
}
static int uinput_request_send(struct uinput_device *udev,
struct uinput_request *request)
{
int retval;
retval = mutex_lock_interruptible(&udev->mutex);
if (retval)
return retval;
if (udev->state != UIST_CREATED) {
retval = -ENODEV;
goto out;
}
init_completion(&request->done);
/*
* Tell our userspace application about this new request
* by queueing an input event.
*/
uinput_dev_event(udev->dev, EV_UINPUT, request->code, request->id);
out:
mutex_unlock(&udev->mutex);
return retval;
}
static int uinput_request_submit(struct uinput_device *udev,
struct uinput_request *request)
{
int error;
error = uinput_request_reserve_slot(udev, request);
if (error)
return error;
error = uinput_request_send(udev, request);
if (error) {
uinput_request_done(udev, request);
return error;
}
wait_for_completion(&request->done);
return request->retval;
}
/*
* Fail all outstanding requests so handlers don't wait for the userspace
* to finish processing them.
*/
static void uinput_flush_requests(struct uinput_device *udev)
{
struct uinput_request *request;
int i;
spin_lock(&udev->requests_lock);
for (i = 0; i < UINPUT_NUM_REQUESTS; i++) {
request = udev->requests[i];
if (request) {
request->retval = -ENODEV;
uinput_request_done(udev, request);
}
}
spin_unlock(&udev->requests_lock);
}
static void uinput_dev_set_gain(struct input_dev *dev, u16 gain)
{
uinput_dev_event(dev, EV_FF, FF_GAIN, gain);
}
static void uinput_dev_set_autocenter(struct input_dev *dev, u16 magnitude)
{
uinput_dev_event(dev, EV_FF, FF_AUTOCENTER, magnitude);
}
static int uinput_dev_playback(struct input_dev *dev, int effect_id, int value)
{
return uinput_dev_event(dev, EV_FF, effect_id, value);
}
static int uinput_dev_upload_effect(struct input_dev *dev,
struct ff_effect *effect,
struct ff_effect *old)
{
struct uinput_device *udev = input_get_drvdata(dev);
struct uinput_request request;
/*
* uinput driver does not currently support periodic effects with
* custom waveform since it does not have a way to pass buffer of
* samples (custom_data) to userspace. If ever there is a device
* supporting custom waveforms we would need to define an additional
* ioctl (UI_UPLOAD_SAMPLES) but for now we just bail out.
*/
if (effect->type == FF_PERIODIC &&
effect->u.periodic.waveform == FF_CUSTOM)
return -EINVAL;
request.code = UI_FF_UPLOAD;
request.u.upload.effect = effect;
request.u.upload.old = old;
return uinput_request_submit(udev, &request);
}
static int uinput_dev_erase_effect(struct input_dev *dev, int effect_id)
{
struct uinput_device *udev = input_get_drvdata(dev);
struct uinput_request request;
if (!test_bit(EV_FF, dev->evbit))
return -ENOSYS;
request.code = UI_FF_ERASE;
request.u.effect_id = effect_id;
return uinput_request_submit(udev, &request);
}
static void uinput_destroy_device(struct uinput_device *udev)
{
const char *name, *phys;
struct input_dev *dev = udev->dev;
enum uinput_state old_state = udev->state;
udev->state = UIST_NEW_DEVICE;
if (dev) {
name = dev->name;
phys = dev->phys;
if (old_state == UIST_CREATED) {
uinput_flush_requests(udev);
input_unregister_device(dev);
} else {
input_free_device(dev);
}
kfree(name);
kfree(phys);
udev->dev = NULL;
}
}
static int uinput_create_device(struct uinput_device *udev)
{
struct input_dev *dev = udev->dev;
int error, nslot;
if (udev->state != UIST_SETUP_COMPLETE) {
printk(KERN_DEBUG "%s: write device info first\n", UINPUT_NAME);
return -EINVAL;
}
if (test_bit(EV_ABS, dev->evbit)) {
input_alloc_absinfo(dev);
if (!dev->absinfo) {
error = -EINVAL;
goto fail1;
}
if (test_bit(ABS_MT_SLOT, dev->absbit)) {
nslot = input_abs_get_max(dev, ABS_MT_SLOT) + 1;
error = input_mt_init_slots(dev, nslot, 0);
if (error)
goto fail1;
} else if (test_bit(ABS_MT_POSITION_X, dev->absbit)) {
input_set_events_per_packet(dev, 60);
}
}
if (test_bit(EV_FF, dev->evbit) && !udev->ff_effects_max) {
printk(KERN_DEBUG "%s: ff_effects_max should be non-zero when FF_BIT is set\n",
UINPUT_NAME);
error = -EINVAL;
goto fail1;
}
if (udev->ff_effects_max) {
error = input_ff_create(dev, udev->ff_effects_max);
if (error)
goto fail1;
dev->ff->upload = uinput_dev_upload_effect;
dev->ff->erase = uinput_dev_erase_effect;
dev->ff->playback = uinput_dev_playback;
dev->ff->set_gain = uinput_dev_set_gain;
dev->ff->set_autocenter = uinput_dev_set_autocenter;
}
error = input_register_device(udev->dev);
if (error)
goto fail2;
udev->state = UIST_CREATED;
return 0;
fail2: input_ff_destroy(dev);
fail1: uinput_destroy_device(udev);
return error;
}
static int uinput_open(struct inode *inode, struct file *file)
{
struct uinput_device *newdev;
newdev = kzalloc(sizeof(struct uinput_device), GFP_KERNEL);
if (!newdev)
return -ENOMEM;
mutex_init(&newdev->mutex);
spin_lock_init(&newdev->requests_lock);
init_waitqueue_head(&newdev->requests_waitq);
init_waitqueue_head(&newdev->waitq);
newdev->state = UIST_NEW_DEVICE;
file->private_data = newdev;
nonseekable_open(inode, file);
return 0;
}
static int uinput_validate_absinfo(struct input_dev *dev, unsigned int code,
const struct input_absinfo *abs)
{
int min, max;
min = abs->minimum;
max = abs->maximum;
if ((min != 0 || max != 0) && max <= min) {
printk(KERN_DEBUG
"%s: invalid abs[%02x] min:%d max:%d\n",
UINPUT_NAME, code, min, max);
return -EINVAL;
}
if (abs->flat > max - min) {
printk(KERN_DEBUG
"%s: abs_flat #%02x out of range: %d (min:%d/max:%d)\n",
UINPUT_NAME, code, abs->flat, min, max);
return -EINVAL;
}
return 0;
}
static int uinput_validate_absbits(struct input_dev *dev)
{
unsigned int cnt;
int error;
if (!test_bit(EV_ABS, dev->evbit))
return 0;
/*
* Check if absmin/absmax/absfuzz/absflat are sane.
*/
for_each_set_bit(cnt, dev->absbit, ABS_CNT) {
if (!dev->absinfo)
return -EINVAL;
error = uinput_validate_absinfo(dev, cnt, &dev->absinfo[cnt]);
if (error)
return error;
}
return 0;
}
static int uinput_allocate_device(struct uinput_device *udev)
{
udev->dev = input_allocate_device();
if (!udev->dev)
return -ENOMEM;
udev->dev->event = uinput_dev_event;
input_set_drvdata(udev->dev, udev);
return 0;
}
static int uinput_dev_setup(struct uinput_device *udev,
struct uinput_setup __user *arg)
{
struct uinput_setup setup;
struct input_dev *dev;
if (udev->state == UIST_CREATED)
return -EINVAL;
if (copy_from_user(&setup, arg, sizeof(setup)))
return -EFAULT;
if (!setup.name[0])
return -EINVAL;
dev = udev->dev;
dev->id = setup.id;
udev->ff_effects_max = setup.ff_effects_max;
kfree(dev->name);
dev->name = kstrndup(setup.name, UINPUT_MAX_NAME_SIZE, GFP_KERNEL);
if (!dev->name)
return -ENOMEM;
udev->state = UIST_SETUP_COMPLETE;
return 0;
}
static int uinput_abs_setup(struct uinput_device *udev,
struct uinput_setup __user *arg, size_t size)
{
struct uinput_abs_setup setup = {};
struct input_dev *dev;
int error;
if (size > sizeof(setup))
return -E2BIG;
if (udev->state == UIST_CREATED)
return -EINVAL;
if (copy_from_user(&setup, arg, size))
return -EFAULT;
if (setup.code > ABS_MAX)
return -ERANGE;
dev = udev->dev;
error = uinput_validate_absinfo(dev, setup.code, &setup.absinfo);
if (error)
return error;
input_alloc_absinfo(dev);
if (!dev->absinfo)
return -ENOMEM;
set_bit(setup.code, dev->absbit);
dev->absinfo[setup.code] = setup.absinfo;
return 0;
}
/* legacy setup via write() */
static int uinput_setup_device_legacy(struct uinput_device *udev,
const char __user *buffer, size_t count)
{
struct uinput_user_dev *user_dev;
struct input_dev *dev;
int i;
int retval;
if (count != sizeof(struct uinput_user_dev))
return -EINVAL;
if (!udev->dev) {
retval = uinput_allocate_device(udev);
if (retval)
return retval;
}
dev = udev->dev;
user_dev = memdup_user(buffer, sizeof(struct uinput_user_dev));
if (IS_ERR(user_dev))
return PTR_ERR(user_dev);
udev->ff_effects_max = user_dev->ff_effects_max;
/* Ensure name is filled in */
if (!user_dev->name[0]) {
retval = -EINVAL;
goto exit;
}
kfree(dev->name);
dev->name = kstrndup(user_dev->name, UINPUT_MAX_NAME_SIZE,
GFP_KERNEL);
if (!dev->name) {
retval = -ENOMEM;
goto exit;
}
dev->id.bustype = user_dev->id.bustype;
dev->id.vendor = user_dev->id.vendor;
dev->id.product = user_dev->id.product;
dev->id.version = user_dev->id.version;
for (i = 0; i < ABS_CNT; i++) {
input_abs_set_max(dev, i, user_dev->absmax[i]);
input_abs_set_min(dev, i, user_dev->absmin[i]);
input_abs_set_fuzz(dev, i, user_dev->absfuzz[i]);
input_abs_set_flat(dev, i, user_dev->absflat[i]);
}
retval = uinput_validate_absbits(dev);
if (retval < 0)
goto exit;
udev->state = UIST_SETUP_COMPLETE;
retval = count;
exit:
kfree(user_dev);
return retval;
}
static ssize_t uinput_inject_events(struct uinput_device *udev,
const char __user *buffer, size_t count)
{
struct input_event ev;
size_t bytes = 0;
if (count != 0 && count < input_event_size())
return -EINVAL;
while (bytes + input_event_size() <= count) {
/*
* Note that even if some events were fetched successfully
* we are still going to return EFAULT instead of partial
* count to let userspace know that it got it's buffers
* all wrong.
*/
if (input_event_from_user(buffer + bytes, &ev))
return -EFAULT;
input_event(udev->dev, ev.type, ev.code, ev.value);
bytes += input_event_size();
}
return bytes;
}
static ssize_t uinput_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
struct uinput_device *udev = file->private_data;
int retval;
if (count == 0)
return 0;
retval = mutex_lock_interruptible(&udev->mutex);
if (retval)
return retval;
retval = udev->state == UIST_CREATED ?
uinput_inject_events(udev, buffer, count) :
uinput_setup_device_legacy(udev, buffer, count);
mutex_unlock(&udev->mutex);
return retval;
}
static bool uinput_fetch_next_event(struct uinput_device *udev,
struct input_event *event)
{
bool have_event;
spin_lock_irq(&udev->dev->event_lock);
have_event = udev->head != udev->tail;
if (have_event) {
*event = udev->buff[udev->tail];
udev->tail = (udev->tail + 1) % UINPUT_BUFFER_SIZE;
}
spin_unlock_irq(&udev->dev->event_lock);
return have_event;
}
static ssize_t uinput_events_to_user(struct uinput_device *udev,
char __user *buffer, size_t count)
{
struct input_event event;
size_t read = 0;
while (read + input_event_size() <= count &&
uinput_fetch_next_event(udev, &event)) {
if (input_event_to_user(buffer + read, &event))
return -EFAULT;
read += input_event_size();
}
return read;
}
static ssize_t uinput_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
struct uinput_device *udev = file->private_data;
ssize_t retval;
if (count != 0 && count < input_event_size())
return -EINVAL;
do {
retval = mutex_lock_interruptible(&udev->mutex);
if (retval)
return retval;
if (udev->state != UIST_CREATED)
retval = -ENODEV;
else if (udev->head == udev->tail &&
(file->f_flags & O_NONBLOCK))
retval = -EAGAIN;
else
retval = uinput_events_to_user(udev, buffer, count);
mutex_unlock(&udev->mutex);
if (retval || count == 0)
break;
if (!(file->f_flags & O_NONBLOCK))
retval = wait_event_interruptible(udev->waitq,
udev->head != udev->tail ||
udev->state != UIST_CREATED);
} while (retval == 0);
return retval;
}
static unsigned int uinput_poll(struct file *file, poll_table *wait)
{
struct uinput_device *udev = file->private_data;
poll_wait(file, &udev->waitq, wait);
if (udev->head != udev->tail)
return POLLIN | POLLRDNORM;
return 0;
}
static int uinput_release(struct inode *inode, struct file *file)
{
struct uinput_device *udev = file->private_data;
uinput_destroy_device(udev);
kfree(udev);
return 0;
}
#ifdef CONFIG_COMPAT
struct uinput_ff_upload_compat {
__u32 request_id;
__s32 retval;
struct ff_effect_compat effect;
struct ff_effect_compat old;
};
static int uinput_ff_upload_to_user(char __user *buffer,
const struct uinput_ff_upload *ff_up)
{
if (in_compat_syscall()) {
struct uinput_ff_upload_compat ff_up_compat;
ff_up_compat.request_id = ff_up->request_id;
ff_up_compat.retval = ff_up->retval;
/*
* It so happens that the pointer that gives us the trouble
* is the last field in the structure. Since we don't support
* custom waveforms in uinput anyway we can just copy the whole
* thing (to the compat size) and ignore the pointer.
*/
memcpy(&ff_up_compat.effect, &ff_up->effect,
sizeof(struct ff_effect_compat));
memcpy(&ff_up_compat.old, &ff_up->old,
sizeof(struct ff_effect_compat));
if (copy_to_user(buffer, &ff_up_compat,
sizeof(struct uinput_ff_upload_compat)))
return -EFAULT;
} else {
if (copy_to_user(buffer, ff_up,
sizeof(struct uinput_ff_upload)))
return -EFAULT;
}
return 0;
}
static int uinput_ff_upload_from_user(const char __user *buffer,
struct uinput_ff_upload *ff_up)
{
if (in_compat_syscall()) {
struct uinput_ff_upload_compat ff_up_compat;
if (copy_from_user(&ff_up_compat, buffer,
sizeof(struct uinput_ff_upload_compat)))
return -EFAULT;
ff_up->request_id = ff_up_compat.request_id;
ff_up->retval = ff_up_compat.retval;
memcpy(&ff_up->effect, &ff_up_compat.effect,
sizeof(struct ff_effect_compat));
memcpy(&ff_up->old, &ff_up_compat.old,
sizeof(struct ff_effect_compat));
} else {
if (copy_from_user(ff_up, buffer,
sizeof(struct uinput_ff_upload)))
return -EFAULT;
}
return 0;
}
#else
static int uinput_ff_upload_to_user(char __user *buffer,
const struct uinput_ff_upload *ff_up)
{
if (copy_to_user(buffer, ff_up, sizeof(struct uinput_ff_upload)))
return -EFAULT;
return 0;
}
static int uinput_ff_upload_from_user(const char __user *buffer,
struct uinput_ff_upload *ff_up)
{
if (copy_from_user(ff_up, buffer, sizeof(struct uinput_ff_upload)))
return -EFAULT;
return 0;
}
#endif
#define uinput_set_bit(_arg, _bit, _max) \
({ \
int __ret = 0; \
if (udev->state == UIST_CREATED) \
__ret = -EINVAL; \
else if ((_arg) > (_max)) \
__ret = -EINVAL; \
else set_bit((_arg), udev->dev->_bit); \
__ret; \
})
static int uinput_str_to_user(void __user *dest, const char *str,
unsigned int maxlen)
{
char __user *p = dest;
int len, ret;
if (!str)
return -ENOENT;
if (maxlen == 0)
return -EINVAL;
len = strlen(str) + 1;
if (len > maxlen)
len = maxlen;
ret = copy_to_user(p, str, len);
if (ret)
return -EFAULT;
/* force terminating '\0' */
ret = put_user(0, p + len - 1);
return ret ? -EFAULT : len;
}
static long uinput_ioctl_handler(struct file *file, unsigned int cmd,
unsigned long arg, void __user *p)
{
int retval;
struct uinput_device *udev = file->private_data;
struct uinput_ff_upload ff_up;
struct uinput_ff_erase ff_erase;
struct uinput_request *req;
char *phys;
const char *name;
unsigned int size;
retval = mutex_lock_interruptible(&udev->mutex);
if (retval)
return retval;
if (!udev->dev) {
retval = uinput_allocate_device(udev);
if (retval)
goto out;
}
switch (cmd) {
case UI_GET_VERSION:
if (put_user(UINPUT_VERSION,
(unsigned int __user *)p))
retval = -EFAULT;
goto out;
case UI_DEV_CREATE:
retval = uinput_create_device(udev);
goto out;
case UI_DEV_DESTROY:
uinput_destroy_device(udev);
goto out;
case UI_DEV_SETUP:
retval = uinput_dev_setup(udev, p);
goto out;
/* UI_ABS_SETUP is handled in the variable size ioctls */
case UI_SET_EVBIT:
retval = uinput_set_bit(arg, evbit, EV_MAX);
goto out;
case UI_SET_KEYBIT:
retval = uinput_set_bit(arg, keybit, KEY_MAX);
goto out;
case UI_SET_RELBIT:
retval = uinput_set_bit(arg, relbit, REL_MAX);
goto out;
case UI_SET_ABSBIT:
retval = uinput_set_bit(arg, absbit, ABS_MAX);
goto out;
case UI_SET_MSCBIT:
retval = uinput_set_bit(arg, mscbit, MSC_MAX);
goto out;
case UI_SET_LEDBIT:
retval = uinput_set_bit(arg, ledbit, LED_MAX);
goto out;
case UI_SET_SNDBIT:
retval = uinput_set_bit(arg, sndbit, SND_MAX);
goto out;
case UI_SET_FFBIT:
retval = uinput_set_bit(arg, ffbit, FF_MAX);
goto out;
case UI_SET_SWBIT:
retval = uinput_set_bit(arg, swbit, SW_MAX);
goto out;
case UI_SET_PROPBIT:
retval = uinput_set_bit(arg, propbit, INPUT_PROP_MAX);
goto out;
case UI_SET_PHYS:
if (udev->state == UIST_CREATED) {
retval = -EINVAL;
goto out;
}
phys = strndup_user(p, 1024);
if (IS_ERR(phys)) {
retval = PTR_ERR(phys);
goto out;
}
kfree(udev->dev->phys);
udev->dev->phys = phys;
goto out;
case UI_BEGIN_FF_UPLOAD:
retval = uinput_ff_upload_from_user(p, &ff_up);
if (retval)
goto out;
req = uinput_request_find(udev, ff_up.request_id);
if (!req || req->code != UI_FF_UPLOAD ||
!req->u.upload.effect) {
retval = -EINVAL;
goto out;
}
ff_up.retval = 0;
ff_up.effect = *req->u.upload.effect;
if (req->u.upload.old)
ff_up.old = *req->u.upload.old;
else
memset(&ff_up.old, 0, sizeof(struct ff_effect));
retval = uinput_ff_upload_to_user(p, &ff_up);
goto out;
case UI_BEGIN_FF_ERASE:
if (copy_from_user(&ff_erase, p, sizeof(ff_erase))) {
retval = -EFAULT;
goto out;
}
req = uinput_request_find(udev, ff_erase.request_id);
if (!req || req->code != UI_FF_ERASE) {
retval = -EINVAL;
goto out;
}
ff_erase.retval = 0;
ff_erase.effect_id = req->u.effect_id;
if (copy_to_user(p, &ff_erase, sizeof(ff_erase))) {
retval = -EFAULT;
goto out;
}
goto out;
case UI_END_FF_UPLOAD:
retval = uinput_ff_upload_from_user(p, &ff_up);
if (retval)
goto out;
req = uinput_request_find(udev, ff_up.request_id);
if (!req || req->code != UI_FF_UPLOAD ||
!req->u.upload.effect) {
retval = -EINVAL;
goto out;
}
req->retval = ff_up.retval;
uinput_request_done(udev, req);
goto out;
case UI_END_FF_ERASE:
if (copy_from_user(&ff_erase, p, sizeof(ff_erase))) {
retval = -EFAULT;
goto out;
}
req = uinput_request_find(udev, ff_erase.request_id);
if (!req || req->code != UI_FF_ERASE) {
retval = -EINVAL;
goto out;
}
req->retval = ff_erase.retval;
uinput_request_done(udev, req);
goto out;
}
size = _IOC_SIZE(cmd);
/* Now check variable-length commands */
switch (cmd & ~IOCSIZE_MASK) {
case UI_GET_SYSNAME(0):
if (udev->state != UIST_CREATED) {
retval = -ENOENT;
goto out;
}
name = dev_name(&udev->dev->dev);
retval = uinput_str_to_user(p, name, size);
goto out;
case UI_ABS_SETUP & ~IOCSIZE_MASK:
retval = uinput_abs_setup(udev, p, size);
goto out;
}
retval = -EINVAL;
out:
mutex_unlock(&udev->mutex);
return retval;
}
static long uinput_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
return uinput_ioctl_handler(file, cmd, arg, (void __user *)arg);
}
#ifdef CONFIG_COMPAT
#define UI_SET_PHYS_COMPAT _IOW(UINPUT_IOCTL_BASE, 108, compat_uptr_t)
static long uinput_compat_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
if (cmd == UI_SET_PHYS_COMPAT)
cmd = UI_SET_PHYS;
return uinput_ioctl_handler(file, cmd, arg, compat_ptr(arg));
}
#endif
static const struct file_operations uinput_fops = {
.owner = THIS_MODULE,
.open = uinput_open,
.release = uinput_release,
.read = uinput_read,
.write = uinput_write,
.poll = uinput_poll,
.unlocked_ioctl = uinput_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = uinput_compat_ioctl,
#endif
.llseek = no_llseek,
};
static struct miscdevice uinput_misc = {
.fops = &uinput_fops,
.minor = UINPUT_MINOR,
.name = UINPUT_NAME,
};
module_misc_device(uinput_misc);
MODULE_ALIAS_MISCDEV(UINPUT_MINOR);
MODULE_ALIAS("devname:" UINPUT_NAME);
MODULE_AUTHOR("Aristeu Sergio Rozanski Filho");
MODULE_DESCRIPTION("User level driver support for input subsystem");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.3");
| mkvdv/au-linux-kernel-autumn-2017 | linux/drivers/input/misc/uinput.c | C | gpl-3.0 | 23,650 |
<?php
/**
* SimplePie
*
* A PHP-Based RSS and Atom Feed Framework.
* Takes the hard work out of managing a complete RSS/Atom solution.
*
* Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of the SimplePie Team nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
* AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package SimplePie
* @version 1.3.1
* @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue
* @author Ryan Parman
* @author Geoffrey Sneddon
* @author Ryan McCue
* @link http://simplepie.org/ SimplePie
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
/**
* Used for data cleanup and post-processing
*
*
* This class can be overloaded with {@see SimplePie::set_sanitize_class()}
*
* @package SimplePie
* @todo Move to using an actual HTML parser (this will allow tags to be properly stripped, and to switch between HTML and XHTML), this will also make it easier to shorten a string while preserving HTML tags
*/
class SimplePie_Sanitize
{
// Private vars
var $base;
// Options
var $remove_div = true;
var $image_handler = '';
var $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style');
var $encode_instead_of_strip = false;
var $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc');
var $strip_comments = false;
var $output_encoding = 'UTF-8';
var $enable_cache = true;
var $cache_location = './cache';
var $cache_name_function = 'md5';
var $timeout = 10;
var $useragent = '';
var $force_fsockopen = false;
var $replace_url_attributes = null;
public function __construct()
{
// Set defaults
$this->set_url_replacements(null);
}
public function remove_div($enable = true)
{
$this->remove_div = (bool) $enable;
}
public function set_image_handler($page = false)
{
if ($page)
{
$this->image_handler = (string) $page;
}
else
{
$this->image_handler = false;
}
}
public function set_registry(SimplePie_Registry $registry)
{
$this->registry = $registry;
}
public function pass_cache_data($enable_cache = true, $cache_location = './cache', $cache_name_function = 'md5', $cache_class = 'SimplePie_Cache')
{
if (isset($enable_cache))
{
$this->enable_cache = (bool) $enable_cache;
}
if ($cache_location)
{
$this->cache_location = (string) $cache_location;
}
if ($cache_name_function)
{
$this->cache_name_function = (string) $cache_name_function;
}
}
public function pass_file_data($file_class = 'SimplePie_File', $timeout = 10, $useragent = '', $force_fsockopen = false)
{
if ($timeout)
{
$this->timeout = (string) $timeout;
}
if ($useragent)
{
$this->useragent = (string) $useragent;
}
if ($force_fsockopen)
{
$this->force_fsockopen = (string) $force_fsockopen;
}
}
public function strip_htmltags($tags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'))
{
if ($tags)
{
if (is_array($tags))
{
$this->strip_htmltags = $tags;
}
else
{
$this->strip_htmltags = explode(',', $tags);
}
}
else
{
$this->strip_htmltags = false;
}
}
public function encode_instead_of_strip($encode = false)
{
$this->encode_instead_of_strip = (bool) $encode;
}
public function strip_attributes($attribs = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'))
{
if ($attribs)
{
if (is_array($attribs))
{
$this->strip_attributes = $attribs;
}
else
{
$this->strip_attributes = explode(',', $attribs);
}
}
else
{
$this->strip_attributes = false;
}
}
public function strip_comments($strip = false)
{
$this->strip_comments = (bool) $strip;
}
public function set_output_encoding($encoding = 'UTF-8')
{
$this->output_encoding = (string) $encoding;
}
/**
* Set element/attribute key/value pairs of HTML attributes
* containing URLs that need to be resolved relative to the feed
*
* Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite,
* |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite,
* |q|@cite
*
* @since 1.0
* @param array|null $element_attribute Element/attribute key/value pairs, null for default
*/
public function set_url_replacements($element_attribute = null)
{
if ($element_attribute === null)
{
$element_attribute = array(
'a' => 'href',
'area' => 'href',
'blockquote' => 'cite',
'del' => 'cite',
'form' => 'action',
'img' => array(
'longdesc',
'src'
),
'input' => 'src',
'ins' => 'cite',
'q' => 'cite'
);
}
$this->replace_url_attributes = (array) $element_attribute;
}
public function sanitize($data, $type, $base = '')
{
$data = trim($data);
if ($data !== '' || $type & SIMPLEPIE_CONSTRUCT_IRI)
{
if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML)
{
if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data))
{
$type |= SIMPLEPIE_CONSTRUCT_HTML;
}
else
{
$type |= SIMPLEPIE_CONSTRUCT_TEXT;
}
}
if ($type & SIMPLEPIE_CONSTRUCT_BASE64)
{
$data = base64_decode($data);
}
if ($type & (SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML))
{
if (!class_exists('DOMDocument'))
{
$this->registry->call('Misc', 'error', array('DOMDocument not found, unable to use sanitizer', E_USER_WARNING, __FILE__, __LINE__));
return '';
}
$document = new DOMDocument();
$document->encoding = 'UTF-8';
$data = $this->preprocess($data, $type);
set_error_handler(array('SimplePie_Misc', 'silence_errors'));
$document->loadHTML($data);
restore_error_handler();
// Strip comments
if ($this->strip_comments)
{
$xpath = new DOMXPath($document);
$comments = $xpath->query('//comment()');
foreach ($comments as $comment)
{
$comment->parentNode->removeChild($comment);
}
}
// Strip out HTML tags and attributes that might cause various security problems.
// Based on recommendations by Mark Pilgrim at:
// http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely
if ($this->strip_htmltags)
{
foreach ($this->strip_htmltags as $tag)
{
$this->strip_tag($tag, $document, $type);
}
}
if ($this->strip_attributes)
{
foreach ($this->strip_attributes as $attrib)
{
$this->strip_attr($attrib, $document);
}
}
// Replace relative URLs
$this->base = $base;
foreach ($this->replace_url_attributes as $element => $attributes)
{
$this->replace_urls($document, $element, $attributes);
}
// If image handling (caching, etc.) is enabled, cache and rewrite all the image tags.
if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache)
{
$images = $document->getElementsByTagName('img');
foreach ($images as $img)
{
if ($img->hasAttribute('src'))
{
$image_url = call_user_func($this->cache_name_function, $img->getAttribute('src'));
$cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, $image_url, 'spi'));
if ($cache->load())
{
$img->setAttribute('src', $this->image_handler . $image_url);
}
else
{
$file = $this->registry->create('File', array($img->getAttribute('src'), $this->timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen));
$headers = $file->headers;
if ($file->success && ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300)))
{
if ($cache->save(array('headers' => $file->headers, 'body' => $file->body)))
{
$img->setAttribute('src', $this->image_handler . $image_url);
}
else
{
trigger_error("$this->cache_location is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
}
}
}
}
}
}
// Remove the DOCTYPE
// Seems to cause segfaulting if we don't do this
if ($document->firstChild instanceof DOMDocumentType)
{
$document->removeChild($document->firstChild);
}
// Move everything from the body to the root
$real_body = $document->getElementsByTagName('body')->item(0)->childNodes->item(0);
$document->replaceChild($real_body, $document->firstChild);
// Finally, convert to a HTML string
$data = trim($document->saveHTML());
if ($this->remove_div)
{
$data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '', $data);
$data = preg_replace('/<\/div>$/', '', $data);
}
else
{
$data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
}
}
if ($type & SIMPLEPIE_CONSTRUCT_IRI)
{
$absolute = $this->registry->call('Misc', 'absolutize_url', array($data, $base));
if ($absolute !== false)
{
$data = $absolute;
}
}
if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI))
{
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
if ($this->output_encoding !== 'UTF-8')
{
$data = $this->registry->call('Misc', 'change_encoding', array($data, 'UTF-8', $this->output_encoding));
}
}
return $data;
}
protected function preprocess($html, $type)
{
$ret = '';
if ($type & ~SIMPLEPIE_CONSTRUCT_XHTML)
{
// Atom XHTML constructs are wrapped with a div by default
// Note: No protection if $html contains a stray </div>!
$html = '<div>' . $html . '</div>';
$ret .= '<!DOCTYPE html>';
$content_type = 'text/html';
}
else
{
$ret .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
$content_type = 'application/xhtml+xml';
}
$ret .= '<html><head>';
$ret .= '<meta http-equiv="Content-Type" content="' . $content_type . '; charset=utf-8" />';
$ret .= '</head><body>' . $html . '</body></html>';
return $ret;
}
public function replace_urls($document, $tag, $attributes)
{
if (!is_array($attributes))
{
$attributes = array($attributes);
}
if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags))
{
$elements = $document->getElementsByTagName($tag);
foreach ($elements as $element)
{
foreach ($attributes as $attribute)
{
if ($element->hasAttribute($attribute))
{
$value = $this->registry->call('Misc', 'absolutize_url', array($element->getAttribute($attribute), $this->base));
if ($value !== false)
{
$element->setAttribute($attribute, $value);
}
}
}
}
}
}
public function do_strip_htmltags($match)
{
if ($this->encode_instead_of_strip)
{
if (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
{
$match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8');
$match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8');
return "<$match[1]$match[2]>$match[3]</$match[1]>";
}
else
{
return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8');
}
}
elseif (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
{
return $match[4];
}
else
{
return '';
}
}
protected function strip_tag($tag, $document, $type)
{
$xpath = new DOMXPath($document);
$elements = $xpath->query('body//' . $tag);
if ($this->encode_instead_of_strip)
{
foreach ($elements as $element)
{
$fragment = $document->createDocumentFragment();
// For elements which aren't script or style, include the tag itself
if (!in_array($tag, array('script', 'style')))
{
$text = '<' . $tag;
if ($element->hasAttributes())
{
$attrs = array();
foreach ($element->attributes as $name => $attr)
{
$value = $attr->value;
// In XHTML, empty values should never exist, so we repeat the value
if (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_XHTML))
{
$value = $name;
}
// For HTML, empty is fine
elseif (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_HTML))
{
$attrs[] = $name;
continue;
}
// Standard attribute text
$attrs[] = $name . '="' . $attr->value . '"';
}
$text .= ' ' . implode(' ', $attrs);
}
$text .= '>';
$fragment->appendChild(new DOMText($text));
}
$number = $element->childNodes->length;
for ($i = $number; $i > 0; $i--)
{
$child = $element->childNodes->item(0);
$fragment->appendChild($child);
}
if (!in_array($tag, array('script', 'style')))
{
$fragment->appendChild(new DOMText('</' . $tag . '>'));
}
$element->parentNode->replaceChild($fragment, $element);
}
return;
}
elseif (in_array($tag, array('script', 'style')))
{
foreach ($elements as $element)
{
$element->parentNode->removeChild($element);
}
return;
}
else
{
foreach ($elements as $element)
{
$fragment = $document->createDocumentFragment();
$number = $element->childNodes->length;
for ($i = $number; $i > 0; $i--)
{
$child = $element->childNodes->item(0);
$fragment->appendChild($child);
}
$element->parentNode->replaceChild($fragment, $element);
}
}
}
protected function strip_attr($attrib, $document)
{
$xpath = new DOMXPath($document);
$elements = $xpath->query('//*[@' . $attrib . ']');
foreach ($elements as $element)
{
$element->removeAttribute($attrib);
}
}
}
| gdombchik/nabcacatholic | zzz wp-includes ORIG/SimplePie/Sanitize.php | PHP | gpl-2.0 | 15,698 |
/*
* CPU subsystem support
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/cpu.h>
#include <linux/topology.h>
#include <linux/device.h>
#include <linux/node.h>
#include <linux/gfp.h>
#include <linux/slab.h>
#include <linux/percpu.h>
#include <linux/acpi.h>
#include <linux/of.h>
#include <linux/cpufeature.h>
#include <linux/tick.h>
#include "base.h"
static DEFINE_PER_CPU(struct device *, cpu_sys_devices);
static int cpu_subsys_match(struct device *dev, struct device_driver *drv)
{
/* ACPI style match is the only one that may succeed. */
if (acpi_driver_match_device(dev, drv))
return 1;
return 0;
}
#ifdef CONFIG_HOTPLUG_CPU
static void change_cpu_under_node(struct cpu *cpu,
unsigned int from_nid, unsigned int to_nid)
{
int cpuid = cpu->dev.id;
unregister_cpu_under_node(cpuid, from_nid);
register_cpu_under_node(cpuid, to_nid);
cpu->node_id = to_nid;
}
static int cpu_subsys_online(struct device *dev)
{
struct cpu *cpu = container_of(dev, struct cpu, dev);
int cpuid = dev->id;
int from_nid, to_nid;
int ret;
from_nid = cpu_to_node(cpuid);
if (from_nid == NUMA_NO_NODE)
return -ENODEV;
ret = cpu_up(cpuid);
/*
* When hot adding memory to memoryless node and enabling a cpu
* on the node, node number of the cpu may internally change.
*/
to_nid = cpu_to_node(cpuid);
if (from_nid != to_nid)
change_cpu_under_node(cpu, from_nid, to_nid);
return ret;
}
static int cpu_subsys_offline(struct device *dev)
{
return cpu_down(dev->id);
}
void unregister_cpu(struct cpu *cpu)
{
int logical_cpu = cpu->dev.id;
unregister_cpu_under_node(logical_cpu, cpu_to_node(logical_cpu));
device_unregister(&cpu->dev);
per_cpu(cpu_sys_devices, logical_cpu) = NULL;
return;
}
#ifdef CONFIG_ARCH_CPU_PROBE_RELEASE
static ssize_t cpu_probe_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
ssize_t cnt;
int ret;
ret = lock_device_hotplug_sysfs();
if (ret)
return ret;
cnt = arch_cpu_probe(buf, count);
unlock_device_hotplug();
return cnt;
}
static ssize_t cpu_release_store(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
ssize_t cnt;
int ret;
ret = lock_device_hotplug_sysfs();
if (ret)
return ret;
cnt = arch_cpu_release(buf, count);
unlock_device_hotplug();
return cnt;
}
static DEVICE_ATTR(probe, S_IWUSR, NULL, cpu_probe_store);
static DEVICE_ATTR(release, S_IWUSR, NULL, cpu_release_store);
#endif /* CONFIG_ARCH_CPU_PROBE_RELEASE */
#endif /* CONFIG_HOTPLUG_CPU */
struct bus_type cpu_subsys = {
.name = "cpu",
.dev_name = "cpu",
.match = cpu_subsys_match,
#ifdef CONFIG_HOTPLUG_CPU
.online = cpu_subsys_online,
.offline = cpu_subsys_offline,
#endif
};
EXPORT_SYMBOL_GPL(cpu_subsys);
#ifdef CONFIG_KEXEC
#include <linux/kexec.h>
static ssize_t show_crash_notes(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct cpu *cpu = container_of(dev, struct cpu, dev);
ssize_t rc;
unsigned long long addr;
int cpunum;
cpunum = cpu->dev.id;
/*
* Might be reading other cpu's data based on which cpu read thread
* has been scheduled. But cpu data (memory) is allocated once during
* boot up and this data does not change there after. Hence this
* operation should be safe. No locking required.
*/
addr = per_cpu_ptr_to_phys(per_cpu_ptr(crash_notes, cpunum));
rc = sprintf(buf, "%Lx\n", addr);
return rc;
}
static DEVICE_ATTR(crash_notes, 0400, show_crash_notes, NULL);
static ssize_t show_crash_notes_size(struct device *dev,
struct device_attribute *attr,
char *buf)
{
ssize_t rc;
rc = sprintf(buf, "%zu\n", sizeof(note_buf_t));
return rc;
}
static DEVICE_ATTR(crash_notes_size, 0400, show_crash_notes_size, NULL);
static struct attribute *crash_note_cpu_attrs[] = {
&dev_attr_crash_notes.attr,
&dev_attr_crash_notes_size.attr,
NULL
};
static struct attribute_group crash_note_cpu_attr_group = {
.attrs = crash_note_cpu_attrs,
};
#endif
static const struct attribute_group *common_cpu_attr_groups[] = {
#ifdef CONFIG_KEXEC
&crash_note_cpu_attr_group,
#endif
NULL
};
static const struct attribute_group *hotplugable_cpu_attr_groups[] = {
#ifdef CONFIG_KEXEC
&crash_note_cpu_attr_group,
#endif
NULL
};
/*
* Print cpu online, possible, present, and system maps
*/
struct cpu_attr {
struct device_attribute attr;
const struct cpumask *const map;
};
static ssize_t show_cpus_attr(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct cpu_attr *ca = container_of(attr, struct cpu_attr, attr);
return cpumap_print_to_pagebuf(true, buf, ca->map);
}
#define _CPU_ATTR(name, map) \
{ __ATTR(name, 0444, show_cpus_attr, NULL), map }
/* Keep in sync with cpu_subsys_attrs */
static struct cpu_attr cpu_attrs[] = {
_CPU_ATTR(online, &__cpu_online_mask),
_CPU_ATTR(possible, &__cpu_possible_mask),
_CPU_ATTR(present, &__cpu_present_mask),
};
/*
* Print values for NR_CPUS and offlined cpus
*/
static ssize_t print_cpus_kernel_max(struct device *dev,
struct device_attribute *attr, char *buf)
{
int n = snprintf(buf, PAGE_SIZE-2, "%d\n", NR_CPUS - 1);
return n;
}
static DEVICE_ATTR(kernel_max, 0444, print_cpus_kernel_max, NULL);
/* arch-optional setting to enable display of offline cpus >= nr_cpu_ids */
unsigned int total_cpus;
static ssize_t print_cpus_offline(struct device *dev,
struct device_attribute *attr, char *buf)
{
int n = 0, len = PAGE_SIZE-2;
cpumask_var_t offline;
/* display offline cpus < nr_cpu_ids */
if (!alloc_cpumask_var(&offline, GFP_KERNEL))
return -ENOMEM;
cpumask_andnot(offline, cpu_possible_mask, cpu_online_mask);
n = scnprintf(buf, len, "%*pbl", cpumask_pr_args(offline));
free_cpumask_var(offline);
/* display offline cpus >= nr_cpu_ids */
if (total_cpus && nr_cpu_ids < total_cpus) {
if (n && n < len)
buf[n++] = ',';
if (nr_cpu_ids == total_cpus-1)
n += snprintf(&buf[n], len - n, "%d", nr_cpu_ids);
else
n += snprintf(&buf[n], len - n, "%d-%d",
nr_cpu_ids, total_cpus-1);
}
n += snprintf(&buf[n], len - n, "\n");
return n;
}
static DEVICE_ATTR(offline, 0444, print_cpus_offline, NULL);
static ssize_t print_cpus_isolated(struct device *dev,
struct device_attribute *attr, char *buf)
{
int n = 0, len = PAGE_SIZE-2;
n = scnprintf(buf, len, "%*pbl\n", cpumask_pr_args(cpu_isolated_map));
return n;
}
static DEVICE_ATTR(isolated, 0444, print_cpus_isolated, NULL);
#ifdef CONFIG_NO_HZ_FULL
static ssize_t print_cpus_nohz_full(struct device *dev,
struct device_attribute *attr, char *buf)
{
int n = 0, len = PAGE_SIZE-2;
n = scnprintf(buf, len, "%*pbl\n", cpumask_pr_args(tick_nohz_full_mask));
return n;
}
static DEVICE_ATTR(nohz_full, 0444, print_cpus_nohz_full, NULL);
#endif
static void cpu_device_release(struct device *dev)
{
/*
* This is an empty function to prevent the driver core from spitting a
* warning at us. Yes, I know this is directly opposite of what the
* documentation for the driver core and kobjects say, and the author
* of this code has already been publically ridiculed for doing
* something as foolish as this. However, at this point in time, it is
* the only way to handle the issue of statically allocated cpu
* devices. The different architectures will have their cpu device
* code reworked to properly handle this in the near future, so this
* function will then be changed to correctly free up the memory held
* by the cpu device.
*
* Never copy this way of doing things, or you too will be made fun of
* on the linux-kernel list, you have been warned.
*/
}
#ifdef CONFIG_GENERIC_CPU_AUTOPROBE
static ssize_t print_cpu_modalias(struct device *dev,
struct device_attribute *attr,
char *buf)
{
ssize_t n;
u32 i;
n = sprintf(buf, "cpu:type:" CPU_FEATURE_TYPEFMT ":feature:",
CPU_FEATURE_TYPEVAL);
for (i = 0; i < MAX_CPU_FEATURES; i++)
if (cpu_have_feature(i)) {
if (PAGE_SIZE < n + sizeof(",XXXX\n")) {
WARN(1, "CPU features overflow page\n");
break;
}
n += sprintf(&buf[n], ",%04X", i);
}
buf[n++] = '\n';
return n;
}
static int cpu_uevent(struct device *dev, struct kobj_uevent_env *env)
{
char *buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
if (buf) {
print_cpu_modalias(NULL, NULL, buf);
add_uevent_var(env, "MODALIAS=%s", buf);
kfree(buf);
}
return 0;
}
#endif
/*
* register_cpu - Setup a sysfs device for a CPU.
* @cpu - cpu->hotpluggable field set to 1 will generate a control file in
* sysfs for this CPU.
* @num - CPU number to use when creating the device.
*
* Initialize and register the CPU device.
*/
int register_cpu(struct cpu *cpu, int num)
{
int error;
cpu->node_id = cpu_to_node(num);
memset(&cpu->dev, 0x00, sizeof(struct device));
cpu->dev.id = num;
cpu->dev.bus = &cpu_subsys;
cpu->dev.release = cpu_device_release;
cpu->dev.offline_disabled = !cpu->hotpluggable;
cpu->dev.offline = !cpu_online(num);
cpu->dev.of_node = of_get_cpu_node(num, NULL);
#ifdef CONFIG_GENERIC_CPU_AUTOPROBE
cpu->dev.bus->uevent = cpu_uevent;
#endif
cpu->dev.groups = common_cpu_attr_groups;
if (cpu->hotpluggable)
cpu->dev.groups = hotplugable_cpu_attr_groups;
error = device_register(&cpu->dev);
if (error)
return error;
per_cpu(cpu_sys_devices, num) = &cpu->dev;
register_cpu_under_node(num, cpu_to_node(num));
return 0;
}
struct device *get_cpu_device(unsigned cpu)
{
if (cpu < nr_cpu_ids && cpu_possible(cpu))
return per_cpu(cpu_sys_devices, cpu);
else
return NULL;
}
EXPORT_SYMBOL_GPL(get_cpu_device);
static void device_create_release(struct device *dev)
{
kfree(dev);
}
static struct device *
__cpu_device_create(struct device *parent, void *drvdata,
const struct attribute_group **groups,
const char *fmt, va_list args)
{
struct device *dev = NULL;
int retval = -ENODEV;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
retval = -ENOMEM;
goto error;
}
device_initialize(dev);
dev->parent = parent;
dev->groups = groups;
dev->release = device_create_release;
dev_set_drvdata(dev, drvdata);
retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
if (retval)
goto error;
retval = device_add(dev);
if (retval)
goto error;
return dev;
error:
put_device(dev);
return ERR_PTR(retval);
}
struct device *cpu_device_create(struct device *parent, void *drvdata,
const struct attribute_group **groups,
const char *fmt, ...)
{
va_list vargs;
struct device *dev;
va_start(vargs, fmt);
dev = __cpu_device_create(parent, drvdata, groups, fmt, vargs);
va_end(vargs);
return dev;
}
EXPORT_SYMBOL_GPL(cpu_device_create);
#ifdef CONFIG_GENERIC_CPU_AUTOPROBE
static DEVICE_ATTR(modalias, 0444, print_cpu_modalias, NULL);
#endif
static struct attribute *cpu_root_attrs[] = {
#ifdef CONFIG_ARCH_CPU_PROBE_RELEASE
&dev_attr_probe.attr,
&dev_attr_release.attr,
#endif
&cpu_attrs[0].attr.attr,
&cpu_attrs[1].attr.attr,
&cpu_attrs[2].attr.attr,
&dev_attr_kernel_max.attr,
&dev_attr_offline.attr,
&dev_attr_isolated.attr,
#ifdef CONFIG_NO_HZ_FULL
&dev_attr_nohz_full.attr,
#endif
#ifdef CONFIG_GENERIC_CPU_AUTOPROBE
&dev_attr_modalias.attr,
#endif
NULL
};
static struct attribute_group cpu_root_attr_group = {
.attrs = cpu_root_attrs,
};
static const struct attribute_group *cpu_root_attr_groups[] = {
&cpu_root_attr_group,
NULL,
};
bool cpu_is_hotpluggable(unsigned cpu)
{
struct device *dev = get_cpu_device(cpu);
return dev && container_of(dev, struct cpu, dev)->hotpluggable;
}
EXPORT_SYMBOL_GPL(cpu_is_hotpluggable);
#ifdef CONFIG_GENERIC_CPU_DEVICES
static DEFINE_PER_CPU(struct cpu, cpu_devices);
#endif
static void __init cpu_dev_register_generic(void)
{
#ifdef CONFIG_GENERIC_CPU_DEVICES
int i;
for_each_possible_cpu(i) {
if (register_cpu(&per_cpu(cpu_devices, i), i))
panic("Failed to register CPU device");
}
#endif
}
void __init cpu_dev_init(void)
{
if (subsys_system_register(&cpu_subsys, cpu_root_attr_groups))
panic("Failed to register CPU subsystem");
cpu_dev_register_generic();
}
| dperezde/little-penguin | linux/drivers/base/cpu.c | C | gpl-2.0 | 12,138 |
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using referrer-policy/generic/template/test.release.html.template. -->
<html>
<head>
<title>Referrer-Policy: Referrer Policy is set to 'origin-only'</title>
<meta name="description" content="Check that all subresources in all casses get only the origin portion of the referrer URL.">
<meta name="referrer" content="origin">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="https://w3c.github.io/webappsec/specs/referrer-policy/#referrer-policy-state-origin">
<meta name="assert" content="The referrer URL is origin when a
document served over http requires an http
sub-resource via iframe-tag using the meta-referrer
delivery method with keep-origin-redirect and when
the target request is same-origin.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<!-- TODO(kristijanburnik): Minify and merge both: -->
<script src="/referrer-policy/generic/common.js"></script>
<script src="/referrer-policy/generic/referrer-policy-test-case.js?pipe=sub"></script>
</head>
<body>
<script>
ReferrerPolicyTestCase(
{
"referrer_policy": "origin",
"delivery_method": "meta-referrer",
"redirection": "keep-origin-redirect",
"origin": "same-origin",
"source_protocol": "http",
"target_protocol": "http",
"subresource": "iframe-tag",
"subresource_path": "/referrer-policy/generic/subresource/document.py",
"referrer_url": "origin"
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
| youtube/cobalt | third_party/web_platform_tests/referrer-policy/origin-only/meta-referrer/same-origin/http-http/iframe-tag/generic.keep-origin-redirect.http.html | HTML | bsd-3-clause | 1,972 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Binding to Remote Data - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
<link rel="stylesheet" type="text/css" href="../demo.css">
<script type="text/javascript" src="../../jquery.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
</head>
<body>
<h2>Binding to Remote Data</h2>
<p>The DataList is bound to a remote data.</p>
<div style="margin:20px 0"></div>
<div class="easyui-datalist" title="Remote Data" style="width:400px;height:250px" data-options="
url: 'datalist_data1.json',
method: 'get'
">
</div>
</body>
</html> | zyzydream/zhihu | zhihu/src/main/webapp/easyui/demo/datalist/remotedata.html | HTML | gpl-3.0 | 773 |
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-device-orientation
이 플러그인 디바이스의 나침반에 대 한 액세스를 제공합니다. 나침반 방향 또는 표제는 장치 지적 이다, 일반적으로 장치 위에서 감지 하는 센서입니다. 359.99, 0가 북쪽을 0에서도에서 머리글을 측정 합니다.
글로벌 `navigator.compass` 개체를 통해 액세스가입니다.
개체 `navigator` 글로벌 범위 첨부 아니에요 때까지 사용할 수 있는 `deviceready` 이벤트 후.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.compass);
}
## 설치
cordova plugin add cordova-plugin-device-orientation
## 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* 브라우저
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7, 8 (사용 가능한 경우 하드웨어)
* 윈도우 8
## 메서드
* navigator.compass.getCurrentHeading
* navigator.compass.watchHeading
* navigator.compass.clearWatch
## navigator.compass.getCurrentHeading
현재 나침반 제목 좀. 나침반 제목 `compassSuccess` 콜백 함수를 사용 하 여 `CompassHeading` 개체를 통해 반환 됩니다.
navigator.compass.getCurrentHeading(compassSuccess, compassError);
### 예를 들어
function onSuccess(heading) {
alert('Heading: ' + heading.magneticHeading);
};
function onError(error) {
alert('CompassError: ' + error.code);
};
navigator.compass.getCurrentHeading(onSuccess, onError);
## navigator.compass.watchHeading
정기적 장치의 현재 머리글을 가져옵니다. 제목 검색 때마다 `headingSuccess` 콜백 함수가 실행 됩니다.
반환 된 시계 ID 나침반 시계 간격을 참조합니다. 시계 ID는 navigator.compass를 보는 중지 하 `navigator.compass.clearWatch`와 함께 사용할 수 있습니다.
var watchID = navigator.compass.watchHeading(compassSuccess, compassError, [compassOptions]);
`compassOptions`는 다음 키를 포함할 수 있습니다.
* **frequency**: 자주 밀리초에서 나침반 머리글을 검색 하는 방법. *(수)* (기본값: 100)
* **filter**:도 watchHeading 성공 콜백을 시작 하는 데 필요한 변경. 이 값을 설정 하는 경우 **주파수** 는 무시 됩니다. *(수)*
### 예를 들어
function onSuccess(heading) {
var element = document.getElementById('heading');
element.innerHTML = 'Heading: ' + heading.magneticHeading;
};
function onError(compassError) {
alert('Compass error: ' + compassError.code);
};
var options = {
frequency: 3000
}; // Update every 3 seconds
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
### 브라우저 만지면
현재 제목에 대 한 값은 나침반을 시뮬레이션 하기 위해 임의로 생성 됩니다.
### iOS 단점
하나의 `watchHeading` iOS에서 한 번에 적용에서 될 수 있습니다. `watchHeading` 필터를 사용 하는 경우 `getCurrentHeading` 또는 `watchHeading` 호출 사용 하 여 기존 필터 값 지정 제목 변경. 필터와 제목 변화를 보고 시간을 간격으로 보다 더 효율적입니다.
### 아마존 화재 OS 단점
* `filter`지원 되지 않습니다.
### 안 드 로이드 단점
* 대 한 지원`filter`.
### 파이어 폭스 OS 단점
* 대 한 지원`filter`.
### Tizen 특수
* 대 한 지원`filter`.
### Windows Phone 7, 8 특수
* 대 한 지원`filter`.
## navigator.compass.clearWatch
시계 ID 매개 변수에서 참조 하는 나침반을 보고 중지 합니다.
navigator.compass.clearWatch(watchID);
* **watchID**: ID 반환`navigator.compass.watchHeading`.
### 예를 들어
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
// ... later on ...
navigator.compass.clearWatch(watchID);
## CompassHeading
`CompassHeading` 개체는 `compassSuccess` 콜백 함수에 반환 됩니다.
### 속성
* **magneticHeading**: 단일 시점에서 0-359.99에서도 제목. *(수)*
* **trueHeading**: 단일 시점에서 0-359.99에서에서 지리적 북극을 기준으로 향하고. 음수 값을 나타냅니다 진정한 표제를 확인할 수 없습니다. *(수)*
* **headingAccuracy**: 보고 된 머리글 사이의 진정한 제목도 편차. *(수)*
* **타임 스탬프**:이 제목 결정 하는 시간. *(밀리초)*
### 아마존 화재 OS 단점
* `trueHeading`지원 되지 않습니다 하지만 같은 값으로 보고`magneticHeading`
* `headingAccuracy`항상 0 사이 차이가 있기 때문에 `magneticHeading` 와`trueHeading`
### 안 드 로이드 단점
* `trueHeading`속성은 지원 되지 않습니다 하지만 같은 값으로 보고`magneticHeading`.
* `headingAccuracy`속성은 항상 0 사이 차이가 있기 때문에 `magneticHeading` 와`trueHeading`.
### 파이어 폭스 OS 단점
* `trueHeading`속성은 지원 되지 않습니다 하지만 같은 값으로 보고`magneticHeading`.
* `headingAccuracy`속성은 항상 0 사이 차이가 있기 때문에 `magneticHeading` 와`trueHeading`.
### iOS 단점
* `trueHeading`속성을 통해 위치 서비스에 대 한 반환만`navigator.geolocation.watchLocation()`.
* IOS 4 장치에 대 한 위의 제목 소자의 현재 방향에서 요인 그리고, 그 방향을 지 원하는 애플 리 케이 션에 대 한 그것의 절대 위치를 참조 하지 않습니다.
## CompassError
`CompassError` 개체는 오류가 발생 하면 `compassError` 콜백 함수에 반환 됩니다.
### 속성
* **코드**: 미리 정의 된 오류 코드 중 하나가 아래에 나열 된.
### 상수
* `CompassError.COMPASS_INTERNAL_ERR`
* `CompassError.COMPASS_NOT_SUPPORTED`
| forsrc/MyStudy | src/main/webapp/MyStudy/plugins/cordova-plugin-device-orientation/doc/ko/index.md | Markdown | apache-2.0 | 6,806 |
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Constraint that asserts that a string is valid JSON.
*
* @author Sebastian Bergmann <sebastian@phpunit.de>
* @copyright Sebastian Bergmann <sebastian@phpunit.de>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://www.phpunit.de/
* @since Class available since Release 3.7.20
*/
class PHPUnit_Framework_Constraint_IsJson extends PHPUnit_Framework_Constraint
{
/**
* Evaluates the constraint for parameter $other. Returns true if the
* constraint is met, false otherwise.
*
* @param mixed $other Value or object to evaluate.
* @return bool
*/
protected function matches($other)
{
json_decode($other);
if (json_last_error()) {
return false;
}
return true;
}
/**
* Returns the description of the failure
*
* The beginning of failure messages is "Failed asserting that" in most
* cases. This method should return the second part of that sentence.
*
* @param mixed $other Evaluated value or object.
* @return string
*/
protected function failureDescription($other)
{
json_decode($other);
$error = PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider::determineJsonError(
json_last_error()
);
return sprintf(
'%s is valid JSON (%s)',
$this->exporter->shortenedExport($other),
$error
);
}
/**
* Returns a string representation of the constraint.
*
* @return string
*/
public function toString()
{
return 'is valid JSON';
}
}
| ederunt/practicaN | vendor/phpunit/phpunit/src/Framework/Constraint/IsJson.php | PHP | bsd-3-clause | 1,922 |
class Sslyze < Formula
desc "SSL scanner"
homepage "https://github.com/nabla-c0d3/sslyze"
url "https://github.com/nabla-c0d3/sslyze/archive/release-0.11.tar.gz"
sha256 "d0adf9be09d5b27803a923dfabd459c84a2eddb457dac2418f1bf074153f8f93"
version "0.11.0"
bottle do
cellar :any
sha256 "af01a93c9a4b8d8e38c4b03255fd522234fdb24165cdde6b5a910187fa9fa16b" => :yosemite
sha256 "63f3129057130bc335464e64ac4a408947c39f58d04b051a55360644b05bc803" => :mavericks
sha256 "6ef8e398d5ecd7b71e80d8fe113c23acd5be75055bf8253dbb42e2e4a0e825d8" => :mountain_lion
end
depends_on :arch => :x86_64
depends_on :python if MacOS.version <= :snow_leopard
resource "nassl" do
url "https://github.com/nabla-c0d3/nassl/archive/v0.11.tar.gz"
sha256 "83fe1623ad3e67ba01a3e692211e9fde15c6388f5f3d92bd5c0423d4e9e79391"
end
resource "openssl" do
url "https://www.openssl.org/source/openssl-1.0.2a.tar.gz"
sha256 "15b6393c20030aab02c8e2fe0243cb1d1d18062f6c095d67bca91871dc7f324a"
end
resource "zlib" do
url "http://zlib.net/zlib-1.2.8.tar.gz"
sha256 "36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d"
end
def install
# openssl fails on parallel build. Related issues:
# - http://rt.openssl.org/Ticket/Display.html?id=3736
# - http://rt.openssl.org/Ticket/Display.html?id=3737
ENV.deparallelize
resource("openssl").stage do
(buildpath/"nassl/openssl-1.0.2a").install Dir["*"]
end
resource("zlib").stage do
(buildpath/"nassl/zlib-1.2.8").install Dir["*"]
end
resource("nassl").stage do
(buildpath/"nassl").install Dir["*"]
end
cd "nassl" do
system "python", "buildAll_unix.py"
libexec.install "test/nassl"
end
libexec.install %w[plugins utils sslyze.py xml_out.xsd]
bin.install_symlink libexec/"sslyze.py" => "sslyze"
end
test do
assert_equal "0.11.0", shell_output("#{bin}/sslyze --version").strip
assert_match "SCAN COMPLETED", shell_output("#{bin}/sslyze --regular google.com")
end
end
| Lywangwenbin/homebrew | Library/Formula/sslyze.rb | Ruby | bsd-2-clause | 2,049 |
/*!
* Bootstrap v3.0.2 by @fat and @mdo
* Copyright 2013 Twitter, Inc.
* Licensed under http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @mdo and @fat.
*/
.btn-default,
.btn-primary,
.btn-success,
.btn-info,
.btn-warning,
.btn-danger {
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);
}
.btn-default:active,
.btn-primary:active,
.btn-success:active,
.btn-info:active,
.btn-warning:active,
.btn-danger:active,
.btn-default.active,
.btn-primary.active,
.btn-success.active,
.btn-info.active,
.btn-warning.active,
.btn-danger.active {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn:active,
.btn.active {
background-image: none;
}
.btn-default {
text-shadow: 0 1px 0 #fff;
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#ffffff), to(#e0e0e0));
background-image: -webkit-linear-gradient(top, #ffffff 0%, #e0e0e0 100%);
background-image: -moz-linear-gradient(top, #ffffff 0%, #e0e0e0 100%);
background-image: linear-gradient(to bottom, #ffffff 0%, #e0e0e0 100%);
background-repeat: repeat-x;
border-color: #dbdbdb;
border-color: #ccc;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.btn-default:hover,
.btn-default:focus {
background-color: #e0e0e0;
background-position: 0 -15px;
}
.btn-default:active,
.btn-default.active {
background-color: #e0e0e0;
border-color: #dbdbdb;
}
.btn-primary {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#2d6ca2));
background-image: -webkit-linear-gradient(top, #428bca 0%, #2d6ca2 100%);
background-image: -moz-linear-gradient(top, #428bca 0%, #2d6ca2 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #2d6ca2 100%);
background-repeat: repeat-x;
border-color: #2b669a;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff2d6ca2', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.btn-primary:hover,
.btn-primary:focus {
background-color: #2d6ca2;
background-position: 0 -15px;
}
.btn-primary:active,
.btn-primary.active {
background-color: #2d6ca2;
border-color: #2b669a;
}
.btn-success {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5cb85c), to(#419641));
background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%);
background-image: -moz-linear-gradient(top, #5cb85c 0%, #419641 100%);
background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%);
background-repeat: repeat-x;
border-color: #3e8f3e;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.btn-success:hover,
.btn-success:focus {
background-color: #419641;
background-position: 0 -15px;
}
.btn-success:active,
.btn-success.active {
background-color: #419641;
border-color: #3e8f3e;
}
.btn-warning {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f0ad4e), to(#eb9316));
background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);
background-image: -moz-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);
background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%);
background-repeat: repeat-x;
border-color: #e38d13;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.btn-warning:hover,
.btn-warning:focus {
background-color: #eb9316;
background-position: 0 -15px;
}
.btn-warning:active,
.btn-warning.active {
background-color: #eb9316;
border-color: #e38d13;
}
.btn-danger {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9534f), to(#c12e2a));
background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%);
background-image: -moz-linear-gradient(top, #d9534f 0%, #c12e2a 100%);
background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%);
background-repeat: repeat-x;
border-color: #b92c28;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.btn-danger:hover,
.btn-danger:focus {
background-color: #c12e2a;
background-position: 0 -15px;
}
.btn-danger:active,
.btn-danger.active {
background-color: #c12e2a;
border-color: #b92c28;
}
.btn-info {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5bc0de), to(#2aabd2));
background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);
background-image: -moz-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);
background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%);
background-repeat: repeat-x;
border-color: #28a4c9;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.btn-info:hover,
.btn-info:focus {
background-color: #2aabd2;
background-position: 0 -15px;
}
.btn-info:active,
.btn-info.active {
background-color: #2aabd2;
border-color: #28a4c9;
}
.thumbnail,
.img-thumbnail {
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
background-color: #e8e8e8;
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f5f5f5), to(#e8e8e8));
background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: -moz-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
background-color: #357ebd;
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#357ebd));
background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%);
background-image: -moz-linear-gradient(top, #428bca 0%, #357ebd 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0);
}
.navbar-default {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#ffffff), to(#f8f8f8));
background-image: -webkit-linear-gradient(top, #ffffff 0%, #f8f8f8 100%);
background-image: -moz-linear-gradient(top, #ffffff 0%, #f8f8f8 100%);
background-image: linear-gradient(to bottom, #ffffff 0%, #f8f8f8 100%);
background-repeat: repeat-x;
border-radius: 4px;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075);
}
.navbar-default .navbar-nav > .active > a {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#ebebeb), to(#f3f3f3));
background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f3f3f3 100%);
background-image: -moz-linear-gradient(top, #ebebeb 0%, #f3f3f3 100%);
background-image: linear-gradient(to bottom, #ebebeb 0%, #f3f3f3 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff3f3f3', GradientType=0);
-webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075);
}
.navbar-brand,
.navbar-nav > li > a {
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25);
}
.navbar-inverse {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#3c3c3c), to(#222222));
background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222222 100%);
background-image: -moz-linear-gradient(top, #3c3c3c 0%, #222222 100%);
background-image: linear-gradient(to bottom, #3c3c3c 0%, #222222 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
}
.navbar-inverse .navbar-nav > .active > a {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#222222), to(#282828));
background-image: -webkit-linear-gradient(top, #222222 0%, #282828 100%);
background-image: -moz-linear-gradient(top, #222222 0%, #282828 100%);
background-image: linear-gradient(to bottom, #222222 0%, #282828 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff282828', GradientType=0);
-webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25);
box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25);
}
.navbar-inverse .navbar-brand,
.navbar-inverse .navbar-nav > li > a {
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
.navbar-static-top,
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
.alert {
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.2);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05);
}
.alert-success {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#dff0d8), to(#c8e5bc));
background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
background-image: -moz-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%);
background-repeat: repeat-x;
border-color: #b2dba1;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);
}
.alert-info {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9edf7), to(#b9def0));
background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
background-image: -moz-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%);
background-repeat: repeat-x;
border-color: #9acfea;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);
}
.alert-warning {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#fcf8e3), to(#f8efc0));
background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
background-image: -moz-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%);
background-repeat: repeat-x;
border-color: #f5e79e;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);
}
.alert-danger {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f2dede), to(#e7c3c3));
background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
background-image: -moz-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%);
background-repeat: repeat-x;
border-color: #dca7a7;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);
}
.progress {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#ebebeb), to(#f5f5f5));
background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
background-image: -moz-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);
}
.progress-bar {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#3071a9));
background-image: -webkit-linear-gradient(top, #428bca 0%, #3071a9 100%);
background-image: -moz-linear-gradient(top, #428bca 0%, #3071a9 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #3071a9 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3071a9', GradientType=0);
}
.progress-bar-success {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5cb85c), to(#449d44));
background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%);
background-image: -moz-linear-gradient(top, #5cb85c 0%, #449d44 100%);
background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);
}
.progress-bar-info {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5bc0de), to(#31b0d5));
background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
background-image: -moz-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);
}
.progress-bar-warning {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f0ad4e), to(#ec971f));
background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
background-image: -moz-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);
}
.progress-bar-danger {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9534f), to(#c9302c));
background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%);
background-image: -moz-linear-gradient(top, #d9534f 0%, #c9302c 100%);
background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);
}
.list-group {
border-radius: 4px;
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
text-shadow: 0 -1px 0 #3071a9;
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#3278b3));
background-image: -webkit-linear-gradient(top, #428bca 0%, #3278b3 100%);
background-image: -moz-linear-gradient(top, #428bca 0%, #3278b3 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #3278b3 100%);
background-repeat: repeat-x;
border-color: #3278b3;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3278b3', GradientType=0);
}
.panel {
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.panel-default > .panel-heading {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f5f5f5), to(#e8e8e8));
background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: -moz-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
}
.panel-primary > .panel-heading {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#357ebd));
background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%);
background-image: -moz-linear-gradient(top, #428bca 0%, #357ebd 100%);
background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0);
}
.panel-success > .panel-heading {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#dff0d8), to(#d0e9c6));
background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
background-image: -moz-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);
}
.panel-info > .panel-heading {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9edf7), to(#c4e3f3));
background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
background-image: -moz-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);
}
.panel-warning > .panel-heading {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#fcf8e3), to(#faf2cc));
background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
background-image: -moz-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);
}
.panel-danger > .panel-heading {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f2dede), to(#ebcccc));
background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
background-image: -moz-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);
}
.well {
background-image: -webkit-gradient(linear, left 0%, left 100%, from(#e8e8e8), to(#f5f5f5));
background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
background-image: -moz-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%);
background-repeat: repeat-x;
border-color: #dcdcdc;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);
-webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1);
} | sociogenetics/xendor | xendor/static/css/bootstrap-theme.css | CSS | bsd-2-clause | 19,791 |
/* Test the `vqaddu32' ARM Neon intrinsic. */
/* This file was autogenerated by neon-testgen. */
/* { dg-do assemble } */
/* { dg-require-effective-target arm_neon_ok } */
/* { dg-options "-save-temps -O0" } */
/* { dg-add-options arm_neon } */
#include "arm_neon.h"
void test_vqaddu32 (void)
{
uint32x2_t out_uint32x2_t;
uint32x2_t arg0_uint32x2_t;
uint32x2_t arg1_uint32x2_t;
out_uint32x2_t = vqadd_u32 (arg0_uint32x2_t, arg1_uint32x2_t);
}
/* { dg-final { scan-assembler "vqadd\.u32\[ \]+\[dD\]\[0-9\]+, \[dD\]\[0-9\]+, \[dD\]\[0-9\]+!?\(\[ \]+@\[a-zA-Z0-9 \]+\)?\n" } } */
/* { dg-final { cleanup-saved-temps } } */
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/gcc/testsuite/gcc.target/arm/neon/vqaddu32.c | C | gpl-2.0 | 637 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage Yahoo
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: WebResult.php 24593 2012-01-05 20:35:02Z matthew $
*/
/**
* @see Zend_Service_Yahoo_Result
*/
require_once 'Zend/Service/Yahoo/Result.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage Yahoo
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Yahoo_WebResult extends Zend_Service_Yahoo_Result
{
/**
* A summary of the result
*
* @var string
*/
public $Summary;
/**
* The file type of the result (text, html, pdf, etc.)
*
* @var string
*/
public $MimeType;
/**
* The modification time of the result (as a unix timestamp)
*
* @var string
*/
public $ModificationDate;
/**
* The URL for the Yahoo cache of this page, if it exists
*
* @var string
*/
public $CacheUrl;
/**
* The size of the cache entry
*
* @var int
*/
public $CacheSize;
/**
* Web result namespace
*
* @var string
*/
protected $_namespace = 'urn:yahoo:srch';
/**
* Initializes the web result
*
* @param DOMElement $result
* @return void
*/
public function __construct(DOMElement $result)
{
$this->_fields = array('Summary', 'MimeType', 'ModificationDate');
parent::__construct($result);
$this->_xpath = new DOMXPath($result->ownerDocument);
$this->_xpath->registerNamespace('yh', $this->_namespace);
// check if the cache section exists
$cacheUrl = $this->_xpath->query('./yh:Cache/yh:Url/text()', $result)->item(0);
if ($cacheUrl instanceof DOMNode)
{
$this->CacheUrl = $cacheUrl->data;
}
$cacheSize = $this->_xpath->query('./yh:Cache/yh:Size/text()', $result)->item(0);
if ($cacheSize instanceof DOMNode)
{
$this->CacheSize = (int) $cacheSize->data;
}
}
}
| mattsimpson/entrada-1x | www-root/core/library/Zend/Service/Yahoo/WebResult.php | PHP | gpl-3.0 | 2,749 |
/* include/linux/msm_audio.h
*
* Copyright (C) 2008 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#if defined(CONFIG_ARCH_MSM8X60)
#include <linux/msm_audio_8X60.h>
#endif
#ifndef __LINUX_MSM_AUDIO_H
#define __LINUX_MSM_AUDIO_H
#include <linux/types.h>
#include <linux/ioctl.h>
/* PCM Audio */
#define AUDIO_IOCTL_MAGIC 'a'
#define AUDIO_START _IOW(AUDIO_IOCTL_MAGIC, 0, unsigned)
#define AUDIO_STOP _IOW(AUDIO_IOCTL_MAGIC, 1, unsigned)
#define AUDIO_FLUSH _IOW(AUDIO_IOCTL_MAGIC, 2, unsigned)
#define AUDIO_GET_CONFIG _IOR(AUDIO_IOCTL_MAGIC, 3, unsigned)
#define AUDIO_SET_CONFIG _IOW(AUDIO_IOCTL_MAGIC, 4, unsigned)
#define AUDIO_GET_STATS _IOR(AUDIO_IOCTL_MAGIC, 5, unsigned)
#define AUDIO_ENABLE_AUDPP _IOW(AUDIO_IOCTL_MAGIC, 6, unsigned)
#define AUDIO_SET_ADRC _IOW(AUDIO_IOCTL_MAGIC, 7, unsigned)
#define AUDIO_SET_EQ _IOW(AUDIO_IOCTL_MAGIC, 8, unsigned)
#define AUDIO_SET_RX_IIR _IOW(AUDIO_IOCTL_MAGIC, 9, unsigned)
#define AUDIO_SET_VOLUME _IOW(AUDIO_IOCTL_MAGIC, 10, unsigned)
#define AUDIO_PAUSE _IOW(AUDIO_IOCTL_MAGIC, 11, unsigned)
#define AUDIO_PLAY_DTMF _IOW(AUDIO_IOCTL_MAGIC, 12, unsigned)
#define AUDIO_GET_EVENT _IOR(AUDIO_IOCTL_MAGIC, 13, unsigned)
#define AUDIO_ABORT_GET_EVENT _IOW(AUDIO_IOCTL_MAGIC, 14, unsigned)
#define AUDIO_REGISTER_PMEM _IOW(AUDIO_IOCTL_MAGIC, 15, unsigned)
#define AUDIO_DEREGISTER_PMEM _IOW(AUDIO_IOCTL_MAGIC, 16, unsigned)
#define AUDIO_ASYNC_WRITE _IOW(AUDIO_IOCTL_MAGIC, 17, unsigned)
#define AUDIO_ASYNC_READ _IOW(AUDIO_IOCTL_MAGIC, 18, unsigned)
#define AUDIO_SET_INCALL _IOW(AUDIO_IOCTL_MAGIC, 19, struct msm_voicerec_mode)
#define AUDIO_GET_NUM_SND_DEVICE _IOR(AUDIO_IOCTL_MAGIC, 20, unsigned)
#define AUDIO_GET_SND_DEVICES _IOWR(AUDIO_IOCTL_MAGIC, 21, \
struct msm_snd_device_list)
#define AUDIO_ENABLE_SND_DEVICE _IOW(AUDIO_IOCTL_MAGIC, 22, unsigned)
#define AUDIO_DISABLE_SND_DEVICE _IOW(AUDIO_IOCTL_MAGIC, 23, unsigned)
#define AUDIO_ROUTE_STREAM _IOW(AUDIO_IOCTL_MAGIC, 24, \
struct msm_audio_route_config)
#define AUDIO_GET_PCM_CONFIG _IOR(AUDIO_IOCTL_MAGIC, 30, unsigned)
#define AUDIO_SET_PCM_CONFIG _IOW(AUDIO_IOCTL_MAGIC, 31, unsigned)
#define AUDIO_SWITCH_DEVICE _IOW(AUDIO_IOCTL_MAGIC, 32, unsigned)
#define AUDIO_SET_MUTE _IOW(AUDIO_IOCTL_MAGIC, 33, unsigned)
#define AUDIO_UPDATE_ACDB _IOW(AUDIO_IOCTL_MAGIC, 34, unsigned)
#define AUDIO_START_VOICE _IOW(AUDIO_IOCTL_MAGIC, 35, unsigned)
#define AUDIO_STOP_VOICE _IOW(AUDIO_IOCTL_MAGIC, 36, unsigned)
#define AUDIO_REINIT_ACDB _IOW(AUDIO_IOCTL_MAGIC, 39, unsigned)
#define AUDIO_OUTPORT_FLUSH _IOW(AUDIO_IOCTL_MAGIC, 40, unsigned short)
#define AUDIO_SET_ERR_THRESHOLD_VALUE _IOW(AUDIO_IOCTL_MAGIC, 41, \
unsigned short)
#define AUDIO_GET_BITSTREAM_ERROR_INFO _IOR(AUDIO_IOCTL_MAGIC, 42, \
struct msm_audio_bitstream_error_info)
/* Qualcomm extensions */
#define AUDIO_SET_STREAM_CONFIG _IOW(AUDIO_IOCTL_MAGIC, 80, \
struct msm_audio_stream_config)
#define AUDIO_GET_STREAM_CONFIG _IOR(AUDIO_IOCTL_MAGIC, 81, \
struct msm_audio_stream_config)
#define AUDIO_GET_SESSION_ID _IOR(AUDIO_IOCTL_MAGIC, 82, unsigned short)
#define AUDIO_GET_STREAM_INFO _IOR(AUDIO_IOCTL_MAGIC, 83, \
struct msm_audio_bitstream_info)
#define AUDIO_SET_PAN _IOW(AUDIO_IOCTL_MAGIC, 84, unsigned)
#define AUDIO_SET_QCONCERT_PLUS _IOW(AUDIO_IOCTL_MAGIC, 85, unsigned)
#define AUDIO_SET_MBADRC _IOW(AUDIO_IOCTL_MAGIC, 86, unsigned)
#define AUDIO_SET_VOLUME_PATH _IOW(AUDIO_IOCTL_MAGIC, 87, \
struct msm_vol_info)
#define AUDIO_SET_MAX_VOL_ALL _IOW(AUDIO_IOCTL_MAGIC, 88, unsigned)
#define AUDIO_ENABLE_AUDPRE _IOW(AUDIO_IOCTL_MAGIC, 89, unsigned)
#define AUDIO_SET_AGC _IOW(AUDIO_IOCTL_MAGIC, 90, unsigned)
#define AUDIO_SET_NS _IOW(AUDIO_IOCTL_MAGIC, 91, unsigned)
#define AUDIO_SET_TX_IIR _IOW(AUDIO_IOCTL_MAGIC, 92, unsigned)
#define AUDIO_GET_BUF_CFG _IOW(AUDIO_IOCTL_MAGIC, 93, \
struct msm_audio_buf_cfg)
#define AUDIO_SET_BUF_CFG _IOW(AUDIO_IOCTL_MAGIC, 94, \
struct msm_audio_buf_cfg)
#define AUDIO_SET_ACDB_BLK _IOW(AUDIO_IOCTL_MAGIC, 95, \
struct msm_acdb_cmd_device)
#define AUDIO_GET_ACDB_BLK _IOW(AUDIO_IOCTL_MAGIC, 96, \
struct msm_acdb_cmd_device)
#define AUDIO_MAX_COMMON_IOCTL_NUM 100
#define HANDSET_MIC 0x01
#define HANDSET_SPKR 0x02
#define HEADSET_MIC 0x03
#define HEADSET_SPKR_MONO 0x04
#define HEADSET_SPKR_STEREO 0x05
#define SPKR_PHONE_MIC 0x06
#define SPKR_PHONE_MONO 0x07
#define SPKR_PHONE_STEREO 0x08
#define BT_SCO_MIC 0x09
#define BT_SCO_SPKR 0x0A
#define BT_A2DP_SPKR 0x0B
#define TTY_HEADSET_MIC 0x0C
#define TTY_HEADSET_SPKR 0x0D
/* Default devices are not supported in a */
/* device switching context. Only supported */
/* for stream devices. */
/* DO NOT USE */
#define DEFAULT_TX 0x0E
#define DEFAULT_RX 0x0F
#define BT_A2DP_TX 0x10
#define HEADSET_MONO_PLUS_SPKR_MONO_RX 0x11
#define HEADSET_MONO_PLUS_SPKR_STEREO_RX 0x12
#define HEADSET_STEREO_PLUS_SPKR_MONO_RX 0x13
#define HEADSET_STEREO_PLUS_SPKR_STEREO_RX 0x14
#define I2S_RX 0x20
#define I2S_TX 0x21
#define ADRC_ENABLE 0x0001
#define EQ_ENABLE 0x0002
#define IIR_ENABLE 0x0004
#define QCONCERT_PLUS_ENABLE 0x0008
#define MBADRC_ENABLE 0x0010
#define AGC_ENABLE 0x0001
#define NS_ENABLE 0x0002
#define TX_IIR_ENABLE 0x0004
#define FLUENCE_ENABLE 0x0008
#define VOC_REC_UPLINK 0x00
#define VOC_REC_DOWNLINK 0x01
#define VOC_REC_BOTH 0x02
struct msm_audio_config {
uint32_t buffer_size;
uint32_t buffer_count;
uint32_t channel_count;
uint32_t sample_rate;
uint32_t type;
uint32_t meta_field;
uint32_t bits;
uint32_t unused[3];
};
struct msm_audio_stream_config {
uint32_t buffer_size;
uint32_t buffer_count;
};
struct msm_audio_buf_cfg{
uint32_t meta_info_enable;
uint32_t frames_per_buf;
};
struct msm_audio_stats {
uint32_t byte_count;
uint32_t sample_count;
uint32_t unused[2];
};
struct msm_audio_pmem_info {
int fd;
void *vaddr;
};
struct msm_audio_aio_buf {
void *buf_addr;
uint32_t buf_len;
uint32_t data_len;
void *private_data;
unsigned short mfield_sz; /*only useful for data has meta field */
};
/* Audio routing */
#define SND_IOCTL_MAGIC 's'
#define SND_MUTE_UNMUTED 0
#define SND_MUTE_MUTED 1
struct msm_mute_info {
uint32_t mute;
uint32_t path;
};
struct msm_vol_info {
uint32_t vol;
uint32_t path;
};
struct msm_voicerec_mode {
uint32_t rec_mode;
};
struct msm_snd_device_config {
uint32_t device;
uint32_t ear_mute;
uint32_t mic_mute;
};
#define SND_SET_DEVICE _IOW(SND_IOCTL_MAGIC, 2, struct msm_device_config *)
#define SND_METHOD_VOICE 0
struct msm_snd_volume_config {
uint32_t device;
uint32_t method;
uint32_t volume;
};
#define SND_SET_VOLUME _IOW(SND_IOCTL_MAGIC, 3, struct msm_snd_volume_config *)
/* Returns the number of SND endpoints supported. */
#define SND_GET_NUM_ENDPOINTS _IOR(SND_IOCTL_MAGIC, 4, unsigned *)
struct msm_snd_endpoint {
int id; /* input and output */
char name[64]; /* output only */
};
/* Takes an index between 0 and one less than the number returned by
* SND_GET_NUM_ENDPOINTS, and returns the SND index and name of a
* SND endpoint. On input, the .id field contains the number of the
* endpoint, and on exit it contains the SND index, while .name contains
* the description of the endpoint.
*/
#define SND_GET_ENDPOINT _IOWR(SND_IOCTL_MAGIC, 5, struct msm_snd_endpoint *)
#define SND_AVC_CTL _IOW(SND_IOCTL_MAGIC, 6, unsigned *)
#define SND_AGC_CTL _IOW(SND_IOCTL_MAGIC, 7, unsigned *)
struct msm_audio_pcm_config {
uint32_t pcm_feedback; /* 0 - disable > 0 - enable */
uint32_t buffer_count; /* Number of buffers to allocate */
uint32_t buffer_size; /* Size of buffer for capturing of
PCM samples */
};
#define AUDIO_EVENT_SUSPEND 0
#define AUDIO_EVENT_RESUME 1
#define AUDIO_EVENT_WRITE_DONE 2
#define AUDIO_EVENT_READ_DONE 3
#define AUDIO_EVENT_STREAM_INFO 4
#define AUDIO_EVENT_BITSTREAM_ERROR_INFO 5
#define AUDIO_CODEC_TYPE_MP3 0
#define AUDIO_CODEC_TYPE_AAC 1
struct msm_audio_bitstream_info {
uint32_t codec_type;
uint32_t chan_info;
uint32_t sample_rate;
uint32_t bit_stream_info;
uint32_t bit_rate;
uint32_t unused[3];
};
struct msm_audio_bitstream_error_info {
uint32_t dec_id;
uint32_t err_msg_indicator;
uint32_t err_type;
};
union msm_audio_event_payload {
struct msm_audio_aio_buf aio_buf;
struct msm_audio_bitstream_info stream_info;
struct msm_audio_bitstream_error_info error_info;
int reserved;
};
struct msm_audio_event {
int event_type;
int timeout_ms;
union msm_audio_event_payload event_payload;
};
#define MSM_SNDDEV_CAP_RX 0x1
#define MSM_SNDDEV_CAP_TX 0x2
#define MSM_SNDDEV_CAP_VOICE 0x4
struct msm_snd_device_info {
uint32_t dev_id;
uint32_t dev_cap; /* bitmask describe capability of device */
char dev_name[64];
};
struct msm_snd_device_list {
uint32_t num_dev; /* Indicate number of device info to be retrieved */
struct msm_snd_device_info *list;
};
struct msm_dtmf_config {
uint16_t path;
uint16_t dtmf_hi;
uint16_t dtmf_low;
uint16_t duration;
uint16_t tx_gain;
uint16_t rx_gain;
uint16_t mixing;
};
#define AUDIO_ROUTE_STREAM_VOICE_RX 0
#define AUDIO_ROUTE_STREAM_VOICE_TX 1
#define AUDIO_ROUTE_STREAM_PLAYBACK 2
#define AUDIO_ROUTE_STREAM_REC 3
struct msm_audio_route_config {
uint32_t stream_type;
uint32_t stream_id;
uint32_t dev_id;
};
#define AUDIO_MAX_EQ_BANDS 12
struct msm_audio_eq_band {
uint16_t band_idx; /* The band index, 0 .. 11 */
uint32_t filter_type; /* Filter band type */
uint32_t center_freq_hz; /* Filter band center frequency */
uint32_t filter_gain; /* Filter band initial gain (dB) */
/* Range is +12 dB to -12 dB with 1dB increments. */
uint32_t q_factor;
} __attribute__ ((packed));
struct msm_audio_eq_stream_config {
uint32_t enable; /* Number of consequtive bands specified */
uint32_t num_bands;
struct msm_audio_eq_band eq_bands[AUDIO_MAX_EQ_BANDS];
} __attribute__ ((packed));
struct msm_acdb_cmd_device {
uint32_t command_id;
uint32_t device_id;
uint32_t network_id;
uint32_t sample_rate_id; /* Actual sample rate value */
uint32_t interface_id; /* See interface id's above */
uint32_t algorithm_block_id; /* See enumerations above */
uint32_t total_bytes; /* Length in bytes used by buffer */
uint32_t *phys_buf; /* Physical Address of data */
};
#endif
| Renzo-Olivares/BAMF_android_kernel_htc_msm8660 | include/linux/msm_audio.h | C | gpl-2.0 | 10,911 |
<?php
_deprecated_file( __FILE__, '4.0', 'Tribe__View_Helpers.php' );
class Tribe__Events__View_Helpers extends Tribe__View_Helpers {}
| pdpfsug/wp_raga10 | wp_raga10/wp-content/plugins/the-events-calendar/vendor/tickets/common/src/deprecated/Tribe__Events__View_Helpers.php | PHP | agpl-3.0 | 136 |
var hat = require('../');
var assert = require('assert');
exports.rack = function () {
var rack = hat.rack(4);
var seen = {};
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]$/));
}
assert.throws(function () {
for (var i = 0; i < 10; i++) rack()
});
};
exports.data = function () {
var rack = hat.rack(64);
var a = rack('a!');
var b = rack("it's a b!")
var c = rack([ 'c', 'c', 'c' ]);
assert.equal(rack.get(a), 'a!');
assert.equal(rack.get(b), "it's a b!");
assert.deepEqual(rack.get(c), [ 'c', 'c', 'c' ]);
assert.equal(rack.hats[a], 'a!');
assert.equal(rack.hats[b], "it's a b!");
assert.deepEqual(rack.hats[c], [ 'c', 'c', 'c' ]);
rack.set(a, 'AAA');
assert.equal(rack.get(a), 'AAA');
};
exports.expandBy = function () {
var rack = hat.rack(4, 16, 4);
var seen = {};
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]$/));
}
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]{1,2}$/));
}
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]{2}$/));
}
};
| hendrikusR/open-layer | widget/assets/draw/hat/test/rack.js | JavaScript | bsd-3-clause | 1,569 |
/* ThemeRoller Humanity override style sheet for jQuery date picker v4.0.0. */
@import "ui.datepick.css";
.ui-widget-header a,
.ui-widget-header select {
color: #ffffff; /* Set (.ui-widget-header a) colour from theme here */
}
.ui-widget-header a:hover {
background-color: #f5f0e5; /* Set (.ui-state-hover) colours from theme here */
color: #a46313;
}
.ui-widget-header select,
.ui-widget-header option {
background-color: #cb842e; /* Set (.ui-widget-header) background colour from theme here */
}
.ui-state-highlight a {
color: #060200; /* Set (.ui-state-highlight) colour from theme here */
}
| x112358/cdnjs | ajax/libs/datepick/4.0.2/css/ui-humanity.datepick.css | CSS | mit | 601 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
public class RemoveHeadersTest extends ContextTestSupport {
public void testRemoveHeadersWildcard() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("duck", "Donald");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("dudeCool", "cool");
headers.put("dudeWicket", "wicket");
headers.put("duck", "Donald");
headers.put("foo", "bar");
template.sendBodyAndHeaders("direct:start", "Hello World", headers);
assertMockEndpointsSatisfied();
// breadcrumb is a header added as well so we expect 2
assertEquals(2, mock.getReceivedExchanges().get(0).getIn().getHeaders().size());
}
public void testRemoveHeadersRegEx() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("duck", "Donald");
mock.expectedHeaderReceived("BeerHeineken", "Good");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("dudeCool", "cool");
headers.put("dudeWicket", "wicket");
headers.put("duck", "Donald");
headers.put("BeerCarlsberg", "Great");
headers.put("BeerTuborg", "Also Great");
headers.put("BeerHeineken", "Good");
template.sendBodyAndHeaders("direct:start", "Hello World", headers);
assertMockEndpointsSatisfied();
// breadcrumb is a header added as well so we expect 3
assertEquals(3, mock.getReceivedExchanges().get(0).getIn().getHeaders().size());
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.removeHeaders("dude*")
.removeHeaders("Beer(Carlsberg|Tuborg)")
.removeHeaders("foo")
.to("mock:end");
}
};
}
} | coderczp/camel | camel-core/src/test/java/org/apache/camel/processor/RemoveHeadersTest.java | Java | apache-2.0 | 3,108 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor.aggregator;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.aggregate.AggregateController;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.camel.processor.aggregate.DefaultAggregateController;
import org.junit.Test;
/**
*
*/
public class AggregateControllerTest extends ContextTestSupport {
private AggregateController controller;
public AggregateController getAggregateController() {
if (controller == null) {
controller = new DefaultAggregateController();
}
return controller;
}
@Test
public void testForceCompletionOfAll() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(2);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3", "test2test4");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfAllGroups();
assertEquals(2, groups);
assertMockEndpointsSatisfied();
}
@Test
public void testForceCompletionOfGroup() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(1);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfGroup("1");
assertEquals(1, groups);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.aggregate(header("id"), new MyAggregationStrategy()).aggregateController(getAggregateController())
.completionSize(10)
.to("mock:aggregated");
}
};
}
public static class MyAggregationStrategy implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String body1 = oldExchange.getIn().getBody(String.class);
String body2 = newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(body1 + body2);
return oldExchange;
}
}
} | CandleCandle/camel | camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateControllerTest.java | Java | apache-2.0 | 4,309 |
/*
* Copyright (C) 2000 Harri Porten (porten@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef JSDOMWindowBase_h
#define JSDOMWindowBase_h
#include "JSDOMBinding.h"
#include "JSDOMGlobalObject.h"
#include <wtf/Forward.h>
namespace WebCore {
class DOMWindow;
class Frame;
class DOMWrapperWorld;
class JSDOMWindow;
class JSDOMWindowShell;
class JSDOMWindowBasePrivate;
class JSDOMWindowBase : public JSDOMGlobalObject {
typedef JSDOMGlobalObject Base;
protected:
JSDOMWindowBase(JSC::VM&, JSC::Structure*, PassRefPtr<DOMWindow>, JSDOMWindowShell*);
void finishCreation(JSC::VM&, JSDOMWindowShell*);
static void destroy(JSCell*);
public:
void updateDocument();
DOMWindow* impl() const { return m_impl.get(); }
ScriptExecutionContext* scriptExecutionContext() const;
// Called just before removing this window from the JSDOMWindowShell.
void willRemoveFromWindowShell();
static const JSC::ClassInfo s_info;
static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSValue prototype)
{
return JSC::Structure::create(vm, 0, prototype, JSC::TypeInfo(JSC::GlobalObjectType, StructureFlags), &s_info);
}
static const JSC::GlobalObjectMethodTable s_globalObjectMethodTable;
static bool supportsProfiling(const JSC::JSGlobalObject*);
static bool supportsRichSourceInfo(const JSC::JSGlobalObject*);
static bool shouldInterruptScript(const JSC::JSGlobalObject*);
static bool javaScriptExperimentsEnabled(const JSC::JSGlobalObject*);
void printErrorMessage(const String&) const;
JSDOMWindowShell* shell() const;
static JSC::VM* commonVM();
private:
RefPtr<DOMWindow> m_impl;
JSDOMWindowShell* m_shell;
};
// Returns a JSDOMWindow or jsNull()
// JSDOMGlobalObject* is ignored, accessing a window in any context will
// use that DOMWindow's prototype chain.
JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, DOMWindow*);
JSC::JSValue toJS(JSC::ExecState*, DOMWindow*);
// Returns JSDOMWindow or 0
JSDOMWindow* toJSDOMWindow(Frame*, DOMWrapperWorld*);
JSDOMWindow* toJSDOMWindow(JSC::JSValue);
} // namespace WebCore
#endif // JSDOMWindowBase_h
| Observer-Wu/phantomjs | src/qt/qtwebkit/Source/WebCore/bindings/js/JSDOMWindowBase.h | C | bsd-3-clause | 3,136 |
/* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <mach/board.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/uaccess.h>
#include <media/msm_gemini.h>
#include "msm_gemini_sync.h"
#include "msm_gemini_common.h"
#define MSM_GEMINI_NAME "gemini"
static int msm_gemini_open(struct inode *inode, struct file *filp)
{
int rc;
struct msm_gemini_device *pgmn_dev = container_of(inode->i_cdev,
struct msm_gemini_device, cdev);
filp->private_data = pgmn_dev;
GMN_DBG("%s:%d]\n", __func__, __LINE__);
rc = __msm_gemini_open(pgmn_dev);
GMN_DBG(KERN_INFO "%s:%d] %s open_count = %d\n", __func__, __LINE__,
filp->f_path.dentry->d_name.name, pgmn_dev->open_count);
return rc;
}
static int msm_gemini_release(struct inode *inode, struct file *filp)
{
int rc;
struct msm_gemini_device *pgmn_dev = filp->private_data;
GMN_DBG(KERN_INFO "%s:%d]\n", __func__, __LINE__);
rc = __msm_gemini_release(pgmn_dev);
GMN_DBG(KERN_INFO "%s:%d] %s open_count = %d\n", __func__, __LINE__,
filp->f_path.dentry->d_name.name, pgmn_dev->open_count);
return rc;
}
static long msm_gemini_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
int rc;
struct msm_gemini_device *pgmn_dev = filp->private_data;
GMN_DBG(KERN_INFO "%s:%d] cmd = %d\n", __func__, __LINE__,
_IOC_NR(cmd));
rc = __msm_gemini_ioctl(pgmn_dev, cmd, arg);
GMN_DBG("%s:%d]\n", __func__, __LINE__);
return rc;
}
static const struct file_operations msm_gemini_fops = {
.owner = THIS_MODULE,
.open = msm_gemini_open,
.release = msm_gemini_release,
.unlocked_ioctl = msm_gemini_ioctl,
};
static struct class *msm_gemini_class;
static dev_t msm_gemini_devno;
static struct msm_gemini_device *msm_gemini_device_p;
static int msm_gemini_init(struct platform_device *pdev)
{
int rc = -1;
struct device *dev;
GMN_DBG("%s:%d]\n", __func__, __LINE__);
msm_gemini_device_p = __msm_gemini_init(pdev);
if (msm_gemini_device_p == NULL) {
GMN_PR_ERR("%s: initialization failed\n", __func__);
goto fail;
}
rc = alloc_chrdev_region(&msm_gemini_devno, 0, 1, MSM_GEMINI_NAME);
if (rc < 0) {
GMN_PR_ERR("%s: failed to allocate chrdev\n", __func__);
goto fail_1;
}
if (!msm_gemini_class) {
msm_gemini_class = class_create(THIS_MODULE, MSM_GEMINI_NAME);
if (IS_ERR(msm_gemini_class)) {
rc = PTR_ERR(msm_gemini_class);
GMN_PR_ERR("%s: create device class failed\n",
__func__);
goto fail_2;
}
}
dev = device_create(msm_gemini_class, NULL,
MKDEV(MAJOR(msm_gemini_devno), MINOR(msm_gemini_devno)), NULL,
"%s%d", MSM_GEMINI_NAME, 0);
if (IS_ERR(dev)) {
GMN_PR_ERR("%s: error creating device\n", __func__);
rc = -ENODEV;
goto fail_3;
}
cdev_init(&msm_gemini_device_p->cdev, &msm_gemini_fops);
msm_gemini_device_p->cdev.owner = THIS_MODULE;
msm_gemini_device_p->cdev.ops =
(const struct file_operations *) &msm_gemini_fops;
rc = cdev_add(&msm_gemini_device_p->cdev, msm_gemini_devno, 1);
if (rc < 0) {
GMN_PR_ERR("%s: error adding cdev\n", __func__);
rc = -ENODEV;
goto fail_4;
}
GMN_DBG("%s %s: success\n", __func__, MSM_GEMINI_NAME);
return rc;
fail_4:
device_destroy(msm_gemini_class, msm_gemini_devno);
fail_3:
class_destroy(msm_gemini_class);
fail_2:
unregister_chrdev_region(msm_gemini_devno, 1);
fail_1:
__msm_gemini_exit(msm_gemini_device_p);
fail:
return rc;
}
static void msm_gemini_exit(void)
{
cdev_del(&msm_gemini_device_p->cdev);
device_destroy(msm_gemini_class, msm_gemini_devno);
class_destroy(msm_gemini_class);
unregister_chrdev_region(msm_gemini_devno, 1);
__msm_gemini_exit(msm_gemini_device_p);
}
static int __msm_gemini_probe(struct platform_device *pdev)
{
int rc;
rc = msm_gemini_init(pdev);
return rc;
}
static int __msm_gemini_remove(struct platform_device *pdev)
{
msm_gemini_exit();
return 0;
}
static struct platform_driver msm_gemini_driver = {
.probe = __msm_gemini_probe,
.remove = __msm_gemini_remove,
.driver = {
.name = "msm_gemini",
.owner = THIS_MODULE,
},
};
static int __init msm_gemini_driver_init(void)
{
int rc;
rc = platform_driver_register(&msm_gemini_driver);
return rc;
}
static void __exit msm_gemini_driver_exit(void)
{
platform_driver_unregister(&msm_gemini_driver);
}
MODULE_DESCRIPTION("msm gemini jpeg driver");
MODULE_VERSION("msm gemini 0.1");
module_init(msm_gemini_driver_init);
module_exit(msm_gemini_driver_exit);
| sgs3/SGH-T999V_Kernel | drivers/media/video/msm_zsl/gemini/msm_gemini_dev.c | C | gpl-2.0 | 5,006 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\Writer\Extension\Threading\Renderer;
use DOMDocument;
use DOMElement;
use Zend\Feed\Writer\Extension;
/**
*/
class Entry extends Extension\AbstractRenderer
{
/**
* Set to TRUE if a rendering method actually renders something. This
* is used to prevent premature appending of a XML namespace declaration
* until an element which requires it is actually appended.
*
* @var bool
*/
protected $called = false;
/**
* Render entry
*
* @return void
*/
public function render()
{
if (strtolower($this->getType()) == 'rss') {
return; // Atom 1.0 only
}
$this->_setCommentLink($this->dom, $this->base);
$this->_setCommentFeedLinks($this->dom, $this->base);
$this->_setCommentCount($this->dom, $this->base);
if ($this->called) {
$this->_appendNamespaces();
}
}
/**
* Append entry namespaces
*
* @return void
*/
protected function _appendNamespaces()
{
$this->getRootElement()->setAttribute('xmlns:thr',
'http://purl.org/syndication/thread/1.0');
}
/**
* Set comment link
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setCommentLink(DOMDocument $dom, DOMElement $root)
{
$link = $this->getDataContainer()->getCommentLink();
if (!$link) {
return;
}
$clink = $this->dom->createElement('link');
$clink->setAttribute('rel', 'replies');
$clink->setAttribute('type', 'text/html');
$clink->setAttribute('href', $link);
$count = $this->getDataContainer()->getCommentCount();
if ($count !== null) {
$clink->setAttribute('thr:count', $count);
}
$root->appendChild($clink);
$this->called = true;
}
/**
* Set comment feed links
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setCommentFeedLinks(DOMDocument $dom, DOMElement $root)
{
$links = $this->getDataContainer()->getCommentFeedLinks();
if (!$links || empty($links)) {
return;
}
foreach ($links as $link) {
$flink = $this->dom->createElement('link');
$flink->setAttribute('rel', 'replies');
$flink->setAttribute('type', 'application/' . $link['type'] . '+xml');
$flink->setAttribute('href', $link['uri']);
$count = $this->getDataContainer()->getCommentCount();
if ($count !== null) {
$flink->setAttribute('thr:count', $count);
}
$root->appendChild($flink);
$this->called = true;
}
}
/**
* Set entry comment count
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setCommentCount(DOMDocument $dom, DOMElement $root)
{
$count = $this->getDataContainer()->getCommentCount();
if ($count === null) {
return;
}
$tcount = $this->dom->createElement('thr:total');
$tcount->nodeValue = $count;
$root->appendChild($tcount);
$this->called = true;
}
}
| nickopris/musicapp | www/core/vendor/zendframework/zend-feed/Zend/Feed/Writer/Extension/Threading/Renderer/Entry.php | PHP | apache-2.0 | 3,659 |
import {Parser} from "./state"
import {SourceLocation} from "./locutil"
export class Node {
constructor(parser, pos, loc) {
this.type = ""
this.start = pos
this.end = 0
if (parser.options.locations)
this.loc = new SourceLocation(parser, loc)
if (parser.options.directSourceFile)
this.sourceFile = parser.options.directSourceFile
if (parser.options.ranges)
this.range = [pos, 0]
}
}
// Start an AST node, attaching a start offset.
const pp = Parser.prototype
pp.startNode = function() {
return new Node(this, this.start, this.startLoc)
}
pp.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
}
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type
node.end = pos
if (this.options.locations)
node.loc.end = loc
if (this.options.ranges)
node.range[1] = pos
return node
}
pp.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
}
// Finish node at given position
pp.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
}
| hellokidder/js-studying | 微信小程序/wxtest/node_modules/acorn-jsx/node_modules/acorn/src/node.js | JavaScript | mit | 1,194 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class IgnorePlugin {
constructor(resourceRegExp, contextRegExp) {
this.resourceRegExp = resourceRegExp;
this.contextRegExp = contextRegExp;
this.checkIgnore = this.checkIgnore.bind(this);
}
/*
* Only returns true if a "resourceRegExp" exists
* and the resource given matches the regexp.
*/
checkResource(resource) {
if(!this.resourceRegExp) {
return false;
}
return this.resourceRegExp.test(resource);
}
/*
* Returns true if contextRegExp does not exist
* or if context matches the given regexp.
*/
checkContext(context) {
if(!this.contextRegExp) {
return true;
}
return this.contextRegExp.test(context);
}
/*
* Returns true if result should be ignored.
* false if it shouldn't.
*
* Not that if "contextRegExp" is given, both the "resourceRegExp"
* and "contextRegExp" have to match.
*/
checkResult(result) {
if(!result) {
return true;
}
return this.checkResource(result.request) && this.checkContext(result.context);
}
checkIgnore(result, callback) {
// check if result is ignored
if(this.checkResult(result)) {
return callback();
}
return callback(null, result);
}
apply(compiler) {
compiler.plugin("normal-module-factory", (nmf) => {
nmf.plugin("before-resolve", this.checkIgnore);
});
compiler.plugin("context-module-factory", (cmf) => {
cmf.plugin("before-resolve", this.checkIgnore);
});
}
}
module.exports = IgnorePlugin;
| shikun2014010800/manga | web/console/node_modules/webpack/lib/IgnorePlugin.js | JavaScript | mit | 1,617 |
#!/usr/bin/env python
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# ansible-vault is a script that encrypts/decrypts YAML files. See
# https://docs.ansible.com/playbooks_vault.html for more details.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import time
import os
def main(args):
path = os.path.abspath(args[1])
fo = open(path, 'r+')
content = fo.readlines()
content.append('faux editor added at %s\n' % time.time())
fo.seek(0)
fo.write(''.join(content))
fo.close()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[:]))
| EvanK/ansible | test/integration/targets/vault/faux-editor.py | Python | gpl-3.0 | 1,212 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dataformat.univocity;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* This class tests the options of {@link org.apache.camel.dataformat.univocity.UniVocityCsvDataFormat}.
*/
public final class UniVocityCsvDataFormatTest {
@Test
public void shouldConfigureNullValue() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNullValue("N/A");
assertEquals("N/A", dataFormat.getNullValue());
assertEquals("N/A", dataFormat.createAndConfigureWriterSettings().getNullValue());
assertEquals("N/A", dataFormat.createAndConfigureParserSettings().getNullValue());
}
@Test
public void shouldConfigureSkipEmptyLines() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setSkipEmptyLines(true);
assertTrue(dataFormat.getSkipEmptyLines());
assertTrue(dataFormat.createAndConfigureWriterSettings().getSkipEmptyLines());
assertTrue(dataFormat.createAndConfigureParserSettings().getSkipEmptyLines());
}
@Test
public void shouldConfigureIgnoreTrailingWhitespaces() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setIgnoreTrailingWhitespaces(true);
assertTrue(dataFormat.getIgnoreTrailingWhitespaces());
assertTrue(dataFormat.createAndConfigureWriterSettings().getIgnoreTrailingWhitespaces());
assertTrue(dataFormat.createAndConfigureParserSettings().getIgnoreTrailingWhitespaces());
}
@Test
public void shouldConfigureIgnoreLeadingWhitespaces() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setIgnoreLeadingWhitespaces(true);
assertTrue(dataFormat.getIgnoreLeadingWhitespaces());
assertTrue(dataFormat.createAndConfigureWriterSettings().getIgnoreLeadingWhitespaces());
assertTrue(dataFormat.createAndConfigureParserSettings().getIgnoreLeadingWhitespaces());
}
@Test
public void shouldConfigureHeadersDisabled() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeadersDisabled(true);
assertTrue(dataFormat.isHeadersDisabled());
assertNull(dataFormat.createAndConfigureWriterSettings().getHeaders());
assertNull(dataFormat.createAndConfigureParserSettings().getHeaders());
}
@Test
public void shouldConfigureHeaders() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeaders(new String[]{"A", "B", "C"});
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.getHeaders());
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.createAndConfigureWriterSettings().getHeaders());
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.createAndConfigureParserSettings().getHeaders());
}
@Test
public void shouldConfigureHeaderExtractionEnabled() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeaderExtractionEnabled(true);
assertTrue(dataFormat.getHeaderExtractionEnabled());
assertTrue(dataFormat.createAndConfigureParserSettings().isHeaderExtractionEnabled());
}
@Test
public void shouldConfigureNumberOfRecordsToRead() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNumberOfRecordsToRead(42);
assertEquals(Integer.valueOf(42), dataFormat.getNumberOfRecordsToRead());
assertEquals(42, dataFormat.createAndConfigureParserSettings().getNumberOfRecordsToRead());
}
@Test
public void shouldConfigureEmptyValue() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setEmptyValue("empty");
assertEquals("empty", dataFormat.getEmptyValue());
assertEquals("empty", dataFormat.createAndConfigureWriterSettings().getEmptyValue());
assertEquals("empty", dataFormat.createAndConfigureParserSettings().getEmptyValue());
}
@Test
public void shouldConfigureLineSeparator() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setLineSeparator("ls");
assertEquals("ls", dataFormat.getLineSeparator());
assertEquals("ls", dataFormat.createAndConfigureWriterSettings().getFormat().getLineSeparatorString());
assertEquals("ls", dataFormat.createAndConfigureParserSettings().getFormat().getLineSeparatorString());
}
@Test
public void shouldConfigureNormalizedLineSeparator() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNormalizedLineSeparator('n');
assertEquals(Character.valueOf('n'), dataFormat.getNormalizedLineSeparator());
assertEquals('n', dataFormat.createAndConfigureWriterSettings().getFormat().getNormalizedNewline());
assertEquals('n', dataFormat.createAndConfigureParserSettings().getFormat().getNormalizedNewline());
}
@Test
public void shouldConfigureComment() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setComment('c');
assertEquals(Character.valueOf('c'), dataFormat.getComment());
assertEquals('c', dataFormat.createAndConfigureWriterSettings().getFormat().getComment());
assertEquals('c', dataFormat.createAndConfigureParserSettings().getFormat().getComment());
}
@Test
public void shouldConfigureLazyLoad() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setLazyLoad(true);
assertTrue(dataFormat.isLazyLoad());
}
@Test
public void shouldConfigureAsMap() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setAsMap(true);
assertTrue(dataFormat.isAsMap());
}
@Test
public void shouldConfigureQuoteAllFields() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuoteAllFields(true);
assertTrue(dataFormat.getQuoteAllFields());
assertTrue(dataFormat.createAndConfigureWriterSettings().getQuoteAllFields());
}
@Test
public void shouldConfigureQuote() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuote('q');
assertEquals(Character.valueOf('q'), dataFormat.getQuote());
assertEquals('q', dataFormat.createAndConfigureWriterSettings().getFormat().getQuote());
assertEquals('q', dataFormat.createAndConfigureParserSettings().getFormat().getQuote());
}
@Test
public void shouldConfigureQuoteEscape() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuoteEscape('e');
assertEquals(Character.valueOf('e'), dataFormat.getQuoteEscape());
assertEquals('e', dataFormat.createAndConfigureWriterSettings().getFormat().getQuoteEscape());
assertEquals('e', dataFormat.createAndConfigureParserSettings().getFormat().getQuoteEscape());
}
@Test
public void shouldConfigureDelimiter() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setDelimiter('d');
assertEquals(Character.valueOf('d'), dataFormat.getDelimiter());
assertEquals('d', dataFormat.createAndConfigureWriterSettings().getFormat().getDelimiter());
assertEquals('d', dataFormat.createAndConfigureParserSettings().getFormat().getDelimiter());
}
}
| YMartsynkevych/camel | components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatTest.java | Java | apache-2.0 | 8,709 |
/*
* Copyright (c) 2000-2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_inum.h"
#include "xfs_log.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_inode_item.h"
#include "xfs_btree.h"
#include "xfs_error.h"
#include "xfs_alloc.h"
#include "xfs_ialloc.h"
#include "xfs_fsops.h"
#include "xfs_itable.h"
#include "xfs_trans_space.h"
#include "xfs_rtalloc.h"
#include "xfs_rw.h"
#include "xfs_filestream.h"
#include "xfs_trace.h"
/*
* File system operations
*/
int
xfs_fs_geometry(
xfs_mount_t *mp,
xfs_fsop_geom_t *geo,
int new_version)
{
memset(geo, 0, sizeof(*geo));
geo->blocksize = mp->m_sb.sb_blocksize;
geo->rtextsize = mp->m_sb.sb_rextsize;
geo->agblocks = mp->m_sb.sb_agblocks;
geo->agcount = mp->m_sb.sb_agcount;
geo->logblocks = mp->m_sb.sb_logblocks;
geo->sectsize = mp->m_sb.sb_sectsize;
geo->inodesize = mp->m_sb.sb_inodesize;
geo->imaxpct = mp->m_sb.sb_imax_pct;
geo->datablocks = mp->m_sb.sb_dblocks;
geo->rtblocks = mp->m_sb.sb_rblocks;
geo->rtextents = mp->m_sb.sb_rextents;
geo->logstart = mp->m_sb.sb_logstart;
ASSERT(sizeof(geo->uuid)==sizeof(mp->m_sb.sb_uuid));
memcpy(geo->uuid, &mp->m_sb.sb_uuid, sizeof(mp->m_sb.sb_uuid));
if (new_version >= 2) {
geo->sunit = mp->m_sb.sb_unit;
geo->swidth = mp->m_sb.sb_width;
}
if (new_version >= 3) {
geo->version = XFS_FSOP_GEOM_VERSION;
geo->flags =
(xfs_sb_version_hasattr(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_ATTR : 0) |
(xfs_sb_version_hasnlink(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_NLINK : 0) |
(xfs_sb_version_hasquota(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_QUOTA : 0) |
(xfs_sb_version_hasalign(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_IALIGN : 0) |
(xfs_sb_version_hasdalign(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_DALIGN : 0) |
(xfs_sb_version_hasshared(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_SHARED : 0) |
(xfs_sb_version_hasextflgbit(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_EXTFLG : 0) |
(xfs_sb_version_hasdirv2(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_DIRV2 : 0) |
(xfs_sb_version_hassector(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_SECTOR : 0) |
(xfs_sb_version_hasasciici(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_DIRV2CI : 0) |
(xfs_sb_version_haslazysbcount(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_LAZYSB : 0) |
(xfs_sb_version_hasattr2(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_ATTR2 : 0);
geo->logsectsize = xfs_sb_version_hassector(&mp->m_sb) ?
mp->m_sb.sb_logsectsize : BBSIZE;
geo->rtsectsize = mp->m_sb.sb_blocksize;
geo->dirblocksize = mp->m_dirblksize;
}
if (new_version >= 4) {
geo->flags |=
(xfs_sb_version_haslogv2(&mp->m_sb) ?
XFS_FSOP_GEOM_FLAGS_LOGV2 : 0);
geo->logsunit = mp->m_sb.sb_logsunit;
}
return 0;
}
static int
xfs_growfs_data_private(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_growfs_data_t *in) /* growfs data input struct */
{
xfs_agf_t *agf;
xfs_agi_t *agi;
xfs_agnumber_t agno;
xfs_extlen_t agsize;
xfs_extlen_t tmpsize;
xfs_alloc_rec_t *arec;
struct xfs_btree_block *block;
xfs_buf_t *bp;
int bucket;
int dpct;
int error;
xfs_agnumber_t nagcount;
xfs_agnumber_t nagimax = 0;
xfs_rfsblock_t nb, nb_mod;
xfs_rfsblock_t new;
xfs_rfsblock_t nfree;
xfs_agnumber_t oagcount;
int pct;
xfs_trans_t *tp;
nb = in->newblocks;
pct = in->imaxpct;
if (nb < mp->m_sb.sb_dblocks || pct < 0 || pct > 100)
return XFS_ERROR(EINVAL);
if ((error = xfs_sb_validate_fsb_count(&mp->m_sb, nb)))
return error;
dpct = pct - mp->m_sb.sb_imax_pct;
bp = xfs_buf_read_uncached(mp, mp->m_ddev_targp,
XFS_FSB_TO_BB(mp, nb) - XFS_FSS_TO_BB(mp, 1),
BBTOB(XFS_FSS_TO_BB(mp, 1)), 0);
if (!bp)
return EIO;
xfs_buf_relse(bp);
new = nb; /* use new as a temporary here */
nb_mod = do_div(new, mp->m_sb.sb_agblocks);
nagcount = new + (nb_mod != 0);
if (nb_mod && nb_mod < XFS_MIN_AG_BLOCKS) {
nagcount--;
nb = (xfs_rfsblock_t)nagcount * mp->m_sb.sb_agblocks;
if (nb < mp->m_sb.sb_dblocks)
return XFS_ERROR(EINVAL);
}
new = nb - mp->m_sb.sb_dblocks;
oagcount = mp->m_sb.sb_agcount;
/* allocate the new per-ag structures */
if (nagcount > oagcount) {
error = xfs_initialize_perag(mp, nagcount, &nagimax);
if (error)
return error;
}
tp = xfs_trans_alloc(mp, XFS_TRANS_GROWFS);
tp->t_flags |= XFS_TRANS_RESERVE;
if ((error = xfs_trans_reserve(tp, XFS_GROWFS_SPACE_RES(mp),
XFS_GROWDATA_LOG_RES(mp), 0, 0, 0))) {
xfs_trans_cancel(tp, 0);
return error;
}
/*
* Write new AG headers to disk. Non-transactional, but written
* synchronously so they are completed prior to the growfs transaction
* being logged.
*/
nfree = 0;
for (agno = nagcount - 1; agno >= oagcount; agno--, new -= agsize) {
/*
* AG freelist header block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AG_DADDR(mp, agno, XFS_AGF_DADDR(mp)),
XFS_FSS_TO_BB(mp, 1), XBF_LOCK | XBF_MAPPED);
agf = XFS_BUF_TO_AGF(bp);
memset(agf, 0, mp->m_sb.sb_sectsize);
agf->agf_magicnum = cpu_to_be32(XFS_AGF_MAGIC);
agf->agf_versionnum = cpu_to_be32(XFS_AGF_VERSION);
agf->agf_seqno = cpu_to_be32(agno);
if (agno == nagcount - 1)
agsize =
nb -
(agno * (xfs_rfsblock_t)mp->m_sb.sb_agblocks);
else
agsize = mp->m_sb.sb_agblocks;
agf->agf_length = cpu_to_be32(agsize);
agf->agf_roots[XFS_BTNUM_BNOi] = cpu_to_be32(XFS_BNO_BLOCK(mp));
agf->agf_roots[XFS_BTNUM_CNTi] = cpu_to_be32(XFS_CNT_BLOCK(mp));
agf->agf_levels[XFS_BTNUM_BNOi] = cpu_to_be32(1);
agf->agf_levels[XFS_BTNUM_CNTi] = cpu_to_be32(1);
agf->agf_flfirst = 0;
agf->agf_fllast = cpu_to_be32(XFS_AGFL_SIZE(mp) - 1);
agf->agf_flcount = 0;
tmpsize = agsize - XFS_PREALLOC_BLOCKS(mp);
agf->agf_freeblks = cpu_to_be32(tmpsize);
agf->agf_longest = cpu_to_be32(tmpsize);
error = xfs_bwrite(mp, bp);
if (error) {
goto error0;
}
/*
* AG inode header block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AG_DADDR(mp, agno, XFS_AGI_DADDR(mp)),
XFS_FSS_TO_BB(mp, 1), XBF_LOCK | XBF_MAPPED);
agi = XFS_BUF_TO_AGI(bp);
memset(agi, 0, mp->m_sb.sb_sectsize);
agi->agi_magicnum = cpu_to_be32(XFS_AGI_MAGIC);
agi->agi_versionnum = cpu_to_be32(XFS_AGI_VERSION);
agi->agi_seqno = cpu_to_be32(agno);
agi->agi_length = cpu_to_be32(agsize);
agi->agi_count = 0;
agi->agi_root = cpu_to_be32(XFS_IBT_BLOCK(mp));
agi->agi_level = cpu_to_be32(1);
agi->agi_freecount = 0;
agi->agi_newino = cpu_to_be32(NULLAGINO);
agi->agi_dirino = cpu_to_be32(NULLAGINO);
for (bucket = 0; bucket < XFS_AGI_UNLINKED_BUCKETS; bucket++)
agi->agi_unlinked[bucket] = cpu_to_be32(NULLAGINO);
error = xfs_bwrite(mp, bp);
if (error) {
goto error0;
}
/*
* BNO btree root block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_BNO_BLOCK(mp)),
BTOBB(mp->m_sb.sb_blocksize),
XBF_LOCK | XBF_MAPPED);
block = XFS_BUF_TO_BLOCK(bp);
memset(block, 0, mp->m_sb.sb_blocksize);
block->bb_magic = cpu_to_be32(XFS_ABTB_MAGIC);
block->bb_level = 0;
block->bb_numrecs = cpu_to_be16(1);
block->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
block->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
arec = XFS_ALLOC_REC_ADDR(mp, block, 1);
arec->ar_startblock = cpu_to_be32(XFS_PREALLOC_BLOCKS(mp));
arec->ar_blockcount = cpu_to_be32(
agsize - be32_to_cpu(arec->ar_startblock));
error = xfs_bwrite(mp, bp);
if (error) {
goto error0;
}
/*
* CNT btree root block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_CNT_BLOCK(mp)),
BTOBB(mp->m_sb.sb_blocksize),
XBF_LOCK | XBF_MAPPED);
block = XFS_BUF_TO_BLOCK(bp);
memset(block, 0, mp->m_sb.sb_blocksize);
block->bb_magic = cpu_to_be32(XFS_ABTC_MAGIC);
block->bb_level = 0;
block->bb_numrecs = cpu_to_be16(1);
block->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
block->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
arec = XFS_ALLOC_REC_ADDR(mp, block, 1);
arec->ar_startblock = cpu_to_be32(XFS_PREALLOC_BLOCKS(mp));
arec->ar_blockcount = cpu_to_be32(
agsize - be32_to_cpu(arec->ar_startblock));
nfree += be32_to_cpu(arec->ar_blockcount);
error = xfs_bwrite(mp, bp);
if (error) {
goto error0;
}
/*
* INO btree root block
*/
bp = xfs_buf_get(mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_IBT_BLOCK(mp)),
BTOBB(mp->m_sb.sb_blocksize),
XBF_LOCK | XBF_MAPPED);
block = XFS_BUF_TO_BLOCK(bp);
memset(block, 0, mp->m_sb.sb_blocksize);
block->bb_magic = cpu_to_be32(XFS_IBT_MAGIC);
block->bb_level = 0;
block->bb_numrecs = 0;
block->bb_u.s.bb_leftsib = cpu_to_be32(NULLAGBLOCK);
block->bb_u.s.bb_rightsib = cpu_to_be32(NULLAGBLOCK);
error = xfs_bwrite(mp, bp);
if (error) {
goto error0;
}
}
xfs_trans_agblocks_delta(tp, nfree);
/*
* There are new blocks in the old last a.g.
*/
if (new) {
/*
* Change the agi length.
*/
error = xfs_ialloc_read_agi(mp, tp, agno, &bp);
if (error) {
goto error0;
}
ASSERT(bp);
agi = XFS_BUF_TO_AGI(bp);
be32_add_cpu(&agi->agi_length, new);
ASSERT(nagcount == oagcount ||
be32_to_cpu(agi->agi_length) == mp->m_sb.sb_agblocks);
xfs_ialloc_log_agi(tp, bp, XFS_AGI_LENGTH);
/*
* Change agf length.
*/
error = xfs_alloc_read_agf(mp, tp, agno, 0, &bp);
if (error) {
goto error0;
}
ASSERT(bp);
agf = XFS_BUF_TO_AGF(bp);
be32_add_cpu(&agf->agf_length, new);
ASSERT(be32_to_cpu(agf->agf_length) ==
be32_to_cpu(agi->agi_length));
xfs_alloc_log_agf(tp, bp, XFS_AGF_LENGTH);
/*
* Free the new space.
*/
error = xfs_free_extent(tp, XFS_AGB_TO_FSB(mp, agno,
be32_to_cpu(agf->agf_length) - new), new);
if (error) {
goto error0;
}
}
/*
* Update changed superblock fields transactionally. These are not
* seen by the rest of the world until the transaction commit applies
* them atomically to the superblock.
*/
if (nagcount > oagcount)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_AGCOUNT, nagcount - oagcount);
if (nb > mp->m_sb.sb_dblocks)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_DBLOCKS,
nb - mp->m_sb.sb_dblocks);
if (nfree)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_FDBLOCKS, nfree);
if (dpct)
xfs_trans_mod_sb(tp, XFS_TRANS_SB_IMAXPCT, dpct);
error = xfs_trans_commit(tp, 0);
if (error)
return error;
/* New allocation groups fully initialized, so update mount struct */
if (nagimax)
mp->m_maxagi = nagimax;
if (mp->m_sb.sb_imax_pct) {
__uint64_t icount = mp->m_sb.sb_dblocks * mp->m_sb.sb_imax_pct;
do_div(icount, 100);
mp->m_maxicount = icount << mp->m_sb.sb_inopblog;
} else
mp->m_maxicount = 0;
xfs_set_low_space_thresholds(mp);
/* update secondary superblocks. */
for (agno = 1; agno < nagcount; agno++) {
error = xfs_read_buf(mp, mp->m_ddev_targp,
XFS_AGB_TO_DADDR(mp, agno, XFS_SB_BLOCK(mp)),
XFS_FSS_TO_BB(mp, 1), 0, &bp);
if (error) {
xfs_warn(mp,
"error %d reading secondary superblock for ag %d",
error, agno);
break;
}
xfs_sb_to_disk(XFS_BUF_TO_SBP(bp), &mp->m_sb, XFS_SB_ALL_BITS);
/*
* If we get an error writing out the alternate superblocks,
* just issue a warning and continue. The real work is
* already done and committed.
*/
if (!(error = xfs_bwrite(mp, bp))) {
continue;
} else {
xfs_warn(mp,
"write error %d updating secondary superblock for ag %d",
error, agno);
break; /* no point in continuing */
}
}
return 0;
error0:
xfs_trans_cancel(tp, XFS_TRANS_ABORT);
return error;
}
static int
xfs_growfs_log_private(
xfs_mount_t *mp, /* mount point for filesystem */
xfs_growfs_log_t *in) /* growfs log input struct */
{
xfs_extlen_t nb;
nb = in->newblocks;
if (nb < XFS_MIN_LOG_BLOCKS || nb < XFS_B_TO_FSB(mp, XFS_MIN_LOG_BYTES))
return XFS_ERROR(EINVAL);
if (nb == mp->m_sb.sb_logblocks &&
in->isint == (mp->m_sb.sb_logstart != 0))
return XFS_ERROR(EINVAL);
/*
* Moving the log is hard, need new interfaces to sync
* the log first, hold off all activity while moving it.
* Can have shorter or longer log in the same space,
* or transform internal to external log or vice versa.
*/
return XFS_ERROR(ENOSYS);
}
/*
* protected versions of growfs function acquire and release locks on the mount
* point - exported through ioctls: XFS_IOC_FSGROWFSDATA, XFS_IOC_FSGROWFSLOG,
* XFS_IOC_FSGROWFSRT
*/
int
xfs_growfs_data(
xfs_mount_t *mp,
xfs_growfs_data_t *in)
{
int error;
if (!capable(CAP_SYS_ADMIN))
return XFS_ERROR(EPERM);
if (!mutex_trylock(&mp->m_growlock))
return XFS_ERROR(EWOULDBLOCK);
error = xfs_growfs_data_private(mp, in);
mutex_unlock(&mp->m_growlock);
return error;
}
int
xfs_growfs_log(
xfs_mount_t *mp,
xfs_growfs_log_t *in)
{
int error;
if (!capable(CAP_SYS_ADMIN))
return XFS_ERROR(EPERM);
if (!mutex_trylock(&mp->m_growlock))
return XFS_ERROR(EWOULDBLOCK);
error = xfs_growfs_log_private(mp, in);
mutex_unlock(&mp->m_growlock);
return error;
}
/*
* exported through ioctl XFS_IOC_FSCOUNTS
*/
int
xfs_fs_counts(
xfs_mount_t *mp,
xfs_fsop_counts_t *cnt)
{
xfs_icsb_sync_counters(mp, XFS_ICSB_LAZY_COUNT);
spin_lock(&mp->m_sb_lock);
cnt->freedata = mp->m_sb.sb_fdblocks - XFS_ALLOC_SET_ASIDE(mp);
cnt->freertx = mp->m_sb.sb_frextents;
cnt->freeino = mp->m_sb.sb_ifree;
cnt->allocino = mp->m_sb.sb_icount;
spin_unlock(&mp->m_sb_lock);
return 0;
}
/*
* exported through ioctl XFS_IOC_SET_RESBLKS & XFS_IOC_GET_RESBLKS
*
* xfs_reserve_blocks is called to set m_resblks
* in the in-core mount table. The number of unused reserved blocks
* is kept in m_resblks_avail.
*
* Reserve the requested number of blocks if available. Otherwise return
* as many as possible to satisfy the request. The actual number
* reserved are returned in outval
*
* A null inval pointer indicates that only the current reserved blocks
* available should be returned no settings are changed.
*/
int
xfs_reserve_blocks(
xfs_mount_t *mp,
__uint64_t *inval,
xfs_fsop_resblks_t *outval)
{
__int64_t lcounter, delta, fdblks_delta;
__uint64_t request;
/* If inval is null, report current values and return */
if (inval == (__uint64_t *)NULL) {
if (!outval)
return EINVAL;
outval->resblks = mp->m_resblks;
outval->resblks_avail = mp->m_resblks_avail;
return 0;
}
request = *inval;
/*
* With per-cpu counters, this becomes an interesting
* problem. we needto work out if we are freeing or allocation
* blocks first, then we can do the modification as necessary.
*
* We do this under the m_sb_lock so that if we are near
* ENOSPC, we will hold out any changes while we work out
* what to do. This means that the amount of free space can
* change while we do this, so we need to retry if we end up
* trying to reserve more space than is available.
*
* We also use the xfs_mod_incore_sb() interface so that we
* don't have to care about whether per cpu counter are
* enabled, disabled or even compiled in....
*/
retry:
spin_lock(&mp->m_sb_lock);
xfs_icsb_sync_counters_locked(mp, 0);
/*
* If our previous reservation was larger than the current value,
* then move any unused blocks back to the free pool.
*/
fdblks_delta = 0;
if (mp->m_resblks > request) {
lcounter = mp->m_resblks_avail - request;
if (lcounter > 0) { /* release unused blocks */
fdblks_delta = lcounter;
mp->m_resblks_avail -= lcounter;
}
mp->m_resblks = request;
} else {
__int64_t free;
free = mp->m_sb.sb_fdblocks - XFS_ALLOC_SET_ASIDE(mp);
if (!free)
goto out; /* ENOSPC and fdblks_delta = 0 */
delta = request - mp->m_resblks;
lcounter = free - delta;
if (lcounter < 0) {
/* We can't satisfy the request, just get what we can */
mp->m_resblks += free;
mp->m_resblks_avail += free;
fdblks_delta = -free;
} else {
fdblks_delta = -delta;
mp->m_resblks = request;
mp->m_resblks_avail += delta;
}
}
out:
if (outval) {
outval->resblks = mp->m_resblks;
outval->resblks_avail = mp->m_resblks_avail;
}
spin_unlock(&mp->m_sb_lock);
if (fdblks_delta) {
/*
* If we are putting blocks back here, m_resblks_avail is
* already at its max so this will put it in the free pool.
*
* If we need space, we'll either succeed in getting it
* from the free block count or we'll get an enospc. If
* we get a ENOSPC, it means things changed while we were
* calculating fdblks_delta and so we should try again to
* see if there is anything left to reserve.
*
* Don't set the reserved flag here - we don't want to reserve
* the extra reserve blocks from the reserve.....
*/
int error;
error = xfs_icsb_modify_counters(mp, XFS_SBS_FDBLOCKS,
fdblks_delta, 0);
if (error == ENOSPC)
goto retry;
}
return 0;
}
/*
* Dump a transaction into the log that contains no real change. This is needed
* to be able to make the log dirty or stamp the current tail LSN into the log
* during the covering operation.
*
* We cannot use an inode here for this - that will push dirty state back up
* into the VFS and then periodic inode flushing will prevent log covering from
* making progress. Hence we log a field in the superblock instead and use a
* synchronous transaction to ensure the superblock is immediately unpinned
* and can be written back.
*/
int
xfs_fs_log_dummy(
xfs_mount_t *mp)
{
xfs_trans_t *tp;
int error;
tp = _xfs_trans_alloc(mp, XFS_TRANS_DUMMY1, KM_SLEEP);
error = xfs_trans_reserve(tp, 0, mp->m_sb.sb_sectsize + 128, 0, 0,
XFS_DEFAULT_LOG_COUNT);
if (error) {
xfs_trans_cancel(tp, 0);
return error;
}
/* log the UUID because it is an unchanging field */
xfs_mod_sb(tp, XFS_SB_UUID);
xfs_trans_set_sync(tp);
return xfs_trans_commit(tp, 0);
}
int
xfs_fs_goingdown(
xfs_mount_t *mp,
__uint32_t inflags)
{
switch (inflags) {
case XFS_FSOP_GOING_FLAGS_DEFAULT: {
struct super_block *sb = freeze_bdev(mp->m_super->s_bdev);
if (sb && !IS_ERR(sb)) {
xfs_force_shutdown(mp, SHUTDOWN_FORCE_UMOUNT);
thaw_bdev(sb->s_bdev, sb);
}
break;
}
case XFS_FSOP_GOING_FLAGS_LOGFLUSH:
xfs_force_shutdown(mp, SHUTDOWN_FORCE_UMOUNT);
break;
case XFS_FSOP_GOING_FLAGS_NOLOGFLUSH:
xfs_force_shutdown(mp,
SHUTDOWN_FORCE_UMOUNT | SHUTDOWN_LOG_IO_ERROR);
break;
default:
return XFS_ERROR(EINVAL);
}
return 0;
}
| JijonHyuni/HyperKernel-JB | virt/fs/xfs/xfs_fsops.c | C | gpl-2.0 | 19,130 |
/*****************************************************************************
Copyright(c) 2012 FCI Inc. All Rights Reserved
File name : fc8150_tun.c (BGA & QFN)
Description : fc8150 tuner driver
History :
----------------------------------------------------------------------
2012/01/20 initial 0.1 version
2012/01/25 initial 0.3 version
2012/01/27 initial 0.5 version
2012/01/31 initial 1.0 version
2012/01/31 initial 1.1 version
2012/02/06 initial 1.2 version
2012/02/09 initial 1.3 Version
2012/02/15 initial 1.4 Version
2012/02/15 initial 2.0 Version
2012/02/24 initial 2.01 Version
2012/03/30 initial 3.0 Version
2012/06/07 pre SLR Version
2012/06/11 pre SLR Version
2012/06/15
2012/06/17 SLR 0.3 version
2012/06/19 SLR 0.4 version
2012/06/20
2012/07/04
2012/07/09
2012/07/10
2012/07/15
*******************************************************************************/
#include <linux/init.h> /* miseon.kim 2012.06.21 FC8150 Device Release */
#include <mach/board_lge.h> /* miseon.kim 2012.06.21 FC8150 Device Release */
#include "fci_types.h"
#include "fci_oal.h"
#include "fci_tun.h"
#include "fc8150_regs.h"
#include "fci_hal.h"
#define FC8150_FREQ_XTAL BBM_XTAL_FREQ //32MHZ
static int fc8150_write(HANDLE hDevice, u8 addr, u8 data)
{
int res;
u8 tmp;
tmp = data;
res = tuner_i2c_write(hDevice, addr, 1,&tmp, 1);
return res;
}
static int fc8150_read(HANDLE hDevice, u8 addr, u8 *data)
{
int res;
res = tuner_i2c_read(hDevice, addr, 1,data, 1);
return res;
}
static int fc8150_bb_read(HANDLE hDevice, u16 addr, u8 *data)
{
int res;
res = bbm_read(hDevice, addr, data);
return res;
}
#if 0
static int fc8150_bb_write(HANDLE hDevice, u16 addr, u8 data)
{
int res;
res = bbm_write(hDevice, addr, data);
return res;
}
#endif
static int fc8150_set_filter(HANDLE hDevice)
{
int i;
u8 cal_mon = 0;
#if (FC8150_FREQ_XTAL == 16000)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x20);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 16384)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x21);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 18000)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x24);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 19200)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x26);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 24000)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x30);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 24576)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x31);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 26000)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x34);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 27000)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x36);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 27120)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x36);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 32000)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x40);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 37400)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x4B);
fc8150_write(hDevice, 0x3B, 0x00);
#elif (FC8150_FREQ_XTAL == 38400)
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_write(hDevice, 0x3D, 0x4D);
fc8150_write(hDevice, 0x3B, 0x00);
#else
return BBM_NOK;
#endif
for(i=0; i<10; i++) {
msWait(5);
fc8150_read(hDevice, 0x33, &cal_mon);
if( (cal_mon & 0xC0) == 0xC0)
break;
fc8150_write(hDevice, 0x32, 0x01);
fc8150_write(hDevice, 0x32, 0x09);
}
fc8150_write(hDevice, 0x32, 0x01);
return BBM_OK;
}
int fc8150_tuner_init(HANDLE hDevice, u32 band)
{
PRINTF(hDevice, "fc8150_init\n");
/* miseon.kim 2012.06.21 FC8150 Device Release */
if(lge_get_board_revno() >= HW_REV_C)
{
int i;
int n_RFAGC_PD1_AVG,n_RFAGC_PD2_AVG;
u8 RFPD_REF;
u8 RFAGC_PD2[6],RFAGC_PD2_AVG,RFAGC_PD2_MAX,RFAGC_PD2_MIN;
u8 RFAGC_PD1[6],RFAGC_PD1_AVG,RFAGC_PD1_MAX,RFAGC_PD1_MIN;
int res = BBM_OK;
fc8150_write(hDevice, 0x00, 0x00);
fc8150_write(hDevice, 0x02, 0x81);
fc8150_write(hDevice, 0x15, 0x02);
fc8150_write(hDevice, 0x20, 0x33);
fc8150_write(hDevice, 0x28, 0x62);
fc8150_write(hDevice, 0x35, 0xAA);
fc8150_write(hDevice, 0x38, 0x28);
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_set_filter(hDevice);
fc8150_write(hDevice, 0x3B, 0x00);
fc8150_write(hDevice, 0x56, 0x01);
fc8150_write(hDevice, 0x57, 0x86);
fc8150_write(hDevice, 0x58, 0xA7);
fc8150_write(hDevice, 0x59, 0x4D);
fc8150_write(hDevice, 0x80, 0x17);
fc8150_write(hDevice, 0xAB, 0x48);
fc8150_write(hDevice, 0xA0, 0xC0);
fc8150_write(hDevice, 0xD0, 0x00);
fc8150_write(hDevice, 0xA5, 0x65);
RFAGC_PD1[0] = 0;
RFAGC_PD1[1] = 0;
RFAGC_PD1[2] = 0;
RFAGC_PD1[3] = 0;
RFAGC_PD1[4] = 0;
RFAGC_PD1[5] = 0;
RFAGC_PD1_MAX = 0;
RFAGC_PD1_MIN = 255;
for (i = 0 ; i<6 ; i++){
fc8150_read(hDevice, 0xD8 , &RFAGC_PD1[i] );
if( RFAGC_PD1[i] >= RFAGC_PD1_MAX) RFAGC_PD1_MAX = RFAGC_PD1[i];
if( RFAGC_PD1[i] <= RFAGC_PD1_MIN) RFAGC_PD1_MIN = RFAGC_PD1[i];
}
n_RFAGC_PD1_AVG = (RFAGC_PD1[0] + RFAGC_PD1[1] + RFAGC_PD1[2] + RFAGC_PD1[3] + RFAGC_PD1[4] + RFAGC_PD1[5] - RFAGC_PD1_MAX - RFAGC_PD1_MIN) /4;
RFAGC_PD1_AVG = (unsigned char) n_RFAGC_PD1_AVG;
fc8150_write(hDevice, 0x7F , RFAGC_PD1_AVG);
RFAGC_PD2[0] = 0;
RFAGC_PD2[1] = 0;
RFAGC_PD2[2] = 0;
RFAGC_PD2[3] = 0;
RFAGC_PD2[4] = 0;
RFAGC_PD2[5] = 0;
RFAGC_PD2_MAX = 0;
RFAGC_PD2_MIN = 255;
for (i = 0 ; i<6 ; i++){
fc8150_read(hDevice, 0xD6 , &RFAGC_PD2[i] );
if( RFAGC_PD2[i] >= RFAGC_PD2_MAX) RFAGC_PD2_MAX = RFAGC_PD2[i];
if( RFAGC_PD2[i] <= RFAGC_PD2_MIN) RFAGC_PD2_MIN = RFAGC_PD2[i];
}
n_RFAGC_PD2_AVG = (RFAGC_PD2[0] + RFAGC_PD2[1] + RFAGC_PD2[2] + RFAGC_PD2[3] + RFAGC_PD2[4] + RFAGC_PD2[5] - RFAGC_PD2_MAX - RFAGC_PD2_MIN) /4;
RFAGC_PD2_AVG = (unsigned char) n_RFAGC_PD2_AVG;
fc8150_write(hDevice, 0x7E , RFAGC_PD2_AVG);
res = fc8150_read(hDevice, 0xD6, &RFPD_REF);
if(0x86<=RFPD_REF) fc8150_write(hDevice, 0x7B, 0x8F);
else if (RFPD_REF<0x86) fc8150_write(hDevice, 0x7B, 0x88);
fc8150_write(hDevice, 0x79, 0x32);
fc8150_write(hDevice, 0x7A, 0x2C);
fc8150_write(hDevice, 0x7C, 0x10);
fc8150_write(hDevice, 0x7D, 0x0C);
fc8150_write(hDevice, 0x81, 0x0A);
fc8150_write(hDevice, 0x84, 0x00);
fc8150_write(hDevice, 0x02, 0x81);
}
else
{
u8 RFPD_REF, MIXPD_REF;
fc8150_write(hDevice, 0x00, 0x00);
fc8150_write(hDevice, 0x02, 0x81);
fc8150_write(hDevice, 0x13, 0xF4);
fc8150_write(hDevice, 0x30, 0x0A);
fc8150_write(hDevice, 0x3B, 0x01);
fc8150_set_filter(hDevice);
fc8150_write(hDevice, 0x3B, 0x00);
fc8150_write(hDevice, 0x34, 0x68);
fc8150_write(hDevice, 0x36, 0xFF);
fc8150_write(hDevice, 0x37, 0xFF);
fc8150_write(hDevice, 0x39, 0x11);
fc8150_write(hDevice, 0x3A, 0x00);
fc8150_write(hDevice, 0x52, 0x20);
fc8150_write(hDevice, 0x53, 0x5F);
fc8150_write(hDevice, 0x54, 0x00);
fc8150_write(hDevice, 0x5E, 0x00);
fc8150_write(hDevice, 0x63, 0x30);
fc8150_write(hDevice, 0x56, 0x0F);
fc8150_write(hDevice, 0x57, 0x1F);
fc8150_write(hDevice, 0x58, 0x09);
fc8150_write(hDevice, 0x59, 0x5E);
fc8150_write(hDevice, 0x29, 0x00);
fc8150_write(hDevice, 0x94, 0x00);
fc8150_write(hDevice, 0x95, 0x01);
fc8150_write(hDevice, 0x96, 0x11);
fc8150_write(hDevice, 0x97, 0x21);
fc8150_write(hDevice, 0x98, 0x31);
fc8150_write(hDevice, 0x99, 0x32);
fc8150_write(hDevice, 0x9A, 0x42);
fc8150_write(hDevice, 0x9B, 0x52);
fc8150_write(hDevice, 0x9C, 0x53);
fc8150_write(hDevice, 0x9D, 0x63);
fc8150_write(hDevice, 0x9E, 0x63);
fc8150_write(hDevice, 0x9F, 0x63);
fc8150_write(hDevice, 0x79, 0x2A);
fc8150_write(hDevice, 0x7A, 0x24);
fc8150_write(hDevice, 0x7B, 0xFF);
fc8150_write(hDevice, 0x7C, 0x1B);
fc8150_write(hDevice, 0x7D, 0x17);
fc8150_write(hDevice, 0x84, 0x00);
fc8150_write(hDevice, 0x85, 0x08);
fc8150_write(hDevice, 0x86, 0x00);
fc8150_write(hDevice, 0x87, 0x08);
fc8150_write(hDevice, 0x88, 0x00);
fc8150_write(hDevice, 0x89, 0x08);
fc8150_write(hDevice, 0x8A, 0x00);
fc8150_write(hDevice, 0x8B, 0x08);
fc8150_write(hDevice, 0x8C, 0x00);
fc8150_write(hDevice, 0x8D, 0x1D);
fc8150_write(hDevice, 0x8E, 0x13);
fc8150_write(hDevice, 0x8F, 0x1D);
fc8150_write(hDevice, 0x90, 0x13);
fc8150_write(hDevice, 0x91, 0x1D);
fc8150_write(hDevice, 0x92, 0x13);
fc8150_write(hDevice, 0x93, 0x1D);
fc8150_write(hDevice, 0x80, 0x1F);
fc8150_write(hDevice, 0x81, 0x0A);
fc8150_write(hDevice, 0x82, 0x40);
fc8150_write(hDevice, 0x83, 0x0A);
fc8150_write(hDevice, 0xA0, 0xC0);
fc8150_write(hDevice, 0x7E, 0x7F);
fc8150_write(hDevice, 0x7F, 0x7F);
fc8150_write(hDevice, 0xD0, 0x0A);
fc8150_write(hDevice, 0xD2, 0x28);
fc8150_write(hDevice, 0xD4, 0x28);
fc8150_write(hDevice, 0xA0, 0x17);
fc8150_write(hDevice, 0xD0, 0x00);
fc8150_write(hDevice, 0xA1, 0x1D);
msWait(100);
fc8150_read(hDevice, 0xD6, &RFPD_REF);
fc8150_read(hDevice, 0xD8, &MIXPD_REF);
fc8150_write(hDevice, 0xA0, 0xD7);
fc8150_write(hDevice, 0xD0, 0x0A);
fc8150_write(hDevice, 0x7E, RFPD_REF);
fc8150_write(hDevice, 0x7F, MIXPD_REF);
fc8150_write(hDevice, 0xA0, 0xC0);
fc8150_write(hDevice, 0xA1, 0x00);
}
return BBM_OK;
}
int fc8150_set_freq(HANDLE hDevice, band_type band, u32 rf_kHz)
{
int n_captune = 0;
unsigned long f_diff, f_diff_shifted, n_val, k_val;
unsigned long f_vco, f_comp;
unsigned char r_val, data_0x56;
unsigned char pre_shift_bits = 4;
f_vco = (rf_kHz) << 2;
if(f_vco < FC8150_FREQ_XTAL*40)
r_val = 2;
else
r_val = 1;
f_comp = FC8150_FREQ_XTAL / r_val;
n_val = f_vco / f_comp;
f_diff = f_vco - f_comp * n_val;
f_diff_shifted = f_diff << (20 - pre_shift_bits);
/* miseon.kim 2012.06.21 FC8150 Device Release */
if(lge_get_board_revno() >= HW_REV_C)
{
k_val = (f_diff_shifted ) / (f_comp >> pre_shift_bits);
k_val = (k_val | 1);
if(470000<rf_kHz && rf_kHz<=473143){
fc8150_write(hDevice, 0x1E, 0x04);
fc8150_write(hDevice, 0x1F, 0x36);
fc8150_write(hDevice, 0x14, 0x84);
} else if(473143<rf_kHz && rf_kHz<=485143){
fc8150_write(hDevice, 0x1E, 0x03);
fc8150_write(hDevice, 0x1F, 0x3E);
fc8150_write(hDevice, 0x14, 0x84);
} else if(485143<rf_kHz && rf_kHz<=551143){
fc8150_write(hDevice, 0x1E, 0x04);
fc8150_write(hDevice, 0x1F, 0x36);
fc8150_write(hDevice, 0x14, 0x84);
} else if(551143<rf_kHz && rf_kHz<=563143){
fc8150_write(hDevice, 0x1E, 0x03);
fc8150_write(hDevice, 0x1F, 0x3E);
fc8150_write(hDevice, 0x14, 0xC4);
} else if(563143<rf_kHz && rf_kHz<=593143){
fc8150_write(hDevice, 0x1E, 0x02);
fc8150_write(hDevice, 0x1F, 0x3E);
fc8150_write(hDevice, 0x14, 0xC4);
} else if(593143<rf_kHz && rf_kHz<=659143){
fc8150_write(hDevice, 0x1E, 0x02);
fc8150_write(hDevice, 0x1F, 0x36);
fc8150_write(hDevice, 0x14, 0x84);
} else if(659143<rf_kHz && rf_kHz<=767143){
fc8150_write(hDevice, 0x1E, 0x01);
fc8150_write(hDevice, 0x1F, 0x36);
fc8150_write(hDevice, 0x14, 0x84);
} else if(767143<rf_kHz){
fc8150_write(hDevice, 0x1E, 0x00);
fc8150_write(hDevice, 0x1F, 0x36);
fc8150_write(hDevice, 0x14, 0x84);
} else{
fc8150_write(hDevice, 0x1E, 0x05);
fc8150_write(hDevice, 0x1F, 0x36);
fc8150_write(hDevice, 0x14, 0x84);
}
data_0x56 = ((r_val==1)? 0 : 0x10) + (unsigned char)(k_val>>16);
fc8150_write(hDevice, 0x56, data_0x56);
fc8150_write(hDevice, 0x57, (unsigned char)((k_val>>8)&0xFF));
fc8150_write(hDevice, 0x58, (unsigned char)(((k_val)&0xFF)));
fc8150_write(hDevice, 0x59, (unsigned char) n_val);
if(rf_kHz<525000){
fc8150_write(hDevice, 0x55, 0x0E);
} else if (525000<=rf_kHz && rf_kHz<600000){
fc8150_write(hDevice, 0x55, 0x0C);
} else if (600000<=rf_kHz && rf_kHz<700000){
fc8150_write(hDevice, 0x55, 0x08);
} else if (700000<rf_kHz){
fc8150_write(hDevice, 0x55, 0x06);
}
if(rf_kHz<=491143){
fc8150_write(hDevice, 0x79, 0x28);
fc8150_write(hDevice, 0x7A, 0x24);
} else if (491143<rf_kHz && rf_kHz<=659143){
fc8150_write(hDevice, 0x79, 0x2A);
fc8150_write(hDevice, 0x7A, 0x26);
} else if (659143<rf_kHz && rf_kHz<=773143){
fc8150_write(hDevice, 0x79, 0x2C);
fc8150_write(hDevice, 0x7A, 0x28);
} else if(773143<rf_kHz){
fc8150_write(hDevice, 0x79, 0x2F);
fc8150_write(hDevice, 0x7A, 0x2B);
}
if(rf_kHz<=707143){
fc8150_write(hDevice, 0x54, 0x00);
fc8150_write(hDevice, 0x53, 0x5F);
} else if (707143<rf_kHz){
fc8150_write(hDevice, 0x54, 0x04);
fc8150_write(hDevice, 0x53, 0x9F);
}
}
else
{
k_val = (f_diff_shifted + (f_comp >> (pre_shift_bits+1))) / (f_comp >> pre_shift_bits);
k_val = (k_val | 1);
if(470000<rf_kHz && rf_kHz<=505000){
n_captune = 4;
}
else if(505000<rf_kHz && rf_kHz<=545000){
n_captune = 3;
}
else if(545000<rf_kHz && rf_kHz<=610000){
n_captune = 2;
}
else if(610000<rf_kHz && rf_kHz<=695000){
n_captune = 1;
}
else if(695000<rf_kHz){
n_captune = 0;
}
fc8150_write(hDevice, 0x1E, (unsigned char)n_captune);
data_0x56 = ((r_val==1)? 0 : 0x10) + (unsigned char)(k_val>>16);
fc8150_write(hDevice, 0x56, data_0x56);
fc8150_write(hDevice, 0x57, (unsigned char)((k_val>>8)&0xFF));
fc8150_write(hDevice, 0x58, (unsigned char)(((k_val)&0xFF)));
fc8150_write(hDevice, 0x59, (unsigned char) n_val);
if(rf_kHz<=600000){
fc8150_write(hDevice, 0x55, 0x07);
}
else {
fc8150_write(hDevice, 0x55, 0x05);
}
if((490000<rf_kHz)&& (560000>=rf_kHz)){
fc8150_write(hDevice, 0x1F, 0x0E);
}
else {
fc8150_write(hDevice, 0x1F, 0x06);
}
}
return BBM_OK;
}
int fc8150_get_rssi(HANDLE hDevice, int *rssi)
{
int res = BBM_OK;
u8 LNA, RFVGA, CSF,PREAMP_PGA = 0x00;
int K = -101;
int PGA = 0;
res |= fc8150_read(hDevice, 0xA3, &LNA);
res |= fc8150_read(hDevice, 0xA4, &RFVGA);
res |= fc8150_read(hDevice, 0xA8, &CSF);
res |= fc8150_bb_read(hDevice, 0x106E, &PREAMP_PGA);
if(res != BBM_OK)
return res;
if (127<PREAMP_PGA) PGA = -1*((256-PREAMP_PGA)+1);
else if(PREAMP_PGA<=127) PGA = PREAMP_PGA;
//*rssi = (LNA & 0x07) * 6 + (RFVGA & 0x1F) + ((CSF & 0x03)+((CSF & 0x70) >> 4) )*6 - PGA * 0.25f + K ;
*rssi = (LNA & 0x07) * 6 + (RFVGA & 0x1F) + ((CSF & 0x03)+((CSF & 0x70) >> 4) )*6 - PGA / 4 + K;
return BBM_OK;
}
int fc8150_tuner_deinit(HANDLE hDevice)
{
return BBM_OK;
}
| jokersax/lgogsprint3.4kernel | drivers/broadcast/oneseg/fc8150/drv/fc8150_tun.c | C | gpl-2.0 | 15,794 |
/*! jQuery UI - v1.10.3 - 2013-06-12
* http://jqueryui.com
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.he={closeText:"סגור",prevText:"<הקודם",nextText:"הבא>",currentText:"היום",monthNames:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],monthNamesShort:["ינו","פבר","מרץ","אפר","מאי","יוני","יולי","אוג","ספט","אוק","נוב","דצמ"],dayNames:["ראשון","שני","שלישי","רביעי","חמישי","שישי","שבת"],dayNamesShort:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],dayNamesMin:["א'","ב'","ג'","ד'","ה'","ו'","שבת"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!0,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.he)}); | jcdude/LamPI-1.8 | www/jquery-ui-1.10.3.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-he.min.js | JavaScript | gpl-3.0 | 934 |
package trust
import (
"crypto/x509"
"errors"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/docker/libtrust/trustgraph"
)
type TrustStore struct {
path string
caPool *x509.CertPool
graph trustgraph.TrustGraph
expiration time.Time
fetcher *time.Timer
fetchTime time.Duration
autofetch bool
httpClient *http.Client
baseEndpoints map[string]*url.URL
sync.RWMutex
}
// defaultFetchtime represents the starting duration to wait between
// fetching sections of the graph. Unsuccessful fetches should
// increase time between fetching.
const defaultFetchtime = 45 * time.Second
var baseEndpoints = map[string]string{"official": "https://dvjy3tqbc323p.cloudfront.net/trust/official.json"}
func NewTrustStore(path string) (*TrustStore, error) {
abspath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
// Create base graph url map
endpoints := map[string]*url.URL{}
for name, endpoint := range baseEndpoints {
u, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
endpoints[name] = u
}
// Load grant files
t := &TrustStore{
path: abspath,
caPool: nil,
httpClient: &http.Client{},
fetchTime: time.Millisecond,
baseEndpoints: endpoints,
}
if err := t.reload(); err != nil {
return nil, err
}
return t, nil
}
func (t *TrustStore) reload() error {
t.Lock()
defer t.Unlock()
matches, err := filepath.Glob(filepath.Join(t.path, "*.json"))
if err != nil {
return err
}
statements := make([]*trustgraph.Statement, len(matches))
for i, match := range matches {
f, err := os.Open(match)
if err != nil {
return err
}
statements[i], err = trustgraph.LoadStatement(f, nil)
if err != nil {
f.Close()
return err
}
f.Close()
}
if len(statements) == 0 {
if t.autofetch {
logrus.Debugf("No grants, fetching")
t.fetcher = time.AfterFunc(t.fetchTime, t.fetch)
}
return nil
}
grants, expiration, err := trustgraph.CollapseStatements(statements, true)
if err != nil {
return err
}
t.expiration = expiration
t.graph = trustgraph.NewMemoryGraph(grants)
logrus.Debugf("Reloaded graph with %d grants expiring at %s", len(grants), expiration)
if t.autofetch {
nextFetch := expiration.Sub(time.Now())
if nextFetch < 0 {
nextFetch = defaultFetchtime
} else {
nextFetch = time.Duration(0.8 * (float64)(nextFetch))
}
t.fetcher = time.AfterFunc(nextFetch, t.fetch)
}
return nil
}
func (t *TrustStore) fetchBaseGraph(u *url.URL) (*trustgraph.Statement, error) {
req := &http.Request{
Method: "GET",
URL: u,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
Body: nil,
Host: u.Host,
}
resp, err := t.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == 404 {
return nil, errors.New("base graph does not exist")
}
defer resp.Body.Close()
return trustgraph.LoadStatement(resp.Body, t.caPool)
}
// fetch retrieves updated base graphs. This function cannot error, it
// should only log errors
func (t *TrustStore) fetch() {
t.Lock()
defer t.Unlock()
if t.autofetch && t.fetcher == nil {
// Do nothing ??
return
}
fetchCount := 0
for bg, ep := range t.baseEndpoints {
statement, err := t.fetchBaseGraph(ep)
if err != nil {
logrus.Infof("Trust graph fetch failed: %s", err)
continue
}
b, err := statement.Bytes()
if err != nil {
logrus.Infof("Bad trust graph statement: %s", err)
continue
}
// TODO check if value differs
if err := ioutil.WriteFile(path.Join(t.path, bg+".json"), b, 0600); err != nil {
logrus.Infof("Error writing trust graph statement: %s", err)
}
fetchCount++
}
logrus.Debugf("Fetched %d base graphs at %s", fetchCount, time.Now())
if fetchCount > 0 {
go func() {
if err := t.reload(); err != nil {
logrus.Infof("Reload of trust graph failed: %s", err)
}
}()
t.fetchTime = defaultFetchtime
t.fetcher = nil
} else if t.autofetch {
maxTime := 10 * defaultFetchtime
t.fetchTime = time.Duration(1.5 * (float64)(t.fetchTime+time.Second))
if t.fetchTime > maxTime {
t.fetchTime = maxTime
}
t.fetcher = time.AfterFunc(t.fetchTime, t.fetch)
}
}
| rhuss/gofabric8 | vendor/github.com/docker/docker/trust/trusts.go | GO | apache-2.0 | 4,317 |
/*!
* Connect - cookieParser
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('./../utils')
, cookie = require('cookie');
/**
* Cookie parser:
*
* Parse _Cookie_ header and populate `req.cookies`
* with an object keyed by the cookie names. Optionally
* you may enabled signed cookie support by passing
* a `secret` string, which assigns `req.secret` so
* it may be used by other middleware.
*
* Examples:
*
* connect()
* .use(connect.cookieParser('optional secret string'))
* .use(function(req, res, next){
* res.end(JSON.stringify(req.cookies));
* })
*
* @param {String} secret
* @return {Function}
* @api public
*/
module.exports = function cookieParser(secret){
return function cookieParser(req, res, next) {
if (req.cookies) return next();
var cookies = req.headers.cookie;
req.secret = secret;
req.cookies = {};
req.signedCookies = {};
if (cookies) {
try {
req.cookies = cookie.parse(cookies);
if (secret) {
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
req.cookies = utils.parseJSONCookies(req.cookies);
} catch (err) {
err.status = 400;
return next(err);
}
}
next();
};
};
| BrowenChen/classroomDashboard | zzishwebsite/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js | JavaScript | mit | 1,440 |
YUI.add("lang/datatype-date-format_es-EC",function(a){a.Intl.add("datatype-date-format","es-EC",{"a":["dom","lun","mar","mié","jue","vie","sáb"],"A":["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],"b":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"B":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],"c":"%a, %d %b %Y %H:%M:%S %Z","p":["A.M.","P.M."],"P":["a.m.","p.m."],"x":"%d/%m/%y","X":"%H:%M:%S"});},"@VERSION@"); | BobbieBel/cdnjs | ajax/libs/yui/3.7.0pr1/datatype-date-format/lang/datatype-date-format_es-EC.js | JavaScript | mit | 537 |
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.datasource;
/**
* Base implementation of {@link DataSubscriber} that ensures that the data source is closed when
* the subscriber has finished with it.
* <p>
* Sample usage:
* <pre>
* <code>
* dataSource.subscribe(
* new BaseDataSubscriber() {
* {@literal @}Override
* public void onNewResultImpl(DataSource dataSource) {
* // Store image ref to be released later.
* mCloseableImageRef = dataSource.getResult();
* // Use the image.
* updateImage(mCloseableImageRef);
* // No need to do any cleanup of the data source.
* }
*
* {@literal @}Override
* public void onFailureImpl(DataSource dataSource) {
* // No cleanup of the data source required here.
* }
* });
* </code>
* </pre>
*/
public abstract class BaseDataSubscriber<T> implements DataSubscriber<T> {
@Override
public void onNewResult(DataSource<T> dataSource) {
try {
onNewResultImpl(dataSource);
} finally {
if (dataSource.isFinished()) {
dataSource.close();
}
}
}
@Override
public void onFailure(DataSource<T> dataSource) {
try {
onFailureImpl(dataSource);
} finally {
dataSource.close();
}
}
@Override
public void onCancellation(DataSource<T> dataSource) {
}
@Override
public void onProgressUpdate(DataSource<T> dataSource) {
}
protected abstract void onNewResultImpl(DataSource<T> dataSource);
protected abstract void onFailureImpl(DataSource<T> dataSource);
}
| ppamorim/fresco | fbcore/src/main/java/com/facebook/datasource/BaseDataSubscriber.java | Java | bsd-3-clause | 1,838 |
/**************************************************************************
*
* Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
/*
* Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
*/
#include "ttm/ttm_module.h"
#include "ttm/ttm_bo_driver.h"
#include "ttm/ttm_placement.h"
#include <linux/jiffies.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/file.h>
#include <linux/module.h>
#include <linux/atomic.h>
#define TTM_ASSERT_LOCKED(param)
#define TTM_DEBUG(fmt, arg...)
#define TTM_BO_HASH_ORDER 13
static int ttm_bo_setup_vm(struct ttm_buffer_object *bo);
static int ttm_bo_swapout(struct ttm_mem_shrink *shrink);
static void ttm_bo_global_kobj_release(struct kobject *kobj);
static struct attribute ttm_bo_count = {
.name = "bo_count",
.mode = S_IRUGO
};
static inline int ttm_mem_type_from_flags(uint32_t flags, uint32_t *mem_type)
{
int i;
for (i = 0; i <= TTM_PL_PRIV5; i++)
if (flags & (1 << i)) {
*mem_type = i;
return 0;
}
return -EINVAL;
}
static void ttm_mem_type_debug(struct ttm_bo_device *bdev, int mem_type)
{
struct ttm_mem_type_manager *man = &bdev->man[mem_type];
printk(KERN_ERR TTM_PFX " has_type: %d\n", man->has_type);
printk(KERN_ERR TTM_PFX " use_type: %d\n", man->use_type);
printk(KERN_ERR TTM_PFX " flags: 0x%08X\n", man->flags);
printk(KERN_ERR TTM_PFX " gpu_offset: 0x%08lX\n", man->gpu_offset);
printk(KERN_ERR TTM_PFX " size: %llu\n", man->size);
printk(KERN_ERR TTM_PFX " available_caching: 0x%08X\n",
man->available_caching);
printk(KERN_ERR TTM_PFX " default_caching: 0x%08X\n",
man->default_caching);
if (mem_type != TTM_PL_SYSTEM)
(*man->func->debug)(man, TTM_PFX);
}
static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
struct ttm_placement *placement)
{
int i, ret, mem_type;
printk(KERN_ERR TTM_PFX "No space for %p (%lu pages, %luK, %luM)\n",
bo, bo->mem.num_pages, bo->mem.size >> 10,
bo->mem.size >> 20);
for (i = 0; i < placement->num_placement; i++) {
ret = ttm_mem_type_from_flags(placement->placement[i],
&mem_type);
if (ret)
return;
printk(KERN_ERR TTM_PFX " placement[%d]=0x%08X (%d)\n",
i, placement->placement[i], mem_type);
ttm_mem_type_debug(bo->bdev, mem_type);
}
}
static ssize_t ttm_bo_global_show(struct kobject *kobj,
struct attribute *attr,
char *buffer)
{
struct ttm_bo_global *glob =
container_of(kobj, struct ttm_bo_global, kobj);
return snprintf(buffer, PAGE_SIZE, "%lu\n",
(unsigned long) atomic_read(&glob->bo_count));
}
static struct attribute *ttm_bo_global_attrs[] = {
&ttm_bo_count,
NULL
};
static const struct sysfs_ops ttm_bo_global_ops = {
.show = &ttm_bo_global_show
};
static struct kobj_type ttm_bo_glob_kobj_type = {
.release = &ttm_bo_global_kobj_release,
.sysfs_ops = &ttm_bo_global_ops,
.default_attrs = ttm_bo_global_attrs
};
static inline uint32_t ttm_bo_type_flags(unsigned type)
{
return 1 << (type);
}
static void ttm_bo_release_list(struct kref *list_kref)
{
struct ttm_buffer_object *bo =
container_of(list_kref, struct ttm_buffer_object, list_kref);
struct ttm_bo_device *bdev = bo->bdev;
BUG_ON(atomic_read(&bo->list_kref.refcount));
BUG_ON(atomic_read(&bo->kref.refcount));
BUG_ON(atomic_read(&bo->cpu_writers));
BUG_ON(bo->sync_obj != NULL);
BUG_ON(bo->mem.mm_node != NULL);
BUG_ON(!list_empty(&bo->lru));
BUG_ON(!list_empty(&bo->ddestroy));
if (bo->ttm)
ttm_tt_destroy(bo->ttm);
atomic_dec(&bo->glob->bo_count);
if (bo->destroy)
bo->destroy(bo);
else {
ttm_mem_global_free(bdev->glob->mem_glob, bo->acc_size);
kfree(bo);
}
}
int ttm_bo_wait_unreserved(struct ttm_buffer_object *bo, bool interruptible)
{
if (interruptible) {
return wait_event_interruptible(bo->event_queue,
atomic_read(&bo->reserved) == 0);
} else {
wait_event(bo->event_queue, atomic_read(&bo->reserved) == 0);
return 0;
}
}
EXPORT_SYMBOL(ttm_bo_wait_unreserved);
void ttm_bo_add_to_lru(struct ttm_buffer_object *bo)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_mem_type_manager *man;
BUG_ON(!atomic_read(&bo->reserved));
if (!(bo->mem.placement & TTM_PL_FLAG_NO_EVICT)) {
BUG_ON(!list_empty(&bo->lru));
man = &bdev->man[bo->mem.mem_type];
list_add_tail(&bo->lru, &man->lru);
kref_get(&bo->list_kref);
if (bo->ttm != NULL) {
list_add_tail(&bo->swap, &bo->glob->swap_lru);
kref_get(&bo->list_kref);
}
}
}
int ttm_bo_del_from_lru(struct ttm_buffer_object *bo)
{
int put_count = 0;
if (!list_empty(&bo->swap)) {
list_del_init(&bo->swap);
++put_count;
}
if (!list_empty(&bo->lru)) {
list_del_init(&bo->lru);
++put_count;
}
/*
* TODO: Add a driver hook to delete from
* driver-specific LRU's here.
*/
return put_count;
}
int ttm_bo_reserve_locked(struct ttm_buffer_object *bo,
bool interruptible,
bool no_wait, bool use_sequence, uint32_t sequence)
{
struct ttm_bo_global *glob = bo->glob;
int ret;
while (unlikely(atomic_cmpxchg(&bo->reserved, 0, 1) != 0)) {
/**
* Deadlock avoidance for multi-bo reserving.
*/
if (use_sequence && bo->seq_valid) {
/**
* We've already reserved this one.
*/
if (unlikely(sequence == bo->val_seq))
return -EDEADLK;
/**
* Already reserved by a thread that will not back
* off for us. We need to back off.
*/
if (unlikely(sequence - bo->val_seq < (1 << 31)))
return -EAGAIN;
}
if (no_wait)
return -EBUSY;
spin_unlock(&glob->lru_lock);
ret = ttm_bo_wait_unreserved(bo, interruptible);
spin_lock(&glob->lru_lock);
if (unlikely(ret))
return ret;
}
if (use_sequence) {
/**
* Wake up waiters that may need to recheck for deadlock,
* if we decreased the sequence number.
*/
if (unlikely((bo->val_seq - sequence < (1 << 31))
|| !bo->seq_valid))
wake_up_all(&bo->event_queue);
bo->val_seq = sequence;
bo->seq_valid = true;
} else {
bo->seq_valid = false;
}
return 0;
}
EXPORT_SYMBOL(ttm_bo_reserve);
static void ttm_bo_ref_bug(struct kref *list_kref)
{
BUG();
}
void ttm_bo_list_ref_sub(struct ttm_buffer_object *bo, int count,
bool never_free)
{
kref_sub(&bo->list_kref, count,
(never_free) ? ttm_bo_ref_bug : ttm_bo_release_list);
}
int ttm_bo_reserve(struct ttm_buffer_object *bo,
bool interruptible,
bool no_wait, bool use_sequence, uint32_t sequence)
{
struct ttm_bo_global *glob = bo->glob;
int put_count = 0;
int ret;
spin_lock(&glob->lru_lock);
ret = ttm_bo_reserve_locked(bo, interruptible, no_wait, use_sequence,
sequence);
if (likely(ret == 0))
put_count = ttm_bo_del_from_lru(bo);
spin_unlock(&glob->lru_lock);
ttm_bo_list_ref_sub(bo, put_count, true);
return ret;
}
void ttm_bo_unreserve_locked(struct ttm_buffer_object *bo)
{
ttm_bo_add_to_lru(bo);
atomic_set(&bo->reserved, 0);
wake_up_all(&bo->event_queue);
}
void ttm_bo_unreserve(struct ttm_buffer_object *bo)
{
struct ttm_bo_global *glob = bo->glob;
spin_lock(&glob->lru_lock);
ttm_bo_unreserve_locked(bo);
spin_unlock(&glob->lru_lock);
}
EXPORT_SYMBOL(ttm_bo_unreserve);
/*
* Call bo->mutex locked.
*/
static int ttm_bo_add_ttm(struct ttm_buffer_object *bo, bool zero_alloc)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_bo_global *glob = bo->glob;
int ret = 0;
uint32_t page_flags = 0;
TTM_ASSERT_LOCKED(&bo->mutex);
bo->ttm = NULL;
if (bdev->need_dma32)
page_flags |= TTM_PAGE_FLAG_DMA32;
switch (bo->type) {
case ttm_bo_type_device:
if (zero_alloc)
page_flags |= TTM_PAGE_FLAG_ZERO_ALLOC;
case ttm_bo_type_kernel:
bo->ttm = ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT,
page_flags, glob->dummy_read_page);
if (unlikely(bo->ttm == NULL))
ret = -ENOMEM;
break;
case ttm_bo_type_user:
bo->ttm = ttm_tt_create(bdev, bo->num_pages << PAGE_SHIFT,
page_flags | TTM_PAGE_FLAG_USER,
glob->dummy_read_page);
if (unlikely(bo->ttm == NULL)) {
ret = -ENOMEM;
break;
}
ret = ttm_tt_set_user(bo->ttm, current,
bo->buffer_start, bo->num_pages);
if (unlikely(ret != 0)) {
ttm_tt_destroy(bo->ttm);
bo->ttm = NULL;
}
break;
default:
printk(KERN_ERR TTM_PFX "Illegal buffer object type\n");
ret = -EINVAL;
break;
}
return ret;
}
static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
struct ttm_mem_reg *mem,
bool evict, bool interruptible,
bool no_wait_reserve, bool no_wait_gpu)
{
struct ttm_bo_device *bdev = bo->bdev;
bool old_is_pci = ttm_mem_reg_is_pci(bdev, &bo->mem);
bool new_is_pci = ttm_mem_reg_is_pci(bdev, mem);
struct ttm_mem_type_manager *old_man = &bdev->man[bo->mem.mem_type];
struct ttm_mem_type_manager *new_man = &bdev->man[mem->mem_type];
int ret = 0;
if (old_is_pci || new_is_pci ||
((mem->placement & bo->mem.placement & TTM_PL_MASK_CACHING) == 0)) {
ret = ttm_mem_io_lock(old_man, true);
if (unlikely(ret != 0))
goto out_err;
ttm_bo_unmap_virtual_locked(bo);
ttm_mem_io_unlock(old_man);
}
/*
* Create and bind a ttm if required.
*/
if (!(new_man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
if (bo->ttm == NULL) {
bool zero = !(old_man->flags & TTM_MEMTYPE_FLAG_FIXED);
ret = ttm_bo_add_ttm(bo, zero);
if (ret)
goto out_err;
}
ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement);
if (ret)
goto out_err;
if (mem->mem_type != TTM_PL_SYSTEM) {
ret = ttm_tt_bind(bo->ttm, mem);
if (ret)
goto out_err;
}
if (bo->mem.mem_type == TTM_PL_SYSTEM) {
if (bdev->driver->move_notify)
bdev->driver->move_notify(bo, mem);
bo->mem = *mem;
mem->mm_node = NULL;
goto moved;
}
}
if (bdev->driver->move_notify)
bdev->driver->move_notify(bo, mem);
if (!(old_man->flags & TTM_MEMTYPE_FLAG_FIXED) &&
!(new_man->flags & TTM_MEMTYPE_FLAG_FIXED))
ret = ttm_bo_move_ttm(bo, evict, no_wait_reserve, no_wait_gpu, mem);
else if (bdev->driver->move)
ret = bdev->driver->move(bo, evict, interruptible,
no_wait_reserve, no_wait_gpu, mem);
else
ret = ttm_bo_move_memcpy(bo, evict, no_wait_reserve, no_wait_gpu, mem);
if (ret)
goto out_err;
moved:
if (bo->evicted) {
ret = bdev->driver->invalidate_caches(bdev, bo->mem.placement);
if (ret)
printk(KERN_ERR TTM_PFX "Can not flush read caches\n");
bo->evicted = false;
}
if (bo->mem.mm_node) {
bo->offset = (bo->mem.start << PAGE_SHIFT) +
bdev->man[bo->mem.mem_type].gpu_offset;
bo->cur_placement = bo->mem.placement;
} else
bo->offset = 0;
return 0;
out_err:
new_man = &bdev->man[bo->mem.mem_type];
if ((new_man->flags & TTM_MEMTYPE_FLAG_FIXED) && bo->ttm) {
ttm_tt_unbind(bo->ttm);
ttm_tt_destroy(bo->ttm);
bo->ttm = NULL;
}
return ret;
}
/**
* Call bo::reserved.
* Will release GPU memory type usage on destruction.
* This is the place to put in driver specific hooks to release
* driver private resources.
* Will release the bo::reserved lock.
*/
static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
{
if (bo->ttm) {
ttm_tt_unbind(bo->ttm);
ttm_tt_destroy(bo->ttm);
bo->ttm = NULL;
}
ttm_bo_mem_put(bo, &bo->mem);
atomic_set(&bo->reserved, 0);
/*
* Make processes trying to reserve really pick it up.
*/
smp_mb__after_atomic_dec();
wake_up_all(&bo->event_queue);
}
static void ttm_bo_cleanup_refs_or_queue(struct ttm_buffer_object *bo)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_bo_global *glob = bo->glob;
struct ttm_bo_driver *driver;
void *sync_obj = NULL;
void *sync_obj_arg;
int put_count;
int ret;
spin_lock(&bdev->fence_lock);
(void) ttm_bo_wait(bo, false, false, true);
if (!bo->sync_obj) {
spin_lock(&glob->lru_lock);
/**
* Lock inversion between bo:reserve and bdev::fence_lock here,
* but that's OK, since we're only trylocking.
*/
ret = ttm_bo_reserve_locked(bo, false, true, false, 0);
if (unlikely(ret == -EBUSY))
goto queue;
spin_unlock(&bdev->fence_lock);
put_count = ttm_bo_del_from_lru(bo);
spin_unlock(&glob->lru_lock);
ttm_bo_cleanup_memtype_use(bo);
ttm_bo_list_ref_sub(bo, put_count, true);
return;
} else {
spin_lock(&glob->lru_lock);
}
queue:
driver = bdev->driver;
if (bo->sync_obj)
sync_obj = driver->sync_obj_ref(bo->sync_obj);
sync_obj_arg = bo->sync_obj_arg;
kref_get(&bo->list_kref);
list_add_tail(&bo->ddestroy, &bdev->ddestroy);
spin_unlock(&glob->lru_lock);
spin_unlock(&bdev->fence_lock);
if (sync_obj) {
driver->sync_obj_flush(sync_obj, sync_obj_arg);
driver->sync_obj_unref(&sync_obj);
}
schedule_delayed_work(&bdev->wq,
((HZ / 100) < 1) ? 1 : HZ / 100);
}
/**
* function ttm_bo_cleanup_refs
* If bo idle, remove from delayed- and lru lists, and unref.
* If not idle, do nothing.
*
* @interruptible Any sleeps should occur interruptibly.
* @no_wait_reserve Never wait for reserve. Return -EBUSY instead.
* @no_wait_gpu Never wait for gpu. Return -EBUSY instead.
*/
static int ttm_bo_cleanup_refs(struct ttm_buffer_object *bo,
bool interruptible,
bool no_wait_reserve,
bool no_wait_gpu)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_bo_global *glob = bo->glob;
int put_count;
int ret = 0;
retry:
spin_lock(&bdev->fence_lock);
ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
spin_unlock(&bdev->fence_lock);
if (unlikely(ret != 0))
return ret;
spin_lock(&glob->lru_lock);
ret = ttm_bo_reserve_locked(bo, interruptible,
no_wait_reserve, false, 0);
if (unlikely(ret != 0) || list_empty(&bo->ddestroy)) {
spin_unlock(&glob->lru_lock);
return ret;
}
/**
* We can re-check for sync object without taking
* the bo::lock since setting the sync object requires
* also bo::reserved. A busy object at this point may
* be caused by another thread recently starting an accelerated
* eviction.
*/
if (unlikely(bo->sync_obj)) {
atomic_set(&bo->reserved, 0);
wake_up_all(&bo->event_queue);
spin_unlock(&glob->lru_lock);
goto retry;
}
put_count = ttm_bo_del_from_lru(bo);
list_del_init(&bo->ddestroy);
++put_count;
spin_unlock(&glob->lru_lock);
ttm_bo_cleanup_memtype_use(bo);
ttm_bo_list_ref_sub(bo, put_count, true);
return 0;
}
/**
* Traverse the delayed list, and call ttm_bo_cleanup_refs on all
* encountered buffers.
*/
static int ttm_bo_delayed_delete(struct ttm_bo_device *bdev, bool remove_all)
{
struct ttm_bo_global *glob = bdev->glob;
struct ttm_buffer_object *entry = NULL;
int ret = 0;
spin_lock(&glob->lru_lock);
if (list_empty(&bdev->ddestroy))
goto out_unlock;
entry = list_first_entry(&bdev->ddestroy,
struct ttm_buffer_object, ddestroy);
kref_get(&entry->list_kref);
for (;;) {
struct ttm_buffer_object *nentry = NULL;
if (entry->ddestroy.next != &bdev->ddestroy) {
nentry = list_first_entry(&entry->ddestroy,
struct ttm_buffer_object, ddestroy);
kref_get(&nentry->list_kref);
}
spin_unlock(&glob->lru_lock);
ret = ttm_bo_cleanup_refs(entry, false, !remove_all,
!remove_all);
kref_put(&entry->list_kref, ttm_bo_release_list);
entry = nentry;
if (ret || !entry)
goto out;
spin_lock(&glob->lru_lock);
if (list_empty(&entry->ddestroy))
break;
}
out_unlock:
spin_unlock(&glob->lru_lock);
out:
if (entry)
kref_put(&entry->list_kref, ttm_bo_release_list);
return ret;
}
static void ttm_bo_delayed_workqueue(struct work_struct *work)
{
struct ttm_bo_device *bdev =
container_of(work, struct ttm_bo_device, wq.work);
if (ttm_bo_delayed_delete(bdev, false)) {
schedule_delayed_work(&bdev->wq,
((HZ / 100) < 1) ? 1 : HZ / 100);
}
}
static void ttm_bo_release(struct kref *kref)
{
struct ttm_buffer_object *bo =
container_of(kref, struct ttm_buffer_object, kref);
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
if (likely(bo->vm_node != NULL)) {
rb_erase(&bo->vm_rb, &bdev->addr_space_rb);
drm_mm_put_block(bo->vm_node);
bo->vm_node = NULL;
}
write_unlock(&bdev->vm_lock);
ttm_mem_io_lock(man, false);
ttm_mem_io_free_vm(bo);
ttm_mem_io_unlock(man);
ttm_bo_cleanup_refs_or_queue(bo);
kref_put(&bo->list_kref, ttm_bo_release_list);
write_lock(&bdev->vm_lock);
}
void ttm_bo_unref(struct ttm_buffer_object **p_bo)
{
struct ttm_buffer_object *bo = *p_bo;
struct ttm_bo_device *bdev = bo->bdev;
*p_bo = NULL;
write_lock(&bdev->vm_lock);
kref_put(&bo->kref, ttm_bo_release);
write_unlock(&bdev->vm_lock);
}
EXPORT_SYMBOL(ttm_bo_unref);
int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev)
{
return cancel_delayed_work_sync(&bdev->wq);
}
EXPORT_SYMBOL(ttm_bo_lock_delayed_workqueue);
void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched)
{
if (resched)
schedule_delayed_work(&bdev->wq,
((HZ / 100) < 1) ? 1 : HZ / 100);
}
EXPORT_SYMBOL(ttm_bo_unlock_delayed_workqueue);
static int ttm_bo_evict(struct ttm_buffer_object *bo, bool interruptible,
bool no_wait_reserve, bool no_wait_gpu)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_mem_reg evict_mem;
struct ttm_placement placement;
int ret = 0;
spin_lock(&bdev->fence_lock);
ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
spin_unlock(&bdev->fence_lock);
if (unlikely(ret != 0)) {
if (ret != -ERESTARTSYS) {
printk(KERN_ERR TTM_PFX
"Failed to expire sync object before "
"buffer eviction.\n");
}
goto out;
}
BUG_ON(!atomic_read(&bo->reserved));
evict_mem = bo->mem;
evict_mem.mm_node = NULL;
evict_mem.bus.io_reserved_vm = false;
evict_mem.bus.io_reserved_count = 0;
placement.fpfn = 0;
placement.lpfn = 0;
placement.num_placement = 0;
placement.num_busy_placement = 0;
bdev->driver->evict_flags(bo, &placement);
ret = ttm_bo_mem_space(bo, &placement, &evict_mem, interruptible,
no_wait_reserve, no_wait_gpu);
if (ret) {
if (ret != -ERESTARTSYS) {
printk(KERN_ERR TTM_PFX
"Failed to find memory space for "
"buffer 0x%p eviction.\n", bo);
ttm_bo_mem_space_debug(bo, &placement);
}
goto out;
}
ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, interruptible,
no_wait_reserve, no_wait_gpu);
if (ret) {
if (ret != -ERESTARTSYS)
printk(KERN_ERR TTM_PFX "Buffer eviction failed\n");
ttm_bo_mem_put(bo, &evict_mem);
goto out;
}
bo->evicted = true;
out:
return ret;
}
static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
uint32_t mem_type,
bool interruptible, bool no_wait_reserve,
bool no_wait_gpu)
{
struct ttm_bo_global *glob = bdev->glob;
struct ttm_mem_type_manager *man = &bdev->man[mem_type];
struct ttm_buffer_object *bo;
int ret, put_count = 0;
retry:
spin_lock(&glob->lru_lock);
if (list_empty(&man->lru)) {
spin_unlock(&glob->lru_lock);
return -EBUSY;
}
bo = list_first_entry(&man->lru, struct ttm_buffer_object, lru);
kref_get(&bo->list_kref);
if (!list_empty(&bo->ddestroy)) {
spin_unlock(&glob->lru_lock);
ret = ttm_bo_cleanup_refs(bo, interruptible,
no_wait_reserve, no_wait_gpu);
kref_put(&bo->list_kref, ttm_bo_release_list);
if (likely(ret == 0 || ret == -ERESTARTSYS))
return ret;
goto retry;
}
ret = ttm_bo_reserve_locked(bo, false, no_wait_reserve, false, 0);
if (unlikely(ret == -EBUSY)) {
spin_unlock(&glob->lru_lock);
if (likely(!no_wait_gpu))
ret = ttm_bo_wait_unreserved(bo, interruptible);
kref_put(&bo->list_kref, ttm_bo_release_list);
/**
* We *need* to retry after releasing the lru lock.
*/
if (unlikely(ret != 0))
return ret;
goto retry;
}
put_count = ttm_bo_del_from_lru(bo);
spin_unlock(&glob->lru_lock);
BUG_ON(ret != 0);
ttm_bo_list_ref_sub(bo, put_count, true);
ret = ttm_bo_evict(bo, interruptible, no_wait_reserve, no_wait_gpu);
ttm_bo_unreserve(bo);
kref_put(&bo->list_kref, ttm_bo_release_list);
return ret;
}
void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem)
{
struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
if (mem->mm_node)
(*man->func->put_node)(man, mem);
}
EXPORT_SYMBOL(ttm_bo_mem_put);
/**
* Repeatedly evict memory from the LRU for @mem_type until we create enough
* space, or we've evicted everything and there isn't enough space.
*/
static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
uint32_t mem_type,
struct ttm_placement *placement,
struct ttm_mem_reg *mem,
bool interruptible,
bool no_wait_reserve,
bool no_wait_gpu)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_mem_type_manager *man = &bdev->man[mem_type];
int ret;
do {
ret = (*man->func->get_node)(man, bo, placement, mem);
if (unlikely(ret != 0))
return ret;
if (mem->mm_node)
break;
ret = ttm_mem_evict_first(bdev, mem_type, interruptible,
no_wait_reserve, no_wait_gpu);
if (unlikely(ret != 0))
return ret;
} while (1);
if (mem->mm_node == NULL)
return -ENOMEM;
mem->mem_type = mem_type;
return 0;
}
static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
uint32_t cur_placement,
uint32_t proposed_placement)
{
uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
/**
* Keep current caching if possible.
*/
if ((cur_placement & caching) != 0)
result |= (cur_placement & caching);
else if ((man->default_caching & caching) != 0)
result |= man->default_caching;
else if ((TTM_PL_FLAG_CACHED & caching) != 0)
result |= TTM_PL_FLAG_CACHED;
else if ((TTM_PL_FLAG_WC & caching) != 0)
result |= TTM_PL_FLAG_WC;
else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
result |= TTM_PL_FLAG_UNCACHED;
return result;
}
static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
bool disallow_fixed,
uint32_t mem_type,
uint32_t proposed_placement,
uint32_t *masked_placement)
{
uint32_t cur_flags = ttm_bo_type_flags(mem_type);
if ((man->flags & TTM_MEMTYPE_FLAG_FIXED) && disallow_fixed)
return false;
if ((cur_flags & proposed_placement & TTM_PL_MASK_MEM) == 0)
return false;
if ((proposed_placement & man->available_caching) == 0)
return false;
cur_flags |= (proposed_placement & man->available_caching);
*masked_placement = cur_flags;
return true;
}
/**
* Creates space for memory region @mem according to its type.
*
* This function first searches for free space in compatible memory types in
* the priority order defined by the driver. If free space isn't found, then
* ttm_bo_mem_force_space is attempted in priority order to evict and find
* space.
*/
int ttm_bo_mem_space(struct ttm_buffer_object *bo,
struct ttm_placement *placement,
struct ttm_mem_reg *mem,
bool interruptible, bool no_wait_reserve,
bool no_wait_gpu)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_mem_type_manager *man;
uint32_t mem_type = TTM_PL_SYSTEM;
uint32_t cur_flags = 0;
bool type_found = false;
bool type_ok = false;
bool has_erestartsys = false;
int i, ret;
mem->mm_node = NULL;
for (i = 0; i < placement->num_placement; ++i) {
ret = ttm_mem_type_from_flags(placement->placement[i],
&mem_type);
if (ret)
return ret;
man = &bdev->man[mem_type];
type_ok = ttm_bo_mt_compatible(man,
bo->type == ttm_bo_type_user,
mem_type,
placement->placement[i],
&cur_flags);
if (!type_ok)
continue;
cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
cur_flags);
/*
* Use the access and other non-mapping-related flag bits from
* the memory placement flags to the current flags
*/
ttm_flag_masked(&cur_flags, placement->placement[i],
~TTM_PL_MASK_MEMTYPE);
if (mem_type == TTM_PL_SYSTEM)
break;
if (man->has_type && man->use_type) {
type_found = true;
ret = (*man->func->get_node)(man, bo, placement, mem);
if (unlikely(ret))
return ret;
}
if (mem->mm_node)
break;
}
if ((type_ok && (mem_type == TTM_PL_SYSTEM)) || mem->mm_node) {
mem->mem_type = mem_type;
mem->placement = cur_flags;
return 0;
}
if (!type_found)
return -EINVAL;
for (i = 0; i < placement->num_busy_placement; ++i) {
ret = ttm_mem_type_from_flags(placement->busy_placement[i],
&mem_type);
if (ret)
return ret;
man = &bdev->man[mem_type];
if (!man->has_type)
continue;
if (!ttm_bo_mt_compatible(man,
bo->type == ttm_bo_type_user,
mem_type,
placement->busy_placement[i],
&cur_flags))
continue;
cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
cur_flags);
/*
* Use the access and other non-mapping-related flag bits from
* the memory placement flags to the current flags
*/
ttm_flag_masked(&cur_flags, placement->busy_placement[i],
~TTM_PL_MASK_MEMTYPE);
if (mem_type == TTM_PL_SYSTEM) {
mem->mem_type = mem_type;
mem->placement = cur_flags;
mem->mm_node = NULL;
return 0;
}
ret = ttm_bo_mem_force_space(bo, mem_type, placement, mem,
interruptible, no_wait_reserve, no_wait_gpu);
if (ret == 0 && mem->mm_node) {
mem->placement = cur_flags;
return 0;
}
if (ret == -ERESTARTSYS)
has_erestartsys = true;
}
ret = (has_erestartsys) ? -ERESTARTSYS : -ENOMEM;
return ret;
}
EXPORT_SYMBOL(ttm_bo_mem_space);
int ttm_bo_wait_cpu(struct ttm_buffer_object *bo, bool no_wait)
{
if ((atomic_read(&bo->cpu_writers) > 0) && no_wait)
return -EBUSY;
return wait_event_interruptible(bo->event_queue,
atomic_read(&bo->cpu_writers) == 0);
}
EXPORT_SYMBOL(ttm_bo_wait_cpu);
int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
struct ttm_placement *placement,
bool interruptible, bool no_wait_reserve,
bool no_wait_gpu)
{
int ret = 0;
struct ttm_mem_reg mem;
struct ttm_bo_device *bdev = bo->bdev;
BUG_ON(!atomic_read(&bo->reserved));
/*
* FIXME: It's possible to pipeline buffer moves.
* Have the driver move function wait for idle when necessary,
* instead of doing it here.
*/
spin_lock(&bdev->fence_lock);
ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
spin_unlock(&bdev->fence_lock);
if (ret)
return ret;
mem.num_pages = bo->num_pages;
mem.size = mem.num_pages << PAGE_SHIFT;
mem.page_alignment = bo->mem.page_alignment;
mem.bus.io_reserved_vm = false;
mem.bus.io_reserved_count = 0;
/*
* Determine where to move the buffer.
*/
ret = ttm_bo_mem_space(bo, placement, &mem, interruptible, no_wait_reserve, no_wait_gpu);
if (ret)
goto out_unlock;
ret = ttm_bo_handle_move_mem(bo, &mem, false, interruptible, no_wait_reserve, no_wait_gpu);
out_unlock:
if (ret && mem.mm_node)
ttm_bo_mem_put(bo, &mem);
return ret;
}
static int ttm_bo_mem_compat(struct ttm_placement *placement,
struct ttm_mem_reg *mem)
{
int i;
if (mem->mm_node && placement->lpfn != 0 &&
(mem->start < placement->fpfn ||
mem->start + mem->num_pages > placement->lpfn))
return -1;
for (i = 0; i < placement->num_placement; i++) {
if ((placement->placement[i] & mem->placement &
TTM_PL_MASK_CACHING) &&
(placement->placement[i] & mem->placement &
TTM_PL_MASK_MEM))
return i;
}
return -1;
}
int ttm_bo_validate(struct ttm_buffer_object *bo,
struct ttm_placement *placement,
bool interruptible, bool no_wait_reserve,
bool no_wait_gpu)
{
int ret;
BUG_ON(!atomic_read(&bo->reserved));
/* Check that range is valid */
if (placement->lpfn || placement->fpfn)
if (placement->fpfn > placement->lpfn ||
(placement->lpfn - placement->fpfn) < bo->num_pages)
return -EINVAL;
/*
* Check whether we need to move buffer.
*/
ret = ttm_bo_mem_compat(placement, &bo->mem);
if (ret < 0) {
ret = ttm_bo_move_buffer(bo, placement, interruptible, no_wait_reserve, no_wait_gpu);
if (ret)
return ret;
} else {
/*
* Use the access and other non-mapping-related flag bits from
* the compatible memory placement flags to the active flags
*/
ttm_flag_masked(&bo->mem.placement, placement->placement[ret],
~TTM_PL_MASK_MEMTYPE);
}
/*
* We might need to add a TTM.
*/
if (bo->mem.mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
ret = ttm_bo_add_ttm(bo, true);
if (ret)
return ret;
}
return 0;
}
EXPORT_SYMBOL(ttm_bo_validate);
int ttm_bo_check_placement(struct ttm_buffer_object *bo,
struct ttm_placement *placement)
{
BUG_ON((placement->fpfn || placement->lpfn) &&
(bo->mem.num_pages > (placement->lpfn - placement->fpfn)));
return 0;
}
int ttm_bo_init(struct ttm_bo_device *bdev,
struct ttm_buffer_object *bo,
unsigned long size,
enum ttm_bo_type type,
struct ttm_placement *placement,
uint32_t page_alignment,
unsigned long buffer_start,
bool interruptible,
struct file *persistent_swap_storage,
size_t acc_size,
void (*destroy) (struct ttm_buffer_object *))
{
int ret = 0;
unsigned long num_pages;
size += buffer_start & ~PAGE_MASK;
num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
if (num_pages == 0) {
printk(KERN_ERR TTM_PFX "Illegal buffer object size.\n");
if (destroy)
(*destroy)(bo);
else
kfree(bo);
return -EINVAL;
}
bo->destroy = destroy;
kref_init(&bo->kref);
kref_init(&bo->list_kref);
atomic_set(&bo->cpu_writers, 0);
atomic_set(&bo->reserved, 1);
init_waitqueue_head(&bo->event_queue);
INIT_LIST_HEAD(&bo->lru);
INIT_LIST_HEAD(&bo->ddestroy);
INIT_LIST_HEAD(&bo->swap);
INIT_LIST_HEAD(&bo->io_reserve_lru);
bo->bdev = bdev;
bo->glob = bdev->glob;
bo->type = type;
bo->num_pages = num_pages;
bo->mem.size = num_pages << PAGE_SHIFT;
bo->mem.mem_type = TTM_PL_SYSTEM;
bo->mem.num_pages = bo->num_pages;
bo->mem.mm_node = NULL;
bo->mem.page_alignment = page_alignment;
bo->mem.bus.io_reserved_vm = false;
bo->mem.bus.io_reserved_count = 0;
bo->buffer_start = buffer_start & PAGE_MASK;
bo->priv_flags = 0;
bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
bo->seq_valid = false;
bo->persistent_swap_storage = persistent_swap_storage;
bo->acc_size = acc_size;
atomic_inc(&bo->glob->bo_count);
ret = ttm_bo_check_placement(bo, placement);
if (unlikely(ret != 0))
goto out_err;
/*
* For ttm_bo_type_device buffers, allocate
* address space from the device.
*/
if (bo->type == ttm_bo_type_device) {
ret = ttm_bo_setup_vm(bo);
if (ret)
goto out_err;
}
ret = ttm_bo_validate(bo, placement, interruptible, false, false);
if (ret)
goto out_err;
ttm_bo_unreserve(bo);
return 0;
out_err:
ttm_bo_unreserve(bo);
ttm_bo_unref(&bo);
return ret;
}
EXPORT_SYMBOL(ttm_bo_init);
static inline size_t ttm_bo_size(struct ttm_bo_global *glob,
unsigned long num_pages)
{
size_t page_array_size = (num_pages * sizeof(void *) + PAGE_SIZE - 1) &
PAGE_MASK;
return glob->ttm_bo_size + 2 * page_array_size;
}
int ttm_bo_create(struct ttm_bo_device *bdev,
unsigned long size,
enum ttm_bo_type type,
struct ttm_placement *placement,
uint32_t page_alignment,
unsigned long buffer_start,
bool interruptible,
struct file *persistent_swap_storage,
struct ttm_buffer_object **p_bo)
{
struct ttm_buffer_object *bo;
struct ttm_mem_global *mem_glob = bdev->glob->mem_glob;
int ret;
size_t acc_size =
ttm_bo_size(bdev->glob, (size + PAGE_SIZE - 1) >> PAGE_SHIFT);
ret = ttm_mem_global_alloc(mem_glob, acc_size, false, false);
if (unlikely(ret != 0))
return ret;
bo = kzalloc(sizeof(*bo), GFP_KERNEL);
if (unlikely(bo == NULL)) {
ttm_mem_global_free(mem_glob, acc_size);
return -ENOMEM;
}
ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
buffer_start, interruptible,
persistent_swap_storage, acc_size, NULL);
if (likely(ret == 0))
*p_bo = bo;
return ret;
}
static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
unsigned mem_type, bool allow_errors)
{
struct ttm_mem_type_manager *man = &bdev->man[mem_type];
struct ttm_bo_global *glob = bdev->glob;
int ret;
/*
* Can't use standard list traversal since we're unlocking.
*/
spin_lock(&glob->lru_lock);
while (!list_empty(&man->lru)) {
spin_unlock(&glob->lru_lock);
ret = ttm_mem_evict_first(bdev, mem_type, false, false, false);
if (ret) {
if (allow_errors) {
return ret;
} else {
printk(KERN_ERR TTM_PFX
"Cleanup eviction failed\n");
}
}
spin_lock(&glob->lru_lock);
}
spin_unlock(&glob->lru_lock);
return 0;
}
int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
{
struct ttm_mem_type_manager *man;
int ret = -EINVAL;
if (mem_type >= TTM_NUM_MEM_TYPES) {
printk(KERN_ERR TTM_PFX "Illegal memory type %d\n", mem_type);
return ret;
}
man = &bdev->man[mem_type];
if (!man->has_type) {
printk(KERN_ERR TTM_PFX "Trying to take down uninitialized "
"memory manager type %u\n", mem_type);
return ret;
}
man->use_type = false;
man->has_type = false;
ret = 0;
if (mem_type > 0) {
ttm_bo_force_list_clean(bdev, mem_type, false);
ret = (*man->func->takedown)(man);
}
return ret;
}
EXPORT_SYMBOL(ttm_bo_clean_mm);
int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
{
struct ttm_mem_type_manager *man = &bdev->man[mem_type];
if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
printk(KERN_ERR TTM_PFX
"Illegal memory manager memory type %u.\n",
mem_type);
return -EINVAL;
}
if (!man->has_type) {
printk(KERN_ERR TTM_PFX
"Memory type %u has not been initialized.\n",
mem_type);
return 0;
}
return ttm_bo_force_list_clean(bdev, mem_type, true);
}
EXPORT_SYMBOL(ttm_bo_evict_mm);
int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
unsigned long p_size)
{
int ret = -EINVAL;
struct ttm_mem_type_manager *man;
BUG_ON(type >= TTM_NUM_MEM_TYPES);
man = &bdev->man[type];
BUG_ON(man->has_type);
man->io_reserve_fastpath = true;
man->use_io_reserve_lru = false;
mutex_init(&man->io_reserve_mutex);
INIT_LIST_HEAD(&man->io_reserve_lru);
ret = bdev->driver->init_mem_type(bdev, type, man);
if (ret)
return ret;
man->bdev = bdev;
ret = 0;
if (type != TTM_PL_SYSTEM) {
ret = (*man->func->init)(man, p_size);
if (ret)
return ret;
}
man->has_type = true;
man->use_type = true;
man->size = p_size;
INIT_LIST_HEAD(&man->lru);
return 0;
}
EXPORT_SYMBOL(ttm_bo_init_mm);
static void ttm_bo_global_kobj_release(struct kobject *kobj)
{
struct ttm_bo_global *glob =
container_of(kobj, struct ttm_bo_global, kobj);
ttm_mem_unregister_shrink(glob->mem_glob, &glob->shrink);
__free_page(glob->dummy_read_page);
kfree(glob);
}
void ttm_bo_global_release(struct drm_global_reference *ref)
{
struct ttm_bo_global *glob = ref->object;
kobject_del(&glob->kobj);
kobject_put(&glob->kobj);
}
EXPORT_SYMBOL(ttm_bo_global_release);
int ttm_bo_global_init(struct drm_global_reference *ref)
{
struct ttm_bo_global_ref *bo_ref =
container_of(ref, struct ttm_bo_global_ref, ref);
struct ttm_bo_global *glob = ref->object;
int ret;
mutex_init(&glob->device_list_mutex);
spin_lock_init(&glob->lru_lock);
glob->mem_glob = bo_ref->mem_glob;
glob->dummy_read_page = alloc_page(__GFP_ZERO | GFP_DMA32);
if (unlikely(glob->dummy_read_page == NULL)) {
ret = -ENOMEM;
goto out_no_drp;
}
INIT_LIST_HEAD(&glob->swap_lru);
INIT_LIST_HEAD(&glob->device_list);
ttm_mem_init_shrink(&glob->shrink, ttm_bo_swapout);
ret = ttm_mem_register_shrink(glob->mem_glob, &glob->shrink);
if (unlikely(ret != 0)) {
printk(KERN_ERR TTM_PFX
"Could not register buffer object swapout.\n");
goto out_no_shrink;
}
glob->ttm_bo_extra_size =
ttm_round_pot(sizeof(struct ttm_tt)) +
ttm_round_pot(sizeof(struct ttm_backend));
glob->ttm_bo_size = glob->ttm_bo_extra_size +
ttm_round_pot(sizeof(struct ttm_buffer_object));
atomic_set(&glob->bo_count, 0);
ret = kobject_init_and_add(
&glob->kobj, &ttm_bo_glob_kobj_type, ttm_get_kobj(), "buffer_objects");
if (unlikely(ret != 0))
kobject_put(&glob->kobj);
return ret;
out_no_shrink:
__free_page(glob->dummy_read_page);
out_no_drp:
kfree(glob);
return ret;
}
EXPORT_SYMBOL(ttm_bo_global_init);
int ttm_bo_device_release(struct ttm_bo_device *bdev)
{
int ret = 0;
unsigned i = TTM_NUM_MEM_TYPES;
struct ttm_mem_type_manager *man;
struct ttm_bo_global *glob = bdev->glob;
while (i--) {
man = &bdev->man[i];
if (man->has_type) {
man->use_type = false;
if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
ret = -EBUSY;
printk(KERN_ERR TTM_PFX
"DRM memory manager type %d "
"is not clean.\n", i);
}
man->has_type = false;
}
}
mutex_lock(&glob->device_list_mutex);
list_del(&bdev->device_list);
mutex_unlock(&glob->device_list_mutex);
cancel_delayed_work_sync(&bdev->wq);
while (ttm_bo_delayed_delete(bdev, true))
;
spin_lock(&glob->lru_lock);
if (list_empty(&bdev->ddestroy))
TTM_DEBUG("Delayed destroy list was clean\n");
if (list_empty(&bdev->man[0].lru))
TTM_DEBUG("Swap list was clean\n");
spin_unlock(&glob->lru_lock);
BUG_ON(!drm_mm_clean(&bdev->addr_space_mm));
write_lock(&bdev->vm_lock);
drm_mm_takedown(&bdev->addr_space_mm);
write_unlock(&bdev->vm_lock);
return ret;
}
EXPORT_SYMBOL(ttm_bo_device_release);
int ttm_bo_device_init(struct ttm_bo_device *bdev,
struct ttm_bo_global *glob,
struct ttm_bo_driver *driver,
uint64_t file_page_offset,
bool need_dma32)
{
int ret = -EINVAL;
rwlock_init(&bdev->vm_lock);
bdev->driver = driver;
memset(bdev->man, 0, sizeof(bdev->man));
/*
* Initialize the system memory buffer type.
* Other types need to be driver / IOCTL initialized.
*/
ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
if (unlikely(ret != 0))
goto out_no_sys;
bdev->addr_space_rb = RB_ROOT;
ret = drm_mm_init(&bdev->addr_space_mm, file_page_offset, 0x10000000);
if (unlikely(ret != 0))
goto out_no_addr_mm;
INIT_DELAYED_WORK(&bdev->wq, ttm_bo_delayed_workqueue);
bdev->nice_mode = true;
INIT_LIST_HEAD(&bdev->ddestroy);
bdev->dev_mapping = NULL;
bdev->glob = glob;
bdev->need_dma32 = need_dma32;
bdev->val_seq = 0;
spin_lock_init(&bdev->fence_lock);
mutex_lock(&glob->device_list_mutex);
list_add_tail(&bdev->device_list, &glob->device_list);
mutex_unlock(&glob->device_list_mutex);
return 0;
out_no_addr_mm:
ttm_bo_clean_mm(bdev, 0);
out_no_sys:
return ret;
}
EXPORT_SYMBOL(ttm_bo_device_init);
/*
* buffer object vm functions.
*/
bool ttm_mem_reg_is_pci(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
{
struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
if (mem->mem_type == TTM_PL_SYSTEM)
return false;
if (man->flags & TTM_MEMTYPE_FLAG_CMA)
return false;
if (mem->placement & TTM_PL_FLAG_CACHED)
return false;
}
return true;
}
void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
{
struct ttm_bo_device *bdev = bo->bdev;
loff_t offset = (loff_t) bo->addr_space_offset;
loff_t holelen = ((loff_t) bo->mem.num_pages) << PAGE_SHIFT;
if (!bdev->dev_mapping)
return;
unmap_mapping_range(bdev->dev_mapping, offset, holelen, 1);
ttm_mem_io_free_vm(bo);
}
void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
{
struct ttm_bo_device *bdev = bo->bdev;
struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
ttm_mem_io_lock(man, false);
ttm_bo_unmap_virtual_locked(bo);
ttm_mem_io_unlock(man);
}
EXPORT_SYMBOL(ttm_bo_unmap_virtual);
static void ttm_bo_vm_insert_rb(struct ttm_buffer_object *bo)
{
struct ttm_bo_device *bdev = bo->bdev;
struct rb_node **cur = &bdev->addr_space_rb.rb_node;
struct rb_node *parent = NULL;
struct ttm_buffer_object *cur_bo;
unsigned long offset = bo->vm_node->start;
unsigned long cur_offset;
while (*cur) {
parent = *cur;
cur_bo = rb_entry(parent, struct ttm_buffer_object, vm_rb);
cur_offset = cur_bo->vm_node->start;
if (offset < cur_offset)
cur = &parent->rb_left;
else if (offset > cur_offset)
cur = &parent->rb_right;
else
BUG();
}
rb_link_node(&bo->vm_rb, parent, cur);
rb_insert_color(&bo->vm_rb, &bdev->addr_space_rb);
}
/**
* ttm_bo_setup_vm:
*
* @bo: the buffer to allocate address space for
*
* Allocate address space in the drm device so that applications
* can mmap the buffer and access the contents. This only
* applies to ttm_bo_type_device objects as others are not
* placed in the drm device address space.
*/
static int ttm_bo_setup_vm(struct ttm_buffer_object *bo)
{
struct ttm_bo_device *bdev = bo->bdev;
int ret;
retry_pre_get:
ret = drm_mm_pre_get(&bdev->addr_space_mm);
if (unlikely(ret != 0))
return ret;
write_lock(&bdev->vm_lock);
bo->vm_node = drm_mm_search_free(&bdev->addr_space_mm,
bo->mem.num_pages, 0, 0);
if (unlikely(bo->vm_node == NULL)) {
ret = -ENOMEM;
goto out_unlock;
}
bo->vm_node = drm_mm_get_block_atomic(bo->vm_node,
bo->mem.num_pages, 0);
if (unlikely(bo->vm_node == NULL)) {
write_unlock(&bdev->vm_lock);
goto retry_pre_get;
}
ttm_bo_vm_insert_rb(bo);
write_unlock(&bdev->vm_lock);
bo->addr_space_offset = ((uint64_t) bo->vm_node->start) << PAGE_SHIFT;
return 0;
out_unlock:
write_unlock(&bdev->vm_lock);
return ret;
}
int ttm_bo_wait(struct ttm_buffer_object *bo,
bool lazy, bool interruptible, bool no_wait)
{
struct ttm_bo_driver *driver = bo->bdev->driver;
struct ttm_bo_device *bdev = bo->bdev;
void *sync_obj;
void *sync_obj_arg;
int ret = 0;
if (likely(bo->sync_obj == NULL))
return 0;
while (bo->sync_obj) {
if (driver->sync_obj_signaled(bo->sync_obj, bo->sync_obj_arg)) {
void *tmp_obj = bo->sync_obj;
bo->sync_obj = NULL;
clear_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags);
spin_unlock(&bdev->fence_lock);
driver->sync_obj_unref(&tmp_obj);
spin_lock(&bdev->fence_lock);
continue;
}
if (no_wait)
return -EBUSY;
sync_obj = driver->sync_obj_ref(bo->sync_obj);
sync_obj_arg = bo->sync_obj_arg;
spin_unlock(&bdev->fence_lock);
ret = driver->sync_obj_wait(sync_obj, sync_obj_arg,
lazy, interruptible);
if (unlikely(ret != 0)) {
driver->sync_obj_unref(&sync_obj);
spin_lock(&bdev->fence_lock);
return ret;
}
spin_lock(&bdev->fence_lock);
if (likely(bo->sync_obj == sync_obj &&
bo->sync_obj_arg == sync_obj_arg)) {
void *tmp_obj = bo->sync_obj;
bo->sync_obj = NULL;
clear_bit(TTM_BO_PRIV_FLAG_MOVING,
&bo->priv_flags);
spin_unlock(&bdev->fence_lock);
driver->sync_obj_unref(&sync_obj);
driver->sync_obj_unref(&tmp_obj);
spin_lock(&bdev->fence_lock);
} else {
spin_unlock(&bdev->fence_lock);
driver->sync_obj_unref(&sync_obj);
spin_lock(&bdev->fence_lock);
}
}
return 0;
}
EXPORT_SYMBOL(ttm_bo_wait);
int ttm_bo_synccpu_write_grab(struct ttm_buffer_object *bo, bool no_wait)
{
struct ttm_bo_device *bdev = bo->bdev;
int ret = 0;
/*
* Using ttm_bo_reserve makes sure the lru lists are updated.
*/
ret = ttm_bo_reserve(bo, true, no_wait, false, 0);
if (unlikely(ret != 0))
return ret;
spin_lock(&bdev->fence_lock);
ret = ttm_bo_wait(bo, false, true, no_wait);
spin_unlock(&bdev->fence_lock);
if (likely(ret == 0))
atomic_inc(&bo->cpu_writers);
ttm_bo_unreserve(bo);
return ret;
}
EXPORT_SYMBOL(ttm_bo_synccpu_write_grab);
void ttm_bo_synccpu_write_release(struct ttm_buffer_object *bo)
{
if (atomic_dec_and_test(&bo->cpu_writers))
wake_up_all(&bo->event_queue);
}
EXPORT_SYMBOL(ttm_bo_synccpu_write_release);
/**
* A buffer object shrink method that tries to swap out the first
* buffer object on the bo_global::swap_lru list.
*/
static int ttm_bo_swapout(struct ttm_mem_shrink *shrink)
{
struct ttm_bo_global *glob =
container_of(shrink, struct ttm_bo_global, shrink);
struct ttm_buffer_object *bo;
int ret = -EBUSY;
int put_count;
uint32_t swap_placement = (TTM_PL_FLAG_CACHED | TTM_PL_FLAG_SYSTEM);
spin_lock(&glob->lru_lock);
while (ret == -EBUSY) {
if (unlikely(list_empty(&glob->swap_lru))) {
spin_unlock(&glob->lru_lock);
return -EBUSY;
}
bo = list_first_entry(&glob->swap_lru,
struct ttm_buffer_object, swap);
kref_get(&bo->list_kref);
if (!list_empty(&bo->ddestroy)) {
spin_unlock(&glob->lru_lock);
(void) ttm_bo_cleanup_refs(bo, false, false, false);
kref_put(&bo->list_kref, ttm_bo_release_list);
continue;
}
/**
* Reserve buffer. Since we unlock while sleeping, we need
* to re-check that nobody removed us from the swap-list while
* we slept.
*/
ret = ttm_bo_reserve_locked(bo, false, true, false, 0);
if (unlikely(ret == -EBUSY)) {
spin_unlock(&glob->lru_lock);
ttm_bo_wait_unreserved(bo, false);
kref_put(&bo->list_kref, ttm_bo_release_list);
spin_lock(&glob->lru_lock);
}
}
BUG_ON(ret != 0);
put_count = ttm_bo_del_from_lru(bo);
spin_unlock(&glob->lru_lock);
ttm_bo_list_ref_sub(bo, put_count, true);
/**
* Wait for GPU, then move to system cached.
*/
spin_lock(&bo->bdev->fence_lock);
ret = ttm_bo_wait(bo, false, false, false);
spin_unlock(&bo->bdev->fence_lock);
if (unlikely(ret != 0))
goto out;
if ((bo->mem.placement & swap_placement) != swap_placement) {
struct ttm_mem_reg evict_mem;
evict_mem = bo->mem;
evict_mem.mm_node = NULL;
evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
evict_mem.mem_type = TTM_PL_SYSTEM;
ret = ttm_bo_handle_move_mem(bo, &evict_mem, true,
false, false, false);
if (unlikely(ret != 0))
goto out;
}
ttm_bo_unmap_virtual(bo);
/**
* Swap out. Buffer will be swapped in again as soon as
* anyone tries to access a ttm page.
*/
if (bo->bdev->driver->swap_notify)
bo->bdev->driver->swap_notify(bo);
ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
out:
/**
*
* Unreserve without putting on LRU to avoid swapping out an
* already swapped buffer.
*/
atomic_set(&bo->reserved, 0);
wake_up_all(&bo->event_queue);
kref_put(&bo->list_kref, ttm_bo_release_list);
return ret;
}
void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
{
while (ttm_bo_swapout(&bdev->glob->shrink) == 0)
;
}
EXPORT_SYMBOL(ttm_bo_swapout_all);
| sahdman/rpi_android_kernel | linux-3.1.9/drivers/gpu/drm/ttm/ttm_bo.c | C | mit | 47,176 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"OD",
"OT"
],
"DAY": [
"Jumapil",
"Wuok Tich",
"Tich Ariyo",
"Tich Adek",
"Tich Ang\u2019wen",
"Tich Abich",
"Ngeso"
],
"ERANAMES": [
"Kapok Kristo obiro",
"Ka Kristo osebiro"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"Dwe mar Achiel",
"Dwe mar Ariyo",
"Dwe mar Adek",
"Dwe mar Ang\u2019wen",
"Dwe mar Abich",
"Dwe mar Auchiel",
"Dwe mar Abiriyo",
"Dwe mar Aboro",
"Dwe mar Ochiko",
"Dwe mar Apar",
"Dwe mar gi achiel",
"Dwe mar Apar gi ariyo"
],
"SHORTDAY": [
"JMP",
"WUT",
"TAR",
"TAD",
"TAN",
"TAB",
"NGS"
],
"SHORTMONTH": [
"DAC",
"DAR",
"DAD",
"DAN",
"DAH",
"DAU",
"DAO",
"DAB",
"DOC",
"DAP",
"DGI",
"DAG"
],
"STANDALONEMONTH": [
"Dwe mar Achiel",
"Dwe mar Ariyo",
"Dwe mar Adek",
"Dwe mar Ang\u2019wen",
"Dwe mar Abich",
"Dwe mar Auchiel",
"Dwe mar Abiriyo",
"Dwe mar Aboro",
"Dwe mar Ochiko",
"Dwe mar Apar",
"Dwe mar gi achiel",
"Dwe mar Apar gi ariyo"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Ksh",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a4",
"posPre": "",
"posSuf": "\u00a4"
}
]
},
"id": "luo",
"localeID": "luo",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| okboy5555/demo | 基于angular的图书管理/src/framework/angular-1.5.8/i18n/angular-locale_luo.js | JavaScript | apache-2.0 | 2,946 |
/*
* Copyright (C) 2009,2010,2011,2012 Samuel Audet
*
* This file is part of JavaCV.
*
* JavaCV is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* JavaCV is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JavaCV. If not, see <http://www.gnu.org/licenses/>.
*/
package com.googlecode.javacv;
import static com.googlecode.javacv.cpp.cvkernels.*;
import static com.googlecode.javacv.cpp.opencv_calib3d.*;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
/**
*
* @author Samuel Audet
*/
public class ProCamTransformer implements ImageTransformer {
public ProCamTransformer(double[] referencePoints,
CameraDevice camera, ProjectorDevice projector) {
this(referencePoints, camera, projector, null);
}
public ProCamTransformer(double[] referencePoints,
CameraDevice camera, ProjectorDevice projector, CvMat n) {
this.camera = camera;
this.projector = projector;
if (referencePoints != null) {
this.surfaceTransformer = new ProjectiveColorTransformer(
camera.cameraMatrix, camera.cameraMatrix, null, null, n,
referencePoints, null, null, 3, 0);
}
double[] referencePoints1 = { 0, 0, camera.imageWidth/2, camera.imageHeight, camera.imageWidth, 0 };
double[] referencePoints2 = { 0, 0, projector.imageWidth/2, projector.imageHeight, projector.imageWidth, 0 };
if (n != null) {
invCameraMatrix = CvMat.create(3, 3);
cvInvert(camera.cameraMatrix, invCameraMatrix);
JavaCV.perspectiveTransform(referencePoints2, referencePoints1,
invCameraMatrix, projector.cameraMatrix, projector.R, projector.T, n, true);
}
this.projectorTransformer = new ProjectiveColorTransformer(
camera.cameraMatrix, projector.cameraMatrix, projector.R, projector.T, null,
referencePoints1, referencePoints2, projector.colorMixingMatrix,
/*surfaceTransformer == null ? 3 : */1, 3);
// CvMat n2 = createParameters().getN();
if (referencePoints != null && n != null) {
frontoParallelH = camera.getFrontoParallelH(referencePoints, n, CvMat.create(3, 3));
invFrontoParallelH = frontoParallelH.clone();
cvInvert(frontoParallelH, invFrontoParallelH);
}
}
protected CameraDevice camera = null;
protected ProjectorDevice projector = null;
protected ProjectiveColorTransformer surfaceTransformer = null;
protected ProjectiveColorTransformer projectorTransformer = null;
protected IplImage[] projectorImage = null, surfaceImage = null;
protected CvScalar fillColor = cvScalar(0.0, 0.0, 0.0, 1.0);
protected CvRect roi = new CvRect();
protected CvMat frontoParallelH = null, invFrontoParallelH = null;
protected CvMat invCameraMatrix = null;
protected KernelData kernelData = null;
protected CvMat[] H1 = null;
protected CvMat[] H2 = null;
protected CvMat[] X = null;
public int getNumGains() {
return projectorTransformer.getNumGains();
}
public int getNumBiases() {
return projectorTransformer.getNumBiases();
}
public CvScalar getFillColor() {
return fillColor;
}
public void setFillColor(CvScalar fillColor) {
this.fillColor = fillColor;
}
public ProjectiveColorTransformer getSurfaceTransformer() {
return surfaceTransformer;
}
public ProjectiveColorTransformer getProjectorTransformer() {
return projectorTransformer;
}
public IplImage getProjectorImage(int pyramidLevel) {
return projectorImage[pyramidLevel];
}
public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel) {
setProjectorImage(projectorImage0, minLevel, maxLevel, true);
}
public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel, boolean convertToFloat) {
if (projectorImage == null || projectorImage.length != maxLevel+1) {
projectorImage = new IplImage[maxLevel+1];
}
if (projectorImage0.depth() == IPL_DEPTH_32F || !convertToFloat) {
projectorImage[minLevel] = projectorImage0;
} else {
if (projectorImage[minLevel] == null) {
projectorImage[minLevel] = IplImage.create(projectorImage0.width(), projectorImage0.height(),
IPL_DEPTH_32F, projectorImage0.nChannels(), projectorImage0.origin());
}
IplROI ir = projectorImage0.roi();
if (ir != null) {
int align = 1<<(maxLevel+1);
roi.x(Math.max(0, (int)Math.floor((double)ir.xOffset()/align)*align));
roi.y(Math.max(0, (int)Math.floor((double)ir.yOffset()/align)*align));
roi.width (Math.min(projectorImage0.width(), (int)Math.ceil((double)ir.width() /align)*align));
roi.height(Math.min(projectorImage0.height(), (int)Math.ceil((double)ir.height()/align)*align));
cvSetImageROI(projectorImage0, roi);
cvSetImageROI(projectorImage[minLevel], roi);
} else {
cvResetImageROI(projectorImage0);
cvResetImageROI(projectorImage[minLevel]);
}
cvConvertScale(projectorImage0, projectorImage[minLevel], 1.0/255.0, 0);
}
// CvScalar.ByValue average = cvAvg(projectorImage[0], null);
// cvSubS(projectorImage[0], average, projectorImage[0], null);
for (int i = minLevel+1; i <= maxLevel; i++) {
int w = projectorImage[i-1].width()/2;
int h = projectorImage[i-1].height()/2;
int d = projectorImage[i-1].depth();
int c = projectorImage[i-1].nChannels();
int o = projectorImage[i-1].origin();
if (projectorImage[i] == null) {
projectorImage[i] = IplImage.create(w, h, d, c, o);
}
IplROI ir = projectorImage[i-1].roi();
if (ir != null) {
roi.x(ir.xOffset()/2); roi.width (ir.width() /2);
roi.y(ir.yOffset()/2); roi.height(ir.height()/2);
cvSetImageROI(projectorImage[i], roi);
} else {
cvResetImageROI(projectorImage[i]);
}
cvPyrDown(projectorImage[i-1], projectorImage[i], CV_GAUSSIAN_5x5);
cvResetImageROI(projectorImage[i-1]);
}
}
public IplImage getSurfaceImage(int pyramidLevel) {
return surfaceImage[pyramidLevel];
}
public void setSurfaceImage(IplImage surfaceImage0, int pyramidLevels) {
if (surfaceImage == null || surfaceImage.length != pyramidLevels) {
surfaceImage = new IplImage[pyramidLevels];
}
surfaceImage[0] = surfaceImage0;
cvResetImageROI(surfaceImage0);
for (int i = 1; i < pyramidLevels; i++) {
int w = surfaceImage[i-1].width()/2;
int h = surfaceImage[i-1].height()/2;
int d = surfaceImage[i-1].depth();
int c = surfaceImage[i-1].nChannels();
int o = surfaceImage[i-1].origin();
if (surfaceImage[i] == null) {
surfaceImage[i] = IplImage.create(w, h, d, c, o);
} else {
cvResetImageROI(surfaceImage[i]);
}
cvPyrDown(surfaceImage[i-1], surfaceImage[i], CV_GAUSSIAN_5x5);
}
}
protected void prepareTransforms(CvMat H1, CvMat H2, CvMat X, int pyramidLevel, Parameters p) {
ProjectiveColorTransformer.Parameters cameraParameters = p.getSurfaceParameters();
ProjectiveColorTransformer.Parameters projectorParameters = p.getProjectorParameters();
if (surfaceTransformer != null) {
cvInvert(cameraParameters.getH(), H1);
}
cvInvert(projectorParameters.getH(), H2);
// adjust the scale of the transformation based on the pyramid level
if (pyramidLevel > 0) {
int scale = 1<<pyramidLevel;
if (surfaceTransformer != null) {
H1.put(2, H1.get(2)/scale);
H1.put(5, H1.get(5)/scale);
H1.put(6, H1.get(6)*scale);
H1.put(7, H1.get(7)*scale);
}
H2.put(2, H2.get(2)/scale);
H2.put(5, H2.get(5)/scale);
H2.put(6, H2.get(6)*scale);
H2.put(7, H2.get(7)*scale);
}
double[] x = projector.colorMixingMatrix.get();
double[] a = projectorParameters.getColorParameters();
double a2 = a[0];
X.put(a2*x[0], a2*x[1], a2*x[2], a[1],
a2*x[3], a2*x[4], a2*x[5], a[2],
a2*x[6], a2*x[7], a2*x[8], a[3],
0, 0, 0, 1);
}
public void transform(final IplImage srcImage, final IplImage dstImage, final CvRect roi,
final int pyramidLevel, final ImageTransformer.Parameters parameters, final boolean inverse) {
if (inverse) {
throw new UnsupportedOperationException("Inverse transform not supported.");
}
final Parameters p = ((Parameters)parameters);
final ProjectiveTransformer.Parameters cameraParameters = p.getSurfaceParameters();
final ProjectiveTransformer.Parameters projectorParameters = p.getProjectorParameters();
if (p.tempImage == null || p.tempImage.length <= pyramidLevel) {
p.tempImage = new IplImage[pyramidLevel+1];
}
p.tempImage[pyramidLevel] = IplImage.createIfNotCompatible(p.tempImage[pyramidLevel], dstImage);
if (roi == null) {
cvResetImageROI(p.tempImage[pyramidLevel]);
} else {
cvSetImageROI(p.tempImage[pyramidLevel], roi);
}
// Parallel.run(new Runnable() { public void run() {
// warp the template image
if (surfaceTransformer != null) {
surfaceTransformer.transform(srcImage, p.tempImage[pyramidLevel], roi, pyramidLevel, cameraParameters, false);
}
// }}, new Runnable() { public void run() {
// warp the projector image
projectorTransformer.transform(projectorImage[pyramidLevel], dstImage, roi, pyramidLevel, projectorParameters, false);
// }});
// multiply projector image with template image
if (surfaceTransformer != null) {
cvMul(dstImage, p.tempImage[pyramidLevel], dstImage, 1/dstImage.highValue());
} else {
cvCopy(p.tempImage[pyramidLevel], dstImage);
}
}
public void transform(CvMat srcPts, CvMat dstPts, ImageTransformer.Parameters parameters, boolean inverse) {
if (surfaceTransformer != null) {
surfaceTransformer.transform(srcPts, dstPts, ((Parameters)parameters).surfaceParameters, inverse);
} else if (dstPts != srcPts) {
dstPts.put(srcPts);
}
}
public void transform(Data[] data, CvRect roi, ImageTransformer.Parameters[] parameters, boolean[] inverses) {
assert data.length == parameters.length;
if (kernelData == null || kernelData.capacity() < data.length) {
kernelData = new KernelData(data.length);
}
if ((H1 == null || H1.length < data.length) && surfaceTransformer != null) {
H1 = new CvMat[data.length];
for (int i = 0; i < H1.length; i++) {
H1[i] = CvMat.create(3, 3);
}
}
if (H2 == null || H2.length < data.length) {
H2 = new CvMat[data.length];
for (int i = 0; i < H2.length; i++) {
H2[i] = CvMat.create(3, 3);
}
}
if (X == null || X.length < data.length) {
X = new CvMat[data.length];
for (int i = 0; i < X.length; i++) {
X[i] = CvMat.create(4, 4);
}
}
for (int i = 0; i < data.length; i++) {
kernelData.position(i);
kernelData.srcImg(projectorImage[data[i].pyramidLevel]);
kernelData.srcImg2(surfaceTransformer == null ? null : data[i].srcImg);
kernelData.subImg(data[i].subImg);
kernelData.srcDotImg(data[i].srcDotImg);
kernelData.mask(data[i].mask);
kernelData.zeroThreshold(data[i].zeroThreshold);
kernelData.outlierThreshold(data[i].outlierThreshold);
if (inverses != null && inverses[i]) {
throw new UnsupportedOperationException("Inverse transform not supported.");
}
prepareTransforms(surfaceTransformer == null ? null : H1[i],
H2[i], X[i], data[i].pyramidLevel, (Parameters)parameters[i]);
kernelData.H1(H2[i]);
kernelData.H2(surfaceTransformer == null ? null : H1[i]);
kernelData.X (X [i]);
kernelData.transImg(data[i].transImg);
kernelData.dstImg(data[i].dstImg);
kernelData.dstDstDot(data[i].dstDstDot);
}
int fullCapacity = kernelData.capacity();
kernelData.capacity(data.length);
multiWarpColorTransform(kernelData, roi, getFillColor());
kernelData.capacity(fullCapacity);
for (int i = 0; i < data.length; i++) {
kernelData.position(i);
data[i].dstCount = kernelData.dstCount();
data[i].dstCountZero = kernelData.dstCountZero();
data[i].dstCountOutlier = kernelData.dstCountOutlier();
data[i].srcDstDot = kernelData.srcDstDot();
}
// if (data[0].dstCountZero > 0) {
// System.err.println(data[0].dstCountZero + " out of " + data[0].dstCount
// + " are zero = " + 100*data[0].dstCountZero/data[0].dstCount + "%");
// }
}
public Parameters createParameters() {
return new Parameters();
}
public class Parameters implements ImageTransformer.Parameters {
protected Parameters() {
reset(false);
}
protected Parameters(ProjectiveColorTransformer.Parameters surfaceParameters,
ProjectiveColorTransformer.Parameters projectorParameters) {
reset(surfaceParameters, projectorParameters);
}
private ProjectiveColorTransformer.Parameters surfaceParameters = null;
private ProjectiveColorTransformer.Parameters projectorParameters = null;
private IplImage[] tempImage = null;
private CvMat H = CvMat.create(3, 3), R = CvMat.create(3, 3),
n = CvMat.create(3, 1), t = CvMat.create(3, 1);
public ProjectiveColorTransformer.Parameters getSurfaceParameters() {
return surfaceParameters;
}
public ProjectiveColorTransformer.Parameters getProjectorParameters() {
return projectorParameters;
}
private int getSizeForSurface() {
return surfaceTransformer == null ? 0 : surfaceParameters.size() -
surfaceTransformer.getNumGains() - surfaceTransformer.getNumBiases();
}
private int getSizeForProjector() {
return projectorParameters.size();
}
public int size() {
return getSizeForSurface() + getSizeForProjector();
}
public double[] get() {
double[] p = new double[size()];
for (int i = 0; i < p.length; i++) {
p[i] = get(i);
}
return p;
}
public double get(int i) {
if (i < getSizeForSurface()) {
return surfaceParameters.get(i);
} else {
return projectorParameters.get(i-getSizeForSurface());
}
}
public void set(double ... p) {
for (int i = 0; i < p.length; i++) {
set(i, p[i]);
}
}
public void set(int i, double p) {
if (i < getSizeForSurface()) {
surfaceParameters.set(i, p);
} else {
projectorParameters.set(i-getSizeForSurface(), p);
}
}
public void set(ImageTransformer.Parameters p) {
Parameters pcp = (Parameters)p;
if (surfaceTransformer != null) {
surfaceParameters.set(pcp.getSurfaceParameters());
surfaceParameters.resetColor(false);
}
projectorParameters.set(pcp.getProjectorParameters());
}
public void reset(boolean asIdentity) {
reset(null, null);
}
public void reset(ProjectiveColorTransformer.Parameters surfaceParameters,
ProjectiveColorTransformer.Parameters projectorParameters) {
if (surfaceParameters == null && surfaceTransformer != null) {
surfaceParameters = surfaceTransformer.createParameters();
}
if (projectorParameters == null) {
projectorParameters = projectorTransformer.createParameters();
}
this.surfaceParameters = surfaceParameters;
this.projectorParameters = projectorParameters;
setSubspace(getSubspace());
}
// public boolean addDelta(int i) {
// return addDelta(i, 1);
// }
// public boolean addDelta(int i, double scale) {
// // gradient varies linearly with intensity, so
// // the increment value is not very important, but
// // referenceCameraImage is good only for the value 1,
// // so let's use that
// if (i < getSizeForSurface()) {
// surfaceParameters.addDelta(i, scale);
// projectorParameters.setUpdateNeeded(true);
// } else {
// projectorParameters.addDelta(i-getSizeForSurface(), scale);
// }
//
// return false;
// }
public double getConstraintError() {
double error = surfaceTransformer == null ? 0 : surfaceParameters.getConstraintError();
projectorParameters.update();
return error;
}
public void compose(ImageTransformer.Parameters p1, boolean inverse1,
ImageTransformer.Parameters p2, boolean inverse2) {
throw new UnsupportedOperationException("Compose operation not supported.");
}
public boolean preoptimize() {
double[] p = setSubspaceInternal(getSubspaceInternal());
if (p != null) {
set(8, p[8]);
set(9, p[9]);
set(10, p[10]);
return true;
}
return false;
}
public void setSubspace(double ... p) {
double[] dst = setSubspaceInternal(p);
if (dst != null) {
set(dst);
}
}
public double[] getSubspace() {
return getSubspaceInternal();
}
private double[] setSubspaceInternal(double ... p) {
if (invFrontoParallelH == null) {
return null;
}
double[] dst = new double[8+3];
t.put(p[0], p[1], p[2]);
cvRodrigues2(t, R, null);
t.put(p[3], p[4], p[5]);
// compute new H
H.put(R.get(0), R.get(1), t.get(0),
R.get(3), R.get(4), t.get(1),
R.get(6), R.get(7), t.get(2));
cvMatMul(H, invFrontoParallelH, H);
cvMatMul(surfaceTransformer.getK2(), H, H);
cvMatMul(H, surfaceTransformer.getInvK1(), H);
// compute new n, rotation from the z-axis
cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T);
double scale = 1/t.get(2);
n.put(0.0, 0.0, 1.0);
cvGEMM(R, n, scale, null, 0, n, 0);
// compute and set new three points
double[] src = projectorTransformer.getReferencePoints2();
JavaCV.perspectiveTransform(src, dst,
projectorTransformer.getInvK1(),projectorTransformer.getK2(),
projectorTransformer.getR(), projectorTransformer.getT(), n, true);
dst[8] = dst[0];
dst[9] = dst[2];
dst[10] = dst[4];
// compute and set new four points
JavaCV.perspectiveTransform(surfaceTransformer.getReferencePoints1(), dst, H);
return dst;
}
private double[] getSubspaceInternal() {
if (frontoParallelH == null) {
return null;
}
cvMatMul(surfaceTransformer.getK1(), frontoParallelH, H);
cvMatMul(surfaceParameters .getH(), H, H);
cvMatMul(surfaceTransformer.getInvK2(), H, H);
JavaCV.HtoRt(H, R, t);
cvRodrigues2(R, n, null);
double[] p = { n.get(0), n.get(1), n.get(2),
t.get(0), t.get(1), t.get(2) };
return p;
}
public CvMat getN() {
double[] src = projectorTransformer.getReferencePoints2();
double[] dst = projectorTransformer.getReferencePoints1().clone();
dst[0] = projectorParameters.get(0);
dst[2] = projectorParameters.get(1);
dst[4] = projectorParameters.get(2);
// get plane parameters n, but since we model the target to be
// the camera, we have to inverse everything before calling
// getPlaneParameters() and reframe the n it returns
cvTranspose(projectorTransformer.getR(), R);
cvGEMM(R, projectorTransformer.getT(), -1, null, 0, t, 0);
JavaCV.getPlaneParameters(src, dst, projectorTransformer.getInvK2(),
projectorTransformer.getK1(), R, t, n);
double d = 1 + cvDotProduct(n, projectorTransformer.getT());
cvGEMM(R, n, 1/d, null, 0, n, 0);
return n;
}
public CvMat getN0() {
n = getN();
if (surfaceTransformer == null) {
return n;
}
// remove projective effect of the current n,
// leaving only the effect of n0
camera.getFrontoParallelH(surfaceParameters.get(), n, R);
cvInvert(surfaceParameters.getH(), H);
cvMatMul(H, surfaceTransformer.getK2(), H);
cvMatMul(H, R, H);
cvMatMul(surfaceTransformer.getInvK1(), H, H);
JavaCV.HtoRt(H, R, t);
// compute n0, as a rotation from the z-axis
cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T);
double scale = 1/t.get(2);
n.put(0.0, 0.0, 1.0);
cvGEMM(R, n, scale, null, 0, n, 0);
return n;
}
@Override public Parameters clone() {
Parameters p = new Parameters();
p.surfaceParameters = surfaceParameters == null ? null : surfaceParameters.clone();
p.projectorParameters = projectorParameters.clone();
return p;
}
@Override public String toString() {
if (surfaceParameters != null) {
return surfaceParameters.toString() + projectorParameters.toString();
} else {
return projectorParameters.toString();
}
}
}
}
| JanesR/javacv | src/main/java/com/googlecode/javacv/ProCamTransformer.java | Java | gpl-2.0 | 23,990 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service_Rackspace
* @subpackage Files
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
require_once 'Zend/Service/Rackspace/Files.php';
class Zend_Service_Rackspace_Files_Object
{
/**
* The service that has created the object
*
* @var Zend_Service_Rackspace_Files
*/
protected $service;
/**
* Name of the object
*
* @var string
*/
protected $name;
/**
* MD5 value of the object's content
*
* @var string
*/
protected $hash;
/**
* Size in bytes of the object's content
*
* @var integer
*/
protected $size;
/**
* Content type of the object's content
*
* @var string
*/
protected $contentType;
/**
* Date of the last modified of the object
*
* @var string
*/
protected $lastModified;
/**
* Object content
*
* @var string
*/
protected $content;
/**
* Name of the container where the object is stored
*
* @var string
*/
protected $container;
/**
* Constructor
*
* You must pass the Zend_Service_Rackspace_Files object of the caller and an associative
* array with the keys "name", "container", "hash", "bytes", "content_type",
* "last_modified", "file" where:
* name= name of the object
* container= name of the container where the object is stored
* hash= the MD5 of the object's content
* bytes= size in bytes of the object's content
* content_type= content type of the object's content
* last_modified= date of the last modified of the object
* content= content of the object
*
* @param Zend_Service_Rackspace_Files $service
* @param array $data
*/
public function __construct($service,$data)
{
if (!($service instanceof Zend_Service_Rackspace_Files) || !is_array($data)) {
require_once 'Zend/Service/Rackspace/Files/Exception.php';
throw new Zend_Service_Rackspace_Files_Exception("You must pass a RackspaceFiles and an array");
}
if (!array_key_exists('name', $data)) {
require_once 'Zend/Service/Rackspace/Files/Exception.php';
throw new Zend_Service_Rackspace_Files_Exception("You must pass the name of the object in the array (name)");
}
if (!array_key_exists('container', $data)) {
require_once 'Zend/Service/Rackspace/Files/Exception.php';
throw new Zend_Service_Rackspace_Files_Exception("You must pass the container of the object in the array (container)");
}
if (!array_key_exists('hash', $data)) {
require_once 'Zend/Service/Rackspace/Files/Exception.php';
throw new Zend_Service_Rackspace_Files_Exception("You must pass the hash of the object in the array (hash)");
}
if (!array_key_exists('bytes', $data)) {
require_once 'Zend/Service/Rackspace/Files/Exception.php';
throw new Zend_Service_Rackspace_Files_Exception("You must pass the byte size of the object in the array (bytes)");
}
if (!array_key_exists('content_type', $data)) {
require_once 'Zend/Service/Rackspace/Files/Exception.php';
throw new Zend_Service_Rackspace_Files_Exception("You must pass the content type of the object in the array (content_type)");
}
if (!array_key_exists('last_modified', $data)) {
require_once 'Zend/Service/Rackspace/Files/Exception.php';
throw new Zend_Service_Rackspace_Files_Exception("You must pass the last modified data of the object in the array (last_modified)");
}
$this->name= $data['name'];
$this->container= $data['container'];
$this->hash= $data['hash'];
$this->size= $data['bytes'];
$this->contentType= $data['content_type'];
$this->lastModified= $data['last_modified'];
if (!empty($data['content'])) {
$this->content= $data['content'];
}
$this->service= $service;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get the name of the container
*
* @return string
*/
public function getContainer()
{
return $this->container;
}
/**
* Get the MD5 of the object's content
*
* @return string|boolean
*/
public function getHash()
{
return $this->hash;
}
/**
* Get the size (in bytes) of the object's content
*
* @return integer|boolean
*/
public function getSize()
{
return $this->size;
}
/**
* Get the content type of the object's content
*
* @return string
*/
public function getContentType()
{
return $this->contentType;
}
/**
* Get the data of the last modified of the object
*
* @return string
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* Get the content of the object
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Get the metadata of the object
* If you don't pass the $key it returns the entire array of metadata value
*
* @param string $key
* @return string|array|boolean
*/
public function getMetadata($key=null)
{
$result= $this->service->getMetadataObject($this->container,$this->name);
if (!empty($result)) {
if (empty($key)) {
return $result['metadata'];
}
if (isset($result['metadata'][$key])) {
return $result['metadata'][$key];
}
}
return false;
}
/**
* Set the metadata value
* The old metadata values are replaced with the new one
*
* @param array $metadata
* @return boolean
*/
public function setMetadata($metadata)
{
return $this->service->setMetadataObject($this->container,$this->name,$metadata);
}
/**
* Copy the object to another container
* You can add metadata information to the destination object, change the
* content_type and the name of the object
*
* @param string $container_dest
* @param string $name_dest
* @param array $metadata
* @param string $content_type
* @return boolean
*/
public function copyTo($container_dest,$name_dest,$metadata=array(),$content_type=null)
{
return $this->service->copyObject($this->container,$this->name,$container_dest,$name_dest,$metadata,$content_type);
}
/**
* Get the CDN URL of the object
*
* @return string
*/
public function getCdnUrl()
{
$result= $this->service->getInfoCdnContainer($this->container);
if ($result!==false) {
if ($result['cdn_enabled']) {
return $result['cdn_uri'].'/'.$this->name;
}
}
return false;
}
/**
* Get the CDN SSL URL of the object
*
* @return string
*/
public function getCdnUrlSsl()
{
$result= $this->service->getInfoCdnContainer($this->container);
if ($result!==false) {
if ($result['cdn_enabled']) {
return $result['cdn_uri_ssl'].'/'.$this->name;
}
}
return false;
}
}
| mattsimpson/entrada-1x | www-root/core/library/Zend/Service/Rackspace/Files/Object.php | PHP | gpl-3.0 | 8,137 |
// SPDX-License-Identifier: GPL-2.0
#include <linux/bug.h>
#include <linux/kernel.h>
#include <linux/bitops.h>
#include <linux/math64.h>
#include <linux/log2.h>
#include <linux/err.h>
#include <linux/module.h>
#include "qcom-vadc-common.h"
/* Voltage to temperature */
static const struct vadc_map_pt adcmap_100k_104ef_104fb[] = {
{1758, -40},
{1742, -35},
{1719, -30},
{1691, -25},
{1654, -20},
{1608, -15},
{1551, -10},
{1483, -5},
{1404, 0},
{1315, 5},
{1218, 10},
{1114, 15},
{1007, 20},
{900, 25},
{795, 30},
{696, 35},
{605, 40},
{522, 45},
{448, 50},
{383, 55},
{327, 60},
{278, 65},
{237, 70},
{202, 75},
{172, 80},
{146, 85},
{125, 90},
{107, 95},
{92, 100},
{79, 105},
{68, 110},
{59, 115},
{51, 120},
{44, 125}
};
/*
* Voltage to temperature table for 100k pull up for NTCG104EF104 with
* 1.875V reference.
*/
static const struct vadc_map_pt adcmap_100k_104ef_104fb_1875_vref[] = {
{ 1831, -40000 },
{ 1814, -35000 },
{ 1791, -30000 },
{ 1761, -25000 },
{ 1723, -20000 },
{ 1675, -15000 },
{ 1616, -10000 },
{ 1545, -5000 },
{ 1463, 0 },
{ 1370, 5000 },
{ 1268, 10000 },
{ 1160, 15000 },
{ 1049, 20000 },
{ 937, 25000 },
{ 828, 30000 },
{ 726, 35000 },
{ 630, 40000 },
{ 544, 45000 },
{ 467, 50000 },
{ 399, 55000 },
{ 340, 60000 },
{ 290, 65000 },
{ 247, 70000 },
{ 209, 75000 },
{ 179, 80000 },
{ 153, 85000 },
{ 130, 90000 },
{ 112, 95000 },
{ 96, 100000 },
{ 82, 105000 },
{ 71, 110000 },
{ 62, 115000 },
{ 53, 120000 },
{ 46, 125000 },
};
static int qcom_vadc_scale_hw_calib_volt(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_uv);
static int qcom_vadc_scale_hw_calib_therm(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec);
static int qcom_vadc_scale_hw_smb_temp(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec);
static int qcom_vadc_scale_hw_chg5_temp(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec);
static int qcom_vadc_scale_hw_calib_die_temp(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec);
static struct qcom_adc5_scale_type scale_adc5_fn[] = {
[SCALE_HW_CALIB_DEFAULT] = {qcom_vadc_scale_hw_calib_volt},
[SCALE_HW_CALIB_THERM_100K_PULLUP] = {qcom_vadc_scale_hw_calib_therm},
[SCALE_HW_CALIB_XOTHERM] = {qcom_vadc_scale_hw_calib_therm},
[SCALE_HW_CALIB_PMIC_THERM] = {qcom_vadc_scale_hw_calib_die_temp},
[SCALE_HW_CALIB_PM5_CHG_TEMP] = {qcom_vadc_scale_hw_chg5_temp},
[SCALE_HW_CALIB_PM5_SMB_TEMP] = {qcom_vadc_scale_hw_smb_temp},
};
static int qcom_vadc_map_voltage_temp(const struct vadc_map_pt *pts,
u32 tablesize, s32 input, int *output)
{
bool descending = 1;
u32 i = 0;
if (!pts)
return -EINVAL;
/* Check if table is descending or ascending */
if (tablesize > 1) {
if (pts[0].x < pts[1].x)
descending = 0;
}
while (i < tablesize) {
if ((descending) && (pts[i].x < input)) {
/* table entry is less than measured*/
/* value and table is descending, stop */
break;
} else if ((!descending) &&
(pts[i].x > input)) {
/* table entry is greater than measured*/
/*value and table is ascending, stop */
break;
}
i++;
}
if (i == 0) {
*output = pts[0].y;
} else if (i == tablesize) {
*output = pts[tablesize - 1].y;
} else {
/* result is between search_index and search_index-1 */
/* interpolate linearly */
*output = (((s32)((pts[i].y - pts[i - 1].y) *
(input - pts[i - 1].x)) /
(pts[i].x - pts[i - 1].x)) +
pts[i - 1].y);
}
return 0;
}
static void qcom_vadc_scale_calib(const struct vadc_linear_graph *calib_graph,
u16 adc_code,
bool absolute,
s64 *scale_voltage)
{
*scale_voltage = (adc_code - calib_graph->gnd);
*scale_voltage *= calib_graph->dx;
*scale_voltage = div64_s64(*scale_voltage, calib_graph->dy);
if (absolute)
*scale_voltage += calib_graph->dx;
if (*scale_voltage < 0)
*scale_voltage = 0;
}
static int qcom_vadc_scale_volt(const struct vadc_linear_graph *calib_graph,
const struct vadc_prescale_ratio *prescale,
bool absolute, u16 adc_code,
int *result_uv)
{
s64 voltage = 0, result = 0;
qcom_vadc_scale_calib(calib_graph, adc_code, absolute, &voltage);
voltage = voltage * prescale->den;
result = div64_s64(voltage, prescale->num);
*result_uv = result;
return 0;
}
static int qcom_vadc_scale_therm(const struct vadc_linear_graph *calib_graph,
const struct vadc_prescale_ratio *prescale,
bool absolute, u16 adc_code,
int *result_mdec)
{
s64 voltage = 0;
int ret;
qcom_vadc_scale_calib(calib_graph, adc_code, absolute, &voltage);
if (absolute)
voltage = div64_s64(voltage, 1000);
ret = qcom_vadc_map_voltage_temp(adcmap_100k_104ef_104fb,
ARRAY_SIZE(adcmap_100k_104ef_104fb),
voltage, result_mdec);
if (ret)
return ret;
*result_mdec *= 1000;
return 0;
}
static int qcom_vadc_scale_die_temp(const struct vadc_linear_graph *calib_graph,
const struct vadc_prescale_ratio *prescale,
bool absolute,
u16 adc_code, int *result_mdec)
{
s64 voltage = 0;
u64 temp; /* Temporary variable for do_div */
qcom_vadc_scale_calib(calib_graph, adc_code, absolute, &voltage);
if (voltage > 0) {
temp = voltage * prescale->den;
do_div(temp, prescale->num * 2);
voltage = temp;
} else {
voltage = 0;
}
voltage -= KELVINMIL_CELSIUSMIL;
*result_mdec = voltage;
return 0;
}
static int qcom_vadc_scale_chg_temp(const struct vadc_linear_graph *calib_graph,
const struct vadc_prescale_ratio *prescale,
bool absolute,
u16 adc_code, int *result_mdec)
{
s64 voltage = 0, result = 0;
qcom_vadc_scale_calib(calib_graph, adc_code, absolute, &voltage);
voltage = voltage * prescale->den;
voltage = div64_s64(voltage, prescale->num);
voltage = ((PMI_CHG_SCALE_1) * (voltage * 2));
voltage = (voltage + PMI_CHG_SCALE_2);
result = div64_s64(voltage, 1000000);
*result_mdec = result;
return 0;
}
static int qcom_vadc_scale_code_voltage_factor(u16 adc_code,
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
unsigned int factor)
{
s64 voltage, temp, adc_vdd_ref_mv = 1875;
/*
* The normal data range is between 0V to 1.875V. On cases where
* we read low voltage values, the ADC code can go beyond the
* range and the scale result is incorrect so we clamp the values
* for the cases where the code represents a value below 0V
*/
if (adc_code > VADC5_MAX_CODE)
adc_code = 0;
/* (ADC code * vref_vadc (1.875V)) / full_scale_code */
voltage = (s64) adc_code * adc_vdd_ref_mv * 1000;
voltage = div64_s64(voltage, data->full_scale_code_volt);
if (voltage > 0) {
voltage *= prescale->den;
temp = prescale->num * factor;
voltage = div64_s64(voltage, temp);
} else {
voltage = 0;
}
return (int) voltage;
}
static int qcom_vadc_scale_hw_calib_volt(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_uv)
{
*result_uv = qcom_vadc_scale_code_voltage_factor(adc_code,
prescale, data, 1);
return 0;
}
static int qcom_vadc_scale_hw_calib_therm(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec)
{
int voltage;
voltage = qcom_vadc_scale_code_voltage_factor(adc_code,
prescale, data, 1000);
/* Map voltage to temperature from look-up table */
return qcom_vadc_map_voltage_temp(adcmap_100k_104ef_104fb_1875_vref,
ARRAY_SIZE(adcmap_100k_104ef_104fb_1875_vref),
voltage, result_mdec);
}
static int qcom_vadc_scale_hw_calib_die_temp(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec)
{
*result_mdec = qcom_vadc_scale_code_voltage_factor(adc_code,
prescale, data, 2);
*result_mdec -= KELVINMIL_CELSIUSMIL;
return 0;
}
static int qcom_vadc_scale_hw_smb_temp(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec)
{
*result_mdec = qcom_vadc_scale_code_voltage_factor(adc_code * 100,
prescale, data, PMIC5_SMB_TEMP_SCALE_FACTOR);
*result_mdec = PMIC5_SMB_TEMP_CONSTANT - *result_mdec;
return 0;
}
static int qcom_vadc_scale_hw_chg5_temp(
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result_mdec)
{
*result_mdec = qcom_vadc_scale_code_voltage_factor(adc_code,
prescale, data, 4);
*result_mdec = PMIC5_CHG_TEMP_SCALE_FACTOR - *result_mdec;
return 0;
}
int qcom_vadc_scale(enum vadc_scale_fn_type scaletype,
const struct vadc_linear_graph *calib_graph,
const struct vadc_prescale_ratio *prescale,
bool absolute,
u16 adc_code, int *result)
{
switch (scaletype) {
case SCALE_DEFAULT:
return qcom_vadc_scale_volt(calib_graph, prescale,
absolute, adc_code,
result);
case SCALE_THERM_100K_PULLUP:
case SCALE_XOTHERM:
return qcom_vadc_scale_therm(calib_graph, prescale,
absolute, adc_code,
result);
case SCALE_PMIC_THERM:
return qcom_vadc_scale_die_temp(calib_graph, prescale,
absolute, adc_code,
result);
case SCALE_PMI_CHG_TEMP:
return qcom_vadc_scale_chg_temp(calib_graph, prescale,
absolute, adc_code,
result);
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(qcom_vadc_scale);
int qcom_adc5_hw_scale(enum vadc_scale_fn_type scaletype,
const struct vadc_prescale_ratio *prescale,
const struct adc5_data *data,
u16 adc_code, int *result)
{
if (!(scaletype >= SCALE_HW_CALIB_DEFAULT &&
scaletype < SCALE_HW_CALIB_INVALID)) {
pr_err("Invalid scale type %d\n", scaletype);
return -EINVAL;
}
return scale_adc5_fn[scaletype].scale_fn(prescale, data,
adc_code, result);
}
EXPORT_SYMBOL(qcom_adc5_hw_scale);
int qcom_vadc_decimation_from_dt(u32 value)
{
if (!is_power_of_2(value) || value < VADC_DECIMATION_MIN ||
value > VADC_DECIMATION_MAX)
return -EINVAL;
return __ffs64(value / VADC_DECIMATION_MIN);
}
EXPORT_SYMBOL(qcom_vadc_decimation_from_dt);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Qualcomm ADC common functionality");
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-5.4/drivers/iio/adc/qcom-vadc-common.c | C | gpl-2.0 | 10,376 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {
@XmlAttribute
private String name;
@XmlAttribute
private String value;
public Bar() {
}
public void setName(String name) {
this.name = name;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
| CandleCandle/camel | components/camel-jaxb/src/test/java/org/apache/camel/example/Bar.java | Java | apache-2.0 | 1,514 |
<?php
/**
* @file
* Sample hooks demonstrating usage in Webform.
*/
/**
* @defgroup webform_hooks Webform Module Hooks
* @{
* Webform's hooks enable other modules to intercept events within Webform, such
* as the completion of a submission or adding validation. Webform's hooks also
* allow other modules to provide additional components for use within forms.
*/
/**
* Define callbacks that can be used as select list options.
*
* When users create a select component, they may select a pre-built list of
* certain options. Webform core provides a few of these lists such as the
* United States, countries of the world, and days of the week. This hook
* provides additional lists that may be utilized.
*
* @see webform_options_example()
* @see hook_webform_select_options_info_alter()
*
* @return
* An array of callbacks that can be used for select list options. This array
* should be keyed by the "name" of the pre-defined list. The values should
* be an array with the following additional keys:
* - title: The translated title for this list.
* - options callback: The name of the function that will return the list.
* - options arguments: Any additional arguments to send to the callback.
* - file: Optional. The file containing the options callback, relative to
* the module root.
*/
function hook_webform_select_options_info() {
$items = array();
$items['days'] = array(
'title' => t('Days of the week'),
'options callback' => 'webform_options_days',
'file' => 'includes/webform.options.inc',
);
return $items;
}
/**
* Alter the list of select list options provided by Webform and other modules.
*
* @see hook_webform_select_options_info().
*/
function hook_webform_select_options_info_alter(&$items) {
// Remove the days of the week options.
unset($items['days']);
}
/**
* This is an example function to demonstrate a webform options callback.
*
* This function returns a list of options that Webform may use in a select
* component. In order to be called, the function name
* ("webform_options_example" in this case), needs to be specified as a callback
* in hook_webform_select_options_info().
*
* @param $component
* The Webform component array for the select component being displayed.
* @param $flat
* Boolean value indicating whether the returned list needs to be a flat array
* of key => value pairs. Select components support up to one level of
* nesting, but when results are displayed, the list needs to be returned
* without the nesting.
* @param $arguments
* The "options arguments" specified in hook_webform_select_options_info().
* @return
* An array of key => value pairs suitable for a select list's #options
* FormAPI property.
*/
function webform_options_example($component, $flat, $arguments) {
$options = array(
'one' => t('Pre-built option one'),
'two' => t('Pre-built option two'),
'three' => t('Pre-built option three'),
);
return $options;
}
/**
* Respond to the loading of Webform submissions.
*
* @param $submissions
* An array of Webform submissions that are being loaded, keyed by the
* submission ID. Modifications to the submissions are done by reference.
*/
function hook_webform_submission_load(&$submissions) {
foreach ($submissions as $sid => $submission) {
$submissions[$sid]->new_property = 'foo';
}
}
/**
* Respond to the creation of a new submission from form values.
*
* This hook is called when a user has completed a submission to initialize the
* submission object. After this object has its values populated, it will be
* saved by webform_submission_insert(). Note that this hook is only called for
* new submissions, not for submissions being edited. If responding to the
* saving of all submissions, it's recommended to use
* hook_webform_submission_presave().
*
* @param $submission
* The submission object that has been created.
* @param $node
* The Webform node for which this submission is being saved.
* @param $account
* The user account that is creating the submission.
* @param $form_state
* The contents of form state that is the basis for this submission.
*
* @see webform_submission_create()
*/
function hook_webform_submission_create($submission, $node, $account, $form_state) {
$submission->new_property = TRUE;
}
/**
* Modify a Webform submission, prior to saving it in the database.
*
* @param $node
* The Webform node on which this submission was made.
* @param $submission
* The Webform submission that is about to be saved to the database.
*/
function hook_webform_submission_presave($node, &$submission) {
// Update some component's value before it is saved.
$component_id = 4;
$submission->data[$component_id][0] = 'foo';
}
/**
* Respond to a Webform submission being inserted.
*
* Note that this hook is called after a submission has already been saved to
* the database. If needing to modify the submission prior to insertion, use
* hook_webform_submission_presave().
*
* @param $node
* The Webform node on which this submission was made.
* @param $submission
* The Webform submission that was just inserted into the database.
*/
function hook_webform_submission_insert($node, $submission) {
// Insert a record into a 3rd-party module table when a submission is added.
db_insert('mymodule_table')
->fields(array(
'nid' => $node->nid,
'sid' => $submission->sid,
'foo' => 'foo_data',
))
->execute();
}
/**
* Respond to a Webform submission being updated.
*
* Note that this hook is called after a submission has already been saved to
* the database. If needing to modify the submission prior to updating, use
* hook_webform_submission_presave().
*
* @param $node
* The Webform node on which this submission was made.
* @param $submission
* The Webform submission that was just updated in the database.
*/
function hook_webform_submission_update($node, $submission) {
// Update a record in a 3rd-party module table when a submission is updated.
db_update('mymodule_table')
->fields(array(
'foo' => 'foo_data',
))
->condition('nid', $node->nid)
->condition('sid', $submission->sid)
->execute();
}
/**
* Respond to a Webform submission being deleted.
*
* @param $node
* The Webform node on which this submission was made.
* @param $submission
* The Webform submission that was just deleted from the database.
*/
function hook_webform_submission_delete($node, $submission) {
// Delete a record from a 3rd-party module table when a submission is deleted.
db_delete('mymodule_table')
->condition('nid', $node->nid)
->condition('sid', $submission->sid)
->execute();
}
/**
* Provide a list of actions that can be executed on a submission.
*
* Some actions are displayed in the list of submissions such as edit, view, and
* delete. All other actions are displayed only when viewing the submission.
* These additional actions may be specified in this hook. Examples included
* directly in the Webform module include PDF, print, and resend e-mails. Other
* modules may extend this list by using this hook.
*
* @param $node
* The Webform node on which this submission was made.
* @param $submission
* The Webform submission on which the actions may be performed.
*/
function hook_webform_submission_actions($node, $submission) {
$actions= array();
if (webform_results_access($node)) {
$actions['myaction'] = array(
'title' => t('Do my action'),
'href' => 'node/' . $node->nid . '/submission/' . $submission->sid . '/myaction',
'query' => drupal_get_destination(),
);
}
return $actions;
}
/**
* Modify the draft to be presented for editing.
*
* When drafts are enabled for the webform, by default, a pre-existig draft is
* presented when the webform is displayed to that user. To allow multiple
* drafts, implement this alter function to set the $sid to NULL, or use your
* application's business logic to determine whether a new draft or which of
* he pre-existing drafts should be presented.
*
* @param integer $sid
* The id of the most recent submission to be presented for editing. Change
* to a different draft's sid or set to NULL for a new draft.
* @param array $context
* Array of context with indices 'nid' and 'uid'.
*/
function hook_webform_draft_alter(&$sid, $context) {
if ($_GET['newdraft']) {
$sid = NULL;
}
}
/**
* Alter the display of a Webform submission.
*
* This function applies to both e-mails sent by Webform and normal display of
* submissions when viewing through the adminsitrative interface.
*
* @param $renderable
* The Webform submission in a renderable array, similar to FormAPI's
* structure. This variable must be passed in by-reference. Important
* properties of this array include #node, #submission, #email, and #format,
* which can be used to find the context of the submission that is being
* rendered.
*/
function hook_webform_submission_render_alter(&$renderable) {
// Remove page breaks from sent e-mails.
if (isset($renderable['#email'])) {
foreach (element_children($renderable) as $key) {
if ($renderable[$key]['#component']['type'] == 'pagebreak') {
unset($renderable[$key]);
}
}
}
}
/**
* Modify a loaded Webform component.
*
* IMPORTANT: This hook does not actually exist because components are loaded
* in bulk as part of webform_node_load(). Use hook_node_load() to modify loaded
* components when the node is loaded. This example is provided merely to point
* to hook_node_load().
*
* @see hook_nodeapi()
* @see webform_node_load()
*/
function hook_webform_component_load() {
// This hook does not exist. Instead use hook_node_load().
}
/**
* Modify a Webform component before it is saved to the database.
*
* Note that most of the time this hook is not necessary, because Webform will
* automatically add data to the component based on the component form. Using
* hook_form_alter() will be sufficient in most cases.
*
* @see hook_form_alter()
* @see webform_component_edit_form()
*
* @param $component
* The Webform component being saved.
*/
function hook_webform_component_presave(&$component) {
$component['extra']['new_option'] = 'foo';
}
/**
* Respond to a Webform component being inserted into the database.
*/
function hook_webform_component_insert($component) {
// Insert a record into a 3rd-party module table when a component is inserted.
db_insert('mymodule_table')
->fields(array(
'nid' => $component['nid'],
'cid' => $component['cid'],
'foo' => 'foo_data',
))
->execute();
}
/**
* Respond to a Webform component being updated in the database.
*/
function hook_webform_component_update($component) {
// Update a record in a 3rd-party module table when a component is updated.
db_update('mymodule_table')
->fields(array(
'foo' => 'foo_data',
))
->condition('nid', $component['nid'])
->condition('cid', $component['cid'])
->execute();
}
/**
* Respond to a Webform component being deleted.
*/
function hook_webform_component_delete($component) {
// Delete a record in a 3rd-party module table when a component is deleted.
db_delete('mymodule_table')
->condition('nid', $component['nid'])
->condition('cid', $component['cid'])
->execute();
}
/**
* Alter the entire analysis before rendering to the page on the Analysis tab.
*
* This alter hook allows modification of the entire analysis of a node's
* Webform results. The resulting analysis is displayed on the Results ->
* Analysis tab on the Webform.
*
* @param array $analysis
* A Drupal renderable array, passed by reference, containing the entire
* contents of the analysis page. This typically will contain the following
* two major keys:
* - form: The form for configuring the shown analysis.
* - components: The list of analyses for each analysis-enabled component
* for the node. Each keyed by its component ID.
*/
function hook_webform_analysis_alter(&$analysis) {
$node = $analysis['#node'];
// Add an additional piece of information to every component's analysis:
foreach (element_children($analysis['components']) as $cid) {
$component = $node->components[$cid];
$analysis['components'][$cid]['chart'] = array(
'#markup' => t('Chart for the @name component', array('@name' => $component['name'])),
);
}
}
/**
* Alter data when displaying an analysis on that component.
*
* This hook modifies the data from an individual component's analysis results.
* It can be used to add additional analysis, or to modify the existing results.
* If needing to alter the entire set of analyses rather than an individual
* component, hook_webform_analysis_alter() may be used instead.
*
* @param array $data
* An array containing the result of a components analysis hook, passed by
* reference. This is passed directly from a component's
* _webform_analysis_component() function. See that hook for more information
* on this value.
* @param object $node
* The node object that contains the component being analyzed.
* @param array $component
* The Webform component array whose analysis results are being displayed.
*
* @see _webform_analysis_component()
* @see hook_webform_analysis_alter()
*/
function hook_webform_analysis_component_data_alter(&$data, $node, $component) {
if ($component['type'] === 'textfield') {
// Do not display rows that contain a zero value.
foreach ($data as $row_number => $row_data) {
if ($row_data[1] === 0) {
unset($data[$row_number]);
}
}
}
}
/**
* Alter a Webform submission's header when exported.
*/
function hook_webform_csv_header_alter(&$header, $component) {
// Use the machine name for component headers, but only for the webform
// with node 5 and components that are text fields.
if ($component['nid'] == 5 && $component['type'] == 'textfield') {
$header[2] = $component['form_key'];
}
}
/**
* Alter a Webform submission's data when exported.
*/
function hook_webform_csv_data_alter(&$data, $component, $submission) {
// If a value of a field was left blank, use the value from another
// field.
if ($component['cid'] == 1 && empty($data)) {
$data = $submission->data[2]['value'][0];
}
}
/**
* Define components to Webform.
*
* @return
* An array of components, keyed by machine name. Required properties are
* "label" and "description". The "features" array defines which capabilities
* the component has, such as being displayed in e-mails or csv downloads.
* A component like "markup" for example would not show in these locations.
* The possible features of a component include:
*
* - csv
* - email
* - email_address
* - email_name
* - required
* - conditional
* - spam_analysis
* - group
*
* Note that most of these features do not indicate the default state, but
* determine if the component can have this property at all. Setting
* "required" to TRUE does not mean that a component's fields will always be
* required, but instead give the option to the administrator to choose the
* requiredness. See the example implementation for details on how these
* features may be set.
*
* An optional "file" may be specified to be loaded when the component is
* needed. A set of callbacks will be established based on the name of the
* component. All components follow the pattern:
*
* _webform_[callback]_[component]
*
* Where [component] is the name of the key of the component and [callback] is
* any of the following:
*
* - defaults
* - edit
* - render
* - display
* - submit
* - delete
* - help
* - theme
* - analysis
* - table
* - csv_headers
* - csv_data
*
* See the sample component implementation for details on each one of these
* callbacks.
*
* @see webform_components()
*/
function hook_webform_component_info() {
$components = array();
$components['textfield'] = array(
'label' => t('Textfield'),
'description' => t('Basic textfield type.'),
'features' => array(
// This component includes an analysis callback. Defaults to TRUE.
'analysis' => TRUE,
// Add content to CSV downloads. Defaults to TRUE.
'csv' => TRUE,
// This component supports default values. Defaults to TRUE.
'default_value' => FALSE,
// This component supports a description field. Defaults to TRUE.
'description' => FALSE,
// Show this component in e-mailed submissions. Defaults to TRUE.
'email' => TRUE,
// Allow this component to be used as an e-mail FROM or TO address.
// Defaults to FALSE.
'email_address' => FALSE,
// Allow this component to be used as an e-mail SUBJECT or FROM name.
// Defaults to FALSE.
'email_name' => TRUE,
// This component may be toggled as required or not. Defaults to TRUE.
'required' => TRUE,
// This component supports a title attribute. Defaults to TRUE.
'title' => FALSE,
// This component has a title that can be toggled as displayed or not.
'title_display' => TRUE,
// This component has a title that can be displayed inline.
'title_inline' => TRUE,
// If this component can be used as a conditional SOURCE. All components
// may always be displayed conditionally, regardless of this setting.
// Defaults to TRUE.
'conditional' => TRUE,
// If this component allows other components to be grouped within it
// (like a fieldset or tabs). Defaults to FALSE.
'group' => FALSE,
// If this component can be used for SPAM analysis, usually with Mollom.
'spam_analysis' => FALSE,
// If this component saves a file that can be used as an e-mail
// attachment. Defaults to FALSE.
'attachment' => FALSE,
// If this component reflects a time range and should use labels such as
// "Before" and "After" when exposed as filters in Views module.
'views_range' => FALSE,
),
// Specify the conditional behaviour of this component.
// Examples are 'string', 'date', 'time', 'numeric', 'select'.
// Defaults to 'string'.
'conditional_type' => 'string',
'file' => 'components/textfield.inc',
);
return $components;
}
/**
* Alter the list of available Webform components.
*
* @param $components
* A list of existing components as defined by hook_webform_component_info().
*
* @see hook_webform_component_info()
*/
function hook_webform_component_info_alter(&$components) {
// Completely remove a component.
unset($components['grid']);
// Change the name of a component.
$components['textarea']['label'] = t('Text box');
}
/**
* Alter the list of Webform component default values.
*
* @param $defaults
* A list of component defaults as defined by _webform_defaults_COMPONENT().
* @param $type
* The component type whose defaults are being provided.
*
* @see _webform_defaults_component()
*/
function hook_webform_component_defaults_alter(&$defaults, $type) {
// Alter a default for all component types.
$defaults['required'] = 1;
// Add a default for a new field added via hook_form_alter() or
// hook_form_FORM_ID_alter() for all component types.
$defaults['extra']['added_field'] = t('Added default value');
// Add or alter defaults for specific component types:
switch ($type) {
case 'select':
$defaults['extra']['optrand'] = 1;
break;
case 'textfield':
case 'textarea':
$defaults['extra']['another_added_field'] = t('Another added default value');
}
}
/**
* Alter access to a Webform submission.
*
* @param $node
* The Webform node on which this submission was made.
* @param $submission
* The Webform submission.
* @param $op
* The operation to be performed on the submission. Possible values are:
* - "view"
* - "edit"
* - "delete"
* - "list"
* @param $account
* A user account object.
* @return
* TRUE if the current user has access to submission,
* or FALSE otherwise.
*/
function hook_webform_submission_access($node, $submission, $op = 'view', $account = NULL) {
switch ($op) {
case 'view':
return TRUE;
break;
case 'edit':
return FALSE;
break;
case 'delete':
return TRUE;
break;
case 'list':
return TRUE;
break;
}
}
/**
* Determine if a user has access to see the results of a webform.
*
* Note in addition to the view access to the results granted here, the $account
* must also have view access to the Webform node in order to see results.
* Access via this hook is in addition (adds permission) to the standard
* webform access.
*
* @see webform_results_access().
*
* @param $node
* The Webform node to check access on.
* @param $account
* The user account to check access on.
* @return
* TRUE or FALSE if the user can access the webform results.
*/
function hook_webform_results_access($node, $account) {
// Let editors view results of unpublished webforms.
if ($node->status == 0 && in_array('editor', $account->roles)) {
return TRUE;
}
else {
return FALSE;
}
}
/**
* Determine if a user has access to clear the results of a webform.
*
* Access via this hook is in addition (adds permission) to the standard
* webform access (delete all webform submissions).
*
* @see webform_results_clear_access().
*
* @param object $node
* The Webform node to check access on.
* @param object $account
* The user account to check access on.
* @return boolean
* TRUE or FALSE if the user can access the webform results.
*/
function hook_webform_results_clear_access($node, $account) {
return user_access('my additional access', $account);
}
/**
* Overrides the node_access and user_access permission to access and edit
* webform components, e-mails, conditions, and form settings.
*
* Return NULL to defer to other modules. If all implementations defer, then
* access to the node's EDIT tab plus 'edit webform components' permission
* determines access. To grant access, return TRUE; to deny access, return
* FALSE. If more than one implementation return TRUE/FALSE, all must be TRUE
* to grant access.
*
* In this way, access to the EDIT tab of the node may be decoupled from
* access to the WEBFORM tab. When returning TRUE, consider all aspects of
* access as this will be the only test. For example, 'return TRUE;' would grant
* annonymous access to creating webform components, which seldom be desired.
*
* @see webform_node_update_access().
*
* @param object $node
* The Webform node to check access on.
* @param object $account
* The user account to check access on.
* @return boolean|NULL
* TRUE or FALSE if the user can access the webform results, or NULL if
* access should be deferred to other implementations of this hook or
* node_access('update') plus user_access('edit webform components').
*/
function hook_webform_update_access($node, $account) {
// Allow anyone who can see webform_editable_by_user nodes and who has
// 'my webform component edit access' permission to see, edit, and delete the
// webform components, e-mails, conditionals, and form settings.
if ($node->type == 'webform_editable_by_user') {
return node_access('view', $node, $account) && user_access('my webform component edit access', $account);
}
}
/**
* Return an array of files associated with the component.
*
* The output of this function will be used to attach files to e-mail messages.
*
* @param $component
* A Webform component array.
* @param $value
* An array of information containing the submission result, directly
* correlating to the webform_submitted_data database schema.
* @return
* An array of files, each file is an array with following keys:
* - filepath: The relative path to the file.
* - filename: The name of the file including the extension.
* - filemime: The mimetype of the file.
* This will result in an array looking something like this:
* @code
* array[0] => array(
* 'filepath' => '/sites/default/files/attachment.txt',
* 'filename' => 'attachment.txt',
* 'filemime' => 'text/plain',
* );
* @endcode
*/
function _webform_attachments_component($component, $value) {
$files = array();
$files[] = (array) file_load($value[0]);
return $files;
}
/**
* Alter default settings for a newly created webform node.
*
* @param array $defaults
* Default settings for a newly created webform node as defined by webform_node_defaults().
*
* @see webform_node_defaults()
*/
function hook_webform_node_defaults_alter(&$defaults) {
$defaults['allow_draft'] = '1';
}
/**
* Add additional fields to submission data downloads.
*
* @return
* Keys and titles for default submission information.
*
* @see hook_webform_results_download_submission_information_data()
*/
function hook_webform_results_download_submission_information_info() {
return array(
'field_key_1' => t('Field Title 1'),
'field_key_2' => t('Field Title 2'),
);
}
/**
* Return values for submission data download fields.
*
* @param $token
* The name of the token being replaced.
* @param $submission
* The data for an individual submission from webform_get_submissions().
* @param $options
* A list of options that define the output format. These are generally passed
* through from the GUI interface.
* @param $serial_start
* The starting position for the Serial column in the output.
* @param $row_count
* The number of the row being generated.
*
* @return
* Value for requested submission information field.
*
* @see hook_webform_results_download_submission_information_info()
*/
function hook_webform_results_download_submission_information_data($token, $submission, array $options, $serial_start, $row_count) {
switch ($token) {
case 'field_key_1':
return 'Field Value 1';
case 'field_key_2':
return 'Field Value 2';
}
}
/**
* @}
*/
/**
* @defgroup webform_component Sample Webform Component
* @{
* In each of these examples, the word "component" should be replaced with the,
* name of the component type (such as textfield or select). These are not
* actual hooks, but instead samples of how Webform integrates with its own
* built-in components.
*/
/**
* Specify the default properties of a component.
*
* @return
* An array defining the default structure of a component.
*/
function _webform_defaults_component() {
return array(
'name' => '',
'form_key' => NULL,
'required' => 0,
'pid' => 0,
'weight' => 0,
'extra' => array(
'options' => '',
'questions' => '',
'optrand' => 0,
'qrand' => 0,
'description' => '',
'private' => FALSE,
'analysis' => TRUE,
),
);
}
/**
* Generate the form for editing a component.
*
* Create a set of form elements to be displayed on the form for editing this
* component. Use care naming the form items, as this correlates directly to the
* database schema. The component "Name" and "Description" fields are added to
* every component type and are not necessary to specify here (although they
* may be overridden if desired).
*
* @param $component
* A Webform component array.
* @return
* An array of form items to be displayed on the edit component page
*/
function _webform_edit_component($component) {
$form = array();
// Disabling the description if not wanted.
$form['description'] = array();
// Most options are stored in the "extra" array, which stores any settings
// unique to a particular component type.
$form['extra']['options'] = array(
'#type' => 'textarea',
'#title' => t('Options'),
'#default_value' => $component['extra']['options'],
'#description' => t('Key-value pairs may be entered separated by pipes. i.e. safe_key|Some readable option') . ' ' . theme('webform_token_help'),
'#cols' => 60,
'#rows' => 5,
'#weight' => -3,
'#required' => TRUE,
);
return $form;
}
/**
* Render a Webform component to be part of a form.
*
* @param $component
* A Webform component array.
* @param $value
* If editing an existing submission or resuming a draft, this will contain
* an array of values to be shown instead of the default in the component
* configuration. This value will always be an array, keyed numerically for
* each value saved in this field.
* @param $filter
* Whether or not to filter the contents of descriptions and values when
* rendering the component. Values need to be unfiltered to be editable by
* Form Builder.
* @param $submission
* The submission from which this component is being rendered. Usually not
* needed. Used by _webform_render_date() to validate using the submission's
* completion date.
*
* @see _webform_client_form_add_component()
*/
function _webform_render_component($component, $value = NULL, $filter = TRUE, $submission = NULL) {
$form_item = array(
'#type' => 'textfield',
'#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
'#required' => $component['required'],
'#weight' => $component['weight'],
'#description' => $filter ? webform_filter_descriptions($component['extra']['description']) : $component['extra']['description'],
'#default_value' => $filter ? webform_replace_tokens($component['value']) : $component['value'],
'#prefix' => '<div class="webform-component-textfield" id="webform-component-' . $component['form_key'] . '">',
'#suffix' => '</div>',
);
if (isset($value)) {
$form_item['#default_value'] = $value[0];
}
return $form_item;
}
/**
* Allow modules to modify a webform component that is going to be rendered in a form.
*
* @param array $element
* The display element as returned by _webform_render_component().
* @param array $component
* A Webform component array.
*
* @see _webform_render_component()
*/
function hook_webform_component_render_alter(&$element, &$component) {
if ($component['cid'] == 10) {
$element['#title'] = 'My custom title';
$element['#default_value'] = 42;
}
}
/**
* Display the result of a submission for a component.
*
* The output of this function will be displayed under the "Results" tab then
* "Submissions". This should output the saved data in some reasonable manner.
*
* @param $component
* A Webform component array.
* @param $value
* An array of information containing the submission result, directly
* correlating to the webform_submitted_data database table schema.
* @param $format
* Either 'html' or 'text'. Defines the format that the content should be
* returned as. Make sure that returned content is run through check_plain()
* or other filtering functions when returning HTML.
* @return
* A renderable element containing at the very least these properties:
* - #title
* - #weight
* - #component
* - #format
* - #value
* Webform also uses #theme_wrappers to output the end result to the user,
* which will properly format the label and content for use within an e-mail
* (such as wrapping the text) or as HTML (ensuring consistent output).
*/
function _webform_display_component($component, $value, $format = 'html') {
return array(
'#title' => $component['name'],
'#weight' => $component['weight'],
'#theme' => 'webform_display_textfield',
'#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
'#post_render' => array('webform_element_wrapper'),
'#field_prefix' => $component['extra']['field_prefix'],
'#field_suffix' => $component['extra']['field_suffix'],
'#component' => $component,
'#format' => $format,
'#value' => isset($value[0]) ? $value[0] : '',
);
}
/**
* Allow modules to modify a "display only" webform component.
*
* @param array $element
* The display element as returned by _webform_display_component().
* @param array $component
* A Webform component array.
*
* @see _webform_display_component()
*/
function hook_webform_component_display_alter(&$element, &$component) {
if ($component['cid'] == 10) {
$element['#title'] = 'My custom title';
$element['#default_value'] = 42;
}
}
/**
* A hook for changing the input values before saving to the database.
*
* Webform expects a component to consist of a single field, or a single array
* of fields. If you have a component that requires a deeper form tree
* you must flatten the data into a single array using this callback
* or by setting #parents on each field to avoid data loss and/or unexpected
* behavior.
*
* Note that Webform will save the result of this function directly into the
* database.
*
* @param $component
* A Webform component array.
* @param $value
* The POST data associated with the user input.
* @return
* An array of values to be saved into the database. Note that this should be
* a numerically keyed array.
*/
function _webform_submit_component($component, $value) {
// Clean up a phone number into 123-456-7890 format.
if ($component['extra']['phone_number']) {
$number = preg_replace('/[^0-9]/', '', $value[0]);
if (strlen($number) == 7) {
$number = substr($number, 0, 3) . '-' . substr($number, 3, 4);
}
else {
$number = substr($number, 0, 3) . '-' . substr($number, 3, 3) . '-' . substr($number, 6, 4);
}
}
$value[0] = $number;
return $value;
}
/**
* Delete operation for a component or submission.
*
* @param $component
* A Webform component array.
* @param $value
* An array of information containing the submission result, directly
* correlating to the webform_submitted_data database schema.
*/
function _webform_delete_component($component, $value) {
// Delete corresponding files when a submission is deleted.
if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
file_usage_delete($file, 'webform');
file_delete($file);
}
}
/**
* Module specific instance of hook_help().
*
* This allows each Webform component to add information into hook_help().
*/
function _webform_help_component($section) {
switch ($section) {
case 'admin/config/content/webform#grid_description':
return t('Allows creation of grid questions, denoted by radio buttons.');
}
}
/**
* Module specific instance of hook_theme().
*
* This allows each Webform component to add information into hook_theme(). If
* you specify a file to include, you must define the path to the module that
* this file belongs to.
*/
function _webform_theme_component() {
return array(
'webform_grid' => array(
'render element' => 'element',
'file' => 'components/grid.inc',
'path' => drupal_get_path('module', 'webform'),
),
'webform_display_grid' => array(
'render element' => 'element',
'file' => 'components/grid.inc',
'path' => drupal_get_path('module', 'webform'),
),
);
}
/**
* Calculate and returns statistics about results for this component.
*
* This takes into account all submissions to this webform. The output of this
* function will be displayed under the "Results" tab then "Analysis".
*
* @param $component
* An array of information describing the component, directly correlating to
* the webform_component database schema.
* @param $sids
* An optional array of submission IDs (sid). If supplied, the analysis will
* be limited to these sids.
* @param $single
* Boolean flag determining if the details about a single component are being
* shown. May be used to provided detailed information about a single
* component's analysis, such as showing "Other" options within a select list.
* @param $join
* An optional SelectQuery object to be used to join with the submissions
* table to restrict the submissions being analyzed.
* @return
* An array containing one or more of the following keys:
* - table_rows: If this component has numeric data that can be represented in
* a grid, return the values here. This array assumes a 2-dimensional
* structure, with the first value being a label and subsequent values
* containing a decimal or integer.
* - table_header: If this component has more than a single set of values,
* include a table header so each column can be labeled.
* - other_data: If your component has non-numeric data to include, such as
* a description or link, include that in the other_data array. Each item
* may be a string or an array of values that matches the number of columns
* in the table_header property.
* At the very least, either table_rows or other_data should be provided.
* Note that if you want your component's analysis to be available by default
* without the user specifically enabling it, you must set
* $component['extra']['analysis'] = TRUE in your
* _webform_defaults_component() callback.
*
* @see _webform_defaults_component()
*/
function _webform_analysis_component($component, $sids = array(), $single = FALSE, $join = NULL) {
// Generate the list of options and questions.
$options = _webform_select_options_from_text($component['extra']['options'], TRUE);
$questions = _webform_select_options_from_text($component['extra']['questions'], TRUE);
// Generate a lookup table of results.
$query = db_select('webform_submitted_data', 'wsd')
->fields('wsd', array('no', 'data'))
->condition('nid', $component['nid'])
->condition('cid', $component['cid'])
->condition('data', '', '<>')
->groupBy('no')
->groupBy('data');
$query->addExpression('COUNT(sid)', 'datacount');
if (count($sids)) {
$query->condition('sid', $sids, 'IN');
}
if ($join) {
$query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
}
$result = $query->execute();
$counts = array();
foreach ($result as $data) {
$counts[$data->no][$data->data] = $data->datacount;
}
// Create an entire table to be put into the returned row.
$rows = array();
$header = array('');
// Add options as a header row.
foreach ($options as $option) {
$header[] = $option;
}
// Add questions as each row.
foreach ($questions as $qkey => $question) {
$row = array($question);
foreach ($options as $okey => $option) {
$row[] = !empty($counts[$qkey][$okey]) ? $counts[$qkey][$okey] : 0;
}
$rows[] = $row;
}
$other = array();
$other[] = l(t('More information'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']);
return array(
'table_header' => $header,
'table_rows' => $rows,
'other_data' => $other,
);
}
/**
* Return the result of a component value for display in a table.
*
* The output of this function will be displayed under the "Results" tab then
* "Table".
*
* @param $component
* A Webform component array.
* @param $value
* An array of information containing the submission result, directly
* correlating to the webform_submitted_data database schema.
* @return
* Textual output formatted for human reading.
*/
function _webform_table_component($component, $value) {
$questions = array_values(_webform_component_options($component['extra']['questions']));
$output = '';
// Set the value as a single string.
if (is_array($value)) {
foreach ($value as $item => $value) {
if ($value !== '') {
$output .= $questions[$item] . ': ' . check_plain($value) . '<br />';
}
}
}
else {
$output = check_plain(!isset($value['0']) ? '' : $value['0']);
}
return $output;
}
/**
* Return the header for this component to be displayed in a CSV file.
*
* The output of this function will be displayed under the "Results" tab then
* "Download".
*
* @param $component
* A Webform component array.
* @param $export_options
* An array of options that may configure export of this field.
* @return
* An array of data to be displayed in the first three rows of a CSV file, not
* including either prefixed or trailing commas.
*/
function _webform_csv_headers_component($component, $export_options) {
$header = array();
$header[0] = array('');
$header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name']);
$items = _webform_component_options($component['extra']['questions']);
$count = 0;
foreach ($items as $key => $item) {
// Empty column per sub-field in main header.
if ($count != 0) {
$header[0][] = '';
$header[1][] = '';
}
// The value for this option.
$header[2][] = $item;
$count++;
}
return $header;
}
/**
* Format the submitted data of a component for CSV downloading.
*
* The output of this function will be displayed under the "Results" tab then
* "Download".
*
* @param $component
* A Webform component array.
* @param $export_options
* An array of options that may configure export of this field.
* @param $value
* An array of information containing the submission result, directly
* correlating to the webform_submitted_data database schema.
* @return
* An array of items to be added to the CSV file. Each value within the array
* will be another column within the file. This function is called once for
* every row of data.
*/
function _webform_csv_data_component($component, $export_options, $value) {
$questions = array_keys(_webform_select_options($component['extra']['questions']));
$return = array();
foreach ($questions as $key => $question) {
$return[] = isset($value[$key]) ? $value[$key] : '';
}
return $return;
}
/**
* Adjusts the view field(s) that are automatically generated for number
* components.
*
* Provides each component the opportunity to adjust how this component is
* displayed in a view as a field in a view table. For example, a component may
* modify how it responds to click-sorting. Or it may add additional fields,
* such as a grid component having a column for each question.
*
* @param array $component
* A Webform component array
* @param array $fields
* An array of field-definition arrays. Will be passed one field definition,
* which may be modified. Additional fields may be added to the array.
* @return array
* The modified $fields array.
*/
function _webform_view_field_component($component, $fields) {
foreach ($fields as &$field) {
$field['webform_datatype'] = 'number';
}
return $fields;
}
/**
* Modify the how a view was expanded to show all the components.
*
* This alter function is only called when the view is actually modified. It
* provides modules an opportunity to alter the changes that webform made to
* the view.
*
* This hook is called from webform_views_pre_view. If another module also
* changes views by implementing this same views hook, the relative order of
* execution of the two implementations will depend upon the module weights of
* the two modules. Using hook_webform_view_alter instead guarantees an
* opportuinty to modify the view AFTER webform.
*
* @param object $view
* The view object.
* @param string $display_id
* The display_id that was expanded by webform.
* @param array $args
* The argumentst that were passed to the view.
*/
function hook_webform_view_alter($view, $display_id, $args) {
// Don't show component with cid == 4
$fields = $view->get_items('field', $display_id);
foreach ($fields as $id => $field) {
if (isset($field['webform_cid']) && $field['webform_cid'] == 4) {
unset($fields[$id]);
}
}
$view->display[$display_id]->handler->set_option('fields', $fields);
}
/**
* Modify the list of mail systems that are capable of sending HTML email.
*
* @param array &$systems
* An array of mail system class names.
*/
function hook_webform_html_capable_mail_systems_alter(&$systems) {
if (module_exists('my_module')) {
$systems[] = 'MyModuleMailSystem';
}
}
/**
* @}
*/
| nandoalvarado022/colombianime | sitios/inmobiliaria/sites/all/modules/webform/webform.api.php | PHP | gpl-2.0 | 44,278 |
/******************************************************************************
*
* Copyright(c) 2009-2014 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#ifndef __RTL92E_HW_H__
#define __RTL92E_HW_H__
void rtl92ee_get_hw_reg(struct ieee80211_hw *hw, u8 variable, u8 *val);
void rtl92ee_read_eeprom_info(struct ieee80211_hw *hw);
void rtl92ee_interrupt_recognized(struct ieee80211_hw *hw,
struct rtl_int *int_vec);
int rtl92ee_hw_init(struct ieee80211_hw *hw);
void rtl92ee_card_disable(struct ieee80211_hw *hw);
void rtl92ee_enable_interrupt(struct ieee80211_hw *hw);
void rtl92ee_disable_interrupt(struct ieee80211_hw *hw);
int rtl92ee_set_network_type(struct ieee80211_hw *hw, enum nl80211_iftype type);
void rtl92ee_set_check_bssid(struct ieee80211_hw *hw, bool check_bssid);
void rtl92ee_set_qos(struct ieee80211_hw *hw, int aci);
void rtl92ee_set_beacon_related_registers(struct ieee80211_hw *hw);
void rtl92ee_set_beacon_interval(struct ieee80211_hw *hw);
void rtl92ee_update_interrupt_mask(struct ieee80211_hw *hw,
u32 add_msr, u32 rm_msr);
void rtl92ee_set_hw_reg(struct ieee80211_hw *hw, u8 variable, u8 *val);
void rtl92ee_update_hal_rate_tbl(struct ieee80211_hw *hw,
struct ieee80211_sta *sta, u8 rssi_level,
bool update_bw);
void rtl92ee_update_channel_access_setting(struct ieee80211_hw *hw);
bool rtl92ee_gpio_radio_on_off_checking(struct ieee80211_hw *hw, u8 *valid);
void rtl92ee_enable_hw_security_config(struct ieee80211_hw *hw);
void rtl92ee_set_key(struct ieee80211_hw *hw, u32 key_index,
u8 *p_macaddr, bool is_group, u8 enc_algo,
bool is_wepkey, bool clear_all);
void rtl92ee_read_bt_coexist_info_from_hwpg(struct ieee80211_hw *hw,
bool autoload_fail, u8 *hwinfo);
void rtl92ee_bt_reg_init(struct ieee80211_hw *hw);
void rtl92ee_bt_hw_init(struct ieee80211_hw *hw);
void rtl92ee_suspend(struct ieee80211_hw *hw);
void rtl92ee_resume(struct ieee80211_hw *hw);
void rtl92ee_allow_all_destaddr(struct ieee80211_hw *hw, bool allow_all_da,
bool write_into_reg);
void rtl92ee_fw_clk_off_timer_callback(unsigned long data);
#endif
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.19/drivers/net/wireless/realtek/rtlwifi/rtl8192ee/hw.h | C | gpl-2.0 | 2,911 |
<?php
/**
* Social Login
*
* @version 1.0
* @author SmokerMan, Arkadiy, Joomline
* @copyright © 2012. All rights reserved.
* @license GNU/GPL v.3 or later.
*/
// защита от прямого доступа
defined('_JEXEC') or die('@-_-@');
jimport('joomla.form.formfield');
class JFormFieldCallbackUrl extends JFormField
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
public $type = 'CallbackUrl';
/**
* Method to get the field input markup.
*
* @return string The field input markup.
* @since 1.6
*/
protected function getInput()
{
$task = !empty($this->element['value']) ? '?option=com_slogin&task=check&plugin=' . (string) $this->element['value'] : '';
$readonly = ((string) $this->element['readonly'] == 'true') ? ' readonly="readonly"' : '';
$class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : '';
$CallbackUrl = JURI::root().$task;
if(substr($CallbackUrl, -1, 1) == '/'){
$CallbackUrl = substr($CallbackUrl, 0, -1);
}
$html = '<input type="text" name="' . $this->name . '" id="' . $this->id . '"' . ' value="'.$CallbackUrl.'" size="70%" '. $class . $readonly .' />';
return $html;
}
} | IYEO/Sweettaste | tmp/install_5680f69da1732/install_5680f6ad8ef2b/element/callbackurl.php | PHP | gpl-2.0 | 1,284 |
/*******************************************************************************
Intel PRO/10GbE Linux driver
Copyright(c) 1999 - 2008 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "ixgb_hw.h"
#include "ixgb_ee.h"
/* Local prototypes */
static u16 ixgb_shift_in_bits(struct ixgb_hw *hw);
static void ixgb_shift_out_bits(struct ixgb_hw *hw,
u16 data,
u16 count);
static void ixgb_standby_eeprom(struct ixgb_hw *hw);
static bool ixgb_wait_eeprom_command(struct ixgb_hw *hw);
static void ixgb_cleanup_eeprom(struct ixgb_hw *hw);
/******************************************************************************
* Raises the EEPROM's clock input.
*
* hw - Struct containing variables accessed by shared code
* eecd_reg - EECD's current value
*****************************************************************************/
static void
ixgb_raise_clock(struct ixgb_hw *hw,
u32 *eecd_reg)
{
/* Raise the clock input to the EEPROM (by setting the SK bit), and then
* wait 50 microseconds.
*/
*eecd_reg = *eecd_reg | IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, *eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Lowers the EEPROM's clock input.
*
* hw - Struct containing variables accessed by shared code
* eecd_reg - EECD's current value
*****************************************************************************/
static void
ixgb_lower_clock(struct ixgb_hw *hw,
u32 *eecd_reg)
{
/* Lower the clock input to the EEPROM (by clearing the SK bit), and then
* wait 50 microseconds.
*/
*eecd_reg = *eecd_reg & ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, *eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Shift data bits out to the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* data - data to send to the EEPROM
* count - number of bits to shift out
*****************************************************************************/
static void
ixgb_shift_out_bits(struct ixgb_hw *hw,
u16 data,
u16 count)
{
u32 eecd_reg;
u32 mask;
/* We need to shift "count" bits out to the EEPROM. So, value in the
* "data" parameter will be shifted out to the EEPROM one bit at a time.
* In order to do this, "data" must be broken down into bits.
*/
mask = 0x01 << (count - 1);
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DO | IXGB_EECD_DI);
do {
/* A "1" is shifted out to the EEPROM by setting bit "DI" to a "1",
* and then raising and then lowering the clock (the SK bit controls
* the clock input to the EEPROM). A "0" is shifted out to the EEPROM
* by setting "DI" to "0" and then raising and then lowering the clock.
*/
eecd_reg &= ~IXGB_EECD_DI;
if (data & mask)
eecd_reg |= IXGB_EECD_DI;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
ixgb_raise_clock(hw, &eecd_reg);
ixgb_lower_clock(hw, &eecd_reg);
mask = mask >> 1;
} while (mask);
/* We leave the "DI" bit set to "0" when we leave this routine. */
eecd_reg &= ~IXGB_EECD_DI;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
}
/******************************************************************************
* Shift data bits in from the EEPROM
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static u16
ixgb_shift_in_bits(struct ixgb_hw *hw)
{
u32 eecd_reg;
u32 i;
u16 data;
/* In order to read a register from the EEPROM, we need to shift 16 bits
* in from the EEPROM. Bits are "shifted in" by raising the clock input to
* the EEPROM (setting the SK bit), and then reading the value of the "DO"
* bit. During this "shifting in" process the "DI" bit should always be
* clear..
*/
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DO | IXGB_EECD_DI);
data = 0;
for (i = 0; i < 16; i++) {
data = data << 1;
ixgb_raise_clock(hw, &eecd_reg);
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DI);
if (eecd_reg & IXGB_EECD_DO)
data |= 1;
ixgb_lower_clock(hw, &eecd_reg);
}
return data;
}
/******************************************************************************
* Prepares EEPROM for access
*
* hw - Struct containing variables accessed by shared code
*
* Lowers EEPROM clock. Clears input pin. Sets the chip select pin. This
* function should be called before issuing a command to the EEPROM.
*****************************************************************************/
static void
ixgb_setup_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Clear SK and DI */
eecd_reg &= ~(IXGB_EECD_SK | IXGB_EECD_DI);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
/* Set CS */
eecd_reg |= IXGB_EECD_CS;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
}
/******************************************************************************
* Returns EEPROM to a "standby" state
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_standby_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Deselect EEPROM */
eecd_reg &= ~(IXGB_EECD_CS | IXGB_EECD_SK);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Clock high */
eecd_reg |= IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Select EEPROM */
eecd_reg |= IXGB_EECD_CS;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Clock low */
eecd_reg &= ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Raises then lowers the EEPROM's clock pin
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_clock_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Rising edge of clock */
eecd_reg |= IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Falling edge of clock */
eecd_reg &= ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Terminates a command by lowering the EEPROM's chip select pin
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_cleanup_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_CS | IXGB_EECD_DI);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
ixgb_clock_eeprom(hw);
}
/******************************************************************************
* Waits for the EEPROM to finish the current command.
*
* hw - Struct containing variables accessed by shared code
*
* The command is done when the EEPROM's data out pin goes high.
*
* Returns:
* true: EEPROM data pin is high before timeout.
* false: Time expired.
*****************************************************************************/
static bool
ixgb_wait_eeprom_command(struct ixgb_hw *hw)
{
u32 eecd_reg;
u32 i;
/* Toggle the CS line. This in effect tells to EEPROM to actually execute
* the command in question.
*/
ixgb_standby_eeprom(hw);
/* Now read DO repeatedly until is high (equal to '1'). The EEPROM will
* signal that the command has been completed by raising the DO signal.
* If DO does not go high in 10 milliseconds, then error out.
*/
for (i = 0; i < 200; i++) {
eecd_reg = IXGB_READ_REG(hw, EECD);
if (eecd_reg & IXGB_EECD_DO)
return true;
udelay(50);
}
ASSERT(0);
return false;
}
/******************************************************************************
* Verifies that the EEPROM has a valid checksum
*
* hw - Struct containing variables accessed by shared code
*
* Reads the first 64 16 bit words of the EEPROM and sums the values read.
* If the sum of the 64 16 bit words is 0xBABA, the EEPROM's checksum is
* valid.
*
* Returns:
* true: Checksum is valid
* false: Checksum is not valid.
*****************************************************************************/
bool
ixgb_validate_eeprom_checksum(struct ixgb_hw *hw)
{
u16 checksum = 0;
u16 i;
for (i = 0; i < (EEPROM_CHECKSUM_REG + 1); i++)
checksum += ixgb_read_eeprom(hw, i);
if (checksum == (u16) EEPROM_SUM)
return true;
else
return false;
}
/******************************************************************************
* Calculates the EEPROM checksum and writes it to the EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Sums the first 63 16 bit words of the EEPROM. Subtracts the sum from 0xBABA.
* Writes the difference to word offset 63 of the EEPROM.
*****************************************************************************/
void
ixgb_update_eeprom_checksum(struct ixgb_hw *hw)
{
u16 checksum = 0;
u16 i;
for (i = 0; i < EEPROM_CHECKSUM_REG; i++)
checksum += ixgb_read_eeprom(hw, i);
checksum = (u16) EEPROM_SUM - checksum;
ixgb_write_eeprom(hw, EEPROM_CHECKSUM_REG, checksum);
}
/******************************************************************************
* Writes a 16 bit word to a given offset in the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* reg - offset within the EEPROM to be written to
* data - 16 bit word to be written to the EEPROM
*
* If ixgb_update_eeprom_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
*
*****************************************************************************/
void
ixgb_write_eeprom(struct ixgb_hw *hw, u16 offset, u16 data)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
/* Prepare the EEPROM for writing */
ixgb_setup_eeprom(hw);
/* Send the 9-bit EWEN (write enable) command to the EEPROM (5-bit opcode
* plus 4-bit dummy). This puts the EEPROM into write/erase mode.
*/
ixgb_shift_out_bits(hw, EEPROM_EWEN_OPCODE, 5);
ixgb_shift_out_bits(hw, 0, 4);
/* Prepare the EEPROM */
ixgb_standby_eeprom(hw);
/* Send the Write command (3-bit opcode + 6-bit addr) */
ixgb_shift_out_bits(hw, EEPROM_WRITE_OPCODE, 3);
ixgb_shift_out_bits(hw, offset, 6);
/* Send the data */
ixgb_shift_out_bits(hw, data, 16);
ixgb_wait_eeprom_command(hw);
/* Recover from write */
ixgb_standby_eeprom(hw);
/* Send the 9-bit EWDS (write disable) command to the EEPROM (5-bit
* opcode plus 4-bit dummy). This takes the EEPROM out of write/erase
* mode.
*/
ixgb_shift_out_bits(hw, EEPROM_EWDS_OPCODE, 5);
ixgb_shift_out_bits(hw, 0, 4);
/* Done with writing */
ixgb_cleanup_eeprom(hw);
/* clear the init_ctrl_reg_1 to signify that the cache is invalidated */
ee_map->init_ctrl_reg_1 = cpu_to_le16(EEPROM_ICW1_SIGNATURE_CLEAR);
}
/******************************************************************************
* Reads a 16 bit word from the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* offset - offset of 16 bit word in the EEPROM to read
*
* Returns:
* The 16-bit value read from the eeprom
*****************************************************************************/
u16
ixgb_read_eeprom(struct ixgb_hw *hw,
u16 offset)
{
u16 data;
/* Prepare the EEPROM for reading */
ixgb_setup_eeprom(hw);
/* Send the READ command (opcode + addr) */
ixgb_shift_out_bits(hw, EEPROM_READ_OPCODE, 3);
/*
* We have a 64 word EEPROM, there are 6 address bits
*/
ixgb_shift_out_bits(hw, offset, 6);
/* Read the data */
data = ixgb_shift_in_bits(hw);
/* End this read operation */
ixgb_standby_eeprom(hw);
return data;
}
/******************************************************************************
* Reads eeprom and stores data in shared structure.
* Validates eeprom checksum and eeprom signature.
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* true: if eeprom read is successful
* false: otherwise.
*****************************************************************************/
bool
ixgb_get_eeprom_data(struct ixgb_hw *hw)
{
u16 i;
u16 checksum = 0;
struct ixgb_ee_map_type *ee_map;
ENTER();
ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
pr_debug("Reading eeprom data\n");
for (i = 0; i < IXGB_EEPROM_SIZE ; i++) {
u16 ee_data;
ee_data = ixgb_read_eeprom(hw, i);
checksum += ee_data;
hw->eeprom[i] = cpu_to_le16(ee_data);
}
if (checksum != (u16) EEPROM_SUM) {
pr_debug("Checksum invalid\n");
/* clear the init_ctrl_reg_1 to signify that the cache is
* invalidated */
ee_map->init_ctrl_reg_1 = cpu_to_le16(EEPROM_ICW1_SIGNATURE_CLEAR);
return false;
}
if ((ee_map->init_ctrl_reg_1 & cpu_to_le16(EEPROM_ICW1_SIGNATURE_MASK))
!= cpu_to_le16(EEPROM_ICW1_SIGNATURE_VALID)) {
pr_debug("Signature invalid\n");
return false;
}
return true;
}
/******************************************************************************
* Local function to check if the eeprom signature is good
* If the eeprom signature is good, calls ixgb)get_eeprom_data.
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* true: eeprom signature was good and the eeprom read was successful
* false: otherwise.
******************************************************************************/
static bool
ixgb_check_and_get_eeprom_data (struct ixgb_hw* hw)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
if ((ee_map->init_ctrl_reg_1 & cpu_to_le16(EEPROM_ICW1_SIGNATURE_MASK))
== cpu_to_le16(EEPROM_ICW1_SIGNATURE_VALID)) {
return true;
} else {
return ixgb_get_eeprom_data(hw);
}
}
/******************************************************************************
* return a word from the eeprom
*
* hw - Struct containing variables accessed by shared code
* index - Offset of eeprom word
*
* Returns:
* Word at indexed offset in eeprom, if valid, 0 otherwise.
******************************************************************************/
__le16
ixgb_get_eeprom_word(struct ixgb_hw *hw, u16 index)
{
if ((index < IXGB_EEPROM_SIZE) &&
(ixgb_check_and_get_eeprom_data(hw) == true)) {
return hw->eeprom[index];
}
return 0;
}
/******************************************************************************
* return the mac address from EEPROM
*
* hw - Struct containing variables accessed by shared code
* mac_addr - Ethernet Address if EEPROM contents are valid, 0 otherwise
*
* Returns: None.
******************************************************************************/
void
ixgb_get_ee_mac_addr(struct ixgb_hw *hw,
u8 *mac_addr)
{
int i;
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
ENTER();
if (ixgb_check_and_get_eeprom_data(hw) == true) {
for (i = 0; i < IXGB_ETH_LENGTH_OF_ADDRESS; i++) {
mac_addr[i] = ee_map->mac_addr[i];
}
pr_debug("eeprom mac address = %pM\n", mac_addr);
}
}
/******************************************************************************
* return the Printed Board Assembly number from EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* PBA number if EEPROM contents are valid, 0 otherwise
******************************************************************************/
u32
ixgb_get_ee_pba_number(struct ixgb_hw *hw)
{
if (ixgb_check_and_get_eeprom_data(hw) == true)
return le16_to_cpu(hw->eeprom[EEPROM_PBA_1_2_REG])
| (le16_to_cpu(hw->eeprom[EEPROM_PBA_3_4_REG])<<16);
return 0;
}
/******************************************************************************
* return the Device Id from EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* Device Id if EEPROM contents are valid, 0 otherwise
******************************************************************************/
u16
ixgb_get_ee_device_id(struct ixgb_hw *hw)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
if (ixgb_check_and_get_eeprom_data(hw) == true)
return le16_to_cpu(ee_map->device_id);
return 0;
}
| sahdman/rpi_android_kernel | linux-3.1.9/drivers/net/ixgb/ixgb_ee.c | C | mit | 17,529 |
# $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
Admonition directives.
"""
__docformat__ = 'reStructuredText'
from docutils.parsers.rst import Directive
from docutils.parsers.rst import states, directives
from docutils.parsers.rst.roles import set_classes
from docutils import nodes
class BaseAdmonition(Directive):
final_argument_whitespace = True
option_spec = {'class': directives.class_option,
'name': directives.unchanged}
has_content = True
node_class = None
"""Subclasses must set this to the appropriate admonition node class."""
def run(self):
set_classes(self.options)
self.assert_has_content()
text = '\n'.join(self.content)
admonition_node = self.node_class(text, **self.options)
self.add_name(admonition_node)
if self.node_class is nodes.admonition:
title_text = self.arguments[0]
textnodes, messages = self.state.inline_text(title_text,
self.lineno)
title = nodes.title(title_text, '', *textnodes)
title.source, title.line = (
self.state_machine.get_source_and_line(self.lineno))
admonition_node += title
admonition_node += messages
if not 'classes' in self.options:
admonition_node['classes'] += ['admonition-' +
nodes.make_id(title_text)]
self.state.nested_parse(self.content, self.content_offset,
admonition_node)
return [admonition_node]
class Admonition(BaseAdmonition):
required_arguments = 1
node_class = nodes.admonition
class Attention(BaseAdmonition):
node_class = nodes.attention
class Caution(BaseAdmonition):
node_class = nodes.caution
class Danger(BaseAdmonition):
node_class = nodes.danger
class Error(BaseAdmonition):
node_class = nodes.error
class Hint(BaseAdmonition):
node_class = nodes.hint
class Important(BaseAdmonition):
node_class = nodes.important
class Note(BaseAdmonition):
node_class = nodes.note
class Tip(BaseAdmonition):
node_class = nodes.tip
class Warning(BaseAdmonition):
node_class = nodes.warning
| JulienMcJay/eclock | windows/Python27/Lib/site-packages/docutils/parsers/rst/directives/admonitions.py | Python | gpl-2.0 | 2,413 |
class Blazeblogger < Formula
desc "CMS for the command-line"
homepage "http://blaze.blackened.cz/"
url "https://blazeblogger.googlecode.com/files/blazeblogger-1.2.0.tar.gz"
sha1 "280894fca6594d0c0df925aa0a16b9116ee19f17"
bottle do
cellar :any
sha1 "2576ceff864dd2059bcd73af26f735725dd7274c" => :yosemite
sha1 "068b94d384d5820938c4561df7357ae116bf23c4" => :mavericks
sha1 "da491de4ea179354dcb8345b244d36fec30c0c6a" => :mountain_lion
end
def install
# https://code.google.com/p/blazeblogger/issues/detail?id=51
ENV.deparallelize
system "make", "prefix=#{prefix}", "compdir=#{prefix}", "install"
end
test do
system bin/"blaze", "init"
system bin/"blaze", "config", "blog.title", "Homebrew!"
system bin/"blaze", "make"
assert File.exist? "default.css"
assert File.read(".blaze/config").include?("Homebrew!")
end
end
| kyanny/homebrew | Library/Formula/blazeblogger.rb | Ruby | bsd-2-clause | 883 |
require 'formula'
class Mad < Formula
desc "MPEG audio decoder"
homepage 'http://www.underbit.com/products/mad/'
url 'https://downloads.sourceforge.net/project/mad/libmad/0.15.1b/libmad-0.15.1b.tar.gz'
sha1 'cac19cd00e1a907f3150cc040ccc077783496d76'
bottle do
cellar :any
revision 1
sha1 "ec696978cd2bbd43ed11b6b1d3b78156d2b97c71" => :yosemite
sha1 "b8ea86acc3a5aab051e7df3d6e1b00ac1acac346" => :mavericks
sha1 "7164d878d4467cda6bbed49fd46129a4ae3169ec" => :mountain_lion
end
def install
fpm = MacOS.prefer_64_bit? ? '64bit': 'intel'
system "./configure", "--disable-debugging", "--enable-fpm=#{fpm}", "--prefix=#{prefix}"
system "make", "CFLAGS=#{ENV.cflags}", "LDFLAGS=#{ENV.ldflags}", "install"
(lib+'pkgconfig/mad.pc').write pc_file
end
def pc_file; <<-EOS.undent
prefix=#{opt_prefix}
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include
Name: mad
Description: MPEG Audio Decoder
Version: #{version}
Requires:
Conflicts:
Libs: -L${libdir} -lmad -lm
Cflags: -I${includedir}
EOS
end
end
| karlhigley/homebrew | Library/Formula/mad.rb | Ruby | bsd-2-clause | 1,122 |
/*
* Some debug functions
*
* MIPS floating point support
*
* Copyright (C) 1994-2000 Algorithmics Ltd.
* http://www.algor.co.uk
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* Nov 7, 2000
* Modified to build and operate in Linux kernel environment.
*
* Kevin D. Kissell, kevink@mips.com and Carsten Langgaard, carstenl@mips.com
* Copyright (C) 2000 MIPS Technologies, Inc. All rights reserved.
*/
#include <linux/kernel.h>
#include "ieee754.h"
#define DP_EBIAS 1023
#define DP_EMIN (-1022)
#define DP_EMAX 1023
#define DP_FBITS 52
#define SP_EBIAS 127
#define SP_EMIN (-126)
#define SP_EMAX 127
#define SP_FBITS 23
#define DP_MBIT(x) ((u64)1 << (x))
#define DP_HIDDEN_BIT DP_MBIT(DP_FBITS)
#define DP_SIGN_BIT DP_MBIT(63)
#define SP_MBIT(x) ((u32)1 << (x))
#define SP_HIDDEN_BIT SP_MBIT(SP_FBITS)
#define SP_SIGN_BIT SP_MBIT(31)
#define SPSIGN(sp) (sp.parts.sign)
#define SPBEXP(sp) (sp.parts.bexp)
#define SPMANT(sp) (sp.parts.mant)
#define DPSIGN(dp) (dp.parts.sign)
#define DPBEXP(dp) (dp.parts.bexp)
#define DPMANT(dp) (dp.parts.mant)
ieee754dp ieee754dp_dump(char *m, ieee754dp x)
{
int i;
printk("%s", m);
printk("<%08x,%08x>\n", (unsigned) (x.bits >> 32),
(unsigned) x.bits);
printk("\t=");
switch (ieee754dp_class(x)) {
case IEEE754_CLASS_QNAN:
case IEEE754_CLASS_SNAN:
printk("Nan %c", DPSIGN(x) ? '-' : '+');
for (i = DP_FBITS - 1; i >= 0; i--)
printk("%c", DPMANT(x) & DP_MBIT(i) ? '1' : '0');
break;
case IEEE754_CLASS_INF:
printk("%cInfinity", DPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_ZERO:
printk("%cZero", DPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_DNORM:
printk("%c0.", DPSIGN(x) ? '-' : '+');
for (i = DP_FBITS - 1; i >= 0; i--)
printk("%c", DPMANT(x) & DP_MBIT(i) ? '1' : '0');
printk("e%d", DPBEXP(x) - DP_EBIAS);
break;
case IEEE754_CLASS_NORM:
printk("%c1.", DPSIGN(x) ? '-' : '+');
for (i = DP_FBITS - 1; i >= 0; i--)
printk("%c", DPMANT(x) & DP_MBIT(i) ? '1' : '0');
printk("e%d", DPBEXP(x) - DP_EBIAS);
break;
default:
printk("Illegal/Unknown IEEE754 value class");
}
printk("\n");
return x;
}
ieee754sp ieee754sp_dump(char *m, ieee754sp x)
{
int i;
printk("%s=", m);
printk("<%08x>\n", (unsigned) x.bits);
printk("\t=");
switch (ieee754sp_class(x)) {
case IEEE754_CLASS_QNAN:
case IEEE754_CLASS_SNAN:
printk("Nan %c", SPSIGN(x) ? '-' : '+');
for (i = SP_FBITS - 1; i >= 0; i--)
printk("%c", SPMANT(x) & SP_MBIT(i) ? '1' : '0');
break;
case IEEE754_CLASS_INF:
printk("%cInfinity", SPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_ZERO:
printk("%cZero", SPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_DNORM:
printk("%c0.", SPSIGN(x) ? '-' : '+');
for (i = SP_FBITS - 1; i >= 0; i--)
printk("%c", SPMANT(x) & SP_MBIT(i) ? '1' : '0');
printk("e%d", SPBEXP(x) - SP_EBIAS);
break;
case IEEE754_CLASS_NORM:
printk("%c1.", SPSIGN(x) ? '-' : '+');
for (i = SP_FBITS - 1; i >= 0; i--)
printk("%c", SPMANT(x) & SP_MBIT(i) ? '1' : '0');
printk("e%d", SPBEXP(x) - SP_EBIAS);
break;
default:
printk("Illegal/Unknown IEEE754 value class");
}
printk("\n");
return x;
}
| wkritzinger/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/arch/mips/math-emu/ieee754d.c | C | gpl-2.0 | 3,765 |
/*! jQuery UI - v1.9.2 - 2012-11-23
* http://jqueryui.com
* Includes: jquery.ui.datepicker-ro.js
* Copyright 2012 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.ro={closeText:"Închide",prevText:"« Luna precedentă",nextText:"Luna următoare »",currentText:"Azi",monthNames:["Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","Noiembrie","Decembrie"],monthNamesShort:["Ian","Feb","Mar","Apr","Mai","Iun","Iul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Duminică","Luni","Marţi","Miercuri","Joi","Vineri","Sâmbătă"],dayNamesShort:["Dum","Lun","Mar","Mie","Joi","Vin","Sâm"],dayNamesMin:["Du","Lu","Ma","Mi","Jo","Vi","Sâ"],weekHeader:"Săpt",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.ro)}); | ninjablocks/ninja-sentinel | yeoman/components/jquery-ui/ui/minified/i18n/jquery.ui.datepicker-ro.min.js | JavaScript | mit | 888 |
/*
* linux/arch/arm/mach-omap2/board-omap3evm.c
*
* Copyright (C) 2008 Texas Instruments
*
* Modified from mach-omap2/board-3430sdp.c
*
* Initial code: Syed Mohammed Khasim
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/leds.h>
#include <linux/interrupt.h>
#include <linux/spi/spi.h>
#include <linux/spi/ads7846.h>
#include <linux/i2c/twl.h>
#include <linux/usb/otg.h>
#include <linux/smsc911x.h>
#include <linux/regulator/machine.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <plat/board.h>
#include <plat/usb.h>
#include <plat/common.h>
#include <plat/mcspi.h>
#include <plat/display.h>
#include "mux.h"
#include "sdram-micron-mt46h32m32lf-6.h"
#include "hsmmc.h"
#define OMAP3_EVM_TS_GPIO 175
#define OMAP3_EVM_EHCI_VBUS 22
#define OMAP3_EVM_EHCI_SELECT 61
#define OMAP3EVM_ETHR_START 0x2c000000
#define OMAP3EVM_ETHR_SIZE 1024
#define OMAP3EVM_ETHR_ID_REV 0x50
#define OMAP3EVM_ETHR_GPIO_IRQ 176
#define OMAP3EVM_SMSC911X_CS 5
static u8 omap3_evm_version;
u8 get_omap3_evm_rev(void)
{
return omap3_evm_version;
}
EXPORT_SYMBOL(get_omap3_evm_rev);
static void __init omap3_evm_get_revision(void)
{
void __iomem *ioaddr;
unsigned int smsc_id;
/* Ethernet PHY ID is stored at ID_REV register */
ioaddr = ioremap_nocache(OMAP3EVM_ETHR_START, SZ_1K);
if (!ioaddr)
return;
smsc_id = readl(ioaddr + OMAP3EVM_ETHR_ID_REV) & 0xFFFF0000;
iounmap(ioaddr);
switch (smsc_id) {
/*SMSC9115 chipset*/
case 0x01150000:
omap3_evm_version = OMAP3EVM_BOARD_GEN_1;
break;
/*SMSC 9220 chipset*/
case 0x92200000:
default:
omap3_evm_version = OMAP3EVM_BOARD_GEN_2;
}
}
#if defined(CONFIG_SMSC911X) || defined(CONFIG_SMSC911X_MODULE)
static struct resource omap3evm_smsc911x_resources[] = {
[0] = {
.start = OMAP3EVM_ETHR_START,
.end = (OMAP3EVM_ETHR_START + OMAP3EVM_ETHR_SIZE - 1),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = OMAP_GPIO_IRQ(OMAP3EVM_ETHR_GPIO_IRQ),
.end = OMAP_GPIO_IRQ(OMAP3EVM_ETHR_GPIO_IRQ),
.flags = (IORESOURCE_IRQ | IRQF_TRIGGER_LOW),
},
};
static struct smsc911x_platform_config smsc911x_config = {
.phy_interface = PHY_INTERFACE_MODE_MII,
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN,
.flags = (SMSC911X_USE_32BIT | SMSC911X_SAVE_MAC_ADDRESS),
};
static struct platform_device omap3evm_smsc911x_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(omap3evm_smsc911x_resources),
.resource = &omap3evm_smsc911x_resources[0],
.dev = {
.platform_data = &smsc911x_config,
},
};
static inline void __init omap3evm_init_smsc911x(void)
{
int eth_cs;
struct clk *l3ck;
unsigned int rate;
eth_cs = OMAP3EVM_SMSC911X_CS;
l3ck = clk_get(NULL, "l3_ck");
if (IS_ERR(l3ck))
rate = 100000000;
else
rate = clk_get_rate(l3ck);
if (gpio_request(OMAP3EVM_ETHR_GPIO_IRQ, "SMSC911x irq") < 0) {
printk(KERN_ERR "Failed to request GPIO%d for smsc911x IRQ\n",
OMAP3EVM_ETHR_GPIO_IRQ);
return;
}
gpio_direction_input(OMAP3EVM_ETHR_GPIO_IRQ);
platform_device_register(&omap3evm_smsc911x_device);
}
#else
static inline void __init omap3evm_init_smsc911x(void) { return; }
#endif
/*
* OMAP3EVM LCD Panel control signals
*/
#define OMAP3EVM_LCD_PANEL_LR 2
#define OMAP3EVM_LCD_PANEL_UD 3
#define OMAP3EVM_LCD_PANEL_INI 152
#define OMAP3EVM_LCD_PANEL_ENVDD 153
#define OMAP3EVM_LCD_PANEL_QVGA 154
#define OMAP3EVM_LCD_PANEL_RESB 155
#define OMAP3EVM_LCD_PANEL_BKLIGHT_GPIO 210
#define OMAP3EVM_DVI_PANEL_EN_GPIO 199
static int lcd_enabled;
static int dvi_enabled;
static void __init omap3_evm_display_init(void)
{
int r;
r = gpio_request(OMAP3EVM_LCD_PANEL_RESB, "lcd_panel_resb");
if (r) {
printk(KERN_ERR "failed to get lcd_panel_resb\n");
return;
}
gpio_direction_output(OMAP3EVM_LCD_PANEL_RESB, 1);
r = gpio_request(OMAP3EVM_LCD_PANEL_INI, "lcd_panel_ini");
if (r) {
printk(KERN_ERR "failed to get lcd_panel_ini\n");
goto err_1;
}
gpio_direction_output(OMAP3EVM_LCD_PANEL_INI, 1);
r = gpio_request(OMAP3EVM_LCD_PANEL_QVGA, "lcd_panel_qvga");
if (r) {
printk(KERN_ERR "failed to get lcd_panel_qvga\n");
goto err_2;
}
gpio_direction_output(OMAP3EVM_LCD_PANEL_QVGA, 0);
r = gpio_request(OMAP3EVM_LCD_PANEL_LR, "lcd_panel_lr");
if (r) {
printk(KERN_ERR "failed to get lcd_panel_lr\n");
goto err_3;
}
gpio_direction_output(OMAP3EVM_LCD_PANEL_LR, 1);
r = gpio_request(OMAP3EVM_LCD_PANEL_UD, "lcd_panel_ud");
if (r) {
printk(KERN_ERR "failed to get lcd_panel_ud\n");
goto err_4;
}
gpio_direction_output(OMAP3EVM_LCD_PANEL_UD, 1);
r = gpio_request(OMAP3EVM_LCD_PANEL_ENVDD, "lcd_panel_envdd");
if (r) {
printk(KERN_ERR "failed to get lcd_panel_envdd\n");
goto err_5;
}
gpio_direction_output(OMAP3EVM_LCD_PANEL_ENVDD, 0);
return;
err_5:
gpio_free(OMAP3EVM_LCD_PANEL_UD);
err_4:
gpio_free(OMAP3EVM_LCD_PANEL_LR);
err_3:
gpio_free(OMAP3EVM_LCD_PANEL_QVGA);
err_2:
gpio_free(OMAP3EVM_LCD_PANEL_INI);
err_1:
gpio_free(OMAP3EVM_LCD_PANEL_RESB);
}
static int omap3_evm_enable_lcd(struct omap_dss_device *dssdev)
{
if (dvi_enabled) {
printk(KERN_ERR "cannot enable LCD, DVI is enabled\n");
return -EINVAL;
}
gpio_set_value(OMAP3EVM_LCD_PANEL_ENVDD, 0);
if (get_omap3_evm_rev() >= OMAP3EVM_BOARD_GEN_2)
gpio_set_value(OMAP3EVM_LCD_PANEL_BKLIGHT_GPIO, 0);
else
gpio_set_value(OMAP3EVM_LCD_PANEL_BKLIGHT_GPIO, 1);
lcd_enabled = 1;
return 0;
}
static void omap3_evm_disable_lcd(struct omap_dss_device *dssdev)
{
gpio_set_value(OMAP3EVM_LCD_PANEL_ENVDD, 1);
if (get_omap3_evm_rev() >= OMAP3EVM_BOARD_GEN_2)
gpio_set_value(OMAP3EVM_LCD_PANEL_BKLIGHT_GPIO, 1);
else
gpio_set_value(OMAP3EVM_LCD_PANEL_BKLIGHT_GPIO, 0);
lcd_enabled = 0;
}
static struct omap_dss_device omap3_evm_lcd_device = {
.name = "lcd",
.driver_name = "sharp_ls_panel",
.type = OMAP_DISPLAY_TYPE_DPI,
.phy.dpi.data_lines = 18,
.platform_enable = omap3_evm_enable_lcd,
.platform_disable = omap3_evm_disable_lcd,
};
static int omap3_evm_enable_tv(struct omap_dss_device *dssdev)
{
return 0;
}
static void omap3_evm_disable_tv(struct omap_dss_device *dssdev)
{
}
static struct omap_dss_device omap3_evm_tv_device = {
.name = "tv",
.driver_name = "venc",
.type = OMAP_DISPLAY_TYPE_VENC,
.phy.venc.type = OMAP_DSS_VENC_TYPE_SVIDEO,
.platform_enable = omap3_evm_enable_tv,
.platform_disable = omap3_evm_disable_tv,
};
static int omap3_evm_enable_dvi(struct omap_dss_device *dssdev)
{
if (lcd_enabled) {
printk(KERN_ERR "cannot enable DVI, LCD is enabled\n");
return -EINVAL;
}
gpio_set_value(OMAP3EVM_DVI_PANEL_EN_GPIO, 1);
dvi_enabled = 1;
return 0;
}
static void omap3_evm_disable_dvi(struct omap_dss_device *dssdev)
{
gpio_set_value(OMAP3EVM_DVI_PANEL_EN_GPIO, 0);
dvi_enabled = 0;
}
static struct omap_dss_device omap3_evm_dvi_device = {
.name = "dvi",
.driver_name = "generic_panel",
.type = OMAP_DISPLAY_TYPE_DPI,
.phy.dpi.data_lines = 24,
.platform_enable = omap3_evm_enable_dvi,
.platform_disable = omap3_evm_disable_dvi,
};
static struct omap_dss_device *omap3_evm_dss_devices[] = {
&omap3_evm_lcd_device,
&omap3_evm_tv_device,
&omap3_evm_dvi_device,
};
static struct omap_dss_board_info omap3_evm_dss_data = {
.num_devices = ARRAY_SIZE(omap3_evm_dss_devices),
.devices = omap3_evm_dss_devices,
.default_device = &omap3_evm_lcd_device,
};
static struct platform_device omap3_evm_dss_device = {
.name = "omapdss",
.id = -1,
.dev = {
.platform_data = &omap3_evm_dss_data,
},
};
static struct regulator_consumer_supply omap3evm_vmmc1_supply = {
.supply = "vmmc",
};
static struct regulator_consumer_supply omap3evm_vsim_supply = {
.supply = "vmmc_aux",
};
/* VMMC1 for MMC1 pins CMD, CLK, DAT0..DAT3 (20 mA, plus card == max 220 mA) */
static struct regulator_init_data omap3evm_vmmc1 = {
.constraints = {
.min_uV = 1850000,
.max_uV = 3150000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &omap3evm_vmmc1_supply,
};
/* VSIM for MMC1 pins DAT4..DAT7 (2 mA, plus card == max 50 mA) */
static struct regulator_init_data omap3evm_vsim = {
.constraints = {
.min_uV = 1800000,
.max_uV = 3000000,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE
| REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &omap3evm_vsim_supply,
};
static struct omap2_hsmmc_info mmc[] = {
{
.mmc = 1,
.wires = 4,
.gpio_cd = -EINVAL,
.gpio_wp = 63,
},
{} /* Terminator */
};
static struct gpio_led gpio_leds[] = {
{
.name = "omap3evm::ledb",
/* normally not visible (board underside) */
.default_trigger = "default-on",
.gpio = -EINVAL, /* gets replaced */
.active_low = true,
},
};
static struct gpio_led_platform_data gpio_led_info = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
static struct platform_device leds_gpio = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &gpio_led_info,
},
};
static int omap3evm_twl_gpio_setup(struct device *dev,
unsigned gpio, unsigned ngpio)
{
/* gpio + 0 is "mmc0_cd" (input/IRQ) */
omap_mux_init_gpio(63, OMAP_PIN_INPUT);
mmc[0].gpio_cd = gpio + 0;
omap2_hsmmc_init(mmc);
/* link regulators to MMC adapters */
omap3evm_vmmc1_supply.dev = mmc[0].dev;
omap3evm_vsim_supply.dev = mmc[0].dev;
/*
* Most GPIOs are for USB OTG. Some are mostly sent to
* the P2 connector; notably LEDA for the LCD backlight.
*/
/* TWL4030_GPIO_MAX + 0 == ledA, LCD Backlight control */
gpio_request(gpio + TWL4030_GPIO_MAX, "EN_LCD_BKL");
gpio_direction_output(gpio + TWL4030_GPIO_MAX, 0);
/* gpio + 7 == DVI Enable */
gpio_request(gpio + 7, "EN_DVI");
gpio_direction_output(gpio + 7, 0);
/* TWL4030_GPIO_MAX + 1 == ledB (out, active low LED) */
gpio_leds[2].gpio = gpio + TWL4030_GPIO_MAX + 1;
platform_device_register(&leds_gpio);
return 0;
}
static struct twl4030_gpio_platform_data omap3evm_gpio_data = {
.gpio_base = OMAP_MAX_GPIO_LINES,
.irq_base = TWL4030_GPIO_IRQ_BASE,
.irq_end = TWL4030_GPIO_IRQ_END,
.use_leds = true,
.setup = omap3evm_twl_gpio_setup,
};
static struct twl4030_usb_data omap3evm_usb_data = {
.usb_mode = T2_USB_MODE_ULPI,
};
static int board_keymap[] = {
KEY(0, 0, KEY_LEFT),
KEY(0, 1, KEY_DOWN),
KEY(0, 2, KEY_ENTER),
KEY(0, 3, KEY_M),
KEY(1, 0, KEY_RIGHT),
KEY(1, 1, KEY_UP),
KEY(1, 2, KEY_I),
KEY(1, 3, KEY_N),
KEY(2, 0, KEY_A),
KEY(2, 1, KEY_E),
KEY(2, 2, KEY_J),
KEY(2, 3, KEY_O),
KEY(3, 0, KEY_B),
KEY(3, 1, KEY_F),
KEY(3, 2, KEY_K),
KEY(3, 3, KEY_P)
};
static struct matrix_keymap_data board_map_data = {
.keymap = board_keymap,
.keymap_size = ARRAY_SIZE(board_keymap),
};
static struct twl4030_keypad_data omap3evm_kp_data = {
.keymap_data = &board_map_data,
.rows = 4,
.cols = 4,
.rep = 1,
};
static struct twl4030_madc_platform_data omap3evm_madc_data = {
.irq_line = 1,
};
static struct twl4030_codec_audio_data omap3evm_audio_data = {
.audio_mclk = 26000000,
};
static struct twl4030_codec_data omap3evm_codec_data = {
.audio_mclk = 26000000,
.audio = &omap3evm_audio_data,
};
static struct regulator_consumer_supply omap3_evm_vdda_dac_supply = {
.supply = "vdda_dac",
.dev = &omap3_evm_dss_device.dev,
};
/* VDAC for DSS driving S-Video */
static struct regulator_init_data omap3_evm_vdac = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = true,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &omap3_evm_vdda_dac_supply,
};
/* VPLL2 for digital video outputs */
static struct regulator_consumer_supply omap3_evm_vpll2_supply =
REGULATOR_SUPPLY("vdds_dsi", "omapdss");
static struct regulator_init_data omap3_evm_vpll2 = {
.constraints = {
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = true,
.valid_modes_mask = REGULATOR_MODE_NORMAL
| REGULATOR_MODE_STANDBY,
.valid_ops_mask = REGULATOR_CHANGE_MODE
| REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = 1,
.consumer_supplies = &omap3_evm_vpll2_supply,
};
static struct twl4030_platform_data omap3evm_twldata = {
.irq_base = TWL4030_IRQ_BASE,
.irq_end = TWL4030_IRQ_END,
/* platform_data for children goes here */
.keypad = &omap3evm_kp_data,
.madc = &omap3evm_madc_data,
.usb = &omap3evm_usb_data,
.gpio = &omap3evm_gpio_data,
.codec = &omap3evm_codec_data,
.vdac = &omap3_evm_vdac,
.vpll2 = &omap3_evm_vpll2,
};
static struct i2c_board_info __initdata omap3evm_i2c_boardinfo[] = {
{
I2C_BOARD_INFO("twl4030", 0x48),
.flags = I2C_CLIENT_WAKE,
.irq = INT_34XX_SYS_NIRQ,
.platform_data = &omap3evm_twldata,
},
};
static int __init omap3_evm_i2c_init(void)
{
/*
* REVISIT: These entries can be set in omap3evm_twl_data
* after a merge with MFD tree
*/
omap3evm_twldata.vmmc1 = &omap3evm_vmmc1;
omap3evm_twldata.vsim = &omap3evm_vsim;
omap_register_i2c_bus(1, 2600, omap3evm_i2c_boardinfo,
ARRAY_SIZE(omap3evm_i2c_boardinfo));
omap_register_i2c_bus(2, 400, NULL, 0);
omap_register_i2c_bus(3, 400, NULL, 0);
return 0;
}
static void ads7846_dev_init(void)
{
if (gpio_request(OMAP3_EVM_TS_GPIO, "ADS7846 pendown") < 0)
printk(KERN_ERR "can't get ads7846 pen down GPIO\n");
gpio_direction_input(OMAP3_EVM_TS_GPIO);
gpio_set_debounce(OMAP3_EVM_TS_GPIO, 310);
}
static int ads7846_get_pendown_state(void)
{
return !gpio_get_value(OMAP3_EVM_TS_GPIO);
}
struct ads7846_platform_data ads7846_config = {
.x_max = 0x0fff,
.y_max = 0x0fff,
.x_plate_ohms = 180,
.pressure_max = 255,
.debounce_max = 10,
.debounce_tol = 3,
.debounce_rep = 1,
.get_pendown_state = ads7846_get_pendown_state,
.keep_vref_on = 1,
.settle_delay_usecs = 150,
.wakeup = true,
};
static struct omap2_mcspi_device_config ads7846_mcspi_config = {
.turbo_mode = 0,
.single_channel = 1, /* 0: slave, 1: master */
};
struct spi_board_info omap3evm_spi_board_info[] = {
[0] = {
.modalias = "ads7846",
.bus_num = 1,
.chip_select = 0,
.max_speed_hz = 1500000,
.controller_data = &ads7846_mcspi_config,
.irq = OMAP_GPIO_IRQ(OMAP3_EVM_TS_GPIO),
.platform_data = &ads7846_config,
},
};
static struct omap_board_config_kernel omap3_evm_config[] __initdata = {
};
static void __init omap3_evm_init_irq(void)
{
omap_board_config = omap3_evm_config;
omap_board_config_size = ARRAY_SIZE(omap3_evm_config);
omap2_init_common_hw(mt46h32m32lf6_sdrc_params, NULL);
omap_init_irq();
omap_gpio_init();
}
static struct platform_device *omap3_evm_devices[] __initdata = {
&omap3_evm_dss_device,
};
static struct ehci_hcd_omap_platform_data ehci_pdata __initdata = {
.port_mode[0] = EHCI_HCD_OMAP_MODE_UNKNOWN,
.port_mode[1] = EHCI_HCD_OMAP_MODE_PHY,
.port_mode[2] = EHCI_HCD_OMAP_MODE_UNKNOWN,
.phy_reset = true,
/* PHY reset GPIO will be runtime programmed based on EVM version */
.reset_gpio_port[0] = -EINVAL,
.reset_gpio_port[1] = -EINVAL,
.reset_gpio_port[2] = -EINVAL
};
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
OMAP3_MUX(SYS_NIRQ, OMAP_MUX_MODE0 | OMAP_PIN_INPUT_PULLUP |
OMAP_PIN_OFF_INPUT_PULLUP | OMAP_PIN_OFF_OUTPUT_LOW |
OMAP_PIN_OFF_WAKEUPENABLE),
OMAP3_MUX(MCSPI1_CS1, OMAP_MUX_MODE4 | OMAP_PIN_INPUT_PULLUP |
OMAP_PIN_OFF_INPUT_PULLUP | OMAP_PIN_OFF_OUTPUT_LOW),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#else
#define board_mux NULL
#endif
static struct omap_musb_board_data musb_board_data = {
.interface_type = MUSB_INTERFACE_ULPI,
.mode = MUSB_OTG,
.power = 100,
};
static void __init omap3_evm_init(void)
{
omap3_evm_get_revision();
omap3_mux_init(board_mux, OMAP_PACKAGE_CBB);
omap3_evm_i2c_init();
platform_add_devices(omap3_evm_devices, ARRAY_SIZE(omap3_evm_devices));
spi_register_board_info(omap3evm_spi_board_info,
ARRAY_SIZE(omap3evm_spi_board_info));
omap_serial_init();
/* OMAP3EVM uses ISP1504 phy and so register nop transceiver */
usb_nop_xceiv_register();
if (get_omap3_evm_rev() >= OMAP3EVM_BOARD_GEN_2) {
/* enable EHCI VBUS using GPIO22 */
omap_mux_init_gpio(22, OMAP_PIN_INPUT_PULLUP);
gpio_request(OMAP3_EVM_EHCI_VBUS, "enable EHCI VBUS");
gpio_direction_output(OMAP3_EVM_EHCI_VBUS, 0);
gpio_set_value(OMAP3_EVM_EHCI_VBUS, 1);
/* Select EHCI port on main board */
omap_mux_init_gpio(61, OMAP_PIN_INPUT_PULLUP);
gpio_request(OMAP3_EVM_EHCI_SELECT, "select EHCI port");
gpio_direction_output(OMAP3_EVM_EHCI_SELECT, 0);
gpio_set_value(OMAP3_EVM_EHCI_SELECT, 0);
/* setup EHCI phy reset config */
omap_mux_init_gpio(21, OMAP_PIN_INPUT_PULLUP);
ehci_pdata.reset_gpio_port[1] = 21;
/* EVM REV >= E can supply 500mA with EXTVBUS programming */
musb_board_data.power = 500;
musb_board_data.extvbus = 1;
} else {
/* setup EHCI phy reset on MDC */
omap_mux_init_gpio(135, OMAP_PIN_OUTPUT);
ehci_pdata.reset_gpio_port[1] = 135;
}
usb_musb_init(&musb_board_data);
usb_ehci_init(&ehci_pdata);
ads7846_dev_init();
omap3evm_init_smsc911x();
omap3_evm_display_init();
}
MACHINE_START(OMAP3EVM, "OMAP3 EVM")
/* Maintainer: Syed Mohammed Khasim - Texas Instruments */
.phys_io = 0x48000000,
.io_pg_offst = ((0xfa000000) >> 18) & 0xfffc,
.boot_params = 0x80000100,
.map_io = omap3_map_io,
.reserve = omap_reserve,
.init_irq = omap3_evm_init_irq,
.init_machine = omap3_evm_init,
.timer = &omap_timer,
MACHINE_END
| wkritzinger/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/arch/arm/mach-omap2/board-omap3evm.c | C | gpl-2.0 | 18,128 |
<!DOCTYPE html>
<html lang='en'>
<head>
<title>pservers-pattern-07-f-manual.svg</title>
<meta charset='utf-8'>
</head>
<body>
<h1>Source SVG: pservers-pattern-07-f-manual.svg</h1>
<svg id="svg-root" width="100%" height="100%"
viewBox="0 0 480 360" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<!--======================================================================-->
<!--= Copyright 2008 World Wide Web Consortium, (Massachusetts =-->
<!--= Institute of Technology, European Research Consortium for =-->
<!--= Informatics and Mathematics (ERCIM), Keio University). =-->
<!--= All Rights Reserved. =-->
<!--= See http://www.w3.org/Consortium/Legal/. =-->
<!--======================================================================-->
<title id="test-title">$RCSfile: pservers-pattern-07-f.svg,v $</title>
<defs>
<font-face
font-family="SVGFreeSansASCII"
unicode-range="U+0-7F">
<font-face-src>
<font-face-uri xlink:href="../resources/SVGFreeSans.svg#ascii"/>
</font-face-src>
</font-face>
</defs>
<g id="test-body-content" font-family="SVGFreeSansASCII,sans-serif" font-size="18">
<defs>
<pattern id="pattern1" patternUnits="userSpaceOnUse" x="0" y="0" width="100" height="100" viewBox="0 0 10 10">
<circle cx="5" cy="5" r="1.7" fill="red" />
</pattern>
<pattern id="pattern2" xlink:href="#invalidlink" patternUnits="userSpaceOnUse" x="0" y="0" width="100" height="100" viewBox="0 0 10 10">
<circle cx="5" cy="5" r="2" fill="lime" />
</pattern>
</defs>
<rect fill="url(#pattern1)" stroke="none" x="1" y="1" width="200" height="200" />
<rect fill="url(#pattern2)" stroke="none" x="1" y="1" width="200" height="200" />
</g>
<g font-family="SVGFreeSansASCII,sans-serif" font-size="32">
<text id="revision" x="10" y="340" stroke="none"
fill="black">$Revision: 1.2 $</text>
</g>
<rect id="test-frame" x="1" y="1" width="478" height="358" fill="none" stroke="#000"/>
<!-- comment out this watermark once the test is approved -->
<g id="draft-watermark">
<rect x="1" y="1" width="478" height="20" fill="red" stroke="black" stroke-width="1"/>
<text font-family="SVGFreeSansASCII,sans-serif" font-weight="bold" font-size="20" x="240"
text-anchor="middle" y="18" stroke-width="0.5" stroke="black" fill="white">DRAFT</text>
</g>
</svg>
</body>
</html>
| shinglyu/servo | tests/wpt/web-platform-tests/conformance-checkers/html-svg/pservers-pattern-07-f-isvalid.html | HTML | mpl-2.0 | 2,562 |
import { constant } from "../fp";
export = constant;
| BigBoss424/portfolio | v8/development/node_modules/@types/lodash/ts3.1/fp/constant.d.ts | TypeScript | apache-2.0 | 53 |
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
import com.google.gwt.typedarrays.shared.ArrayBufferView;
import com.google.gwt.typedarrays.shared.Float32Array;
import com.google.gwt.typedarrays.shared.TypedArrays;
/** This class wraps a byte buffer to be a float buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p> */
final class DirectReadWriteFloatBufferAdapter extends FloatBuffer implements HasArrayBufferView {
// implements DirectBuffer {
static FloatBuffer wrap (DirectReadWriteByteBuffer byteBuffer) {
return new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
}
private final DirectReadWriteByteBuffer byteBuffer;
private final Float32Array floatArray;
DirectReadWriteFloatBufferAdapter (DirectReadWriteByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 2));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.floatArray = TypedArrays.createFloat32Array(byteBuffer.byteArray.buffer(), byteBuffer.byteArray.byteOffset(), capacity);
}
// TODO(haustein) This will be slow
@Override
public FloatBuffer asReadOnlyBuffer () {
DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public FloatBuffer compact () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public FloatBuffer duplicate () {
DirectReadWriteFloatBufferAdapter buf = new DirectReadWriteFloatBufferAdapter(
(DirectReadWriteByteBuffer)byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public float get () {
// if (position == limit) {
// throw new BufferUnderflowException();
// }
return floatArray.get(position++);
}
@Override
public float get (int index) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
return floatArray.get(index);
}
@Override
public boolean isDirect () {
return true;
}
@Override
public boolean isReadOnly () {
return false;
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected float[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public FloatBuffer put (float c) {
// if (position == limit) {
// throw new BufferOverflowException();
// }
floatArray.set(position++, c);
return this;
}
@Override
public FloatBuffer put (int index, float c) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
floatArray.set(index, c);
return this;
}
@Override
public FloatBuffer slice () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
FloatBuffer result = new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
byteBuffer.clear();
return result;
}
public ArrayBufferView getTypedArray () {
return floatArray;
}
public int getElementSize () {
return 4;
}
}
| nelsonsilva/libgdx | backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java | Java | apache-2.0 | 4,412 |
/* orig : i386 init_task.c */
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/init_task.h>
#include <linux/fs.h>
#include <linux/mqueue.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
static struct fs_struct init_fs = INIT_FS;
static struct files_struct init_files = INIT_FILES;
static struct signal_struct init_signals = INIT_SIGNALS(init_signals);
static struct sighand_struct init_sighand = INIT_SIGHAND(init_sighand);
struct mm_struct init_mm = INIT_MM(init_mm);
EXPORT_SYMBOL(init_mm);
/*
* Initial thread structure.
*
* We need to make sure that this is 8192-byte aligned due to the
* way process stacks are handled. This is done by having a special
* "init_task" linker map entry..
*/
union thread_union init_thread_union
__attribute__((__section__(".data.init_task"))) =
{ INIT_THREAD_INFO(init_task) };
/*
* Initial task structure.
*
* All other task structs will be allocated on slabs in fork.c
*/
struct task_struct init_task = INIT_TASK(init_task);
EXPORT_SYMBOL(init_task);
| impedimentToProgress/UCI-BlueChip | snapgear_linux/linux-2.6.21.1/arch/m32r/kernel/init_task.c | C | mit | 1,078 |
/**
* @module Ink.UI.DatePicker_1
* @version 1
* Date selector
*/
Ink.createModule('Ink.UI.DatePicker', '1', ['Ink.UI.Common_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1','Ink.Util.Date_1', 'Ink.Dom.Browser_1'], function(Common, Event, Css, InkElement, Selector, InkArray, InkDate ) {
'use strict';
// Repeat a string. Long version of (new Array(n)).join(str);
function strRepeat(n, str) {
var ret = '';
for (var i = 0; i < n; i++) {
ret += str;
}
return ret;
}
// Clamp a number into a min/max limit
function clamp(n, min, max) {
if (n > max) { n = max; }
if (n < min) { n = min; }
return n;
}
function dateishFromYMDString(YMD) {
var split = YMD.split('-');
return dateishFromYMD(+split[0], +split[1] - 1, +split[2]);
}
function dateishFromYMD(year, month, day) {
return {_year: year, _month: month, _day: day};
}
function dateishFromDate(date) {
return {_year: date.getFullYear(), _month: date.getMonth(), _day: date.getDate()};
}
/**
* @class Ink.UI.DatePicker
* @constructor
* @version 1
*
* @param {String|DOMElement} selector
* @param {Object} [options] Options
* @param {Boolean} [options.autoOpen] Flag to automatically open the datepicker.
* @param {String} [options.cleanText] Text for the clean button. Defaults to 'Limpar'.
* @param {String} [options.closeText] Text for the close button. Defaults to 'Fechar'.
* @param {String} [options.cssClass] CSS class to be applied on the datepicker
* @param {String} [options.dateRange] Enforce limits to year, month and day for the Date, ex: '1990-08-25:2020-11'
* @param {Boolean} [options.displayInSelect] Flag to display the component in a select element.
* @param {String|DOMElement} [options.dayField] (if using options.displayInSelect) `select` field with days.
* @param {String|DOMElement} [options.monthField] (if using options.displayInSelect) `select` field with months.
* @param {String|DOMElement} [options.yearField] (if using options.displayInSelect) `select` field with years.
* @param {String} [options.format] Date format string
* @param {String} [options.instance] Unique id for the datepicker
* @param {Object} [options.month] Hash of month names. Defaults to portuguese month names. January is 1.
* @param {String} [options.nextLinkText] Text for the previous button. Defaults to '«'.
* @param {String} [options.ofText] Text to show between month and year. Defaults to ' of '.
* @param {Boolean} [options.onFocus] If the datepicker should open when the target element is focused. Defaults to true.
* @param {Function} [options.onMonthSelected] Callback to execute when the month is selected.
* @param {Function} [options.onSetDate] Callback to execute when the date is set.
* @param {Function} [options.onYearSelected] Callback to execute when the year is selected.
* @param {String} [options.position] Position for the datepicker. Either 'right' or 'bottom'. Defaults to 'right'.
* @param {String} [options.prevLinkText] Text for the previous button. Defaults to '«'.
* @param {Boolean} [options.showClean] If the clean button should be visible. Defaults to true.
* @param {Boolean} [options.showClose] If the close button should be visible. Defaults to true.
* @param {Boolean} [options.shy] If the datepicker should start automatically. Defaults to true.
* @param {String} [options.startDate] Date to define initial month. Must be in yyyy-mm-dd format.
* @param {Number} [options.startWeekDay] First day of the week. Sunday is zero. Defaults to 1 (Monday).
* @param {Function} [options.validYearFn] Callback to execute when 'rendering' the month (in the month view)
* @param {Function} [options.validMonthFn] Callback to execute when 'rendering' the month (in the month view)
* @param {Function} [options.validDayFn] Callback to execute when 'rendering' the day (in the month view)
* @param {Function} [options.nextValidDateFn] Function to calculate the next valid date, given the current. Useful when there's invalid dates or time frames.
* @param {Function} [options.prevValidDateFn] Function to calculate the previous valid date, given the current. Useful when there's invalid dates or time frames.
* @param {Object} [options.wDay] Hash of weekdays. Defaults to portuguese names. Sunday is 0.
* @param {String} [options.yearRange] Enforce limits to year for the Date, ex: '1990:2020' (deprecated)
*
* @sample Ink_UI_DatePicker_1.html
*/
var DatePicker = function(selector, options) {
this._element = selector &&
Common.elOrSelector(selector, '[Ink.UI.DatePicker_1]: selector argument');
this._options = Common.options('Ink.UI.DatePicker_1', {
autoOpen: ['Boolean', false],
cleanText: ['String', 'Clear'],
closeText: ['String', 'Close'],
containerElement:['Element', null],
cssClass: ['String', 'ink-calendar bottom'],
dateRange: ['String', null],
// use this in a <select>
displayInSelect: ['Boolean', false],
dayField: ['Element', null],
monthField: ['Element', null],
yearField: ['Element', null],
format: ['String', 'yyyy-mm-dd'],
instance: ['String', 'scdp_' + Math.round(99999 * Math.random())],
nextLinkText: ['String', '»'],
ofText: ['String', ' de '],
onFocus: ['Boolean', true],
onMonthSelected: ['Function', null],
onSetDate: ['Function', null],
onYearSelected: ['Function', null],
position: ['String', 'right'],
prevLinkText: ['String', '«'],
showClean: ['Boolean', true],
showClose: ['Boolean', true],
shy: ['Boolean', true],
startDate: ['String', null], // format yyyy-mm-dd,
startWeekDay: ['Number', 1],
// Validation
validDayFn: ['Function', null],
validMonthFn: ['Function', null],
validYearFn: ['Function', null],
nextValidDateFn: ['Function', null],
prevValidDateFn: ['Function', null],
yearRange: ['String', null],
// Text
month: ['Object', {
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December'
}],
wDay: ['Object', {
0:'Sunday',
1:'Monday',
2:'Tuesday',
3:'Wednesday',
4:'Thursday',
5:'Friday',
6:'Saturday'
}]
}, options || {}, this._element);
this._options.format = this._dateParsers[ this._options.format ] || this._options.format;
this._hoverPicker = false;
this._picker = this._options.pickerField &&
Common.elOrSelector(this._options.pickerField, 'pickerField');
this._setMinMax( this._options.dateRange || this._options.yearRange );
if(this._options.startDate) {
this.setDate( this._options.startDate );
} else if (this._element && this._element.value) {
this.setDate( this._element.value );
} else {
var today = new Date();
this._day = today.getDate( );
this._month = today.getMonth( );
this._year = today.getFullYear( );
}
if (this._options.startWeekDay < 0 || this._options.startWeekDay > 6) {
Ink.warn('Ink.UI.DatePicker_1: option "startWeekDay" must be between 0 (sunday) and 6 (saturday)');
this._options.startWeekDay = clamp(this._options.startWeekDay, 0, 6);
}
if(this._options.displayInSelect &&
!(this._options.dayField && this._options.monthField && this._options.yearField)){
throw new Error(
'Ink.UI.DatePicker: displayInSelect option enabled.'+
'Please specify dayField, monthField and yearField selectors.');
}
this._init();
};
DatePicker.prototype = {
version: '0.1',
/**
* Initialization function. Called by the constructor and receives the same parameters.
*
* @method _init
* @private
*/
_init: function(){
Ink.extendObj(this._options,this._lang || {});
this._render();
this._listenToContainerObjectEvents();
Common.registerInstance(this, this._containerObject, 'datePicker');
},
/**
* Renders the DatePicker's markup.
*
* @method _render
* @private
*/
_render: function() {
this._containerObject = document.createElement('div');
this._containerObject.id = this._options.instance;
this._containerObject.className = this._options.cssClass + ' ink-datepicker-calendar hide-all';
this._renderSuperTopBar();
var calendarTop = document.createElement("div");
calendarTop.className = 'ink-calendar-top';
this._monthDescContainer = document.createElement("div");
this._monthDescContainer.className = 'ink-calendar-month_desc';
this._monthPrev = document.createElement('div');
this._monthPrev.className = 'ink-calendar-prev';
this._monthPrev.innerHTML ='<a href="#prev" class="change_month_prev">' + this._options.prevLinkText + '</a>';
this._monthNext = document.createElement('div');
this._monthNext.className = 'ink-calendar-next';
this._monthNext.innerHTML ='<a href="#next" class="change_month_next">' + this._options.nextLinkText + '</a>';
calendarTop.appendChild(this._monthPrev);
calendarTop.appendChild(this._monthDescContainer);
calendarTop.appendChild(this._monthNext);
this._monthContainer = document.createElement("div");
this._monthContainer.className = 'ink-calendar-month';
this._containerObject.appendChild(calendarTop);
this._containerObject.appendChild(this._monthContainer);
this._monthSelector = this._renderMonthSelector();
this._containerObject.appendChild(this._monthSelector);
this._yearSelector = document.createElement('ul');
this._yearSelector.className = 'ink-calendar-year-selector';
this._containerObject.appendChild(this._yearSelector);
if(!this._options.onFocus || this._options.displayInSelect){
if(!this._options.pickerField){
this._picker = document.createElement('a');
this._picker.href = '#open_cal';
this._picker.innerHTML = 'open';
this._element.parentNode.appendChild(this._picker);
this._picker.className = 'ink-datepicker-picker-field';
} else {
this._picker = Common.elOrSelector(this._options.pickerField, 'pickerField');
}
}
this._appendDatePickerToDom();
this._renderMonth();
this._monthChanger = document.createElement('a');
this._monthChanger.href = '#monthchanger';
this._monthChanger.className = 'ink-calendar-link-month';
this._monthChanger.innerHTML = this._options.month[this._month + 1];
this._ofText = document.createElement('span');
this._ofText.innerHTML = this._options.ofText;
this._yearChanger = document.createElement('a');
this._yearChanger.href = '#yearchanger';
this._yearChanger.className = 'ink-calendar-link-year';
this._yearChanger.innerHTML = this._year;
this._monthDescContainer.innerHTML = '';
this._monthDescContainer.appendChild(this._monthChanger);
this._monthDescContainer.appendChild(this._ofText);
this._monthDescContainer.appendChild(this._yearChanger);
if (!this._options.inline) {
this._addOpenCloseEvents();
} else {
this.show();
}
this._addDateChangeHandlersToInputs();
},
_addDateChangeHandlersToInputs: function () {
var fields = this._element;
if (this._options.displayInSelect) {
fields = [
this._options.dayField,
this._options.monthField,
this._options.yearField];
}
Event.observeMulti(fields ,'change', Ink.bindEvent(function(){
this._updateDate( );
this._showDefaultView( );
this.setDate( );
if ( !this._inline && !this._hoverPicker ) {
this._hide(true);
}
},this));
},
/**
* Shows the calendar.
*
* @method show
**/
show: function () {
this._updateDate();
this._renderMonth();
Css.removeClassName(this._containerObject, 'hide-all');
},
_addOpenCloseEvents: function () {
var opener = this._picker || this._element;
Event.observe(opener, 'click', Ink.bindEvent(function(e){
Event.stop(e);
this.show();
},this));
if (this._options.autoOpen) {
this.show();
}
if(!this._options.displayInSelect){
Event.observe(opener, 'blur', Ink.bindEvent(function() {
if ( !this._hoverPicker ) {
this._hide(true);
}
},this));
}
if (this._options.shy) {
// Close the picker when clicking elsewhere.
Event.observe(document,'click',Ink.bindEvent(function(e){
var target = Event.element(e);
// "elsewhere" is outside any of these elements:
var cannotBe = [
this._options.dayField,
this._options.monthField,
this._options.yearField,
this._picker,
this._element
];
for (var i = 0, len = cannotBe.length; i < len; i++) {
if (cannotBe[i] && InkElement.descendantOf(cannotBe[i], target)) {
return;
}
}
this._hide(true);
},this));
}
},
/**
* Creates the markup of the view with months.
*
* @method _renderMonthSelector
* @private
*/
_renderMonthSelector: function () {
var selector = document.createElement('ul');
selector.className = 'ink-calendar-month-selector';
var ulSelector = document.createElement('ul');
for(var mon=1; mon<=12; mon++){
ulSelector.appendChild(this._renderMonthButton(mon));
if (mon % 4 === 0) {
selector.appendChild(ulSelector);
ulSelector = document.createElement('ul');
}
}
return selector;
},
/**
* Renders a single month button.
*/
_renderMonthButton: function (mon) {
var liMonth = document.createElement('li');
var aMonth = document.createElement('a');
aMonth.setAttribute('data-cal-month', mon);
aMonth.innerHTML = this._options.month[mon].substring(0,3);
liMonth.appendChild(aMonth);
return liMonth;
},
_appendDatePickerToDom: function () {
if(this._options.containerElement) {
var appendTarget =
Ink.i(this._options.containerElement) || // [2.3.0] maybe id; small backwards compatibility thing
Common.elOrSelector(this._options.containerElement);
appendTarget.appendChild(this._containerObject);
}
if (InkElement.findUpwardsBySelector(this._element, '.ink-form .control-group .control') === this._element.parentNode) {
// [3.0.0] Check if the <input> must be a direct child of .control, and if not, remove this block.
this._wrapper = this._element.parentNode;
this._wrapperIsControl = true;
} else {
this._wrapper = InkElement.create('div', { className: 'ink-datepicker-wrapper' });
InkElement.wrap(this._element, this._wrapper);
}
InkElement.insertAfter(this._containerObject, this._element);
},
/**
* Render the topmost bar with the "close" and "clear" buttons.
*/
_renderSuperTopBar: function () {
if((!this._options.showClose) || (!this._options.showClean)){ return; }
this._superTopBar = document.createElement("div");
this._superTopBar.className = 'ink-calendar-top-options';
if(this._options.showClean){
this._superTopBar.appendChild(InkElement.create('a', {
className: 'clean',
setHTML: this._options.cleanText
}));
}
if(this._options.showClose){
this._superTopBar.appendChild(InkElement.create('a', {
className: 'close',
setHTML: this._options.closeText
}));
}
this._containerObject.appendChild(this._superTopBar);
},
_listenToContainerObjectEvents: function () {
Event.observe(this._containerObject,'mouseover',Ink.bindEvent(function(e){
Event.stop( e );
this._hoverPicker = true;
},this));
Event.observe(this._containerObject,'mouseout',Ink.bindEvent(function(e){
Event.stop( e );
this._hoverPicker = false;
},this));
Event.observe(this._containerObject,'click',Ink.bindEvent(this._onClick, this));
},
_onClick: function(e){
var elem = Event.element(e);
if (Css.hasClassName(elem, 'ink-calendar-off')) {
Event.stopDefault(e);
return null;
}
Event.stop(e);
// Relative changers
this._onRelativeChangerClick(elem);
// Absolute changers
this._onAbsoluteChangerClick(elem);
// Mode changers
if (Css.hasClassName(elem, 'ink-calendar-link-month')) {
this._showMonthSelector();
} else if (Css.hasClassName(elem, 'ink-calendar-link-year')) {
this._showYearSelector();
} else if(Css.hasClassName(elem, 'clean')){
this._clean();
} else if(Css.hasClassName(elem, 'close')){
this._hide(false);
}
this._updateDescription();
},
/**
* Handles click events on a changer (« ») for next/prev year/month
* @method _onChangerClick
* @private
**/
_onRelativeChangerClick: function (elem) {
var changeYear = {
change_year_next: 1,
change_year_prev: -1
};
var changeMonth = {
change_month_next: 1,
change_month_prev: -1
};
if( elem.className in changeMonth ) {
this._updateCal(changeMonth[elem.className]);
} else if( elem.className in changeYear ) {
this._showYearSelector(changeYear[elem.className]);
}
},
/**
* Handles click events on an atom-changer (day button, month button, year button)
*
* @method _onAbsoluteChangerClick
* @private
*/
_onAbsoluteChangerClick: function (elem) {
var elemData = InkElement.data(elem);
if( Number(elemData.calDay) ){
this.setDate( [this._year, this._month + 1, elemData.calDay].join('-') );
this._hide();
} else if( Number(elemData.calMonth) ) {
this._month = Number(elemData.calMonth) - 1;
this._showDefaultView();
this._updateCal();
} else if( Number(elemData.calYear) ){
this._changeYear(Number(elemData.calYear));
}
},
_changeYear: function (year) {
year = +year;
if(year){
this._year = year;
if( typeof this._options.onYearSelected === 'function' ){
this._options.onYearSelected(this, {
'year': this._year
});
}
this._showMonthSelector();
}
},
_clean: function () {
if(this._options.displayInSelect){
this._options.yearField.selectedIndex = 0;
this._options.monthField.selectedIndex = 0;
this._options.dayField.selectedIndex = 0;
} else {
this._element.value = '';
}
},
/**
* Hides the DatePicker.
* If the component is shy (options.shy), behaves differently.
*
* @method _hide
* @param {Boolean} [blur] If false, forces hiding even if the component is shy.
*/
_hide: function(blur) {
blur = blur === undefined ? true : blur;
if (blur === false || (blur && this._options.shy)) {
Css.addClassName(this._containerObject, 'hide-all');
}
},
/**
* Sets the range of dates allowed to be selected in the Date Picker
*
* @method _setMinMax
* @param {String} dateRange Two dates separated by a ':'. Example: 2013-01-01:2013-12-12
* @private
*/
_setMinMax: function( dateRange ) {
var self = this;
var noMinLimit = {
_year: -Number.MAX_VALUE,
_month: 0,
_day: 1
};
var noMaxLimit = {
_year: Number.MAX_VALUE,
_month: 11,
_day: 31
};
function noLimits() {
self._min = noMinLimit;
self._max = noMaxLimit;
}
if (!dateRange) { return noLimits(); }
var dates = dateRange.split( ':' );
var rDate = /^(\d{4})((\-)(\d{1,2})((\-)(\d{1,2}))?)?$/;
InkArray.each([
{name: '_min', date: dates[0], noLim: noMinLimit},
{name: '_max', date: dates[1], noLim: noMaxLimit}
], Ink.bind(function (data) {
var lim = data.noLim;
if ( data.date.toUpperCase() === 'NOW' ) {
var now = new Date();
lim = dateishFromDate(now);
} else if (data.date.toUpperCase() === 'EVER') {
lim = data.noLim;
} else if ( rDate.test( data.date ) ) {
lim = dateishFromYMDString(data.date);
lim._month = clamp(lim._month, 0, 11);
lim._day = clamp(lim._day, 1, this._daysInMonth( lim._year, lim._month + 1 ));
}
this[data.name] = lim;
}, this));
// Should be equal, or min should be smaller
var valid = this._dateCmp(this._max, this._min) !== -1;
if (!valid) {
noLimits();
}
},
/**
* Checks if a date is between the valid range.
* Starts by checking if the date passed is valid. If not, will fallback to the 'today' date.
* Then checks if the all params are inside of the date range specified. If not, it will fallback to the nearest valid date (either Min or Max).
*
* @method _fitDateToRange
* @param {Number} year Year with 4 digits (yyyy)
* @param {Number} month Month
* @param {Number} day Day
* @return {Array} Array with the final processed date.
* @private
*/
_fitDateToRange: function( date ) {
if ( !this._isValidDate( date ) ) {
date = dateishFromDate(new Date());
}
if (this._dateCmp(date, this._min) === -1) {
return Ink.extendObj({}, this._min);
} else if (this._dateCmp(date, this._max) === 1) {
return Ink.extendObj({}, this._max);
}
return Ink.extendObj({}, date); // date is okay already, just copy it.
},
/**
* Checks whether a date is within the valid date range
* @method _dateWithinRange
* @param year
* @param month
* @param day
* @return {Boolean}
* @private
*/
_dateWithinRange: function (date) {
if (!arguments.length) {
date = this;
}
return (!this._dateAboveMax(date) &&
(!this._dateBelowMin(date)));
},
_dateAboveMax: function (date) {
return this._dateCmp(date, this._max) === 1;
},
_dateBelowMin: function (date) {
return this._dateCmp(date, this._min) === -1;
},
_dateCmp: function (self, oth) {
return this._dateCmpUntil(self, oth, '_day');
},
/**
* _dateCmp with varied precision. You can compare down to the day field, or, just to the month.
* // the following two dates are considered equal because we asked
* // _dateCmpUntil to just check up to the years.
*
* _dateCmpUntil({_year: 2000, _month: 10}, {_year: 2000, _month: 11}, '_year') === 0
*/
_dateCmpUntil: function (self, oth, depth) {
var props = ['_year', '_month', '_day'];
var i = -1;
do {
i++;
if (self[props[i]] > oth[props[i]]) { return 1; }
else if (self[props[i]] < oth[props[i]]) { return -1; }
} while (props[i] !== depth &&
self[props[i + 1]] !== undefined && oth[props[i + 1]] !== undefined);
return 0;
},
/**
* Sets the markup in the default view mode (showing the days).
* Also disables the previous and next buttons in case they don't meet the range requirements.
*
* @method _showDefaultView
* @private
*/
_showDefaultView: function(){
this._yearSelector.style.display = 'none';
this._monthSelector.style.display = 'none';
this._monthPrev.childNodes[0].className = 'change_month_prev';
this._monthNext.childNodes[0].className = 'change_month_next';
if ( !this._getPrevMonth() ) {
this._monthPrev.childNodes[0].className = 'action_inactive';
}
if ( !this._getNextMonth() ) {
this._monthNext.childNodes[0].className = 'action_inactive';
}
this._monthContainer.style.display = 'block';
},
/**
* Updates the date shown on the datepicker
*
* @method _updateDate
* @private
*/
_updateDate: function(){
var dataParsed;
if(!this._options.displayInSelect && this._element.value){
dataParsed = this._parseDate(this._element.value);
} else if (this._options.displayInSelect) {
dataParsed = {
_year: this._options.yearField[this._options.yearField.selectedIndex].value,
_month: this._options.monthField[this._options.monthField.selectedIndex].value - 1,
_day: this._options.dayField[this._options.dayField.selectedIndex].value
};
}
if (dataParsed) {
dataParsed = this._fitDateToRange(dataParsed);
this._year = dataParsed._year;
this._month = dataParsed._month;
this._day = dataParsed._day;
}
this.setDate();
this._updateDescription();
this._renderMonth();
},
/**
* Updates the date description shown at the top of the datepicker
*
* EG "12 de November"
*
* @method _updateDescription
* @private
*/
_updateDescription: function(){
this._monthChanger.innerHTML = this._options.month[ this._month + 1 ];
this._ofText.innerHTML = this._options.ofText;
this._yearChanger.innerHTML = this._year;
},
/**
* Renders the year selector view of the datepicker
*
* @method _showYearSelector
* @private
*/
_showYearSelector: function(inc){
this._incrementViewingYear(inc);
var firstYear = this._year - (this._year % 10);
var thisYear = firstYear - 1;
var str = "<li><ul>";
if (thisYear > this._min._year) {
str += '<li><a href="#year_prev" class="change_year_prev">' + this._options.prevLinkText + '</a></li>';
} else {
str += '<li> </li>';
}
for (var i=1; i < 11; i++){
if (i % 4 === 0){
str+='</ul><ul>';
}
thisYear = firstYear + i - 1;
str += this._getYearButtonHtml(thisYear);
}
if( thisYear < this._max._year){
str += '<li><a href="#year_next" class="change_year_next">' + this._options.nextLinkText + '</a></li>';
} else {
str += '<li> </li>';
}
str += "</ul></li>";
this._yearSelector.innerHTML = str;
this._monthPrev.childNodes[0].className = 'action_inactive';
this._monthNext.childNodes[0].className = 'action_inactive';
this._monthSelector.style.display = 'none';
this._monthContainer.style.display = 'none';
this._yearSelector.style.display = 'block';
},
/**
* For the year selector.
*
* Update this._year, to find the next decade or use nextValidDateFn to find it.
*/
_incrementViewingYear: function (inc) {
if (!inc) { return; }
var year = +this._year + inc*10;
year = year - year % 10;
if ( year > this._max._year || year + 9 < this._min._year){
return;
}
this._year = +this._year + inc*10;
},
_getYearButtonHtml: function (thisYear) {
if ( this._acceptableYear({_year: thisYear}) ){
var className = (thisYear === this._year) ? ' class="ink-calendar-on"' : '';
return '<li><a href="#" data-cal-year="' + thisYear + '"' + className + '>' + thisYear +'</a></li>';
} else {
return '<li><a href="#" class="ink-calendar-off">' + thisYear +'</a></li>';
}
},
/**
* Show the month selector (happens when you click a year, or the "month" link.
* @method _showMonthSelector
* @private
*/
_showMonthSelector: function () {
this._yearSelector.style.display = 'none';
this._monthContainer.style.display = 'none';
this._monthPrev.childNodes[0].className = 'action_inactive';
this._monthNext.childNodes[0].className = 'action_inactive';
this._addMonthClassNames();
this._monthSelector.style.display = 'block';
},
/**
* This function returns the given date in the dateish format
*
* @method _parseDate
* @param {String} dateStr A date on a string.
* @private
*/
_parseDate: function(dateStr){
var date = InkDate.set( this._options.format , dateStr );
if (date) {
return dateishFromDate(date);
}
return null;
},
/**
* Checks if a date is valid
*
* @method _isValidDate
* @param {Dateish} date
* @private
* @return {Boolean} True if the date is valid, false otherwise
*/
_isValidDate: function(date){
var yearRegExp = /^\d{4}$/;
var validOneOrTwo = /^\d{1,2}$/;
return (
yearRegExp.test(date._year) &&
validOneOrTwo.test(date._month) &&
validOneOrTwo.test(date._day) &&
+date._month + 1 >= 1 &&
+date._month + 1 <= 12 &&
+date._day >= 1 &&
+date._day <= this._daysInMonth(date._year, date._month + 1)
);
},
/**
* Checks if a given date is an valid format.
*
* @method _isDate
* @param {String} format A date format.
* @param {String} dateStr A date on a string.
* @private
* @return {Boolean} True if the given date is valid according to the given format
*/
_isDate: function(format, dateStr){
try {
if (typeof format === 'undefined'){
return false;
}
var date = InkDate.set( format , dateStr );
if( date && this._isValidDate( dateishFromDate(date) )) {
return true;
}
} catch (ex) {}
return false;
},
_acceptableDay: function (date) {
return this._acceptableDateComponent(date, 'validDayFn');
},
_acceptableMonth: function (date) {
return this._acceptableDateComponent(date, 'validMonthFn');
},
_acceptableYear: function (date) {
return this._acceptableDateComponent(date, 'validYearFn');
},
/** DRY base for the above 2 functions */
_acceptableDateComponent: function (date, userCb) {
if (this._options[userCb]) {
return this._callUserCallbackBool(this._options[userCb], date);
} else {
return this._dateWithinRange(date);
}
},
/**
* This method returns the date written with the format specified on the options
*
* @method _writeDateInFormat
* @private
* @return {String} Returns the current date of the object in the specified format
*/
_writeDateInFormat:function(){
return InkDate.get( this._options.format , this.getDate());
},
/**
* This method allows the user to set the DatePicker's date on run-time.
*
* @method setDate
* @param {String} dateString A date string in yyyy-mm-dd format.
* @public
*/
setDate: function( dateString ) {
if ( /\d{4}-\d{1,2}-\d{1,2}/.test( dateString ) ) {
var auxDate = dateString.split( '-' );
this._year = +auxDate[ 0 ];
this._month = +auxDate[ 1 ] - 1;
this._day = +auxDate[ 2 ];
}
this._setDate( );
},
/**
* Gets the current date as a JavaScript date.
*
* @method getDate
*/
getDate: function () {
if (!this._day) {
throw 'Ink.UI.DatePicker: Still picking a date. Cannot getDate now!';
}
return new Date(this._year, this._month, this._day);
},
/**
* Sets the chosen date on the target input field
*
* @method _setDate
* @param {DOMElement} objClicked Clicked object inside the DatePicker's calendar.
* @private
*/
_setDate : function( objClicked ) {
if (objClicked) {
var data = InkElement.data(objClicked);
this._day = (+data.calDay) || this._day;
}
var dt = this._fitDateToRange(this);
this._year = dt._year;
this._month = dt._month;
this._day = dt._day;
if(!this._options.displayInSelect){
this._element.value = this._writeDateInFormat();
} else {
this._options.dayField.value = this._day;
this._options.monthField.value = this._month + 1;
this._options.yearField.value = this._year;
}
if(this._options.onSetDate) {
this._options.onSetDate( this , { date : this.getDate() } );
}
},
/**
* Makes the necessary work to update the calendar
* when choosing a different month
*
* @method _updateCal
* @param {Number} inc Indicates previous or next month
* @private
*/
_updateCal: function(inc){
if( typeof this._options.onMonthSelected === 'function' ){
this._options.onMonthSelected(this, {
'year': this._year,
'month' : this._month
});
}
if (inc && this._updateMonth(inc) === null) {
return;
}
this._renderMonth();
},
/**
* Function that returns the number of days on a given month on a given year
*
* @method _daysInMonth
* @param {Number} _y - year
* @param {Number} _m - month
* @private
* @return {Number} The number of days on a given month on a given year
*/
_daysInMonth: function(_y,_m){
var exceptions = {
2: ((_y % 400 === 0) || (_y % 4 === 0 && _y % 100 !== 0)) ? 29 : 28,
4: 30,
6: 30,
9: 30,
11: 30
};
return exceptions[_m] || 31;
},
/**
* Updates the calendar when a different month is chosen
*
* @method _updateMonth
* @param {Number} incValue - indicates previous or next month
* @private
*/
_updateMonth: function(incValue){
var date;
if (incValue > 0) {
date = this._getNextMonth();
} else if (incValue < 0) {
date = this._getPrevMonth();
}
if (!date) { return null; }
this._year = date._year;
this._month = date._month;
this._day = date._day;
},
/**
* Get the next month we can show.
*/
_getNextMonth: function (date) {
return this._tryLeap( date, 'Month', 'next', function (d) {
d._month += 1;
if (d._month > 11) {
d._month = 0;
d._year += 1;
}
return d;
});
},
/**
* Get the previous month we can show.
*/
_getPrevMonth: function (date) {
return this._tryLeap( date, 'Month', 'prev', function (d) {
d._month -= 1;
if (d._month < 0) {
d._month = 11;
d._year -= 1;
}
return d;
});
},
/**
* Get the next year we can show.
*/
_getPrevYear: function (date) {
return this._tryLeap( date, 'Year', 'prev', function (d) {
d._year -= 1;
return d;
});
},
/**
* Get the next year we can show.
*/
_getNextYear: function (date) {
return this._tryLeap( date, 'Year', 'next', function (d) {
d._year += 1;
return d;
});
},
/**
* DRY base for a function which tries to get the next or previous valid year or month.
*
* It checks if we can go forward by using _dateCmp with atomic
* precision (this means, {_year} for leaping years, and
* {_year, month} for leaping months), then it tries to get the
* result from the user-supplied callback (nextDateFn or prevDateFn),
* and when this is not present, advance the date forward using the
* `advancer` callback.
*/
_tryLeap: function (date, atomName, directionName, advancer) {
date = date || { _year: this._year, _month: this._month, _day: this._day };
var maxOrMin = directionName === 'prev' ? '_min' : '_max';
var boundary = this[maxOrMin];
// Check if we're by the boundary of min/max year/month
if (this._dateCmpUntil(date, boundary, atomName) === 0) {
return null; // We're already at the boundary. Bail.
}
var leapUserCb = this._options[directionName + 'ValidDateFn'];
if (leapUserCb) {
return this._callUserCallbackDate(leapUserCb, date);
} else {
date = advancer(date);
}
date = this._fitDateToRange(date);
return this['_acceptable' + atomName](date) ? date : null;
},
_getNextDecade: function (date) {
date = date || { _year: this._year, _month: this._month, _day: this._day };
var decade = this._getCurrentDecade(date);
if (decade + 10 > this._max._year) { return null; }
return decade + 10;
},
_getPrevDecade: function (date) {
date = date || { _year: this._year, _month: this._month, _day: this._day };
var decade = this._getCurrentDecade(date);
if (decade - 10 < this._min._year) { return null; }
return decade - 10;
},
/** Returns the decade given a date or year*/
_getCurrentDecade: function (year) {
year = year ? (year._year || year) : this._year;
return Math.floor(year / 10) * 10; // Round to first place
},
_callUserCallbackBase: function (cb, date) {
return cb.call(this, date._year, date._month + 1, date._day);
},
_callUserCallbackBool: function (cb, date) {
return !!this._callUserCallbackBase(cb, date);
},
_callUserCallbackDate: function (cb, date) {
var ret = this._callUserCallbackBase(cb, date);
return ret ? dateishFromDate(ret) : null;
},
/**
* Key-value object that (for a given key) points to the correct parsing format for the DatePicker
* @property _dateParsers
* @type {Object}
* @readOnly
*/
_dateParsers: {
'yyyy-mm-dd' : 'Y-m-d' ,
'yyyy/mm/dd' : 'Y/m/d' ,
'yy-mm-dd' : 'y-m-d' ,
'yy/mm/dd' : 'y/m/d' ,
'dd-mm-yyyy' : 'd-m-Y' ,
'dd/mm/yyyy' : 'd/m/Y' ,
'dd-mm-yy' : 'd-m-y' ,
'dd/mm/yy' : 'd/m/y' ,
'mm/dd/yyyy' : 'm/d/Y' ,
'mm-dd-yyyy' : 'm-d-Y'
},
/**
* Renders the current month
*
* @method _renderMonth
* @private
*/
_renderMonth: function(){
var month = this._month;
var year = this._year;
this._showDefaultView();
var html = '';
html += this._getMonthCalendarHeaderHtml(this._options.startWeekDay);
var counter = 0;
html+='<ul>';
var emptyHtml = '<li class="ink-calendar-empty"> </li>';
var firstDayIndex = this._getFirstDayIndex(year, month);
// Add padding if the first day of the month is not monday.
if(firstDayIndex > 0) {
counter += firstDayIndex;
html += strRepeat(firstDayIndex, emptyHtml);
}
html += this._getDayButtonsHtml(year, month);
html += '</ul>';
this._monthContainer.innerHTML = html;
},
/**
* Figure out where the first day of a month lies
* in the first row of the calendar.
*
* having options.startWeekDay === 0
*
* Su Mo Tu We Th Fr Sa
* 1 <- The "1" is in the 7th day. return 6.
* 2 3 4 5 6 7 8
* 9 10 11 12 13 14 15
* 16 17 18 19 20 21 22
* 23 24 25 26 27 28 29
* 30 31
*
* This obviously changes according to the user option "startWeekDay"
**/
_getFirstDayIndex: function (year, month) {
var wDayFirst = (new Date( year , month , 1 )).getDay(); // Sunday=0
var startWeekDay = this._options.startWeekDay || 0; // Sunday=0
var result = wDayFirst - startWeekDay;
result %= 7;
if (result < 0) {
result += 6;
}
return result;
},
_getDayButtonsHtml: function (year, month) {
var counter = this._getFirstDayIndex(year, month);
var daysInMonth = this._daysInMonth(year, month + 1);
var ret = '';
for (var day = 1; day <= daysInMonth; day++) {
if (counter === 7){ // new week
counter=0;
ret += '<ul>';
}
ret += this._getDayButtonHtml(year, month, day);
counter++;
if(counter === 7){
ret += '</ul>';
}
}
return ret;
},
/**
* Get the HTML markup for a single day in month view, given year, month, day.
*
* @method _getDayButtonHtml
* @private
*/
_getDayButtonHtml: function (year, month, day) {
var attrs = ' ';
var date = dateishFromYMD(year, month, day);
if (!this._acceptableDay(date)) {
attrs += 'class="ink-calendar-off"';
} else {
attrs += 'data-cal-day="' + day + '"';
}
if (this._day && this._dateCmp(date, this) === 0) {
attrs += 'class="ink-calendar-on" data-cal-day="' + day + '"';
}
return '<li><a href="#" ' + attrs + '>' + day + '</a></li>';
},
/** Write the top bar of the calendar (M T W T F S S) */
_getMonthCalendarHeaderHtml: function (startWeekDay) {
var ret = '<ul class="ink-calendar-header">';
var wDay;
for(var i=0; i<7; i++){
wDay = (startWeekDay + i) % 7;
ret += '<li>' +
this._options.wDay[wDay].substring(0,1) +
'</li>';
}
return ret + '</ul>';
},
/**
* This method adds class names to month buttons, to visually distinguish.
*
* @method _addMonthClassNames
* @param {DOMElement} parent DOMElement where all the months are.
* @private
*/
_addMonthClassNames: function(parent){
InkArray.forEach(
(parent || this._monthSelector).getElementsByTagName('a'),
Ink.bindMethod(this, '_addMonthButtonClassNames'));
},
/**
* Add the ink-calendar-on className if the given button is the current month,
* otherwise add the ink-calendar-off className if the given button refers to
* an unacceptable month (given dateRange and validMonthFn)
*/
_addMonthButtonClassNames: function (btn) {
var data = InkElement.data(btn);
if (!data.calMonth) { throw 'not a calendar month button!'; }
var month = +data.calMonth - 1;
if ( month === this._month ) {
Css.addClassName( btn, 'ink-calendar-on' ); // This month
Css.removeClassName( btn, 'ink-calendar-off' );
} else {
Css.removeClassName( btn, 'ink-calendar-on' ); // Not this month
var toDisable = !this._acceptableMonth({_year: this._year, _month: month});
Css.addRemoveClassName( btn, 'ink-calendar-off', toDisable);
}
},
/**
* Prototype's method to allow the 'i18n files' to change all objects' language at once.
* @param {Object} options Object with the texts' configuration.
* @param {String} options.closeText Text of the close anchor
* @param {String} options.cleanText Text of the clean text anchor
* @param {String} options.prevLinkText "Previous" link's text
* @param {String} options.nextLinkText "Next" link's text
* @param {String} options.ofText The text "of", present in 'May of 2013'
* @param {Object} options.month An object with keys from 1 to 12 for the full months' names
* @param {Object} options.wDay An object with keys from 0 to 6 for the full weekdays' names
* @public
*/
lang: function( options ){
this._lang = options;
},
/**
* This calls the rendering of the selected month. (Deprecated: use show() instead)
*
*/
showMonth: function(){
this._renderMonth();
},
/**
* Checks if the calendar screen is in 'select day' mode
*
* @return {Boolean} True if the calendar screen is in 'select day' mode
* @public
*/
isMonthRendered: function(){
var header = Selector.select('.ink-calendar-header', this._containerObject)[0];
return ((Css.getStyle(header.parentNode,'display') !== 'none') &&
(Css.getStyle(header.parentNode.parentNode,'display') !== 'none') );
},
/**
* Destroys this datepicker, removing it from the page.
*
* @public
**/
destroy: function () {
InkElement.unwrap(this._element);
InkElement.remove(this._wrapper);
InkElement.remove(this._containerObject);
Common.unregisterInstance.call(this);
}
};
return DatePicker;
}); | siscia/jsdelivr | files/ink/3.0.0/js/ink.datepicker.js | JavaScript | mit | 52,609 |
/* Byte-wise substring search, using the Two-Way algorithm.
* Copyright (C) 2008 Eric Blake
* Permission to use, copy, modify, and distribute this software
* is freely granted, provided that this notice is preserved.
*/
/*
FUNCTION
<<memmem>>---find memory segment
INDEX
memmem
ANSI_SYNOPSIS
#include <string.h>
char *memmem(const void *<[s1]>, size_t <[l1]>, const void *<[s2]>,
size_t <[l2]>);
DESCRIPTION
Locates the first occurrence in the memory region pointed to
by <[s1]> with length <[l1]> of the sequence of bytes pointed
to by <[s2]> of length <[l2]>. If you already know the
lengths of your haystack and needle, <<memmem>> can be much
faster than <<strstr>>.
RETURNS
Returns a pointer to the located segment, or a null pointer if
<[s2]> is not found. If <[l2]> is 0, <[s1]> is returned.
PORTABILITY
<<memmem>> is a newlib extension.
<<memmem>> requires no supporting OS subroutines.
QUICKREF
memmem pure
*/
#include <string.h>
#if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
# define RETURN_TYPE void *
# define AVAILABLE(h, h_l, j, n_l) ((j) <= (h_l) - (n_l))
# include "str-two-way.h"
#endif
void *
_DEFUN (memmem, (haystack_start, haystack_len, needle_start, needle_len),
const void *haystack_start _AND
size_t haystack_len _AND
const void *needle_start _AND
size_t needle_len)
{
/* Abstract memory is considered to be an array of 'unsigned char' values,
not an array of 'char' values. See ISO C 99 section 6.2.6.1. */
const unsigned char *haystack = (const unsigned char *) haystack_start;
const unsigned char *needle = (const unsigned char *) needle_start;
if (needle_len == 0)
/* The first occurrence of the empty string is deemed to occur at
the beginning of the string. */
return (void *) haystack;
#if defined(PREFER_SIZE_OVER_SPEED) || defined(__OPTIMIZE_SIZE__)
/* Less code size, but quadratic performance in the worst case. */
while (needle_len <= haystack_len)
{
if (!memcmp (haystack, needle, needle_len))
return (void *) haystack;
haystack++;
haystack_len--;
}
return NULL;
#else /* compilation for speed */
/* Larger code size, but guaranteed linear performance. */
/* Sanity check, otherwise the loop might search through the whole
memory. */
if (haystack_len < needle_len)
return NULL;
/* Use optimizations in memchr when possible, to reduce the search
size of haystack using a linear algorithm with a smaller
coefficient. However, avoid memchr for long needles, since we
can often achieve sublinear performance. */
if (needle_len < LONG_NEEDLE_THRESHOLD)
{
haystack = memchr (haystack, *needle, haystack_len);
if (!haystack || needle_len == 1)
return (void *) haystack;
haystack_len -= haystack - (const unsigned char *) haystack_start;
if (haystack_len < needle_len)
return NULL;
return two_way_short_needle (haystack, haystack_len, needle, needle_len);
}
return two_way_long_needle (haystack, haystack_len, needle, needle_len);
#endif /* compilation for speed */
}
| GarethNelson/Zoidberg | userland/newlib/newlib/libc/string/memmem.c | C | gpl-2.0 | 3,117 |
/*
* DaVinci Power & Sleep Controller (PSC) defines
*
* Copyright (C) 2006 Texas Instruments.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#ifndef __ASM_ARCH_PSC_H
#define __ASM_ARCH_PSC_H
#define DAVINCI_PWR_SLEEP_CNTRL_BASE 0x01C41000
/* Power and Sleep Controller (PSC) Domains */
#define DAVINCI_GPSC_ARMDOMAIN 0
#define DAVINCI_GPSC_DSPDOMAIN 1
#define DAVINCI_LPSC_VPSSMSTR 0
#define DAVINCI_LPSC_VPSSSLV 1
#define DAVINCI_LPSC_TPCC 2
#define DAVINCI_LPSC_TPTC0 3
#define DAVINCI_LPSC_TPTC1 4
#define DAVINCI_LPSC_EMAC 5
#define DAVINCI_LPSC_EMAC_WRAPPER 6
#define DAVINCI_LPSC_USB 9
#define DAVINCI_LPSC_ATA 10
#define DAVINCI_LPSC_VLYNQ 11
#define DAVINCI_LPSC_UHPI 12
#define DAVINCI_LPSC_DDR_EMIF 13
#define DAVINCI_LPSC_AEMIF 14
#define DAVINCI_LPSC_MMC_SD 15
#define DAVINCI_LPSC_McBSP 17
#define DAVINCI_LPSC_I2C 18
#define DAVINCI_LPSC_UART0 19
#define DAVINCI_LPSC_UART1 20
#define DAVINCI_LPSC_UART2 21
#define DAVINCI_LPSC_SPI 22
#define DAVINCI_LPSC_PWM0 23
#define DAVINCI_LPSC_PWM1 24
#define DAVINCI_LPSC_PWM2 25
#define DAVINCI_LPSC_GPIO 26
#define DAVINCI_LPSC_TIMER0 27
#define DAVINCI_LPSC_TIMER1 28
#define DAVINCI_LPSC_TIMER2 29
#define DAVINCI_LPSC_SYSTEM_SUBSYS 30
#define DAVINCI_LPSC_ARM 31
#define DAVINCI_LPSC_SCR2 32
#define DAVINCI_LPSC_SCR3 33
#define DAVINCI_LPSC_SCR4 34
#define DAVINCI_LPSC_CROSSBAR 35
#define DAVINCI_LPSC_CFG27 36
#define DAVINCI_LPSC_CFG3 37
#define DAVINCI_LPSC_CFG5 38
#define DAVINCI_LPSC_GEM 39
#define DAVINCI_LPSC_IMCOP 40
#define DM355_LPSC_TIMER3 5
#define DM355_LPSC_SPI1 6
#define DM355_LPSC_MMC_SD1 7
#define DM355_LPSC_McBSP1 8
#define DM355_LPSC_PWM3 10
#define DM355_LPSC_SPI2 11
#define DM355_LPSC_RTO 12
#define DM355_LPSC_VPSS_DAC 41
/* DM365 */
#define DM365_LPSC_TIMER3 5
#define DM365_LPSC_SPI1 6
#define DM365_LPSC_MMC_SD1 7
#define DM365_LPSC_McBSP1 8
#define DM365_LPSC_PWM3 10
#define DM365_LPSC_SPI2 11
#define DM365_LPSC_RTO 12
#define DM365_LPSC_TIMER4 17
#define DM365_LPSC_SPI0 22
#define DM365_LPSC_SPI3 38
#define DM365_LPSC_SPI4 39
#define DM365_LPSC_EMAC 40
#define DM365_LPSC_VOICE_CODEC 44
#define DM365_LPSC_DAC_CLK 46
#define DM365_LPSC_VPSSMSTR 47
#define DM365_LPSC_MJCP 50
/*
* LPSC Assignments
*/
#define DM646X_LPSC_ARM 0
#define DM646X_LPSC_C64X_CPU 1
#define DM646X_LPSC_HDVICP0 2
#define DM646X_LPSC_HDVICP1 3
#define DM646X_LPSC_TPCC 4
#define DM646X_LPSC_TPTC0 5
#define DM646X_LPSC_TPTC1 6
#define DM646X_LPSC_TPTC2 7
#define DM646X_LPSC_TPTC3 8
#define DM646X_LPSC_PCI 13
#define DM646X_LPSC_EMAC 14
#define DM646X_LPSC_VDCE 15
#define DM646X_LPSC_VPSSMSTR 16
#define DM646X_LPSC_VPSSSLV 17
#define DM646X_LPSC_TSIF0 18
#define DM646X_LPSC_TSIF1 19
#define DM646X_LPSC_DDR_EMIF 20
#define DM646X_LPSC_AEMIF 21
#define DM646X_LPSC_McASP0 22
#define DM646X_LPSC_McASP1 23
#define DM646X_LPSC_CRGEN0 24
#define DM646X_LPSC_CRGEN1 25
#define DM646X_LPSC_UART0 26
#define DM646X_LPSC_UART1 27
#define DM646X_LPSC_UART2 28
#define DM646X_LPSC_PWM0 29
#define DM646X_LPSC_PWM1 30
#define DM646X_LPSC_I2C 31
#define DM646X_LPSC_SPI 32
#define DM646X_LPSC_GPIO 33
#define DM646X_LPSC_TIMER0 34
#define DM646X_LPSC_TIMER1 35
#define DM646X_LPSC_ARM_INTC 45
/* PSC0 defines */
#define DA8XX_LPSC0_TPCC 0
#define DA8XX_LPSC0_TPTC0 1
#define DA8XX_LPSC0_TPTC1 2
#define DA8XX_LPSC0_EMIF25 3
#define DA8XX_LPSC0_SPI0 4
#define DA8XX_LPSC0_MMC_SD 5
#define DA8XX_LPSC0_AINTC 6
#define DA8XX_LPSC0_ARM_RAM_ROM 7
#define DA8XX_LPSC0_SECU_MGR 8
#define DA8XX_LPSC0_UART0 9
#define DA8XX_LPSC0_SCR0_SS 10
#define DA8XX_LPSC0_SCR1_SS 11
#define DA8XX_LPSC0_SCR2_SS 12
#define DA8XX_LPSC0_PRUSS 13
#define DA8XX_LPSC0_ARM 14
#define DA8XX_LPSC0_GEM 15
/* PSC1 defines */
#define DA850_LPSC1_TPCC1 0
#define DA8XX_LPSC1_USB20 1
#define DA8XX_LPSC1_USB11 2
#define DA8XX_LPSC1_GPIO 3
#define DA8XX_LPSC1_UHPI 4
#define DA8XX_LPSC1_CPGMAC 5
#define DA8XX_LPSC1_EMIF3C 6
#define DA8XX_LPSC1_McASP0 7
#define DA830_LPSC1_McASP1 8
#define DA850_LPSC1_SATA 8
#define DA830_LPSC1_McASP2 9
#define DA8XX_LPSC1_SPI1 10
#define DA8XX_LPSC1_I2C 11
#define DA8XX_LPSC1_UART1 12
#define DA8XX_LPSC1_UART2 13
#define DA8XX_LPSC1_LCDC 16
#define DA8XX_LPSC1_PWM 17
#define DA850_LPSC1_MMC_SD1 18
#define DA8XX_LPSC1_ECAP 20
#define DA830_LPSC1_EQEP 21
#define DA850_LPSC1_TPTC2 21
#define DA8XX_LPSC1_SCR_P0_SS 24
#define DA8XX_LPSC1_SCR_P1_SS 25
#define DA8XX_LPSC1_CR_P3_SS 26
#define DA8XX_LPSC1_L3_CBA_RAM 31
/* TNETV107X LPSC Assignments */
#define TNETV107X_LPSC_ARM 0
#define TNETV107X_LPSC_GEM 1
#define TNETV107X_LPSC_DDR2_PHY 2
#define TNETV107X_LPSC_TPCC 3
#define TNETV107X_LPSC_TPTC0 4
#define TNETV107X_LPSC_TPTC1 5
#define TNETV107X_LPSC_RAM 6
#define TNETV107X_LPSC_MBX_LITE 7
#define TNETV107X_LPSC_LCD 8
#define TNETV107X_LPSC_ETHSS 9
#define TNETV107X_LPSC_AEMIF 10
#define TNETV107X_LPSC_CHIP_CFG 11
#define TNETV107X_LPSC_TSC 12
#define TNETV107X_LPSC_ROM 13
#define TNETV107X_LPSC_UART2 14
#define TNETV107X_LPSC_PKTSEC 15
#define TNETV107X_LPSC_SECCTL 16
#define TNETV107X_LPSC_KEYMGR 17
#define TNETV107X_LPSC_KEYPAD 18
#define TNETV107X_LPSC_GPIO 19
#define TNETV107X_LPSC_MDIO 20
#define TNETV107X_LPSC_SDIO0 21
#define TNETV107X_LPSC_UART0 22
#define TNETV107X_LPSC_UART1 23
#define TNETV107X_LPSC_TIMER0 24
#define TNETV107X_LPSC_TIMER1 25
#define TNETV107X_LPSC_WDT_ARM 26
#define TNETV107X_LPSC_WDT_DSP 27
#define TNETV107X_LPSC_SSP 28
#define TNETV107X_LPSC_TDM0 29
#define TNETV107X_LPSC_VLYNQ 30
#define TNETV107X_LPSC_MCDMA 31
#define TNETV107X_LPSC_USB0 32
#define TNETV107X_LPSC_TDM1 33
#define TNETV107X_LPSC_DEBUGSS 34
#define TNETV107X_LPSC_ETHSS_RGMII 35
#define TNETV107X_LPSC_SYSTEM 36
#define TNETV107X_LPSC_IMCOP 37
#define TNETV107X_LPSC_SPARE 38
#define TNETV107X_LPSC_SDIO1 39
#define TNETV107X_LPSC_USB1 40
#define TNETV107X_LPSC_USBSS 41
#define TNETV107X_LPSC_DDR2_EMIF1_VRST 42
#define TNETV107X_LPSC_DDR2_EMIF2_VCTL_RST 43
#define TNETV107X_LPSC_MAX 44
/* PSC register offsets */
#define EPCPR 0x070
#define PTCMD 0x120
#define PTSTAT 0x128
#define PDSTAT 0x200
#define PDCTL 0x300
#define MDSTAT 0x800
#define MDCTL 0xA00
/* PSC module states */
#define PSC_STATE_SWRSTDISABLE 0
#define PSC_STATE_SYNCRST 1
#define PSC_STATE_DISABLE 2
#define PSC_STATE_ENABLE 3
#define MDSTAT_STATE_MASK 0x3f
#define PDSTAT_STATE_MASK 0x1f
#define MDCTL_FORCE BIT(31)
#define PDCTL_NEXT BIT(0)
#define PDCTL_EPCGOOD BIT(8)
#ifndef __ASSEMBLER__
extern int davinci_psc_is_clk_active(unsigned int ctlr, unsigned int id);
extern void davinci_psc_config(unsigned int domain, unsigned int ctlr,
unsigned int id, bool enable, u32 flags);
#endif
#endif /* __ASM_ARCH_PSC_H */
| kv193/buildroot | linux/linux-kernel/arch/arm/mach-davinci/include/mach/psc.h | C | gpl-2.0 | 7,997 |
package dns
import (
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/rsa"
"io"
"math/big"
"strconv"
"strings"
)
// NewPrivateKey returns a PrivateKey by parsing the string s.
// s should be in the same form of the BIND private key files.
func (k *DNSKEY) NewPrivateKey(s string) (crypto.PrivateKey, error) {
if s == "" || s[len(s)-1] != '\n' { // We need a closing newline
return k.ReadPrivateKey(strings.NewReader(s+"\n"), "")
}
return k.ReadPrivateKey(strings.NewReader(s), "")
}
// ReadPrivateKey reads a private key from the io.Reader q. The string file is
// only used in error reporting.
// The public key must be known, because some cryptographic algorithms embed
// the public inside the privatekey.
func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, error) {
m, err := parseKey(q, file)
if m == nil {
return nil, err
}
if _, ok := m["private-key-format"]; !ok {
return nil, ErrPrivKey
}
if m["private-key-format"] != "v1.2" && m["private-key-format"] != "v1.3" {
return nil, ErrPrivKey
}
// TODO(mg): check if the pubkey matches the private key
algo, err := strconv.Atoi(strings.SplitN(m["algorithm"], " ", 2)[0])
if err != nil {
return nil, ErrPrivKey
}
switch uint8(algo) {
case DSA:
priv, err := readPrivateKeyDSA(m)
if err != nil {
return nil, err
}
pub := k.publicKeyDSA()
if pub == nil {
return nil, ErrKey
}
priv.PublicKey = *pub
return priv, nil
case RSAMD5:
fallthrough
case RSASHA1:
fallthrough
case RSASHA1NSEC3SHA1:
fallthrough
case RSASHA256:
fallthrough
case RSASHA512:
priv, err := readPrivateKeyRSA(m)
if err != nil {
return nil, err
}
pub := k.publicKeyRSA()
if pub == nil {
return nil, ErrKey
}
priv.PublicKey = *pub
return priv, nil
case ECCGOST:
return nil, ErrPrivKey
case ECDSAP256SHA256:
fallthrough
case ECDSAP384SHA384:
priv, err := readPrivateKeyECDSA(m)
if err != nil {
return nil, err
}
pub := k.publicKeyECDSA()
if pub == nil {
return nil, ErrKey
}
priv.PublicKey = *pub
return priv, nil
default:
return nil, ErrPrivKey
}
}
// Read a private key (file) string and create a public key. Return the private key.
func readPrivateKeyRSA(m map[string]string) (*rsa.PrivateKey, error) {
p := new(rsa.PrivateKey)
p.Primes = []*big.Int{nil, nil}
for k, v := range m {
switch k {
case "modulus", "publicexponent", "privateexponent", "prime1", "prime2":
v1, err := fromBase64([]byte(v))
if err != nil {
return nil, err
}
switch k {
case "modulus":
p.PublicKey.N = big.NewInt(0)
p.PublicKey.N.SetBytes(v1)
case "publicexponent":
i := big.NewInt(0)
i.SetBytes(v1)
p.PublicKey.E = int(i.Int64()) // int64 should be large enough
case "privateexponent":
p.D = big.NewInt(0)
p.D.SetBytes(v1)
case "prime1":
p.Primes[0] = big.NewInt(0)
p.Primes[0].SetBytes(v1)
case "prime2":
p.Primes[1] = big.NewInt(0)
p.Primes[1].SetBytes(v1)
}
case "exponent1", "exponent2", "coefficient":
// not used in Go (yet)
case "created", "publish", "activate":
// not used in Go (yet)
}
}
return p, nil
}
func readPrivateKeyDSA(m map[string]string) (*dsa.PrivateKey, error) {
p := new(dsa.PrivateKey)
p.X = big.NewInt(0)
for k, v := range m {
switch k {
case "private_value(x)":
v1, err := fromBase64([]byte(v))
if err != nil {
return nil, err
}
p.X.SetBytes(v1)
case "created", "publish", "activate":
/* not used in Go (yet) */
}
}
return p, nil
}
func readPrivateKeyECDSA(m map[string]string) (*ecdsa.PrivateKey, error) {
p := new(ecdsa.PrivateKey)
p.D = big.NewInt(0)
// TODO: validate that the required flags are present
for k, v := range m {
switch k {
case "privatekey":
v1, err := fromBase64([]byte(v))
if err != nil {
return nil, err
}
p.D.SetBytes(v1)
case "created", "publish", "activate":
/* not used in Go (yet) */
}
}
return p, nil
}
// parseKey reads a private key from r. It returns a map[string]string,
// with the key-value pairs, or an error when the file is not correct.
func parseKey(r io.Reader, file string) (map[string]string, error) {
s := scanInit(r)
m := make(map[string]string)
c := make(chan lex)
k := ""
// Start the lexer
go klexer(s, c)
for l := range c {
// It should alternate
switch l.value {
case zKey:
k = l.token
case zValue:
if k == "" {
return nil, &ParseError{file, "no private key seen", l}
}
//println("Setting", strings.ToLower(k), "to", l.token, "b")
m[strings.ToLower(k)] = l.token
k = ""
}
}
return m, nil
}
// klexer scans the sourcefile and returns tokens on the channel c.
func klexer(s *scan, c chan lex) {
var l lex
str := "" // Hold the current read text
commt := false
key := true
x, err := s.tokenText()
defer close(c)
for err == nil {
l.column = s.position.Column
l.line = s.position.Line
switch x {
case ':':
if commt {
break
}
l.token = str
if key {
l.value = zKey
c <- l
// Next token is a space, eat it
s.tokenText()
key = false
str = ""
} else {
l.value = zValue
}
case ';':
commt = true
case '\n':
if commt {
// Reset a comment
commt = false
}
l.value = zValue
l.token = str
c <- l
str = ""
commt = false
key = true
default:
if commt {
break
}
str += string(x)
}
x, err = s.tokenText()
}
if len(str) > 0 {
// Send remainder
l.token = str
l.value = zValue
c <- l
}
}
| turbosquid/gloon | vendor/src/github.com/miekg/dns/dnssec_keyscan.go | GO | mit | 5,521 |
/*
* linux/arch/arm/mach-at91/gpio.c
*
* Copyright (C) 2005 HP Labs
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/clk.h>
#include <linux/errno.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/irqdomain.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/of_gpio.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <mach/at91_pio.h>
#include "generic.h"
struct at91_gpio_chip {
struct gpio_chip chip;
struct at91_gpio_chip *next; /* Bank sharing same clock */
int pioc_hwirq; /* PIO bank interrupt identifier on AIC */
int pioc_virq; /* PIO bank Linux virtual interrupt */
int pioc_idx; /* PIO bank index */
void __iomem *regbase; /* PIO bank virtual address */
struct clk *clock; /* associated clock */
struct irq_domain *domain; /* associated irq domain */
};
#define to_at91_gpio_chip(c) container_of(c, struct at91_gpio_chip, chip)
static void at91_gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip);
static void at91_gpiolib_set(struct gpio_chip *chip, unsigned offset, int val);
static int at91_gpiolib_get(struct gpio_chip *chip, unsigned offset);
static int at91_gpiolib_direction_output(struct gpio_chip *chip,
unsigned offset, int val);
static int at91_gpiolib_direction_input(struct gpio_chip *chip,
unsigned offset);
static int at91_gpiolib_to_irq(struct gpio_chip *chip, unsigned offset);
#define AT91_GPIO_CHIP(name, nr_gpio) \
{ \
.chip = { \
.label = name, \
.direction_input = at91_gpiolib_direction_input, \
.direction_output = at91_gpiolib_direction_output, \
.get = at91_gpiolib_get, \
.set = at91_gpiolib_set, \
.dbg_show = at91_gpiolib_dbg_show, \
.to_irq = at91_gpiolib_to_irq, \
.ngpio = nr_gpio, \
}, \
}
static struct at91_gpio_chip gpio_chip[] = {
AT91_GPIO_CHIP("pioA", 32),
AT91_GPIO_CHIP("pioB", 32),
AT91_GPIO_CHIP("pioC", 32),
AT91_GPIO_CHIP("pioD", 32),
AT91_GPIO_CHIP("pioE", 32),
};
static int gpio_banks;
static unsigned long at91_gpio_caps;
/* All PIO controllers support PIO3 features */
#define AT91_GPIO_CAP_PIO3 (1 << 0)
#define has_pio3() (at91_gpio_caps & AT91_GPIO_CAP_PIO3)
/*--------------------------------------------------------------------------*/
static inline void __iomem *pin_to_controller(unsigned pin)
{
pin /= 32;
if (likely(pin < gpio_banks))
return gpio_chip[pin].regbase;
return NULL;
}
static inline unsigned pin_to_mask(unsigned pin)
{
return 1 << (pin % 32);
}
static char peripheral_function(void __iomem *pio, unsigned mask)
{
char ret = 'X';
u8 select;
if (pio) {
if (has_pio3()) {
select = !!(__raw_readl(pio + PIO_ABCDSR1) & mask);
select |= (!!(__raw_readl(pio + PIO_ABCDSR2) & mask) << 1);
ret = 'A' + select;
} else {
ret = __raw_readl(pio + PIO_ABSR) & mask ?
'B' : 'A';
}
}
return ret;
}
/*--------------------------------------------------------------------------*/
/* Not all hardware capabilities are exposed through these calls; they
* only encapsulate the most common features and modes. (So if you
* want to change signals in groups, do it directly.)
*
* Bootloaders will usually handle some of the pin multiplexing setup.
* The intent is certainly that by the time Linux is fully booted, all
* pins should have been fully initialized. These setup calls should
* only be used by board setup routines, or possibly in driver probe().
*
* For bootloaders doing all that setup, these calls could be inlined
* as NOPs so Linux won't duplicate any setup code
*/
/*
* mux the pin to the "GPIO" peripheral role.
*/
int __init_or_module at91_set_GPIO_periph(unsigned pin, int use_pullup)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
__raw_writel(mask, pio + PIO_IDR);
__raw_writel(mask, pio + (use_pullup ? PIO_PUER : PIO_PUDR));
__raw_writel(mask, pio + PIO_PER);
return 0;
}
EXPORT_SYMBOL(at91_set_GPIO_periph);
/*
* mux the pin to the "A" internal peripheral role.
*/
int __init_or_module at91_set_A_periph(unsigned pin, int use_pullup)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
__raw_writel(mask, pio + PIO_IDR);
__raw_writel(mask, pio + (use_pullup ? PIO_PUER : PIO_PUDR));
if (has_pio3()) {
__raw_writel(__raw_readl(pio + PIO_ABCDSR1) & ~mask,
pio + PIO_ABCDSR1);
__raw_writel(__raw_readl(pio + PIO_ABCDSR2) & ~mask,
pio + PIO_ABCDSR2);
} else {
__raw_writel(mask, pio + PIO_ASR);
}
__raw_writel(mask, pio + PIO_PDR);
return 0;
}
EXPORT_SYMBOL(at91_set_A_periph);
/*
* mux the pin to the "B" internal peripheral role.
*/
int __init_or_module at91_set_B_periph(unsigned pin, int use_pullup)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
__raw_writel(mask, pio + PIO_IDR);
__raw_writel(mask, pio + (use_pullup ? PIO_PUER : PIO_PUDR));
if (has_pio3()) {
__raw_writel(__raw_readl(pio + PIO_ABCDSR1) | mask,
pio + PIO_ABCDSR1);
__raw_writel(__raw_readl(pio + PIO_ABCDSR2) & ~mask,
pio + PIO_ABCDSR2);
} else {
__raw_writel(mask, pio + PIO_BSR);
}
__raw_writel(mask, pio + PIO_PDR);
return 0;
}
EXPORT_SYMBOL(at91_set_B_periph);
/*
* mux the pin to the "C" internal peripheral role.
*/
int __init_or_module at91_set_C_periph(unsigned pin, int use_pullup)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio || !has_pio3())
return -EINVAL;
__raw_writel(mask, pio + PIO_IDR);
__raw_writel(mask, pio + (use_pullup ? PIO_PUER : PIO_PUDR));
__raw_writel(__raw_readl(pio + PIO_ABCDSR1) & ~mask, pio + PIO_ABCDSR1);
__raw_writel(__raw_readl(pio + PIO_ABCDSR2) | mask, pio + PIO_ABCDSR2);
__raw_writel(mask, pio + PIO_PDR);
return 0;
}
EXPORT_SYMBOL(at91_set_C_periph);
/*
* mux the pin to the "D" internal peripheral role.
*/
int __init_or_module at91_set_D_periph(unsigned pin, int use_pullup)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio || !has_pio3())
return -EINVAL;
__raw_writel(mask, pio + PIO_IDR);
__raw_writel(mask, pio + (use_pullup ? PIO_PUER : PIO_PUDR));
__raw_writel(__raw_readl(pio + PIO_ABCDSR1) | mask, pio + PIO_ABCDSR1);
__raw_writel(__raw_readl(pio + PIO_ABCDSR2) | mask, pio + PIO_ABCDSR2);
__raw_writel(mask, pio + PIO_PDR);
return 0;
}
EXPORT_SYMBOL(at91_set_D_periph);
/*
* mux the pin to the gpio controller (instead of "A", "B", "C"
* or "D" peripheral), and configure it for an input.
*/
int __init_or_module at91_set_gpio_input(unsigned pin, int use_pullup)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
__raw_writel(mask, pio + PIO_IDR);
__raw_writel(mask, pio + (use_pullup ? PIO_PUER : PIO_PUDR));
__raw_writel(mask, pio + PIO_ODR);
__raw_writel(mask, pio + PIO_PER);
return 0;
}
EXPORT_SYMBOL(at91_set_gpio_input);
/*
* mux the pin to the gpio controller (instead of "A", "B", "C"
* or "D" peripheral), and configure it for an output.
*/
int __init_or_module at91_set_gpio_output(unsigned pin, int value)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
__raw_writel(mask, pio + PIO_IDR);
__raw_writel(mask, pio + PIO_PUDR);
__raw_writel(mask, pio + (value ? PIO_SODR : PIO_CODR));
__raw_writel(mask, pio + PIO_OER);
__raw_writel(mask, pio + PIO_PER);
return 0;
}
EXPORT_SYMBOL(at91_set_gpio_output);
/*
* enable/disable the glitch filter; mostly used with IRQ handling.
*/
int __init_or_module at91_set_deglitch(unsigned pin, int is_on)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
if (has_pio3() && is_on)
__raw_writel(mask, pio + PIO_IFSCDR);
__raw_writel(mask, pio + (is_on ? PIO_IFER : PIO_IFDR));
return 0;
}
EXPORT_SYMBOL(at91_set_deglitch);
/*
* enable/disable the debounce filter;
*/
int __init_or_module at91_set_debounce(unsigned pin, int is_on, int div)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio || !has_pio3())
return -EINVAL;
if (is_on) {
__raw_writel(mask, pio + PIO_IFSCER);
__raw_writel(div & PIO_SCDR_DIV, pio + PIO_SCDR);
__raw_writel(mask, pio + PIO_IFER);
} else {
__raw_writel(mask, pio + PIO_IFDR);
}
return 0;
}
EXPORT_SYMBOL(at91_set_debounce);
/*
* enable/disable the multi-driver; This is only valid for output and
* allows the output pin to run as an open collector output.
*/
int __init_or_module at91_set_multi_drive(unsigned pin, int is_on)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
__raw_writel(mask, pio + (is_on ? PIO_MDER : PIO_MDDR));
return 0;
}
EXPORT_SYMBOL(at91_set_multi_drive);
/*
* enable/disable the pull-down.
* If pull-up already enabled while calling the function, we disable it.
*/
int __init_or_module at91_set_pulldown(unsigned pin, int is_on)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio || !has_pio3())
return -EINVAL;
/* Disable pull-up anyway */
__raw_writel(mask, pio + PIO_PUDR);
__raw_writel(mask, pio + (is_on ? PIO_PPDER : PIO_PPDDR));
return 0;
}
EXPORT_SYMBOL(at91_set_pulldown);
/*
* disable Schmitt trigger
*/
int __init_or_module at91_disable_schmitt_trig(unsigned pin)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio || !has_pio3())
return -EINVAL;
__raw_writel(__raw_readl(pio + PIO_SCHMITT) | mask, pio + PIO_SCHMITT);
return 0;
}
EXPORT_SYMBOL(at91_disable_schmitt_trig);
/*
* assuming the pin is muxed as a gpio output, set its value.
*/
int at91_set_gpio_value(unsigned pin, int value)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (!pio)
return -EINVAL;
__raw_writel(mask, pio + (value ? PIO_SODR : PIO_CODR));
return 0;
}
EXPORT_SYMBOL(at91_set_gpio_value);
/*
* read the pin's value (works even if it's not muxed as a gpio).
*/
int at91_get_gpio_value(unsigned pin)
{
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
u32 pdsr;
if (!pio)
return -EINVAL;
pdsr = __raw_readl(pio + PIO_PDSR);
return (pdsr & mask) != 0;
}
EXPORT_SYMBOL(at91_get_gpio_value);
/*--------------------------------------------------------------------------*/
#ifdef CONFIG_PM
static u32 wakeups[MAX_GPIO_BANKS];
static u32 backups[MAX_GPIO_BANKS];
static int gpio_irq_set_wake(struct irq_data *d, unsigned state)
{
struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d);
unsigned mask = 1 << d->hwirq;
unsigned bank = at91_gpio->pioc_idx;
if (unlikely(bank >= MAX_GPIO_BANKS))
return -EINVAL;
if (state)
wakeups[bank] |= mask;
else
wakeups[bank] &= ~mask;
irq_set_irq_wake(at91_gpio->pioc_virq, state);
return 0;
}
void at91_gpio_suspend(void)
{
int i;
for (i = 0; i < gpio_banks; i++) {
void __iomem *pio = gpio_chip[i].regbase;
backups[i] = __raw_readl(pio + PIO_IMR);
__raw_writel(backups[i], pio + PIO_IDR);
__raw_writel(wakeups[i], pio + PIO_IER);
if (!wakeups[i]) {
clk_unprepare(gpio_chip[i].clock);
clk_disable(gpio_chip[i].clock);
} else {
#ifdef CONFIG_PM_DEBUG
printk(KERN_DEBUG "GPIO-%c may wake for %08x\n", 'A'+i, wakeups[i]);
#endif
}
}
}
void at91_gpio_resume(void)
{
int i;
for (i = 0; i < gpio_banks; i++) {
void __iomem *pio = gpio_chip[i].regbase;
if (!wakeups[i]) {
if (clk_prepare(gpio_chip[i].clock) == 0)
clk_enable(gpio_chip[i].clock);
}
__raw_writel(wakeups[i], pio + PIO_IDR);
__raw_writel(backups[i], pio + PIO_IER);
}
}
#else
#define gpio_irq_set_wake NULL
#endif
/* Several AIC controller irqs are dispatched through this GPIO handler.
* To use any AT91_PIN_* as an externally triggered IRQ, first call
* at91_set_gpio_input() then maybe enable its glitch filter.
* Then just request_irq() with the pin ID; it works like any ARM IRQ
* handler.
* First implementation always triggers on rising and falling edges
* whereas the newer PIO3 can be additionally configured to trigger on
* level, edge with any polarity.
*
* Alternatively, certain pins may be used directly as IRQ0..IRQ6 after
* configuring them with at91_set_a_periph() or at91_set_b_periph().
* IRQ0..IRQ6 should be configurable, e.g. level vs edge triggering.
*/
static void gpio_irq_mask(struct irq_data *d)
{
struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d);
void __iomem *pio = at91_gpio->regbase;
unsigned mask = 1 << d->hwirq;
if (pio)
__raw_writel(mask, pio + PIO_IDR);
}
static void gpio_irq_unmask(struct irq_data *d)
{
struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d);
void __iomem *pio = at91_gpio->regbase;
unsigned mask = 1 << d->hwirq;
if (pio)
__raw_writel(mask, pio + PIO_IER);
}
static int gpio_irq_type(struct irq_data *d, unsigned type)
{
switch (type) {
case IRQ_TYPE_NONE:
case IRQ_TYPE_EDGE_BOTH:
return 0;
default:
return -EINVAL;
}
}
/* Alternate irq type for PIO3 support */
static int alt_gpio_irq_type(struct irq_data *d, unsigned type)
{
struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d);
void __iomem *pio = at91_gpio->regbase;
unsigned mask = 1 << d->hwirq;
switch (type) {
case IRQ_TYPE_EDGE_RISING:
__raw_writel(mask, pio + PIO_ESR);
__raw_writel(mask, pio + PIO_REHLSR);
break;
case IRQ_TYPE_EDGE_FALLING:
__raw_writel(mask, pio + PIO_ESR);
__raw_writel(mask, pio + PIO_FELLSR);
break;
case IRQ_TYPE_LEVEL_LOW:
__raw_writel(mask, pio + PIO_LSR);
__raw_writel(mask, pio + PIO_FELLSR);
break;
case IRQ_TYPE_LEVEL_HIGH:
__raw_writel(mask, pio + PIO_LSR);
__raw_writel(mask, pio + PIO_REHLSR);
break;
case IRQ_TYPE_EDGE_BOTH:
/*
* disable additional interrupt modes:
* fall back to default behavior
*/
__raw_writel(mask, pio + PIO_AIMDR);
return 0;
case IRQ_TYPE_NONE:
default:
pr_warn("AT91: No type for irq %d\n", gpio_to_irq(d->irq));
return -EINVAL;
}
/* enable additional interrupt modes */
__raw_writel(mask, pio + PIO_AIMER);
return 0;
}
static struct irq_chip gpio_irqchip = {
.name = "GPIO",
.irq_disable = gpio_irq_mask,
.irq_mask = gpio_irq_mask,
.irq_unmask = gpio_irq_unmask,
/* .irq_set_type is set dynamically */
.irq_set_wake = gpio_irq_set_wake,
};
static void gpio_irq_handler(unsigned irq, struct irq_desc *desc)
{
struct irq_chip *chip = irq_desc_get_chip(desc);
struct irq_data *idata = irq_desc_get_irq_data(desc);
struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(idata);
void __iomem *pio = at91_gpio->regbase;
unsigned long isr;
int n;
chained_irq_enter(chip, desc);
for (;;) {
/* Reading ISR acks pending (edge triggered) GPIO interrupts.
* When there none are pending, we're finished unless we need
* to process multiple banks (like ID_PIOCDE on sam9263).
*/
isr = __raw_readl(pio + PIO_ISR) & __raw_readl(pio + PIO_IMR);
if (!isr) {
if (!at91_gpio->next)
break;
at91_gpio = at91_gpio->next;
pio = at91_gpio->regbase;
continue;
}
n = find_first_bit(&isr, BITS_PER_LONG);
while (n < BITS_PER_LONG) {
generic_handle_irq(irq_find_mapping(at91_gpio->domain, n));
n = find_next_bit(&isr, BITS_PER_LONG, n + 1);
}
}
chained_irq_exit(chip, desc);
/* now it may re-trigger */
}
/*--------------------------------------------------------------------------*/
#ifdef CONFIG_DEBUG_FS
static void gpio_printf(struct seq_file *s, void __iomem *pio, unsigned mask)
{
char *trigger = NULL;
char *polarity = NULL;
if (__raw_readl(pio + PIO_IMR) & mask) {
if (!has_pio3() || !(__raw_readl(pio + PIO_AIMMR) & mask )) {
trigger = "edge";
polarity = "both";
} else {
if (__raw_readl(pio + PIO_ELSR) & mask) {
trigger = "level";
polarity = __raw_readl(pio + PIO_FRLHSR) & mask ?
"high" : "low";
} else {
trigger = "edge";
polarity = __raw_readl(pio + PIO_FRLHSR) & mask ?
"rising" : "falling";
}
}
seq_printf(s, "IRQ:%s-%s\t", trigger, polarity);
} else {
seq_printf(s, "GPIO:%s\t\t",
__raw_readl(pio + PIO_PDSR) & mask ? "1" : "0");
}
}
static int at91_gpio_show(struct seq_file *s, void *unused)
{
int bank, j;
/* print heading */
seq_printf(s, "Pin\t");
for (bank = 0; bank < gpio_banks; bank++) {
seq_printf(s, "PIO%c\t\t", 'A' + bank);
};
seq_printf(s, "\n\n");
/* print pin status */
for (j = 0; j < 32; j++) {
seq_printf(s, "%i:\t", j);
for (bank = 0; bank < gpio_banks; bank++) {
unsigned pin = (32 * bank) + j;
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
if (__raw_readl(pio + PIO_PSR) & mask)
gpio_printf(s, pio, mask);
else
seq_printf(s, "%c\t\t",
peripheral_function(pio, mask));
}
seq_printf(s, "\n");
}
return 0;
}
static int at91_gpio_open(struct inode *inode, struct file *file)
{
return single_open(file, at91_gpio_show, NULL);
}
static const struct file_operations at91_gpio_operations = {
.open = at91_gpio_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init at91_gpio_debugfs_init(void)
{
/* /sys/kernel/debug/at91_gpio */
(void) debugfs_create_file("at91_gpio", S_IFREG | S_IRUGO, NULL, NULL, &at91_gpio_operations);
return 0;
}
postcore_initcall(at91_gpio_debugfs_init);
#endif
/*--------------------------------------------------------------------------*/
/*
* This lock class tells lockdep that GPIO irqs are in a different
* category than their parents, so it won't report false recursion.
*/
static struct lock_class_key gpio_lock_class;
#if defined(CONFIG_OF)
static int at91_gpio_irq_map(struct irq_domain *h, unsigned int virq,
irq_hw_number_t hw)
{
struct at91_gpio_chip *at91_gpio = h->host_data;
irq_set_lockdep_class(virq, &gpio_lock_class);
/*
* Can use the "simple" and not "edge" handler since it's
* shorter, and the AIC handles interrupts sanely.
*/
irq_set_chip_and_handler(virq, &gpio_irqchip,
handle_simple_irq);
set_irq_flags(virq, IRQF_VALID);
irq_set_chip_data(virq, at91_gpio);
return 0;
}
static struct irq_domain_ops at91_gpio_ops = {
.map = at91_gpio_irq_map,
.xlate = irq_domain_xlate_twocell,
};
int __init at91_gpio_of_irq_setup(struct device_node *node,
struct device_node *parent)
{
struct at91_gpio_chip *prev = NULL;
int alias_idx = of_alias_get_id(node, "gpio");
struct at91_gpio_chip *at91_gpio = &gpio_chip[alias_idx];
/* Setup proper .irq_set_type function */
if (has_pio3())
gpio_irqchip.irq_set_type = alt_gpio_irq_type;
else
gpio_irqchip.irq_set_type = gpio_irq_type;
/* Disable irqs of this PIO controller */
__raw_writel(~0, at91_gpio->regbase + PIO_IDR);
/* Setup irq domain */
at91_gpio->domain = irq_domain_add_linear(node, at91_gpio->chip.ngpio,
&at91_gpio_ops, at91_gpio);
if (!at91_gpio->domain)
panic("at91_gpio.%d: couldn't allocate irq domain (DT).\n",
at91_gpio->pioc_idx);
/* Setup chained handler */
if (at91_gpio->pioc_idx)
prev = &gpio_chip[at91_gpio->pioc_idx - 1];
/* The toplevel handler handles one bank of GPIOs, except
* on some SoC it can handles up to three...
* We only set up the handler for the first of the list.
*/
if (prev && prev->next == at91_gpio)
return 0;
at91_gpio->pioc_virq = irq_create_mapping(irq_find_host(parent),
at91_gpio->pioc_hwirq);
irq_set_chip_data(at91_gpio->pioc_virq, at91_gpio);
irq_set_chained_handler(at91_gpio->pioc_virq, gpio_irq_handler);
return 0;
}
#else
int __init at91_gpio_of_irq_setup(struct device_node *node,
struct device_node *parent)
{
return -EINVAL;
}
#endif
/*
* irqdomain initialization: pile up irqdomains on top of AIC range
*/
static void __init at91_gpio_irqdomain(struct at91_gpio_chip *at91_gpio)
{
int irq_base;
irq_base = irq_alloc_descs(-1, 0, at91_gpio->chip.ngpio, 0);
if (irq_base < 0)
panic("at91_gpio.%d: error %d: couldn't allocate IRQ numbers.\n",
at91_gpio->pioc_idx, irq_base);
at91_gpio->domain = irq_domain_add_legacy(NULL, at91_gpio->chip.ngpio,
irq_base, 0,
&irq_domain_simple_ops, NULL);
if (!at91_gpio->domain)
panic("at91_gpio.%d: couldn't allocate irq domain.\n",
at91_gpio->pioc_idx);
}
/*
* Called from the processor-specific init to enable GPIO interrupt support.
*/
void __init at91_gpio_irq_setup(void)
{
unsigned pioc;
int gpio_irqnbr = 0;
struct at91_gpio_chip *this, *prev;
/* Setup proper .irq_set_type function */
if (has_pio3())
gpio_irqchip.irq_set_type = alt_gpio_irq_type;
else
gpio_irqchip.irq_set_type = gpio_irq_type;
for (pioc = 0, this = gpio_chip, prev = NULL;
pioc++ < gpio_banks;
prev = this, this++) {
int offset;
__raw_writel(~0, this->regbase + PIO_IDR);
/* setup irq domain for this GPIO controller */
at91_gpio_irqdomain(this);
for (offset = 0; offset < this->chip.ngpio; offset++) {
unsigned int virq = irq_find_mapping(this->domain, offset);
irq_set_lockdep_class(virq, &gpio_lock_class);
/*
* Can use the "simple" and not "edge" handler since it's
* shorter, and the AIC handles interrupts sanely.
*/
irq_set_chip_and_handler(virq, &gpio_irqchip,
handle_simple_irq);
set_irq_flags(virq, IRQF_VALID);
irq_set_chip_data(virq, this);
gpio_irqnbr++;
}
/* The toplevel handler handles one bank of GPIOs, except
* on some SoC it can handles up to three...
* We only set up the handler for the first of the list.
*/
if (prev && prev->next == this)
continue;
this->pioc_virq = irq_create_mapping(NULL, this->pioc_hwirq);
irq_set_chip_data(this->pioc_virq, this);
irq_set_chained_handler(this->pioc_virq, gpio_irq_handler);
}
pr_info("AT91: %d gpio irqs in %d banks\n", gpio_irqnbr, gpio_banks);
}
/* gpiolib support */
static int at91_gpiolib_direction_input(struct gpio_chip *chip,
unsigned offset)
{
struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip);
void __iomem *pio = at91_gpio->regbase;
unsigned mask = 1 << offset;
__raw_writel(mask, pio + PIO_ODR);
return 0;
}
static int at91_gpiolib_direction_output(struct gpio_chip *chip,
unsigned offset, int val)
{
struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip);
void __iomem *pio = at91_gpio->regbase;
unsigned mask = 1 << offset;
__raw_writel(mask, pio + (val ? PIO_SODR : PIO_CODR));
__raw_writel(mask, pio + PIO_OER);
return 0;
}
static int at91_gpiolib_get(struct gpio_chip *chip, unsigned offset)
{
struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip);
void __iomem *pio = at91_gpio->regbase;
unsigned mask = 1 << offset;
u32 pdsr;
pdsr = __raw_readl(pio + PIO_PDSR);
return (pdsr & mask) != 0;
}
static void at91_gpiolib_set(struct gpio_chip *chip, unsigned offset, int val)
{
struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip);
void __iomem *pio = at91_gpio->regbase;
unsigned mask = 1 << offset;
__raw_writel(mask, pio + (val ? PIO_SODR : PIO_CODR));
}
static void at91_gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip)
{
int i;
for (i = 0; i < chip->ngpio; i++) {
unsigned pin = chip->base + i;
void __iomem *pio = pin_to_controller(pin);
unsigned mask = pin_to_mask(pin);
const char *gpio_label;
gpio_label = gpiochip_is_requested(chip, i);
if (gpio_label) {
seq_printf(s, "[%s] GPIO%s%d: ",
gpio_label, chip->label, i);
if (__raw_readl(pio + PIO_PSR) & mask)
seq_printf(s, "[gpio] %s\n",
at91_get_gpio_value(pin) ?
"set" : "clear");
else
seq_printf(s, "[periph %c]\n",
peripheral_function(pio, mask));
}
}
}
static int at91_gpiolib_to_irq(struct gpio_chip *chip, unsigned offset)
{
struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip);
int virq;
if (offset < chip->ngpio)
virq = irq_create_mapping(at91_gpio->domain, offset);
else
virq = -ENXIO;
dev_dbg(chip->dev, "%s: request IRQ for GPIO %d, return %d\n",
chip->label, offset + chip->base, virq);
return virq;
}
static int __init at91_gpio_setup_clk(int idx)
{
struct at91_gpio_chip *at91_gpio = &gpio_chip[idx];
/* retreive PIO controller's clock */
at91_gpio->clock = clk_get_sys(NULL, at91_gpio->chip.label);
if (IS_ERR(at91_gpio->clock)) {
pr_err("at91_gpio.%d, failed to get clock, ignoring.\n", idx);
goto err;
}
if (clk_prepare(at91_gpio->clock))
goto clk_prep_err;
/* enable PIO controller's clock */
if (clk_enable(at91_gpio->clock)) {
pr_err("at91_gpio.%d, failed to enable clock, ignoring.\n", idx);
goto clk_err;
}
return 0;
clk_err:
clk_unprepare(at91_gpio->clock);
clk_prep_err:
clk_put(at91_gpio->clock);
err:
return -EINVAL;
}
#ifdef CONFIG_OF_GPIO
static void __init of_at91_gpio_init_one(struct device_node *np)
{
int alias_idx;
struct at91_gpio_chip *at91_gpio;
if (!np)
return;
alias_idx = of_alias_get_id(np, "gpio");
if (alias_idx >= MAX_GPIO_BANKS) {
pr_err("at91_gpio, failed alias idx(%d) > MAX_GPIO_BANKS(%d), ignoring.\n",
alias_idx, MAX_GPIO_BANKS);
return;
}
at91_gpio = &gpio_chip[alias_idx];
at91_gpio->chip.base = alias_idx * at91_gpio->chip.ngpio;
at91_gpio->regbase = of_iomap(np, 0);
if (!at91_gpio->regbase) {
pr_err("at91_gpio.%d, failed to map registers, ignoring.\n",
alias_idx);
return;
}
/* Get the interrupts property */
if (of_property_read_u32(np, "interrupts", &at91_gpio->pioc_hwirq)) {
pr_err("at91_gpio.%d, failed to get interrupts property, ignoring.\n",
alias_idx);
goto ioremap_err;
}
/* Get capabilities from compatibility property */
if (of_device_is_compatible(np, "atmel,at91sam9x5-gpio"))
at91_gpio_caps |= AT91_GPIO_CAP_PIO3;
/* Setup clock */
if (at91_gpio_setup_clk(alias_idx))
goto ioremap_err;
at91_gpio->chip.of_node = np;
gpio_banks = max(gpio_banks, alias_idx + 1);
at91_gpio->pioc_idx = alias_idx;
return;
ioremap_err:
iounmap(at91_gpio->regbase);
}
static int __init of_at91_gpio_init(void)
{
struct device_node *np = NULL;
/*
* This isn't ideal, but it gets things hooked up until this
* driver is converted into a platform_device
*/
for_each_compatible_node(np, NULL, "atmel,at91rm9200-gpio")
of_at91_gpio_init_one(np);
return gpio_banks > 0 ? 0 : -EINVAL;
}
#else
static int __init of_at91_gpio_init(void)
{
return -EINVAL;
}
#endif
static void __init at91_gpio_init_one(int idx, u32 regbase, int pioc_hwirq)
{
struct at91_gpio_chip *at91_gpio = &gpio_chip[idx];
at91_gpio->chip.base = idx * at91_gpio->chip.ngpio;
at91_gpio->pioc_hwirq = pioc_hwirq;
at91_gpio->pioc_idx = idx;
at91_gpio->regbase = ioremap(regbase, 512);
if (!at91_gpio->regbase) {
pr_err("at91_gpio.%d, failed to map registers, ignoring.\n", idx);
return;
}
if (at91_gpio_setup_clk(idx))
goto ioremap_err;
gpio_banks = max(gpio_banks, idx + 1);
return;
ioremap_err:
iounmap(at91_gpio->regbase);
}
/*
* Called from the processor-specific init to enable GPIO pin support.
*/
void __init at91_gpio_init(struct at91_gpio_bank *data, int nr_banks)
{
unsigned i;
struct at91_gpio_chip *at91_gpio, *last = NULL;
BUG_ON(nr_banks > MAX_GPIO_BANKS);
if (of_at91_gpio_init() < 0) {
/* No GPIO controller found in device tree */
for (i = 0; i < nr_banks; i++)
at91_gpio_init_one(i, data[i].regbase, data[i].id);
}
for (i = 0; i < gpio_banks; i++) {
at91_gpio = &gpio_chip[i];
/*
* GPIO controller are grouped on some SoC:
* PIOC, PIOD and PIOE can share the same IRQ line
*/
if (last && last->pioc_hwirq == at91_gpio->pioc_hwirq)
last->next = at91_gpio;
last = at91_gpio;
gpiochip_add(&at91_gpio->chip);
}
}
| ystk/linux-poky-debian | arch/arm/mach-at91/gpio.c | C | gpl-2.0 | 28,199 |
! { dg-do compile }
! This tests the fix for PR28735 in which an ICE would be triggered in resolve_ref
! because the references to 'a' and 'b' in the dummy arguments of mysub have
! no symtrees in module bar, being private there.
!
! Contributed by Andrew Sampson <adsspamtrap01@yahoo.com>
!
!-- foo.F -----------------------------------------------
module foo
implicit none
public
integer, allocatable :: a(:), b(:)
end module foo
!-- bar.F ---------------------------------------------
module bar
use foo
implicit none
private ! This triggered the ICE
public :: mysub ! since a and b are not public
contains
subroutine mysub(n, parray1)
integer, intent(in) :: n
real, dimension(a(n):b(n)) :: parray1
if ((n == 1) .and. size(parray1, 1) /= 10) call abort ()
if ((n == 2) .and. size(parray1, 1) /= 42) call abort ()
end subroutine mysub
end module bar
!-- sub.F -------------------------------------------------------
subroutine sub()
use foo
use bar
real :: z(100)
allocate (a(2), b(2))
a = (/1, 6/)
b = (/10, 47/)
call mysub (1, z)
call mysub (2, z)
return
end
!-- MAIN ------------------------------------------------------
use bar
call sub ()
end
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/gfortran.dg/module_private_array_refs_1.f90 | FORTRAN | gpl-3.0 | 1,240 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
internal static partial class Interop
{
internal static partial class Winsock
{
[DllImport(Interop.Libraries.Ws2_32, ExactSpelling = true, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)]
internal static extern int GetAddrInfoW(
[In] string nodename,
[In] string servicename,
[In] ref AddressInfo hints,
[Out] out SafeFreeAddrInfo handle
);
}
}
| nbarbettini/corefx | src/Common/src/Interop/Windows/Winsock/Interop.GetAddrInfoW.cs | C# | mit | 789 |
/*
* AMD 10Gb Ethernet driver
*
* This file is available to you under your choice of the following two
* licenses:
*
* License 1: GPLv2
*
* Copyright (c) 2014 Advanced Micro Devices, Inc.
*
* This file is free software; you may copy, redistribute and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or (at
* your option) any later version.
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
* The Synopsys DWC ETHER XGMAC Software Driver and documentation
* (hereinafter "Software") is an unsupported proprietary work of Synopsys,
* Inc. unless otherwise expressly agreed to in writing between Synopsys
* and you.
*
* The Software IS NOT an item of Licensed Software or Licensed Product
* under any End User Software License Agreement or Agreement for Licensed
* Product with Synopsys or any supplement thereto. Permission is hereby
* granted, free of charge, to any person obtaining a copy of this software
* annotated with this license and the Software, to deal in the Software
* without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THIS SOFTWARE IS BEING DISTRIBUTED BY SYNOPSYS SOLELY ON AN "AS IS"
* BASIS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE HEREBY DISCLAIMED. IN NO EVENT SHALL SYNOPSYS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
*
* License 2: Modified BSD
*
* Copyright (c) 2014 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, Inc. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This file incorporates work covered by the following copyright and
* permission notice:
* The Synopsys DWC ETHER XGMAC Software Driver and documentation
* (hereinafter "Software") is an unsupported proprietary work of Synopsys,
* Inc. unless otherwise expressly agreed to in writing between Synopsys
* and you.
*
* The Software IS NOT an item of Licensed Software or Licensed Product
* under any End User Software License Agreement or Agreement for Licensed
* Product with Synopsys or any supplement thereto. Permission is hereby
* granted, free of charge, to any person obtaining a copy of this software
* annotated with this license and the Software, to deal in the Software
* without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THIS SOFTWARE IS BEING DISTRIBUTED BY SYNOPSYS SOLELY ON AN "AS IS"
* BASIS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE HEREBY DISCLAIMED. IN NO EVENT SHALL SYNOPSYS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/clk.h>
#include <linux/clocksource.h>
#include <linux/ptp_clock_kernel.h>
#include <linux/net_tstamp.h>
#include "xgbe.h"
#include "xgbe-common.h"
static cycle_t xgbe_cc_read(const struct cyclecounter *cc)
{
struct xgbe_prv_data *pdata = container_of(cc,
struct xgbe_prv_data,
tstamp_cc);
u64 nsec;
nsec = pdata->hw_if.get_tstamp_time(pdata);
return nsec;
}
static int xgbe_adjfreq(struct ptp_clock_info *info, s32 delta)
{
struct xgbe_prv_data *pdata = container_of(info,
struct xgbe_prv_data,
ptp_clock_info);
unsigned long flags;
u64 adjust;
u32 addend, diff;
unsigned int neg_adjust = 0;
if (delta < 0) {
neg_adjust = 1;
delta = -delta;
}
adjust = pdata->tstamp_addend;
adjust *= delta;
diff = div_u64(adjust, 1000000000UL);
addend = (neg_adjust) ? pdata->tstamp_addend - diff :
pdata->tstamp_addend + diff;
spin_lock_irqsave(&pdata->tstamp_lock, flags);
pdata->hw_if.update_tstamp_addend(pdata, addend);
spin_unlock_irqrestore(&pdata->tstamp_lock, flags);
return 0;
}
static int xgbe_adjtime(struct ptp_clock_info *info, s64 delta)
{
struct xgbe_prv_data *pdata = container_of(info,
struct xgbe_prv_data,
ptp_clock_info);
unsigned long flags;
spin_lock_irqsave(&pdata->tstamp_lock, flags);
timecounter_adjtime(&pdata->tstamp_tc, delta);
spin_unlock_irqrestore(&pdata->tstamp_lock, flags);
return 0;
}
static int xgbe_gettime(struct ptp_clock_info *info, struct timespec *ts)
{
struct xgbe_prv_data *pdata = container_of(info,
struct xgbe_prv_data,
ptp_clock_info);
unsigned long flags;
u64 nsec;
spin_lock_irqsave(&pdata->tstamp_lock, flags);
nsec = timecounter_read(&pdata->tstamp_tc);
spin_unlock_irqrestore(&pdata->tstamp_lock, flags);
*ts = ns_to_timespec(nsec);
return 0;
}
static int xgbe_settime(struct ptp_clock_info *info, const struct timespec *ts)
{
struct xgbe_prv_data *pdata = container_of(info,
struct xgbe_prv_data,
ptp_clock_info);
unsigned long flags;
u64 nsec;
nsec = timespec_to_ns(ts);
spin_lock_irqsave(&pdata->tstamp_lock, flags);
timecounter_init(&pdata->tstamp_tc, &pdata->tstamp_cc, nsec);
spin_unlock_irqrestore(&pdata->tstamp_lock, flags);
return 0;
}
static int xgbe_enable(struct ptp_clock_info *info,
struct ptp_clock_request *request, int on)
{
return -EOPNOTSUPP;
}
void xgbe_ptp_register(struct xgbe_prv_data *pdata)
{
struct ptp_clock_info *info = &pdata->ptp_clock_info;
struct ptp_clock *clock;
struct cyclecounter *cc = &pdata->tstamp_cc;
u64 dividend;
snprintf(info->name, sizeof(info->name), "%s",
netdev_name(pdata->netdev));
info->owner = THIS_MODULE;
info->max_adj = pdata->ptpclk_rate;
info->adjfreq = xgbe_adjfreq;
info->adjtime = xgbe_adjtime;
info->gettime = xgbe_gettime;
info->settime = xgbe_settime;
info->enable = xgbe_enable;
clock = ptp_clock_register(info, pdata->dev);
if (IS_ERR(clock)) {
dev_err(pdata->dev, "ptp_clock_register failed\n");
return;
}
pdata->ptp_clock = clock;
/* Calculate the addend:
* addend = 2^32 / (PTP ref clock / 50Mhz)
* = (2^32 * 50Mhz) / PTP ref clock
*/
dividend = 50000000;
dividend <<= 32;
pdata->tstamp_addend = div_u64(dividend, pdata->ptpclk_rate);
/* Setup the timecounter */
cc->read = xgbe_cc_read;
cc->mask = CLOCKSOURCE_MASK(64);
cc->mult = 1;
cc->shift = 0;
timecounter_init(&pdata->tstamp_tc, &pdata->tstamp_cc,
ktime_to_ns(ktime_get_real()));
/* Disable all timestamping to start */
XGMAC_IOWRITE(pdata, MAC_TCR, 0);
pdata->tstamp_config.tx_type = HWTSTAMP_TX_OFF;
pdata->tstamp_config.rx_filter = HWTSTAMP_FILTER_NONE;
}
void xgbe_ptp_unregister(struct xgbe_prv_data *pdata)
{
if (pdata->ptp_clock)
ptp_clock_unregister(pdata->ptp_clock);
}
| systemdaemon/systemd | src/linux/drivers/net/ethernet/amd/xgbe/xgbe-ptp.c | C | gpl-2.0 | 10,239 |
/**
* @license AngularJS v1.3.16
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc object
* @name angular.mock
* @description
*
* Namespace from 'angular-mocks.js' which contains testing related code.
*/
angular.mock = {};
/**
* ! This is a private undocumented service !
*
* @name $browser
*
* @description
* This service is a mock implementation of {@link ng.$browser}. It provides fake
* implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
* cookies, etc...
*
* The api of this service is the same as that of the real {@link ng.$browser $browser}, except
* that there are several helper methods available which can be used in tests.
*/
angular.mock.$BrowserProvider = function() {
this.$get = function() {
return new angular.mock.$Browser();
};
};
angular.mock.$Browser = function() {
var self = this;
this.isMock = true;
self.$$url = "http://server/";
self.$$lastUrl = self.$$url; // used by url polling fn
self.pollFns = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = angular.noop;
self.$$incOutstandingRequestCount = angular.noop;
// register url polling fn
self.onUrlChange = function(listener) {
self.pollFns.push(
function() {
if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {
self.$$lastUrl = self.$$url;
self.$$lastState = self.$$state;
listener(self.$$url, self.$$state);
}
}
);
return listener;
};
self.$$checkUrlChange = angular.noop;
self.cookieHash = {};
self.lastCookieHash = {};
self.deferredFns = [];
self.deferredNextId = 0;
self.defer = function(fn, delay) {
delay = delay || 0;
self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
self.deferredFns.sort(function(a, b) { return a.time - b.time;});
return self.deferredNextId++;
};
/**
* @name $browser#defer.now
*
* @description
* Current milliseconds mock time.
*/
self.defer.now = 0;
self.defer.cancel = function(deferId) {
var fnIndex;
angular.forEach(self.deferredFns, function(fn, index) {
if (fn.id === deferId) fnIndex = index;
});
if (fnIndex !== undefined) {
self.deferredFns.splice(fnIndex, 1);
return true;
}
return false;
};
/**
* @name $browser#defer.flush
*
* @description
* Flushes all pending requests and executes the defer callbacks.
*
* @param {number=} number of milliseconds to flush. See {@link #defer.now}
*/
self.defer.flush = function(delay) {
if (angular.isDefined(delay)) {
self.defer.now += delay;
} else {
if (self.deferredFns.length) {
self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;
} else {
throw new Error('No deferred tasks to be flushed');
}
}
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
self.deferredFns.shift().fn();
}
};
self.$$baseHref = '/';
self.baseHref = function() {
return this.$$baseHref;
};
};
angular.mock.$Browser.prototype = {
/**
* @name $browser#poll
*
* @description
* run all fns in pollFns
*/
poll: function poll() {
angular.forEach(this.pollFns, function(pollFn) {
pollFn();
});
},
addPollFn: function(pollFn) {
this.pollFns.push(pollFn);
return pollFn;
},
url: function(url, replace, state) {
if (angular.isUndefined(state)) {
state = null;
}
if (url) {
this.$$url = url;
// Native pushState serializes & copies the object; simulate it.
this.$$state = angular.copy(state);
return this;
}
return this.$$url;
},
state: function() {
return this.$$state;
},
cookies: function(name, value) {
if (name) {
if (angular.isUndefined(value)) {
delete this.cookieHash[name];
} else {
if (angular.isString(value) && //strings only
value.length <= 4096) { //strict cookie storage limits
this.cookieHash[name] = value;
}
}
} else {
if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
this.lastCookieHash = angular.copy(this.cookieHash);
this.cookieHash = angular.copy(this.cookieHash);
}
return this.cookieHash;
}
},
notifyWhenNoOutstandingRequests: function(fn) {
fn();
}
};
/**
* @ngdoc provider
* @name $exceptionHandlerProvider
*
* @description
* Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
* passed to the `$exceptionHandler`.
*/
/**
* @ngdoc service
* @name $exceptionHandler
*
* @description
* Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
* to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
* information.
*
*
* ```js
* describe('$exceptionHandlerProvider', function() {
*
* it('should capture log messages and exceptions', function() {
*
* module(function($exceptionHandlerProvider) {
* $exceptionHandlerProvider.mode('log');
* });
*
* inject(function($log, $exceptionHandler, $timeout) {
* $timeout(function() { $log.log(1); });
* $timeout(function() { $log.log(2); throw 'banana peel'; });
* $timeout(function() { $log.log(3); });
* expect($exceptionHandler.errors).toEqual([]);
* expect($log.assertEmpty());
* $timeout.flush();
* expect($exceptionHandler.errors).toEqual(['banana peel']);
* expect($log.log.logs).toEqual([[1], [2], [3]]);
* });
* });
* });
* ```
*/
angular.mock.$ExceptionHandlerProvider = function() {
var handler;
/**
* @ngdoc method
* @name $exceptionHandlerProvider#mode
*
* @description
* Sets the logging mode.
*
* @param {string} mode Mode of operation, defaults to `rethrow`.
*
* - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
* mode stores an array of errors in `$exceptionHandler.errors`, to allow later
* assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
* {@link ngMock.$log#reset reset()}
* - `rethrow`: If any errors are passed to the handler in tests, it typically means that there
* is a bug in the application or test, so this mock will make these tests fail.
* For any implementations that expect exceptions to be thrown, the `rethrow` mode
* will also maintain a log of thrown errors.
*/
this.mode = function(mode) {
switch (mode) {
case 'log':
case 'rethrow':
var errors = [];
handler = function(e) {
if (arguments.length == 1) {
errors.push(e);
} else {
errors.push([].slice.call(arguments, 0));
}
if (mode === "rethrow") {
throw e;
}
};
handler.errors = errors;
break;
default:
throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
}
};
this.$get = function() {
return handler;
};
this.mode('rethrow');
};
/**
* @ngdoc service
* @name $log
*
* @description
* Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
* (one array per logging level). These arrays are exposed as `logs` property of each of the
* level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
*
*/
angular.mock.$LogProvider = function() {
var debug = true;
function concat(array1, array2, index) {
return array1.concat(Array.prototype.slice.call(array2, index));
}
this.debugEnabled = function(flag) {
if (angular.isDefined(flag)) {
debug = flag;
return this;
} else {
return debug;
}
};
this.$get = function() {
var $log = {
log: function() { $log.log.logs.push(concat([], arguments, 0)); },
warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
info: function() { $log.info.logs.push(concat([], arguments, 0)); },
error: function() { $log.error.logs.push(concat([], arguments, 0)); },
debug: function() {
if (debug) {
$log.debug.logs.push(concat([], arguments, 0));
}
}
};
/**
* @ngdoc method
* @name $log#reset
*
* @description
* Reset all of the logging arrays to empty.
*/
$log.reset = function() {
/**
* @ngdoc property
* @name $log#log.logs
*
* @description
* Array of messages logged using {@link ng.$log#log `log()`}.
*
* @example
* ```js
* $log.log('Some Log');
* var first = $log.log.logs.unshift();
* ```
*/
$log.log.logs = [];
/**
* @ngdoc property
* @name $log#info.logs
*
* @description
* Array of messages logged using {@link ng.$log#info `info()`}.
*
* @example
* ```js
* $log.info('Some Info');
* var first = $log.info.logs.unshift();
* ```
*/
$log.info.logs = [];
/**
* @ngdoc property
* @name $log#warn.logs
*
* @description
* Array of messages logged using {@link ng.$log#warn `warn()`}.
*
* @example
* ```js
* $log.warn('Some Warning');
* var first = $log.warn.logs.unshift();
* ```
*/
$log.warn.logs = [];
/**
* @ngdoc property
* @name $log#error.logs
*
* @description
* Array of messages logged using {@link ng.$log#error `error()`}.
*
* @example
* ```js
* $log.error('Some Error');
* var first = $log.error.logs.unshift();
* ```
*/
$log.error.logs = [];
/**
* @ngdoc property
* @name $log#debug.logs
*
* @description
* Array of messages logged using {@link ng.$log#debug `debug()`}.
*
* @example
* ```js
* $log.debug('Some Error');
* var first = $log.debug.logs.unshift();
* ```
*/
$log.debug.logs = [];
};
/**
* @ngdoc method
* @name $log#assertEmpty
*
* @description
* Assert that all of the logging methods have no logged messages. If any messages are present,
* an exception is thrown.
*/
$log.assertEmpty = function() {
var errors = [];
angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {
angular.forEach($log[logLevel].logs, function(log) {
angular.forEach(log, function(logItem) {
errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
(logItem.stack || ''));
});
});
});
if (errors.length) {
errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " +
"an expected log message was not checked and removed:");
errors.push('');
throw new Error(errors.join('\n---------\n'));
}
};
$log.reset();
return $log;
};
};
/**
* @ngdoc service
* @name $interval
*
* @description
* Mock implementation of the $interval service.
*
* Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that
* time.
*
* @param {function()} fn A function that should be called repeatedly.
* @param {number} delay Number of milliseconds between each function call.
* @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
* indefinitely.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {promise} A promise which will be notified on each iteration.
*/
angular.mock.$IntervalProvider = function() {
this.$get = ['$browser', '$rootScope', '$q', '$$q',
function($browser, $rootScope, $q, $$q) {
var repeatFns = [],
nextRepeatId = 0,
now = 0;
var $interval = function(fn, delay, count, invokeApply) {
var iteration = 0,
skipApply = (angular.isDefined(invokeApply) && !invokeApply),
deferred = (skipApply ? $$q : $q).defer(),
promise = deferred.promise;
count = (angular.isDefined(count)) ? count : 0;
promise.then(null, null, fn);
promise.$$intervalId = nextRepeatId;
function tick() {
deferred.notify(iteration++);
if (count > 0 && iteration >= count) {
var fnIndex;
deferred.resolve(iteration);
angular.forEach(repeatFns, function(fn, index) {
if (fn.id === promise.$$intervalId) fnIndex = index;
});
if (fnIndex !== undefined) {
repeatFns.splice(fnIndex, 1);
}
}
if (skipApply) {
$browser.defer.flush();
} else {
$rootScope.$apply();
}
}
repeatFns.push({
nextTime:(now + delay),
delay: delay,
fn: tick,
id: nextRepeatId,
deferred: deferred
});
repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
nextRepeatId++;
return promise;
};
/**
* @ngdoc method
* @name $interval#cancel
*
* @description
* Cancels a task associated with the `promise`.
*
* @param {promise} promise A promise from calling the `$interval` function.
* @returns {boolean} Returns `true` if the task was successfully cancelled.
*/
$interval.cancel = function(promise) {
if (!promise) return false;
var fnIndex;
angular.forEach(repeatFns, function(fn, index) {
if (fn.id === promise.$$intervalId) fnIndex = index;
});
if (fnIndex !== undefined) {
repeatFns[fnIndex].deferred.reject('canceled');
repeatFns.splice(fnIndex, 1);
return true;
}
return false;
};
/**
* @ngdoc method
* @name $interval#flush
* @description
*
* Runs interval tasks scheduled to be run in the next `millis` milliseconds.
*
* @param {number=} millis maximum timeout amount to flush up until.
*
* @return {number} The amount of time moved forward.
*/
$interval.flush = function(millis) {
now += millis;
while (repeatFns.length && repeatFns[0].nextTime <= now) {
var task = repeatFns[0];
task.fn();
task.nextTime += task.delay;
repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
}
return millis;
};
return $interval;
}];
};
/* jshint -W101 */
/* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
* This directive should go inside the anonymous function but a bug in JSHint means that it would
* not be enacted early enough to prevent the warning.
*/
var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8061_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4] || 0) - tzHour,
int(match[5] || 0) - tzMin,
int(match[6] || 0),
int(match[7] || 0));
return date;
}
return string;
}
function int(str) {
return parseInt(str, 10);
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while (num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
/**
* @ngdoc type
* @name angular.mock.TzDate
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
*
* Mock of the Date type which has its timezone specified via constructor arg.
*
* The main purpose is to create Date-like instances with timezone fixed to the specified timezone
* offset, so that we can test code that depends on local timezone settings without dependency on
* the time zone settings of the machine where the code is running.
*
* @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
* @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
*
* @example
* !!!! WARNING !!!!!
* This is not a complete Date object so only methods that were implemented can be called safely.
* To make matters worse, TzDate instances inherit stuff from Date via a prototype.
*
* We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
* incomplete we might be missing some non-standard methods. This can result in errors like:
* "Date.prototype.foo called on incompatible Object".
*
* ```js
* var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
* newYearInBratislava.getTimezoneOffset() => -60;
* newYearInBratislava.getFullYear() => 2010;
* newYearInBratislava.getMonth() => 0;
* newYearInBratislava.getDate() => 1;
* newYearInBratislava.getHours() => 0;
* newYearInBratislava.getMinutes() => 0;
* newYearInBratislava.getSeconds() => 0;
* ```
*
*/
angular.mock.TzDate = function(offset, timestamp) {
var self = new Date(0);
if (angular.isString(timestamp)) {
var tsStr = timestamp;
self.origDate = jsonStringToDate(timestamp);
timestamp = self.origDate.getTime();
if (isNaN(timestamp))
throw {
name: "Illegal Argument",
message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
};
} else {
self.origDate = new Date(timestamp);
}
var localOffset = new Date(timestamp).getTimezoneOffset();
self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60;
self.date = new Date(timestamp + self.offsetDiff);
self.getTime = function() {
return self.date.getTime() - self.offsetDiff;
};
self.toLocaleDateString = function() {
return self.date.toLocaleDateString();
};
self.getFullYear = function() {
return self.date.getFullYear();
};
self.getMonth = function() {
return self.date.getMonth();
};
self.getDate = function() {
return self.date.getDate();
};
self.getHours = function() {
return self.date.getHours();
};
self.getMinutes = function() {
return self.date.getMinutes();
};
self.getSeconds = function() {
return self.date.getSeconds();
};
self.getMilliseconds = function() {
return self.date.getMilliseconds();
};
self.getTimezoneOffset = function() {
return offset * 60;
};
self.getUTCFullYear = function() {
return self.origDate.getUTCFullYear();
};
self.getUTCMonth = function() {
return self.origDate.getUTCMonth();
};
self.getUTCDate = function() {
return self.origDate.getUTCDate();
};
self.getUTCHours = function() {
return self.origDate.getUTCHours();
};
self.getUTCMinutes = function() {
return self.origDate.getUTCMinutes();
};
self.getUTCSeconds = function() {
return self.origDate.getUTCSeconds();
};
self.getUTCMilliseconds = function() {
return self.origDate.getUTCMilliseconds();
};
self.getDay = function() {
return self.date.getDay();
};
// provide this method only on browsers that already have it
if (self.toISOString) {
self.toISOString = function() {
return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
padNumber(self.origDate.getUTCDate(), 2) + 'T' +
padNumber(self.origDate.getUTCHours(), 2) + ':' +
padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';
};
}
//hide all methods not implemented in this mock that the Date prototype exposes
var unimplementedMethods = ['getUTCDay',
'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
angular.forEach(unimplementedMethods, function(methodName) {
self[methodName] = function() {
throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
};
});
return self;
};
//make "tzDateInstance instanceof Date" return true
angular.mock.TzDate.prototype = Date.prototype;
/* jshint +W101 */
angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
.config(['$provide', function($provide) {
var reflowQueue = [];
$provide.value('$$animateReflow', function(fn) {
var index = reflowQueue.length;
reflowQueue.push(fn);
return function cancel() {
reflowQueue.splice(index, 1);
};
});
$provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$timeout', '$browser',
function($delegate, $$asyncCallback, $timeout, $browser) {
var animate = {
queue: [],
cancel: $delegate.cancel,
enabled: $delegate.enabled,
triggerCallbackEvents: function() {
$$asyncCallback.flush();
},
triggerCallbackPromise: function() {
$timeout.flush(0);
},
triggerCallbacks: function() {
this.triggerCallbackEvents();
this.triggerCallbackPromise();
},
triggerReflow: function() {
angular.forEach(reflowQueue, function(fn) {
fn();
});
reflowQueue = [];
}
};
angular.forEach(
['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) {
animate[method] = function() {
animate.queue.push({
event: method,
element: arguments[0],
options: arguments[arguments.length - 1],
args: arguments
});
return $delegate[method].apply($delegate, arguments);
};
});
return animate;
}]);
}]);
/**
* @ngdoc function
* @name angular.mock.dump
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available function.
*
* Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
* debugging.
*
* This method is also available on window, where it can be used to display objects on debug
* console.
*
* @param {*} object - any object to turn into string.
* @return {string} a serialized string of the argument
*/
angular.mock.dump = function(object) {
return serialize(object);
function serialize(object) {
var out;
if (angular.isElement(object)) {
object = angular.element(object);
out = angular.element('<div></div>');
angular.forEach(object, function(element) {
out.append(angular.element(element).clone());
});
out = out.html();
} else if (angular.isArray(object)) {
out = [];
angular.forEach(object, function(o) {
out.push(serialize(o));
});
out = '[ ' + out.join(', ') + ' ]';
} else if (angular.isObject(object)) {
if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
out = serializeScope(object);
} else if (object instanceof Error) {
out = object.stack || ('' + object.name + ': ' + object.message);
} else {
// TODO(i): this prevents methods being logged,
// we should have a better way to serialize objects
out = angular.toJson(object, true);
}
} else {
out = String(object);
}
return out;
}
function serializeScope(scope, offset) {
offset = offset || ' ';
var log = [offset + 'Scope(' + scope.$id + '): {'];
for (var key in scope) {
if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
log.push(' ' + key + ': ' + angular.toJson(scope[key]));
}
}
var child = scope.$$childHead;
while (child) {
log.push(serializeScope(child, offset + ' '));
child = child.$$nextSibling;
}
log.push('}');
return log.join('\n' + offset);
}
};
/**
* @ngdoc service
* @name $httpBackend
* @description
* Fake HTTP backend implementation suitable for unit testing applications that use the
* {@link ng.$http $http service}.
*
* *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
* development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
*
* During unit testing, we want our unit tests to run quickly and have no external dependencies so
* we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or
* [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is
* to verify whether a certain request has been sent or not, or alternatively just let the
* application make requests, respond with pre-trained responses and assert that the end result is
* what we expect it to be.
*
* This mock implementation can be used to respond with static or dynamic responses via the
* `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
*
* When an Angular application needs some data from a server, it calls the $http service, which
* sends the request to a real server using $httpBackend service. With dependency injection, it is
* easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
* the requests and respond with some testing data without sending a request to a real server.
*
* There are two ways to specify what test data should be returned as http responses by the mock
* backend when the code under test makes http requests:
*
* - `$httpBackend.expect` - specifies a request expectation
* - `$httpBackend.when` - specifies a backend definition
*
*
* # Request Expectations vs Backend Definitions
*
* Request expectations provide a way to make assertions about requests made by the application and
* to define responses for those requests. The test will fail if the expected requests are not made
* or they are made in the wrong order.
*
* Backend definitions allow you to define a fake backend for your application which doesn't assert
* if a particular request was made or not, it just returns a trained response if a request is made.
* The test will pass whether or not the request gets made during testing.
*
*
* <table class="table">
* <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
* <tr>
* <th>Syntax</th>
* <td>.expect(...).respond(...)</td>
* <td>.when(...).respond(...)</td>
* </tr>
* <tr>
* <th>Typical usage</th>
* <td>strict unit tests</td>
* <td>loose (black-box) unit testing</td>
* </tr>
* <tr>
* <th>Fulfills multiple requests</th>
* <td>NO</td>
* <td>YES</td>
* </tr>
* <tr>
* <th>Order of requests matters</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Request required</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Response required</th>
* <td>optional (see below)</td>
* <td>YES</td>
* </tr>
* </table>
*
* In cases where both backend definitions and request expectations are specified during unit
* testing, the request expectations are evaluated first.
*
* If a request expectation has no response specified, the algorithm will search your backend
* definitions for an appropriate response.
*
* If a request didn't match any expectation or if the expectation doesn't have the response
* defined, the backend definitions are evaluated in sequential order to see if any of them match
* the request. The response from the first matched definition is returned.
*
*
* # Flushing HTTP requests
*
* The $httpBackend used in production always responds to requests asynchronously. If we preserved
* this behavior in unit testing, we'd have to create async unit tests, which are hard to write,
* to follow and to maintain. But neither can the testing mock respond synchronously; that would
* change the execution of the code under test. For this reason, the mock $httpBackend has a
* `flush()` method, which allows the test to explicitly flush pending requests. This preserves
* the async api of the backend, while allowing the test to execute synchronously.
*
*
* # Unit testing with mock $httpBackend
* The following code shows how to setup and use the mock backend when unit testing a controller.
* First we create the controller under test:
*
```js
// The module code
angular
.module('MyApp', [])
.controller('MyController', MyController);
// The controller code
function MyController($scope, $http) {
var authToken;
$http.get('/auth.py').success(function(data, status, headers) {
authToken = headers('A-Token');
$scope.user = data;
});
$scope.saveMessage = function(message) {
var headers = { 'Authorization': authToken };
$scope.status = 'Saving...';
$http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
$scope.status = '';
}).error(function() {
$scope.status = 'ERROR!';
});
};
}
```
*
* Now we setup the mock backend and create the test specs:
*
```js
// testing controller
describe('MyController', function() {
var $httpBackend, $rootScope, createController, authRequestHandler;
// Set up the module
beforeEach(module('MyApp'));
beforeEach(inject(function($injector) {
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
authRequestHandler = $httpBackend.when('GET', '/auth.py')
.respond({userId: 'userX'}, {'A-Token': 'xxx'});
// Get hold of a scope (i.e. the root scope)
$rootScope = $injector.get('$rootScope');
// The $controller service is used to create instances of controllers
var $controller = $injector.get('$controller');
createController = function() {
return $controller('MyController', {'$scope' : $rootScope });
};
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('/auth.py');
var controller = createController();
$httpBackend.flush();
});
it('should fail authentication', function() {
// Notice how you can change the response even after it was set
authRequestHandler.respond(401, '');
$httpBackend.expectGET('/auth.py');
var controller = createController();
$httpBackend.flush();
expect($rootScope.status).toBe('Failed...');
});
it('should send msg to server', function() {
var controller = createController();
$httpBackend.flush();
// now you don’t care about the authentication, but
// the controller will still send the request and
// $httpBackend will respond without you having to
// specify the expectation and response for this request
$httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
$rootScope.saveMessage('message content');
expect($rootScope.status).toBe('Saving...');
$httpBackend.flush();
expect($rootScope.status).toBe('');
});
it('should send auth header', function() {
var controller = createController();
$httpBackend.flush();
$httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
// check if the header was send, if it wasn't the expectation won't
// match the request and the test will fail
return headers['Authorization'] == 'xxx';
}).respond(201, '');
$rootScope.saveMessage('whatever');
$httpBackend.flush();
});
});
```
*/
angular.mock.$HttpBackendProvider = function() {
this.$get = ['$rootScope', '$timeout', createHttpBackendMock];
};
/**
* General factory function for $httpBackend mock.
* Returns instance for unit testing (when no arguments specified):
* - passing through is disabled
* - auto flushing is disabled
*
* Returns instance for e2e testing (when `$delegate` and `$browser` specified):
* - passing through (delegating request to real backend) is enabled
* - auto flushing is enabled
*
* @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
* @param {Object=} $browser Auto-flushing enabled if specified
* @return {Object} Instance of $httpBackend mock
*/
function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) {
var definitions = [],
expectations = [],
responses = [],
responsesPush = angular.bind(responses, responses.push),
copy = angular.copy;
function createResponse(status, data, headers, statusText) {
if (angular.isFunction(status)) return status;
return function() {
return angular.isNumber(status)
? [status, data, headers, statusText]
: [200, status, data, headers];
};
}
// TODO(vojta): change params to: method, url, data, headers, callback
function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
var xhr = new MockXhr(),
expectation = expectations[0],
wasExpected = false;
function prettyPrint(data) {
return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
? data
: angular.toJson(data);
}
function wrapResponse(wrapped) {
if (!$browser && timeout) {
timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout);
}
return handleResponse;
function handleResponse() {
var response = wrapped.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
copy(response[3] || ''));
}
function handleTimeout() {
for (var i = 0, ii = responses.length; i < ii; i++) {
if (responses[i] === handleResponse) {
responses.splice(i, 1);
callback(-1, undefined, '');
break;
}
}
}
}
if (expectation && expectation.match(method, url)) {
if (!expectation.matchData(data))
throw new Error('Expected ' + expectation + ' with different data\n' +
'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
if (!expectation.matchHeaders(headers))
throw new Error('Expected ' + expectation + ' with different headers\n' +
'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
prettyPrint(headers));
expectations.shift();
if (expectation.response) {
responses.push(wrapResponse(expectation));
return;
}
wasExpected = true;
}
var i = -1, definition;
while ((definition = definitions[++i])) {
if (definition.match(method, url, data, headers || {})) {
if (definition.response) {
// if $browser specified, we do auto flush all requests
($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
} else if (definition.passThrough) {
$delegate(method, url, data, callback, headers, timeout, withCredentials);
} else throw new Error('No response defined !');
return;
}
}
throw wasExpected ?
new Error('No response defined !') :
new Error('Unexpected request: ' + method + ' ' + url + '\n' +
(expectation ? 'Expected ' + expectation : 'No more request expected'));
}
/**
* @ngdoc method
* @name $httpBackend#when
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
* data string and returns true if the data is as expected.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*
* - respond –
* `{function([status,] data[, headers, statusText])
* | function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can
* return an array containing response status (number), response data (string), response
* headers (Object), and the text for the status (string). The respond method returns the
* `requestHandler` object for possible overrides.
*/
$httpBackend.when = function(method, url, data, headers) {
var definition = new MockHttpExpectation(method, url, data, headers),
chain = {
respond: function(status, data, headers, statusText) {
definition.passThrough = undefined;
definition.response = createResponse(status, data, headers, statusText);
return chain;
}
};
if ($browser) {
chain.passThrough = function() {
definition.response = undefined;
definition.passThrough = true;
return chain;
};
}
definitions.push(definition);
return chain;
};
/**
* @ngdoc method
* @name $httpBackend#whenGET
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenHEAD
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenDELETE
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPOST
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
* data string and returns true if the data is as expected.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPUT
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
* data string and returns true if the data is as expected.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenJSONP
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
createShortMethods('when');
/**
* @ngdoc method
* @name $httpBackend#expect
* @description
* Creates a new request expectation.
*
* @param {string} method HTTP method.
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current expectation.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*
* - respond –
* `{function([status,] data[, headers, statusText])
* | function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can
* return an array containing response status (number), response data (string), response
* headers (Object), and the text for the status (string). The respond method returns the
* `requestHandler` object for possible overrides.
*/
$httpBackend.expect = function(method, url, data, headers) {
var expectation = new MockHttpExpectation(method, url, data, headers),
chain = {
respond: function(status, data, headers, statusText) {
expectation.response = createResponse(status, data, headers, statusText);
return chain;
}
};
expectations.push(expectation);
return chain;
};
/**
* @ngdoc method
* @name $httpBackend#expectGET
* @description
* Creates a new request expectation for GET requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled. See #expect for more info.
*/
/**
* @ngdoc method
* @name $httpBackend#expectHEAD
* @description
* Creates a new request expectation for HEAD requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectDELETE
* @description
* Creates a new request expectation for DELETE requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectPOST
* @description
* Creates a new request expectation for POST requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectPUT
* @description
* Creates a new request expectation for PUT requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectPATCH
* @description
* Creates a new request expectation for PATCH requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
* receives data string and returns true if the data is as expected, or Object if request body
* is in JSON format.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#expectJSONP
* @description
* Creates a new request expectation for JSONP requests. For more info see `expect()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that controls how a matched
* request is handled. You can save this object for later use and invoke `respond` again in
* order to change how a matched request is handled.
*/
createShortMethods('expect');
/**
* @ngdoc method
* @name $httpBackend#flush
* @description
* Flushes all pending requests using the trained responses.
*
* @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
* all pending requests will be flushed. If there are no pending requests when the flush method
* is called an exception is thrown (as this typically a sign of programming error).
*/
$httpBackend.flush = function(count, digest) {
if (digest !== false) $rootScope.$digest();
if (!responses.length) throw new Error('No pending request to flush !');
if (angular.isDefined(count) && count !== null) {
while (count--) {
if (!responses.length) throw new Error('No more pending request to flush !');
responses.shift()();
}
} else {
while (responses.length) {
responses.shift()();
}
}
$httpBackend.verifyNoOutstandingExpectation(digest);
};
/**
* @ngdoc method
* @name $httpBackend#verifyNoOutstandingExpectation
* @description
* Verifies that all of the requests defined via the `expect` api were made. If any of the
* requests were not made, verifyNoOutstandingExpectation throws an exception.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* ```js
* afterEach($httpBackend.verifyNoOutstandingExpectation);
* ```
*/
$httpBackend.verifyNoOutstandingExpectation = function(digest) {
if (digest !== false) $rootScope.$digest();
if (expectations.length) {
throw new Error('Unsatisfied requests: ' + expectations.join(', '));
}
};
/**
* @ngdoc method
* @name $httpBackend#verifyNoOutstandingRequest
* @description
* Verifies that there are no outstanding requests that need to be flushed.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* ```js
* afterEach($httpBackend.verifyNoOutstandingRequest);
* ```
*/
$httpBackend.verifyNoOutstandingRequest = function() {
if (responses.length) {
throw new Error('Unflushed requests: ' + responses.length);
}
};
/**
* @ngdoc method
* @name $httpBackend#resetExpectations
* @description
* Resets all request expectations, but preserves all backend definitions. Typically, you would
* call resetExpectations during a multiple-phase test when you want to reuse the same instance of
* $httpBackend mock.
*/
$httpBackend.resetExpectations = function() {
expectations.length = 0;
responses.length = 0;
};
return $httpBackend;
function createShortMethods(prefix) {
angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
$httpBackend[prefix + method] = function(url, headers) {
return $httpBackend[prefix](method, url, undefined, headers);
};
});
angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
$httpBackend[prefix + method] = function(url, data, headers) {
return $httpBackend[prefix](method, url, data, headers);
};
});
}
}
function MockHttpExpectation(method, url, data, headers) {
this.data = data;
this.headers = headers;
this.match = function(m, u, d, h) {
if (method != m) return false;
if (!this.matchUrl(u)) return false;
if (angular.isDefined(d) && !this.matchData(d)) return false;
if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
return true;
};
this.matchUrl = function(u) {
if (!url) return true;
if (angular.isFunction(url.test)) return url.test(u);
if (angular.isFunction(url)) return url(u);
return url == u;
};
this.matchHeaders = function(h) {
if (angular.isUndefined(headers)) return true;
if (angular.isFunction(headers)) return headers(h);
return angular.equals(headers, h);
};
this.matchData = function(d) {
if (angular.isUndefined(data)) return true;
if (data && angular.isFunction(data.test)) return data.test(d);
if (data && angular.isFunction(data)) return data(d);
if (data && !angular.isString(data)) {
return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));
}
return data == d;
};
this.toString = function() {
return method + ' ' + url;
};
}
function createMockXhr() {
return new MockXhr();
}
function MockXhr() {
// hack for testing $http, $httpBackend
MockXhr.$$lastInstance = this;
this.open = function(method, url, async) {
this.$$method = method;
this.$$url = url;
this.$$async = async;
this.$$reqHeaders = {};
this.$$respHeaders = {};
};
this.send = function(data) {
this.$$data = data;
};
this.setRequestHeader = function(key, value) {
this.$$reqHeaders[key] = value;
};
this.getResponseHeader = function(name) {
// the lookup must be case insensitive,
// that's why we try two quick lookups first and full scan last
var header = this.$$respHeaders[name];
if (header) return header;
name = angular.lowercase(name);
header = this.$$respHeaders[name];
if (header) return header;
header = undefined;
angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
if (!header && angular.lowercase(headerName) == name) header = headerVal;
});
return header;
};
this.getAllResponseHeaders = function() {
var lines = [];
angular.forEach(this.$$respHeaders, function(value, key) {
lines.push(key + ': ' + value);
});
return lines.join('\n');
};
this.abort = angular.noop;
}
/**
* @ngdoc service
* @name $timeout
* @description
*
* This service is just a simple decorator for {@link ng.$timeout $timeout} service
* that adds a "flush" and "verifyNoPendingTasks" methods.
*/
angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) {
/**
* @ngdoc method
* @name $timeout#flush
* @description
*
* Flushes the queue of pending tasks.
*
* @param {number=} delay maximum timeout amount to flush up until
*/
$delegate.flush = function(delay) {
$browser.defer.flush(delay);
};
/**
* @ngdoc method
* @name $timeout#verifyNoPendingTasks
* @description
*
* Verifies that there are no pending tasks that need to be flushed.
*/
$delegate.verifyNoPendingTasks = function() {
if ($browser.deferredFns.length) {
throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
formatPendingTasksAsString($browser.deferredFns));
}
};
function formatPendingTasksAsString(tasks) {
var result = [];
angular.forEach(tasks, function(task) {
result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
});
return result.join(', ');
}
return $delegate;
}];
angular.mock.$RAFDecorator = ['$delegate', function($delegate) {
var queue = [];
var rafFn = function(fn) {
var index = queue.length;
queue.push(fn);
return function() {
queue.splice(index, 1);
};
};
rafFn.supported = $delegate.supported;
rafFn.flush = function() {
if (queue.length === 0) {
throw new Error('No rAF callbacks present');
}
var length = queue.length;
for (var i = 0; i < length; i++) {
queue[i]();
}
queue = [];
};
return rafFn;
}];
angular.mock.$AsyncCallbackDecorator = ['$delegate', function($delegate) {
var callbacks = [];
var addFn = function(fn) {
callbacks.push(fn);
};
addFn.flush = function() {
angular.forEach(callbacks, function(fn) {
fn();
});
callbacks = [];
};
return addFn;
}];
/**
*
*/
angular.mock.$RootElementProvider = function() {
this.$get = function() {
return angular.element('<div ng-app></div>');
};
};
/**
* @ngdoc service
* @name $controller
* @description
* A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing
* controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}.
*
*
* ## Example
*
* ```js
*
* // Directive definition ...
*
* myMod.directive('myDirective', {
* controller: 'MyDirectiveController',
* bindToController: {
* name: '@'
* }
* });
*
*
* // Controller definition ...
*
* myMod.controller('MyDirectiveController', ['log', function($log) {
* $log.info(this.name);
* })];
*
*
* // In a test ...
*
* describe('myDirectiveController', function() {
* it('should write the bound name to the log', inject(function($controller, $log) {
* var ctrl = $controller('MyDirective', { /* no locals */ }, { name: 'Clark Kent' });
* expect(ctrl.name).toEqual('Clark Kent');
* expect($log.info.logs).toEqual(['Clark Kent']);
* });
* });
*
* ```
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
* `window` object (not recommended)
*
* The string can use the `controller as property` syntax, where the controller instance is published
* as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
* to work correctly.
*
* @param {Object} locals Injection locals for Controller.
* @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
* to simulate the `bindToController` feature and simplify certain kinds of tests.
* @return {Object} Instance of given controller.
*/
angular.mock.$ControllerDecorator = ['$delegate', function($delegate) {
return function(expression, locals, later, ident) {
if (later && typeof later === 'object') {
var create = $delegate(expression, locals, true, ident);
angular.extend(create.instance, later);
return create();
}
return $delegate(expression, locals, later, ident);
};
}];
/**
* @ngdoc module
* @name ngMock
* @packageName angular-mocks
* @description
*
* # ngMock
*
* The `ngMock` module provides support to inject and mock Angular services into unit tests.
* In addition, ngMock also extends various core ng services such that they can be
* inspected and controlled in a synchronous manner within test code.
*
*
* <div doc-module-components="ngMock"></div>
*
*/
angular.module('ngMock', ['ng']).provider({
$browser: angular.mock.$BrowserProvider,
$exceptionHandler: angular.mock.$ExceptionHandlerProvider,
$log: angular.mock.$LogProvider,
$interval: angular.mock.$IntervalProvider,
$httpBackend: angular.mock.$HttpBackendProvider,
$rootElement: angular.mock.$RootElementProvider
}).config(['$provide', function($provide) {
$provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
$provide.decorator('$$rAF', angular.mock.$RAFDecorator);
$provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator);
$provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);
$provide.decorator('$controller', angular.mock.$ControllerDecorator);
}]);
/**
* @ngdoc module
* @name ngMockE2E
* @module ngMockE2E
* @packageName angular-mocks
* @description
*
* The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
* Currently there is only one mock present in this module -
* the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
*/
angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
}]);
/**
* @ngdoc service
* @name $httpBackend
* @module ngMockE2E
* @description
* Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
* applications that use the {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for unit testing please see
* {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
*
* This implementation can be used to respond with static or dynamic responses via the `when` api
* and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
* real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
* templates from a webserver).
*
* As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
* is being developed with the real backend api replaced with a mock, it is often desirable for
* certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
* templates or static files from the webserver). To configure the backend with this behavior
* use the `passThrough` request handler of `when` instead of `respond`.
*
* Additionally, we don't want to manually have to flush mocked out requests like we do during unit
* testing. For this reason the e2e $httpBackend flushes mocked out requests
* automatically, closely simulating the behavior of the XMLHttpRequest object.
*
* To setup the application to run with this http backend, you have to create a module that depends
* on the `ngMockE2E` and your application modules and defines the fake backend:
*
* ```js
* myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
* myAppDev.run(function($httpBackend) {
* phones = [{name: 'phone1'}, {name: 'phone2'}];
*
* // returns the current list of phones
* $httpBackend.whenGET('/phones').respond(phones);
*
* // adds a new phone to the phones array
* $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
* var phone = angular.fromJson(data);
* phones.push(phone);
* return [200, phone, {}];
* });
* $httpBackend.whenGET(/^\/templates\//).passThrough();
* //...
* });
* ```
*
* Afterwards, bootstrap your app with this new module.
*/
/**
* @ngdoc method
* @name $httpBackend#when
* @module ngMockE2E
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*
* - respond –
* `{function([status,] data[, headers, statusText])
* | function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string), response headers
* (Object), and the text for the status (string).
* - passThrough – `{function()}` – Any request matching a backend definition with
* `passThrough` handler will be passed through to the real backend (an XHR request will be made
* to the server.)
* - Both methods return the `requestHandler` object for possible overrides.
*/
/**
* @ngdoc method
* @name $httpBackend#whenGET
* @module ngMockE2E
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenHEAD
* @module ngMockE2E
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenDELETE
* @module ngMockE2E
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPOST
* @module ngMockE2E
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPUT
* @module ngMockE2E
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenPATCH
* @module ngMockE2E
* @description
* Creates a new backend definition for PATCH requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
/**
* @ngdoc method
* @name $httpBackend#whenJSONP
* @module ngMockE2E
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp|function(string)} url HTTP url or function that receives the url
* and returns true if the url match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled. You can save this object for later use and invoke
* `respond` or `passThrough` again in order to change how a matched request is handled.
*/
angular.mock.e2e = {};
angular.mock.e2e.$httpBackendDecorator =
['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock];
/**
* @ngdoc type
* @name $rootScope.Scope
* @module ngMock
* @description
* {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These
* methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when
* `ngMock` module is loaded.
*
* In addition to all the regular `Scope` methods, the following helper methods are available:
*/
angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {
var $rootScopePrototype = Object.getPrototypeOf($delegate);
$rootScopePrototype.$countChildScopes = countChildScopes;
$rootScopePrototype.$countWatchers = countWatchers;
return $delegate;
// ------------------------------------------------------------------------------------------ //
/**
* @ngdoc method
* @name $rootScope.Scope#$countChildScopes
* @module ngMock
* @description
* Counts all the direct and indirect child scopes of the current scope.
*
* The current scope is excluded from the count. The count includes all isolate child scopes.
*
* @returns {number} Total number of child scopes.
*/
function countChildScopes() {
// jshint validthis: true
var count = 0; // exclude the current scope
var pendingChildHeads = [this.$$childHead];
var currentScope;
while (pendingChildHeads.length) {
currentScope = pendingChildHeads.shift();
while (currentScope) {
count += 1;
pendingChildHeads.push(currentScope.$$childHead);
currentScope = currentScope.$$nextSibling;
}
}
return count;
}
/**
* @ngdoc method
* @name $rootScope.Scope#$countWatchers
* @module ngMock
* @description
* Counts all the watchers of direct and indirect child scopes of the current scope.
*
* The watchers of the current scope are included in the count and so are all the watchers of
* isolate child scopes.
*
* @returns {number} Total number of watchers.
*/
function countWatchers() {
// jshint validthis: true
var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope
var pendingChildHeads = [this.$$childHead];
var currentScope;
while (pendingChildHeads.length) {
currentScope = pendingChildHeads.shift();
while (currentScope) {
count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
pendingChildHeads.push(currentScope.$$childHead);
currentScope = currentScope.$$nextSibling;
}
}
return count;
}
}];
if (window.jasmine || window.mocha) {
var currentSpec = null,
annotatedFunctions = [],
isSpecRunning = function() {
return !!currentSpec;
};
angular.mock.$$annotate = angular.injector.$$annotate;
angular.injector.$$annotate = function(fn) {
if (typeof fn === 'function' && !fn.$inject) {
annotatedFunctions.push(fn);
}
return angular.mock.$$annotate.apply(this, arguments);
};
(window.beforeEach || window.setup)(function() {
annotatedFunctions = [];
currentSpec = this;
});
(window.afterEach || window.teardown)(function() {
var injector = currentSpec.$injector;
annotatedFunctions.forEach(function(fn) {
delete fn.$inject;
});
angular.forEach(currentSpec.$modules, function(module) {
if (module && module.$$hashKey) {
module.$$hashKey = undefined;
}
});
currentSpec.$injector = null;
currentSpec.$modules = null;
currentSpec = null;
if (injector) {
injector.get('$rootElement').off();
injector.get('$browser').pollFns.length = 0;
}
// clean up jquery's fragment cache
angular.forEach(angular.element.fragments, function(val, key) {
delete angular.element.fragments[key];
});
MockXhr.$$lastInstance = null;
angular.forEach(angular.callbacks, function(val, key) {
delete angular.callbacks[key];
});
angular.callbacks.counter = 0;
});
/**
* @ngdoc function
* @name angular.mock.module
* @description
*
* *NOTE*: This function is also published on window for easy access.<br>
* *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
*
* This function registers a module configuration code. It collects the configuration information
* which will be used when the injector is created by {@link angular.mock.inject inject}.
*
* See {@link angular.mock.inject inject} for usage example
*
* @param {...(string|Function|Object)} fns any number of modules which are represented as string
* aliases or as anonymous module initialization functions. The modules are used to
* configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
* object literal is passed they will be registered as values in the module, the key being
* the module name and the value being what is returned.
*/
window.module = angular.mock.module = function() {
var moduleFns = Array.prototype.slice.call(arguments, 0);
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
if (currentSpec.$injector) {
throw new Error('Injector already created, can not register a module!');
} else {
var modules = currentSpec.$modules || (currentSpec.$modules = []);
angular.forEach(moduleFns, function(module) {
if (angular.isObject(module) && !angular.isArray(module)) {
modules.push(function($provide) {
angular.forEach(module, function(value, key) {
$provide.value(key, value);
});
});
} else {
modules.push(module);
}
});
}
}
};
/**
* @ngdoc function
* @name angular.mock.inject
* @description
*
* *NOTE*: This function is also published on window for easy access.<br>
* *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
*
* The inject function wraps a function into an injectable function. The inject() creates new
* instance of {@link auto.$injector $injector} per test, which is then used for
* resolving references.
*
*
* ## Resolving References (Underscore Wrapping)
* Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
* in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
* that is declared in the scope of the `describe()` block. Since we would, most likely, want
* the variable to have the same name of the reference we have a problem, since the parameter
* to the `inject()` function would hide the outer variable.
*
* To help with this, the injected parameters can, optionally, be enclosed with underscores.
* These are ignored by the injector when the reference name is resolved.
*
* For example, the parameter `_myService_` would be resolved as the reference `myService`.
* Since it is available in the function body as _myService_, we can then assign it to a variable
* defined in an outer scope.
*
* ```
* // Defined out reference variable outside
* var myService;
*
* // Wrap the parameter in underscores
* beforeEach( inject( function(_myService_){
* myService = _myService_;
* }));
*
* // Use myService in a series of tests.
* it('makes use of myService', function() {
* myService.doStuff();
* });
*
* ```
*
* See also {@link angular.mock.module angular.mock.module}
*
* ## Example
* Example of what a typical jasmine tests looks like with the inject method.
* ```js
*
* angular.module('myApplicationModule', [])
* .value('mode', 'app')
* .value('version', 'v1.0.1');
*
*
* describe('MyApp', function() {
*
* // You need to load modules that you want to test,
* // it loads only the "ng" module by default.
* beforeEach(module('myApplicationModule'));
*
*
* // inject() is used to inject arguments of all given functions
* it('should provide a version', inject(function(mode, version) {
* expect(version).toEqual('v1.0.1');
* expect(mode).toEqual('app');
* }));
*
*
* // The inject and module method can also be used inside of the it or beforeEach
* it('should override a version and test the new version is injected', function() {
* // module() takes functions or strings (module aliases)
* module(function($provide) {
* $provide.value('version', 'overridden'); // override version here
* });
*
* inject(function(version) {
* expect(version).toEqual('overridden');
* });
* });
* });
*
* ```
*
* @param {...Function} fns any number of functions which will be injected using the injector.
*/
var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
this.message = e.message;
this.name = e.name;
if (e.line) this.line = e.line;
if (e.sourceId) this.sourceId = e.sourceId;
if (e.stack && errorForStack)
this.stack = e.stack + '\n' + errorForStack.stack;
if (e.stackArray) this.stackArray = e.stackArray;
};
ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
window.inject = angular.mock.inject = function() {
var blockFns = Array.prototype.slice.call(arguments, 0);
var errorForStack = new Error('Declaration Location');
return isSpecRunning() ? workFn.call(currentSpec) : workFn;
/////////////////////
function workFn() {
var modules = currentSpec.$modules || [];
var strictDi = !!currentSpec.$injectorStrict;
modules.unshift('ngMock');
modules.unshift('ng');
var injector = currentSpec.$injector;
if (!injector) {
if (strictDi) {
// If strictDi is enabled, annotate the providerInjector blocks
angular.forEach(modules, function(moduleFn) {
if (typeof moduleFn === "function") {
angular.injector.$$annotate(moduleFn);
}
});
}
injector = currentSpec.$injector = angular.injector(modules, strictDi);
currentSpec.$injectorStrict = strictDi;
}
for (var i = 0, ii = blockFns.length; i < ii; i++) {
if (currentSpec.$injectorStrict) {
// If the injector is strict / strictDi, and the spec wants to inject using automatic
// annotation, then annotate the function here.
injector.annotate(blockFns[i]);
}
try {
/* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
injector.invoke(blockFns[i] || angular.noop, this);
/* jshint +W040 */
} catch (e) {
if (e.stack && errorForStack) {
throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
}
throw e;
} finally {
errorForStack = null;
}
}
}
};
angular.mock.inject.strictDi = function(value) {
value = arguments.length ? !!value : true;
return isSpecRunning() ? workFn() : workFn;
function workFn() {
if (value !== currentSpec.$injectorStrict) {
if (currentSpec.$injector) {
throw new Error('Injector already created, can not modify strict annotations');
} else {
currentSpec.$injectorStrict = value;
}
}
}
};
}
})(window, window.angular);
| DreamInSun/OneRing | xdiamond/bower_components/angular-mocks/angular-mocks.js | JavaScript | apache-2.0 | 82,636 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: $
*/
/**
* @see Zend_Validate_File_Exists
*/
require_once 'Zend/Validate/File/Exists.php';
/**
* Validator which checks if the destination file does not exist
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_File_NotExists extends Zend_Validate_File_Exists
{
/**
* @const string Error constants
*/
const DOES_EXIST = 'fileNotExistsDoesExist';
/**
* @var array Error message templates
*/
protected $_messageTemplates = array(
self::DOES_EXIST => "The file '%value%' does exist"
);
/**
* Defined by Zend_Validate_Interface
*
* Returns true if and only if the file does not exist in the set destinations
*
* @param string $value Real file to check for
* @param array $file File data from Zend_File_Transfer
* @return boolean
*/
public function isValid($value, $file = null)
{
$directories = $this->getDirectory(true);
if (($file !== null) and (!empty($file['destination']))) {
$directories[] = $file['destination'];
} else if (!isset($file['name'])) {
$file['name'] = $value;
}
foreach ($directories as $directory) {
if (empty($directory)) {
continue;
}
$check = true;
if (file_exists($directory . DIRECTORY_SEPARATOR . $file['name'])) {
$this->_throw($file, self::DOES_EXIST);
return false;
}
}
if (!isset($check)) {
$this->_throw($file, self::DOES_EXIST);
return false;
}
return true;
}
}
| jsRuner/wuwenfu.cn | wp-includes/phpQuery/phpQuery/Zend/Validate/File/NotExists.php | PHP | gpl-2.0 | 2,520 |
class MemberDetail < ActiveRecord::Base
belongs_to :member
belongs_to :organization
has_one :member_type, :through => :member
end
| maccman/dtwitter | vendor/rails/activerecord/test/models/member_detail.rb | Ruby | mit | 136 |
/*
* Generic helpers for smp ipi calls
*
* (C) Jens Axboe <jens.axboe@oracle.com> 2008
*/
#include <linux/rcupdate.h>
#include <linux/rculist.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/percpu.h>
#include <linux/init.h>
#include <linux/gfp.h>
#include <linux/smp.h>
#include <linux/cpu.h>
#include "smpboot.h"
#ifdef CONFIG_USE_GENERIC_SMP_HELPERS
enum {
CSD_FLAG_LOCK = 0x01,
};
struct call_function_data {
struct call_single_data __percpu *csd;
cpumask_var_t cpumask;
cpumask_var_t cpumask_ipi;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct call_function_data, cfd_data);
struct call_single_queue {
struct list_head list;
raw_spinlock_t lock;
};
static DEFINE_PER_CPU_SHARED_ALIGNED(struct call_single_queue, call_single_queue);
static int
hotplug_cfd(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
long cpu = (long)hcpu;
struct call_function_data *cfd = &per_cpu(cfd_data, cpu);
switch (action) {
case CPU_UP_PREPARE:
case CPU_UP_PREPARE_FROZEN:
if (!zalloc_cpumask_var_node(&cfd->cpumask, GFP_KERNEL,
cpu_to_node(cpu)))
return notifier_from_errno(-ENOMEM);
if (!zalloc_cpumask_var_node(&cfd->cpumask_ipi, GFP_KERNEL,
cpu_to_node(cpu)))
return notifier_from_errno(-ENOMEM);
cfd->csd = alloc_percpu(struct call_single_data);
if (!cfd->csd) {
free_cpumask_var(cfd->cpumask);
return notifier_from_errno(-ENOMEM);
}
break;
#ifdef CONFIG_HOTPLUG_CPU
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
case CPU_DEAD:
case CPU_DEAD_FROZEN:
free_cpumask_var(cfd->cpumask);
free_cpumask_var(cfd->cpumask_ipi);
free_percpu(cfd->csd);
break;
#endif
};
return NOTIFY_OK;
}
static struct notifier_block __cpuinitdata hotplug_cfd_notifier = {
.notifier_call = hotplug_cfd,
};
void __init call_function_init(void)
{
void *cpu = (void *)(long)smp_processor_id();
int i;
for_each_possible_cpu(i) {
struct call_single_queue *q = &per_cpu(call_single_queue, i);
raw_spin_lock_init(&q->lock);
INIT_LIST_HEAD(&q->list);
}
hotplug_cfd(&hotplug_cfd_notifier, CPU_UP_PREPARE, cpu);
register_cpu_notifier(&hotplug_cfd_notifier);
}
/*
* csd_lock/csd_unlock used to serialize access to per-cpu csd resources
*
* For non-synchronous ipi calls the csd can still be in use by the
* previous function call. For multi-cpu calls its even more interesting
* as we'll have to ensure no other cpu is observing our csd.
*/
static void csd_lock_wait(struct call_single_data *csd)
{
while (csd->flags & CSD_FLAG_LOCK)
cpu_relax();
}
static void csd_lock(struct call_single_data *csd)
{
csd_lock_wait(csd);
csd->flags |= CSD_FLAG_LOCK;
/*
* prevent CPU from reordering the above assignment
* to ->flags with any subsequent assignments to other
* fields of the specified call_single_data structure:
*/
smp_mb();
}
static void csd_unlock(struct call_single_data *csd)
{
WARN_ON(!(csd->flags & CSD_FLAG_LOCK));
/*
* ensure we're all done before releasing data:
*/
smp_mb();
csd->flags &= ~CSD_FLAG_LOCK;
}
/*
* Insert a previously allocated call_single_data element
* for execution on the given CPU. data must already have
* ->func, ->info, and ->flags set.
*/
static
void generic_exec_single(int cpu, struct call_single_data *csd, int wait)
{
struct call_single_queue *dst = &per_cpu(call_single_queue, cpu);
unsigned long flags;
int ipi;
raw_spin_lock_irqsave(&dst->lock, flags);
ipi = list_empty(&dst->list);
list_add_tail(&csd->list, &dst->list);
raw_spin_unlock_irqrestore(&dst->lock, flags);
/*
* The list addition should be visible before sending the IPI
* handler locks the list to pull the entry off it because of
* normal cache coherency rules implied by spinlocks.
*
* If IPIs can go out of order to the cache coherency protocol
* in an architecture, sufficient synchronisation should be added
* to arch code to make it appear to obey cache coherency WRT
* locking and barrier primitives. Generic code isn't really
* equipped to do the right thing...
*/
if (ipi)
arch_send_call_function_single_ipi(cpu);
if (wait)
csd_lock_wait(csd);
}
/*
* Invoked by arch to handle an IPI for call function single. Must be
* called from the arch with interrupts disabled.
*/
void generic_smp_call_function_single_interrupt(void)
{
struct call_single_queue *q = &__get_cpu_var(call_single_queue);
LIST_HEAD(list);
/*
* Shouldn't receive this interrupt on a cpu that is not yet online.
*/
WARN_ON_ONCE(!cpu_online(smp_processor_id()));
raw_spin_lock(&q->lock);
list_replace_init(&q->list, &list);
raw_spin_unlock(&q->lock);
while (!list_empty(&list)) {
struct call_single_data *csd;
unsigned int csd_flags;
csd = list_entry(list.next, struct call_single_data, list);
list_del(&csd->list);
/*
* 'csd' can be invalid after this call if flags == 0
* (when called through generic_exec_single()),
* so save them away before making the call:
*/
csd_flags = csd->flags;
csd->func(csd->info);
/*
* Unlocked CSDs are valid through generic_exec_single():
*/
if (csd_flags & CSD_FLAG_LOCK)
csd_unlock(csd);
}
}
static DEFINE_PER_CPU_SHARED_ALIGNED(struct call_single_data, csd_data);
/*
* smp_call_function_single - Run a function on a specific CPU
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait until function has completed on other CPUs.
*
* Returns 0 on success, else a negative status code.
*/
int smp_call_function_single(int cpu, smp_call_func_t func, void *info,
int wait)
{
struct call_single_data d = {
.flags = 0,
};
unsigned long flags;
int this_cpu;
int err = 0;
/*
* prevent preemption and reschedule on another processor,
* as well as CPU removal
*/
this_cpu = get_cpu();
/*
* Can deadlock when called with interrupts disabled.
* We allow cpu's that are not yet online though, as no one else can
* send smp call function interrupt to this cpu and as such deadlocks
* can't happen.
*/
WARN_ON_ONCE(cpu_online(this_cpu) && irqs_disabled()
&& !oops_in_progress);
if (cpu == this_cpu) {
local_irq_save(flags);
func(info);
local_irq_restore(flags);
} else {
if ((unsigned)cpu < nr_cpu_ids && cpu_online(cpu)) {
struct call_single_data *csd = &d;
if (!wait)
csd = &__get_cpu_var(csd_data);
csd_lock(csd);
csd->func = func;
csd->info = info;
generic_exec_single(cpu, csd, wait);
} else {
err = -ENXIO; /* CPU not online */
}
}
put_cpu();
return err;
}
EXPORT_SYMBOL(smp_call_function_single);
/*
* smp_call_function_any - Run a function on any of the given cpus
* @mask: The mask of cpus it can run on.
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait until function has completed.
*
* Returns 0 on success, else a negative status code (if no cpus were online).
* Note that @wait will be implicitly turned on in case of allocation failures,
* since we fall back to on-stack allocation.
*
* Selection preference:
* 1) current cpu if in @mask
* 2) any cpu of current node if in @mask
* 3) any other online cpu in @mask
*/
int smp_call_function_any(const struct cpumask *mask,
smp_call_func_t func, void *info, int wait)
{
unsigned int cpu;
const struct cpumask *nodemask;
int ret;
/* Try for same CPU (cheapest) */
cpu = get_cpu();
if (cpumask_test_cpu(cpu, mask))
goto call;
/* Try for same node. */
nodemask = cpumask_of_node(cpu_to_node(cpu));
for (cpu = cpumask_first_and(nodemask, mask); cpu < nr_cpu_ids;
cpu = cpumask_next_and(cpu, nodemask, mask)) {
if (cpu_online(cpu))
goto call;
}
/* Any online will do: smp_call_function_single handles nr_cpu_ids. */
cpu = cpumask_any_and(mask, cpu_online_mask);
call:
ret = smp_call_function_single(cpu, func, info, wait);
put_cpu();
return ret;
}
EXPORT_SYMBOL_GPL(smp_call_function_any);
/**
* __smp_call_function_single(): Run a function on a specific CPU
* @cpu: The CPU to run on.
* @data: Pre-allocated and setup data structure
* @wait: If true, wait until function has completed on specified CPU.
*
* Like smp_call_function_single(), but allow caller to pass in a
* pre-allocated data structure. Useful for embedding @data inside
* other structures, for instance.
*/
void __smp_call_function_single(int cpu, struct call_single_data *csd,
int wait)
{
unsigned int this_cpu;
unsigned long flags;
this_cpu = get_cpu();
/*
* Can deadlock when called with interrupts disabled.
* We allow cpu's that are not yet online though, as no one else can
* send smp call function interrupt to this cpu and as such deadlocks
* can't happen.
*/
WARN_ON_ONCE(cpu_online(smp_processor_id()) && wait && irqs_disabled()
&& !oops_in_progress);
if (cpu == this_cpu) {
local_irq_save(flags);
csd->func(csd->info);
local_irq_restore(flags);
} else {
csd_lock(csd);
generic_exec_single(cpu, csd, wait);
}
put_cpu();
}
/**
* smp_call_function_many(): Run a function on a set of other CPUs.
* @mask: The set of cpus to run on (only runs on online subset).
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed
* on other CPUs.
*
* If @wait is true, then returns once @func has returned.
*
* You must not call this function with disabled interrupts or from a
* hardware interrupt handler or from a bottom half handler. Preemption
* must be disabled when calling this function.
*/
void smp_call_function_many(const struct cpumask *mask,
smp_call_func_t func, void *info, bool wait)
{
struct call_function_data *cfd;
int cpu, next_cpu, this_cpu = smp_processor_id();
/*
* Can deadlock when called with interrupts disabled.
* We allow cpu's that are not yet online though, as no one else can
* send smp call function interrupt to this cpu and as such deadlocks
* can't happen.
*/
WARN_ON_ONCE(cpu_online(this_cpu) && irqs_disabled()
&& !oops_in_progress && !early_boot_irqs_disabled);
/* Try to fastpath. So, what's a CPU they want? Ignoring this one. */
cpu = cpumask_first_and(mask, cpu_online_mask);
if (cpu == this_cpu)
cpu = cpumask_next_and(cpu, mask, cpu_online_mask);
/* No online cpus? We're done. */
if (cpu >= nr_cpu_ids)
return;
/* Do we have another CPU which isn't us? */
next_cpu = cpumask_next_and(cpu, mask, cpu_online_mask);
if (next_cpu == this_cpu)
next_cpu = cpumask_next_and(next_cpu, mask, cpu_online_mask);
/* Fastpath: do that cpu by itself. */
if (next_cpu >= nr_cpu_ids) {
smp_call_function_single(cpu, func, info, wait);
return;
}
cfd = &__get_cpu_var(cfd_data);
cpumask_and(cfd->cpumask, mask, cpu_online_mask);
cpumask_clear_cpu(this_cpu, cfd->cpumask);
/* Some callers race with other cpus changing the passed mask */
if (unlikely(!cpumask_weight(cfd->cpumask)))
return;
/*
* After we put an entry into the list, cfd->cpumask may be cleared
* again when another CPU sends another IPI for a SMP function call, so
* cfd->cpumask will be zero.
*/
cpumask_copy(cfd->cpumask_ipi, cfd->cpumask);
for_each_cpu(cpu, cfd->cpumask) {
struct call_single_data *csd = per_cpu_ptr(cfd->csd, cpu);
struct call_single_queue *dst =
&per_cpu(call_single_queue, cpu);
unsigned long flags;
csd_lock(csd);
csd->func = func;
csd->info = info;
raw_spin_lock_irqsave(&dst->lock, flags);
list_add_tail(&csd->list, &dst->list);
raw_spin_unlock_irqrestore(&dst->lock, flags);
}
/* Send a message to all CPUs in the map */
arch_send_call_function_ipi_mask(cfd->cpumask_ipi);
if (wait) {
for_each_cpu(cpu, cfd->cpumask) {
struct call_single_data *csd;
csd = per_cpu_ptr(cfd->csd, cpu);
csd_lock_wait(csd);
}
}
}
EXPORT_SYMBOL(smp_call_function_many);
/**
* smp_call_function(): Run a function on all other CPUs.
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed
* on other CPUs.
*
* Returns 0.
*
* If @wait is true, then returns once @func has returned; otherwise
* it returns just before the target cpu calls @func.
*
* You must not call this function with disabled interrupts or from a
* hardware interrupt handler or from a bottom half handler.
*/
int smp_call_function(smp_call_func_t func, void *info, int wait)
{
preempt_disable();
smp_call_function_many(cpu_online_mask, func, info, wait);
preempt_enable();
return 0;
}
EXPORT_SYMBOL(smp_call_function);
#endif /* USE_GENERIC_SMP_HELPERS */
/* Setup configured maximum number of CPUs to activate */
unsigned int setup_max_cpus = NR_CPUS;
EXPORT_SYMBOL(setup_max_cpus);
/*
* Setup routine for controlling SMP activation
*
* Command-line option of "nosmp" or "maxcpus=0" will disable SMP
* activation entirely (the MPS table probe still happens, though).
*
* Command-line option of "maxcpus=<NUM>", where <NUM> is an integer
* greater than 0, limits the maximum number of CPUs activated in
* SMP mode to <NUM>.
*/
void __weak arch_disable_smp_support(void) { }
static int __init nosmp(char *str)
{
setup_max_cpus = 0;
arch_disable_smp_support();
return 0;
}
early_param("nosmp", nosmp);
/* this is hard limit */
static int __init nrcpus(char *str)
{
int nr_cpus;
get_option(&str, &nr_cpus);
if (nr_cpus > 0 && nr_cpus < nr_cpu_ids)
nr_cpu_ids = nr_cpus;
return 0;
}
early_param("nr_cpus", nrcpus);
static int __init maxcpus(char *str)
{
get_option(&str, &setup_max_cpus);
if (setup_max_cpus == 0)
arch_disable_smp_support();
return 0;
}
early_param("maxcpus", maxcpus);
/* Setup number of possible processor ids */
int nr_cpu_ids __read_mostly = NR_CPUS;
EXPORT_SYMBOL(nr_cpu_ids);
/* An arch may set nr_cpu_ids earlier if needed, so this would be redundant */
void __init setup_nr_cpu_ids(void)
{
nr_cpu_ids = find_last_bit(cpumask_bits(cpu_possible_mask),NR_CPUS) + 1;
}
/* Called by boot processor to activate the rest. */
void __init smp_init(void)
{
unsigned int cpu;
idle_threads_init();
/* FIXME: This should be done in userspace --RR */
for_each_present_cpu(cpu) {
if (num_online_cpus() >= setup_max_cpus)
break;
if (!cpu_online(cpu))
cpu_up(cpu);
}
/* Any cleanup work */
printk(KERN_INFO "Brought up %ld CPUs\n", (long)num_online_cpus());
smp_cpus_done(setup_max_cpus);
}
/*
* Call a function on all processors. May be used during early boot while
* early_boot_irqs_disabled is set. Use local_irq_save/restore() instead
* of local_irq_disable/enable().
*/
int on_each_cpu(void (*func) (void *info), void *info, int wait)
{
unsigned long flags;
int ret = 0;
preempt_disable();
ret = smp_call_function(func, info, wait);
local_irq_save(flags);
func(info);
local_irq_restore(flags);
preempt_enable();
return ret;
}
EXPORT_SYMBOL(on_each_cpu);
/**
* on_each_cpu_mask(): Run a function on processors specified by
* cpumask, which may include the local processor.
* @mask: The set of cpus to run on (only runs on online subset).
* @func: The function to run. This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to the function.
* @wait: If true, wait (atomically) until function has completed
* on other CPUs.
*
* If @wait is true, then returns once @func has returned.
*
* You must not call this function with disabled interrupts or
* from a hardware interrupt handler or from a bottom half handler.
*/
void on_each_cpu_mask(const struct cpumask *mask, smp_call_func_t func,
void *info, bool wait)
{
int cpu = get_cpu();
smp_call_function_many(mask, func, info, wait);
if (cpumask_test_cpu(cpu, mask)) {
local_irq_disable();
func(info);
local_irq_enable();
}
put_cpu();
}
EXPORT_SYMBOL(on_each_cpu_mask);
/*
* on_each_cpu_cond(): Call a function on each processor for which
* the supplied function cond_func returns true, optionally waiting
* for all the required CPUs to finish. This may include the local
* processor.
* @cond_func: A callback function that is passed a cpu id and
* the the info parameter. The function is called
* with preemption disabled. The function should
* return a blooean value indicating whether to IPI
* the specified CPU.
* @func: The function to run on all applicable CPUs.
* This must be fast and non-blocking.
* @info: An arbitrary pointer to pass to both functions.
* @wait: If true, wait (atomically) until function has
* completed on other CPUs.
* @gfp_flags: GFP flags to use when allocating the cpumask
* used internally by the function.
*
* The function might sleep if the GFP flags indicates a non
* atomic allocation is allowed.
*
* Preemption is disabled to protect against CPUs going offline but not online.
* CPUs going online during the call will not be seen or sent an IPI.
*
* You must not call this function with disabled interrupts or
* from a hardware interrupt handler or from a bottom half handler.
*/
void on_each_cpu_cond(bool (*cond_func)(int cpu, void *info),
smp_call_func_t func, void *info, bool wait,
gfp_t gfp_flags)
{
cpumask_var_t cpus;
int cpu, ret;
might_sleep_if(gfp_flags & __GFP_WAIT);
if (likely(zalloc_cpumask_var(&cpus, (gfp_flags|__GFP_NOWARN)))) {
preempt_disable();
for_each_online_cpu(cpu)
if (cond_func(cpu, info))
cpumask_set_cpu(cpu, cpus);
on_each_cpu_mask(cpus, func, info, wait);
preempt_enable();
free_cpumask_var(cpus);
} else {
/*
* No free cpumask, bother. No matter, we'll
* just have to IPI them one by one.
*/
preempt_disable();
for_each_online_cpu(cpu)
if (cond_func(cpu, info)) {
ret = smp_call_function_single(cpu, func,
info, wait);
WARN_ON_ONCE(ret);
}
preempt_enable();
}
}
EXPORT_SYMBOL(on_each_cpu_cond);
static void do_nothing(void *unused)
{
}
/**
* kick_all_cpus_sync - Force all cpus out of idle
*
* Used to synchronize the update of pm_idle function pointer. It's
* called after the pointer is updated and returns after the dummy
* callback function has been executed on all cpus. The execution of
* the function can only happen on the remote cpus after they have
* left the idle function which had been called via pm_idle function
* pointer. So it's guaranteed that nothing uses the previous pointer
* anymore.
*/
void kick_all_cpus_sync(void)
{
/* Make sure the change is visible before we kick the cpus */
smp_mb();
smp_call_function(do_nothing, NULL, 1);
}
EXPORT_SYMBOL_GPL(kick_all_cpus_sync);
| wurikiji/ttFS | ulinux/linux-3.10.61/kernel/smp.c | C | gpl-2.0 | 18,706 |
<?php
/**
* WordPress CRON API
*
* @package WordPress
*/
/**
* Schedules a hook to run only once.
*
* Schedules a hook which will be executed once by the WordPress actions core at
* a time which you specify. The action will fire off when someone visits your
* WordPress site, if the schedule time has passed.
*
* @since 2.1.0
* @link http://codex.wordpress.org/Function_Reference/wp_schedule_single_event
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
*/
function wp_schedule_single_event( $timestamp, $hook, $args = array()) {
// don't schedule a duplicate if there's already an identical event due in the next 10 minutes
$next = wp_next_scheduled($hook, $args);
if ( $next && $next <= $timestamp + 600 )
return;
$crons = _get_cron_array();
$event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => false, 'args' => $args );
$event = apply_filters('schedule_event', $event);
// A plugin disallowed this event
if ( ! $event )
return false;
$key = md5(serialize($event->args));
$crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Schedule a periodic event.
*
* Schedules a hook which will be executed by the WordPress actions core on a
* specific interval, specified by you. The action will trigger when someone
* visits your WordPress site, if the scheduled time has passed.
*
* Valid values for the recurrence are hourly, daily and twicedaily. These can
* be extended using the cron_schedules filter in wp_get_schedules().
*
* Use wp_next_scheduled() to prevent duplicates
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return bool|null False on failure, null when complete with scheduling event.
*/
function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
if ( !isset( $schedules[$recurrence] ) )
return false;
$event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] );
$event = apply_filters('schedule_event', $event);
// A plugin disallowed this event
if ( ! $event )
return false;
$key = md5(serialize($event->args));
$crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args, 'interval' => $event->interval );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Reschedule a recurring event.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return bool|null False on failure. Null when event is rescheduled.
*/
function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
$key = md5(serialize($args));
$interval = 0;
// First we try to get it from the schedule
if ( 0 == $interval )
$interval = $schedules[$recurrence]['interval'];
// Now we try to get it from the saved interval in case the schedule disappears
if ( 0 == $interval )
$interval = $crons[$timestamp][$hook][$key]['interval'];
// Now we assume something is wrong and fail to schedule
if ( 0 == $interval )
return false;
$now = time();
if ( $timestamp >= $now )
$timestamp = $now + $interval;
else
$timestamp = $now + ($interval - (($now - $timestamp) % $interval));
wp_schedule_event( $timestamp, $recurrence, $hook, $args );
}
/**
* Unschedule a previously scheduled cron job.
*
* The $timestamp and $hook parameters are required, so that the event can be
* identified.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $hook Action hook, the execution of which will be unscheduled.
* @param array $args Arguments to pass to the hook's callback function.
* Although not passed to a callback function, these arguments are used
* to uniquely identify the scheduled event, so they should be the same
* as those used when originally scheduling the event.
*/
function wp_unschedule_event( $timestamp, $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
unset( $crons[$timestamp][$hook][$key] );
if ( empty($crons[$timestamp][$hook]) )
unset( $crons[$timestamp][$hook] );
if ( empty($crons[$timestamp]) )
unset( $crons[$timestamp] );
_set_cron_array( $crons );
}
/**
* Unschedule all cron jobs attached to a specific hook.
*
* @since 2.1.0
*
* @param string $hook Action hook, the execution of which will be unscheduled.
* @param array $args Optional. Arguments that were to be pass to the hook's callback function.
*/
function wp_clear_scheduled_hook( $hook, $args = array() ) {
// Backward compatibility
// Previously this function took the arguments as discrete vars rather than an array like the rest of the API
if ( !is_array($args) ) {
_deprecated_argument( __FUNCTION__, '3.0', __('This argument has changed to an array to match the behavior of the other cron functions.') );
$args = array_slice( func_get_args(), 1 );
}
while ( $timestamp = wp_next_scheduled( $hook, $args ) )
wp_unschedule_event( $timestamp, $hook, $args );
}
/**
* Retrieve the next timestamp for a cron event.
*
* @since 2.1.0
*
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return bool|int The UNIX timestamp of the next time the scheduled event will occur.
*/
function wp_next_scheduled( $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $timestamp;
}
return false;
}
/**
* Send request to run cron through HTTP request that doesn't halt page loading.
*
* @since 2.1.0
*
* @return null Cron could not be spawned, because it is not needed to run.
*/
function spawn_cron( $local_time = 0 ) {
if ( !$local_time )
$local_time = time();
if ( defined('DOING_CRON') || isset($_GET['doing_wp_cron']) )
return;
/*
* multiple processes on multiple web servers can run this code concurrently
* try to make this as atomic as possible by setting doing_cron switch
*/
$lock = get_transient('doing_cron');
if ( $lock > $local_time + 10*60 )
$lock = 0;
// don't run if another process is currently running it or more than once every 60 sec.
if ( $lock + WP_CRON_LOCK_TIMEOUT > $local_time )
return;
//sanity check
$crons = _get_cron_array();
if ( !is_array($crons) )
return;
$keys = array_keys( $crons );
if ( isset($keys[0]) && $keys[0] > $local_time )
return;
if ( defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON ) {
if ( !empty($_POST) || defined('DOING_AJAX') )
return;
$doing_wp_cron = $local_time;
set_transient( 'doing_cron', $doing_wp_cron );
ob_start();
wp_redirect( add_query_arg('doing_wp_cron', $doing_wp_cron, stripslashes($_SERVER['REQUEST_URI'])) );
echo ' ';
// flush any buffers and send the headers
while ( @ob_end_flush() );
flush();
WP_DEBUG ? include_once( ABSPATH . 'wp-cron.php' ) : @include_once( ABSPATH . 'wp-cron.php' );
return;
}
$doing_wp_cron = $local_time;
set_transient( 'doing_cron', $doing_wp_cron );
$cron_url = get_option( 'siteurl' ) . '/wp-cron.php?doing_wp_cron=' . $doing_wp_cron;
wp_remote_post( $cron_url, array('timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters('https_local_ssl_verify', true)) );
}
/**
* Run scheduled callbacks or spawn cron for all scheduled events.
*
* @since 2.1.0
*
* @return null When doesn't need to run Cron.
*/
function wp_cron() {
// Prevent infinite loops caused by lack of wp-cron.php
if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false || ( defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ) )
return;
if ( false === $crons = _get_cron_array() )
return;
$local_time = time();
$keys = array_keys( $crons );
if ( isset($keys[0]) && $keys[0] > $local_time )
return;
$schedules = wp_get_schedules();
foreach ( $crons as $timestamp => $cronhooks ) {
if ( $timestamp > $local_time ) break;
foreach ( (array) $cronhooks as $hook => $args ) {
if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) )
continue;
spawn_cron( $local_time );
break 2;
}
}
}
/**
* Retrieve supported and filtered Cron recurrences.
*
* The supported recurrences are 'hourly' and 'daily'. A plugin may add more by
* hooking into the 'cron_schedules' filter. The filter accepts an array of
* arrays. The outer array has a key that is the name of the schedule or for
* example 'weekly'. The value is an array with two keys, one is 'interval' and
* the other is 'display'.
*
* The 'interval' is a number in seconds of when the cron job should run. So for
* 'hourly', the time is 3600 or 60*60. For weekly, the value would be
* 60*60*24*7 or 604800. The value of 'interval' would then be 604800.
*
* The 'display' is the description. For the 'weekly' key, the 'display' would
* be <code>__('Once Weekly')</code>.
*
* For your plugin, you will be passed an array. you can easily add your
* schedule by doing the following.
* <code>
* // filter parameter variable name is 'array'
* $array['weekly'] = array(
* 'interval' => 604800,
* 'display' => __('Once Weekly')
* );
* </code>
*
* @since 2.1.0
*
* @return array
*/
function wp_get_schedules() {
$schedules = array(
'hourly' => array( 'interval' => 3600, 'display' => __('Once Hourly') ),
'twicedaily' => array( 'interval' => 43200, 'display' => __('Twice Daily') ),
'daily' => array( 'interval' => 86400, 'display' => __('Once Daily') ),
);
return array_merge( apply_filters( 'cron_schedules', array() ), $schedules );
}
/**
* Retrieve Cron schedule for hook with arguments.
*
* @since 2.1.0
*
* @param string $hook Action hook to execute when cron is run.
* @param array $args Optional. Arguments to pass to the hook's callback function.
* @return string|bool False, if no schedule. Schedule on success.
*/
function wp_get_schedule($hook, $args = array()) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $cron[$hook][$key]['schedule'];
}
return false;
}
//
// Private functions
//
/**
* Retrieve cron info array option.
*
* @since 2.1.0
* @access private
*
* @return array CRON info array.
*/
function _get_cron_array() {
$cron = get_option('cron');
if ( ! is_array($cron) )
return false;
if ( !isset($cron['version']) )
$cron = _upgrade_cron_array($cron);
unset($cron['version']);
return $cron;
}
/**
* Updates the CRON option with the new CRON array.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
*/
function _set_cron_array($cron) {
$cron['version'] = 2;
update_option( 'cron', $cron );
}
/**
* Upgrade a Cron info array.
*
* This function upgrades the Cron info array to version 2.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
* @return array An upgraded Cron info array.
*/
function _upgrade_cron_array($cron) {
if ( isset($cron['version']) && 2 == $cron['version'])
return $cron;
$new_cron = array();
foreach ( (array) $cron as $timestamp => $hooks) {
foreach ( (array) $hooks as $hook => $args ) {
$key = md5(serialize($args['args']));
$new_cron[$timestamp][$hook][$key] = $args;
}
}
$new_cron['version'] = 2;
update_option( 'cron', $new_cron );
return $new_cron;
}
| andres-torres-marroquin/casa-camila | wp-includes/cron.php | PHP | gpl-2.0 | 12,428 |
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"os"
"runtime"
"k8s.io/kubernetes/cmd/kube-proxy/app"
"k8s.io/kubernetes/pkg/healthz"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/version/verflag"
"github.com/spf13/pflag"
)
func init() {
healthz.DefaultHealthz()
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
s := app.NewProxyServer()
s.AddFlags(pflag.CommandLine)
util.InitFlags()
util.InitLogs()
defer util.FlushLogs()
verflag.PrintAndExitIfRequested()
if err := s.Run(pflag.CommandLine.Args()); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
}
| StevenLudwig/kubernetes | cmd/kube-proxy/proxy.go | GO | apache-2.0 | 1,176 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape Portable Runtime (NSPR).
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef prlink_h___
#define prlink_h___
/*
** API to static and dynamic linking.
*/
#include "prtypes.h"
PR_BEGIN_EXTERN_C
typedef struct PRLibrary PRLibrary;
typedef struct PRStaticLinkTable {
const char *name;
void (*fp)();
} PRStaticLinkTable;
/*
** Change the default library path to the given string. The string is
** copied. This call will fail if it runs out of memory.
**
** The string provided as 'path' is copied. The caller can do whatever is
** convenient with the argument when the function is complete.
*/
NSPR_API(PRStatus) PR_SetLibraryPath(const char *path);
/*
** Return a character string which contains the path used to search for
** dynamically loadable libraries.
**
** The returned value is basically a copy of a PR_SetLibraryPath().
** The storage is allocated by the runtime and becomes the responsibilty
** of the caller.
*/
NSPR_API(char*) PR_GetLibraryPath(void);
/*
** Given a directory name "dir" and a library name "lib" construct a full
** path name that will refer to the actual dynamically loaded
** library. This does not test for existance of said file, it just
** constructs the full filename. The name constructed is system dependent
** and prepared for PR_LoadLibrary. The result must be free'd when the
** caller is done with it.
**
** The storage for the result is allocated by the runtime and becomes the
** responsibility of the caller.
*/
NSPR_API(char*) PR_GetLibraryName(const char *dir, const char *lib);
/*
**
** Free the memory allocated, for the caller, by PR_GetLibraryName
*/
NSPR_API(void) PR_FreeLibraryName(char *mem);
/*
** Given a library "name" try to load the library. The argument "name"
** is a machine-dependent name for the library, such as the full pathname
** returned by PR_GetLibraryName. If the library is already loaded,
** this function will avoid loading the library twice.
**
** If the library is loaded successfully, then a pointer to the PRLibrary
** structure representing the library is returned. Otherwise, NULL is
** returned.
**
** This increments the reference count of the library.
*/
NSPR_API(PRLibrary*) PR_LoadLibrary(const char *name);
/*
** Each operating system has its preferred way of specifying
** a file in the file system. Most operating systems use
** a pathname. Mac OS, on the other hand, uses the FSSpec
** structure to specify a file. PRLibSpec allows NSPR clients
** to use the type of file specification that is most efficient
** for a particular platform.
**
** On some operating systems such as Mac OS, a shared library may
** contain code fragments that can be individually loaded.
** PRLibSpec also allows NSPR clients to identify a code fragment
** in a library, if code fragments are supported by the OS.
** A code fragment can be specified by name or by an integer index.
**
** Right now PRLibSpec supports three types of library specification:
** a pathname, a Mac code fragment by name, and a Mac code fragment
** by index.
*/
typedef enum PRLibSpecType {
PR_LibSpec_Pathname,
PR_LibSpec_MacNamedFragment,
PR_LibSpec_MacIndexedFragment
} PRLibSpecType;
struct FSSpec; /* Mac OS FSSpec */
typedef struct PRLibSpec {
PRLibSpecType type;
union {
/* if type is PR_LibSpec_Pathname */
const char *pathname;
/* if type is PR_LibSpec_MacNamedFragment */
struct {
const struct FSSpec *fsspec;
const char *name;
} mac_named_fragment;
/* if type is PR_LibSpec_MacIndexedFragment */
struct {
const struct FSSpec *fsspec;
PRUint32 index;
} mac_indexed_fragment;
} value;
} PRLibSpec;
/*
** The following bit flags may be or'd together and passed
** as the 'flags' argument to PR_LoadLibraryWithFlags.
** Flags not supported by the underlying OS are ignored.
*/
#define PR_LD_LAZY 0x1 /* equivalent to RTLD_LAZY on Unix */
#define PR_LD_NOW 0x2 /* equivalent to RTLD_NOW on Unix */
#define PR_LD_GLOBAL 0x4 /* equivalent to RTLD_GLOBAL on Unix */
#define PR_LD_LOCAL 0x8 /* equivalent to RTLD_LOCAL on Unix */
/*
** Load the specified library, in the manner specified by 'flags'.
*/
NSPR_API(PRLibrary *)
PR_LoadLibraryWithFlags(
PRLibSpec libSpec, /* the shared library */
PRIntn flags /* flags that affect the loading */
);
/*
** Unload a previously loaded library. If the library was a static
** library then the static link table will no longer be referenced. The
** associated PRLibrary object is freed.
**
** PR_FAILURE is returned if the library cannot be unloaded.
**
** This function decrements the reference count of the library.
*/
NSPR_API(PRStatus) PR_UnloadLibrary(PRLibrary *lib);
/*
** Given the name of a procedure, return the address of the function that
** implements the procedure, or NULL if no such function can be
** found. This does not find symbols in the main program (the ".exe");
** use PR_LoadStaticLibrary to register symbols in the main program.
**
** This function does not modify the reference count of the library.
*/
NSPR_API(void*) PR_FindSymbol(PRLibrary *lib, const char *name);
/*
** Similar to PR_FindSymbol, except that the return value is a pointer to
** a function, and not a pointer to void. Casting between a data pointer
** and a function pointer is not portable according to the C standard.
** Any function pointer can be cast to any other function pointer.
**
** This function does not modify the reference count of the library.
*/
typedef void (*PRFuncPtr)();
NSPR_API(PRFuncPtr) PR_FindFunctionSymbol(PRLibrary *lib, const char *name);
/*
** Finds a symbol in one of the currently loaded libraries. Given the
** name of a procedure, return the address of the function that
** implements the procedure, and return the library that contains that
** symbol, or NULL if no such function can be found. This does not find
** symbols in the main program (the ".exe"); use PR_AddStaticLibrary to
** register symbols in the main program.
**
** This increments the reference count of the library.
*/
NSPR_API(void*) PR_FindSymbolAndLibrary(const char *name,
PRLibrary* *lib);
/*
** Similar to PR_FindSymbolAndLibrary, except that the return value is
** a pointer to a function, and not a pointer to void. Casting between a
** data pointer and a function pointer is not portable according to the C
** standard. Any function pointer can be cast to any other function pointer.
**
** This increments the reference count of the library.
*/
NSPR_API(PRFuncPtr) PR_FindFunctionSymbolAndLibrary(const char *name,
PRLibrary* *lib);
/*
** Register a static link table with the runtime under the name
** "name". The symbols present in the static link table will be made
** available to PR_FindSymbol. If "name" is null then the symbols will be
** made available to the library which represents the executable. The
** tables are not copied.
**
** Returns the library object if successful, null otherwise.
**
** This increments the reference count of the library.
*/
NSPR_API(PRLibrary*) PR_LoadStaticLibrary(
const char *name, const PRStaticLinkTable *table);
/*
** Return the pathname of the file that the library "name" was loaded
** from. "addr" is the address of a function defined in the library.
**
** The caller is responsible for freeing the result with PR_Free.
*/
NSPR_API(char *) PR_GetLibraryFilePathname(const char *name, PRFuncPtr addr);
PR_END_EXTERN_C
#endif /* prlink_h___ */
| Gateworks/platform-external-chromium_org | third_party/npapi/npspy/extern/nspr/prlink.h | C | bsd-3-clause | 8,997 |
import parse = require('xml-parser');
declare var assert: { equal<T>(a: T, b: T): void };
var doc: parse.Document = parse(
'<?xml version="1.0" encoding="utf-8"?>' +
'<mydoc><child a="1">foo</child><child/></mydoc>');
var declaration: parse.Declaration = doc.declaration;
assert.equal(declaration.attributes['version'], '1.0');
assert.equal(declaration.attributes['encoding'], 'utf-8');
var root: parse.Node = doc.root;
assert.equal(root.name, 'mydoc');
var children: parse.Node[] = root.children;
assert.equal(children.length, 2);
var child1: parse.Node = children[0];
assert.equal(child1.name, 'child');
assert.equal(child1.attributes['a'], '1');
assert.equal(child1.content, 'foo');
| aaronryden/DefinitelyTyped | types/xml-parser/xml-parser-tests.ts | TypeScript | mit | 693 |
/*
* File: pn_dev.c
*
* Phonet network device
*
* Copyright (C) 2008 Nokia Corporation.
*
* Contact: Remi Denis-Courmont <remi.denis-courmont@nokia.com>
* Original author: Sakari Ailus <sakari.ailus@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/kernel.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/phonet.h>
#include <net/sock.h>
#include <net/phonet/pn_dev.h>
/* when accessing, remember to lock with spin_lock(&pndevs.lock); */
struct phonet_device_list pndevs = {
.list = LIST_HEAD_INIT(pndevs.list),
.lock = __SPIN_LOCK_UNLOCKED(pndevs.lock),
};
/* Allocate new Phonet device. */
static struct phonet_device *__phonet_device_alloc(struct net_device *dev)
{
struct phonet_device *pnd = kmalloc(sizeof(*pnd), GFP_ATOMIC);
if (pnd == NULL)
return NULL;
pnd->netdev = dev;
bitmap_zero(pnd->addrs, 64);
list_add(&pnd->list, &pndevs.list);
return pnd;
}
static struct phonet_device *__phonet_get(struct net_device *dev)
{
struct phonet_device *pnd;
list_for_each_entry(pnd, &pndevs.list, list) {
if (pnd->netdev == dev)
return pnd;
}
return NULL;
}
static void __phonet_device_free(struct phonet_device *pnd)
{
list_del(&pnd->list);
kfree(pnd);
}
struct net_device *phonet_device_get(struct net *net)
{
struct phonet_device *pnd;
struct net_device *dev;
spin_lock_bh(&pndevs.lock);
list_for_each_entry(pnd, &pndevs.list, list) {
dev = pnd->netdev;
BUG_ON(!dev);
if (net_eq(dev_net(dev), net) &&
(dev->reg_state == NETREG_REGISTERED) &&
((pnd->netdev->flags & IFF_UP)) == IFF_UP)
break;
dev = NULL;
}
if (dev)
dev_hold(dev);
spin_unlock_bh(&pndevs.lock);
return dev;
}
int phonet_address_add(struct net_device *dev, u8 addr)
{
struct phonet_device *pnd;
int err = 0;
spin_lock_bh(&pndevs.lock);
/* Find or create Phonet-specific device data */
pnd = __phonet_get(dev);
if (pnd == NULL)
pnd = __phonet_device_alloc(dev);
if (unlikely(pnd == NULL))
err = -ENOMEM;
else if (test_and_set_bit(addr >> 2, pnd->addrs))
err = -EEXIST;
spin_unlock_bh(&pndevs.lock);
return err;
}
int phonet_address_del(struct net_device *dev, u8 addr)
{
struct phonet_device *pnd;
int err = 0;
spin_lock_bh(&pndevs.lock);
pnd = __phonet_get(dev);
if (!pnd || !test_and_clear_bit(addr >> 2, pnd->addrs))
err = -EADDRNOTAVAIL;
else if (bitmap_empty(pnd->addrs, 64))
__phonet_device_free(pnd);
spin_unlock_bh(&pndevs.lock);
return err;
}
/* Gets a source address toward a destination, through a interface. */
u8 phonet_address_get(struct net_device *dev, u8 addr)
{
struct phonet_device *pnd;
spin_lock_bh(&pndevs.lock);
pnd = __phonet_get(dev);
if (pnd) {
BUG_ON(bitmap_empty(pnd->addrs, 64));
/* Use same source address as destination, if possible */
if (!test_bit(addr >> 2, pnd->addrs))
addr = find_first_bit(pnd->addrs, 64) << 2;
} else
addr = PN_NO_ADDR;
spin_unlock_bh(&pndevs.lock);
return addr;
}
int phonet_address_lookup(struct net *net, u8 addr)
{
struct phonet_device *pnd;
spin_lock_bh(&pndevs.lock);
list_for_each_entry(pnd, &pndevs.list, list) {
if (!net_eq(dev_net(pnd->netdev), net))
continue;
/* Don't allow unregistering devices! */
if ((pnd->netdev->reg_state != NETREG_REGISTERED) ||
((pnd->netdev->flags & IFF_UP)) != IFF_UP)
continue;
if (test_bit(addr >> 2, pnd->addrs)) {
spin_unlock_bh(&pndevs.lock);
return 0;
}
}
spin_unlock_bh(&pndevs.lock);
return -EADDRNOTAVAIL;
}
/* notify Phonet of device events */
static int phonet_device_notify(struct notifier_block *me, unsigned long what,
void *arg)
{
struct net_device *dev = arg;
if (what == NETDEV_UNREGISTER) {
struct phonet_device *pnd;
/* Destroy phonet-specific device data */
spin_lock_bh(&pndevs.lock);
pnd = __phonet_get(dev);
if (pnd)
__phonet_device_free(pnd);
spin_unlock_bh(&pndevs.lock);
}
return 0;
}
static struct notifier_block phonet_device_notifier = {
.notifier_call = phonet_device_notify,
.priority = 0,
};
/* Initialize Phonet devices list */
void phonet_device_init(void)
{
register_netdevice_notifier(&phonet_device_notifier);
}
void phonet_device_exit(void)
{
struct phonet_device *pnd, *n;
rtnl_unregister_all(PF_PHONET);
rtnl_lock();
spin_lock_bh(&pndevs.lock);
list_for_each_entry_safe(pnd, n, &pndevs.list, list)
__phonet_device_free(pnd);
spin_unlock_bh(&pndevs.lock);
rtnl_unlock();
unregister_netdevice_notifier(&phonet_device_notifier);
}
| felixhaedicke/nst-kernel | src/net/phonet/pn_dev.c | C | gpl-2.0 | 5,080 |
let arr = [];
for(let i = 0; i < 10; i++) {
for (let i = 0; i < 10; i++) {
arr.push(() => i);
}
}
| ellbee/babel | test/core/fixtures/transformation/es6.block-scoping/issue-973/actual.js | JavaScript | mit | 106 |
/* SPDX-License-Identifier: BSD-3-Clause-Clear */
/*
* Copyright (c) 2018-2019 The Linux Foundation. All rights reserved.
*/
#ifndef ATH11K_AHB_H
#define ATH11K_AHB_H
#include "core.h"
#define ATH11K_AHB_RECOVERY_TIMEOUT (3 * HZ)
struct ath11k_base;
struct ath11k_ahb {
struct rproc *tgt_rproc;
};
static inline struct ath11k_ahb *ath11k_ahb_priv(struct ath11k_base *ab)
{
return (struct ath11k_ahb *)ab->drv_priv;
}
#endif
| HinTak/linux | drivers/net/wireless/ath/ath11k/ahb.h | C | gpl-2.0 | 432 |
/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file is used by programs that want to link against the
** FTS2 library. All it does is declare the sqlite3Fts2Init() interface.
*/
#include "sqlite3.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int sqlite3Fts2Init(sqlite3 *db);
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
| wangscript/libjingle-1 | trunk/third_party/sqlite/src/ext/fts2/fts2.h | C | bsd-3-clause | 705 |
// basic_types.hpp --------------------------------------------------------------//
// Copyright 2010 Vicente J. Botet Escriba
// Copyright 2015 Andrey Semashev
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#ifndef BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP
#define BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP
#include <cstdarg>
#include <boost/cstdint.hpp>
#include <boost/detail/winapi/config.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined( BOOST_USE_WINDOWS_H )
# include <windows.h>
#elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined(__CYGWIN__)
# include <winerror.h>
# ifdef UNDER_CE
# ifndef WINAPI
# ifndef _WIN32_WCE_EMULATION
# define WINAPI __cdecl // Note this doesn't match the desktop definition
# else
# define WINAPI __stdcall
# endif
# endif
// Windows CE defines a few functions as inline functions in kfuncs.h
typedef int BOOL;
typedef unsigned long DWORD;
typedef void* HANDLE;
# include <kfuncs.h>
# else
# ifndef WINAPI
# define WINAPI __stdcall
# endif
# endif
# ifndef NTAPI
# define NTAPI __stdcall
# endif
#else
# error "Win32 functions not available"
#endif
#ifndef NO_STRICT
#ifndef STRICT
#define STRICT 1
#endif
#endif
#if defined(STRICT)
#define BOOST_DETAIL_WINAPI_DECLARE_HANDLE(x) struct x##__; typedef struct x##__ *x
#else
#define BOOST_DETAIL_WINAPI_DECLARE_HANDLE(x) typedef void* x
#endif
#if !defined( BOOST_USE_WINDOWS_H )
extern "C" {
union _LARGE_INTEGER;
struct _SECURITY_ATTRIBUTES;
BOOST_DETAIL_WINAPI_DECLARE_HANDLE(HINSTANCE);
typedef HINSTANCE HMODULE;
}
#endif
#if defined(__GNUC__)
#define BOOST_DETAIL_WINAPI_MAY_ALIAS __attribute__ ((__may_alias__))
#else
#define BOOST_DETAIL_WINAPI_MAY_ALIAS
#endif
// MinGW64 gcc 4.8.2 fails to compile function declarations with boost::detail::winapi::VOID_ arguments even though
// the typedef expands to void. In Windows SDK, VOID is a macro which unfolds to void. We use our own macro in such cases.
#define BOOST_DETAIL_WINAPI_VOID void
namespace boost {
namespace detail {
namespace winapi {
#if defined( BOOST_USE_WINDOWS_H )
typedef ::BOOL BOOL_;
typedef ::PBOOL PBOOL_;
typedef ::LPBOOL LPBOOL_;
typedef ::BOOLEAN BOOLEAN_;
typedef ::PBOOLEAN PBOOLEAN_;
typedef ::BYTE BYTE_;
typedef ::PBYTE PBYTE_;
typedef ::LPBYTE LPBYTE_;
typedef ::WORD WORD_;
typedef ::PWORD PWORD_;
typedef ::LPWORD LPWORD_;
typedef ::DWORD DWORD_;
typedef ::PDWORD PDWORD_;
typedef ::LPDWORD LPDWORD_;
typedef ::HANDLE HANDLE_;
typedef ::PHANDLE PHANDLE_;
typedef ::SHORT SHORT_;
typedef ::PSHORT PSHORT_;
typedef ::USHORT USHORT_;
typedef ::PUSHORT PUSHORT_;
typedef ::INT INT_;
typedef ::PINT PINT_;
typedef ::LPINT LPINT_;
typedef ::UINT UINT_;
typedef ::PUINT PUINT_;
typedef ::LONG LONG_;
typedef ::PLONG PLONG_;
typedef ::LPLONG LPLONG_;
typedef ::ULONG ULONG_;
typedef ::PULONG PULONG_;
typedef ::LONGLONG LONGLONG_;
typedef ::ULONGLONG ULONGLONG_;
typedef ::INT_PTR INT_PTR_;
typedef ::UINT_PTR UINT_PTR_;
typedef ::LONG_PTR LONG_PTR_;
typedef ::ULONG_PTR ULONG_PTR_;
typedef ::DWORD_PTR DWORD_PTR_;
typedef ::PDWORD_PTR PDWORD_PTR_;
typedef ::SIZE_T SIZE_T_;
typedef ::PSIZE_T PSIZE_T_;
typedef ::SSIZE_T SSIZE_T_;
typedef ::PSSIZE_T PSSIZE_T_;
typedef VOID VOID_; // VOID is a macro
typedef ::PVOID PVOID_;
typedef ::LPVOID LPVOID_;
typedef ::LPCVOID LPCVOID_;
typedef ::CHAR CHAR_;
typedef ::LPSTR LPSTR_;
typedef ::LPCSTR LPCSTR_;
typedef ::WCHAR WCHAR_;
typedef ::LPWSTR LPWSTR_;
typedef ::LPCWSTR LPCWSTR_;
#else // defined( BOOST_USE_WINDOWS_H )
typedef int BOOL_;
typedef BOOL_* PBOOL_;
typedef BOOL_* LPBOOL_;
typedef unsigned char BYTE_;
typedef BYTE_* PBYTE_;
typedef BYTE_* LPBYTE_;
typedef BYTE_ BOOLEAN_;
typedef BOOLEAN_* PBOOLEAN_;
typedef unsigned short WORD_;
typedef WORD_* PWORD_;
typedef WORD_* LPWORD_;
typedef unsigned long DWORD_;
typedef DWORD_* PDWORD_;
typedef DWORD_* LPDWORD_;
typedef void* HANDLE_;
typedef void** PHANDLE_;
typedef short SHORT_;
typedef SHORT_* PSHORT_;
typedef unsigned short USHORT_;
typedef USHORT_* PUSHORT_;
typedef int INT_;
typedef INT_* PINT_;
typedef INT_* LPINT_;
typedef unsigned int UINT_;
typedef UINT_* PUINT_;
typedef long LONG_;
typedef LONG_* PLONG_;
typedef LONG_* LPLONG_;
typedef unsigned long ULONG_;
typedef ULONG_* PULONG_;
typedef boost::int64_t LONGLONG_;
typedef boost::uint64_t ULONGLONG_;
# ifdef _WIN64
# if defined(__CYGWIN__)
typedef long INT_PTR_;
typedef unsigned long UINT_PTR_;
typedef long LONG_PTR_;
typedef unsigned long ULONG_PTR_;
# else
typedef __int64 INT_PTR_;
typedef unsigned __int64 UINT_PTR_;
typedef __int64 LONG_PTR_;
typedef unsigned __int64 ULONG_PTR_;
# endif
# else
typedef int INT_PTR_;
typedef unsigned int UINT_PTR_;
typedef long LONG_PTR_;
typedef unsigned long ULONG_PTR_;
# endif
typedef ULONG_PTR_ DWORD_PTR_, *PDWORD_PTR_;
typedef ULONG_PTR_ SIZE_T_, *PSIZE_T_;
typedef LONG_PTR_ SSIZE_T_, *PSSIZE_T_;
typedef void VOID_;
typedef void *PVOID_;
typedef void *LPVOID_;
typedef const void *LPCVOID_;
typedef char CHAR_;
typedef CHAR_ *LPSTR_;
typedef const CHAR_ *LPCSTR_;
typedef wchar_t WCHAR_;
typedef WCHAR_ *LPWSTR_;
typedef const WCHAR_ *LPCWSTR_;
#endif // defined( BOOST_USE_WINDOWS_H )
typedef ::HMODULE HMODULE_;
typedef union BOOST_DETAIL_WINAPI_MAY_ALIAS _LARGE_INTEGER {
struct {
DWORD_ LowPart;
LONG_ HighPart;
} u;
LONGLONG_ QuadPart;
} LARGE_INTEGER_, *PLARGE_INTEGER_;
typedef struct BOOST_DETAIL_WINAPI_MAY_ALIAS _SECURITY_ATTRIBUTES {
DWORD_ nLength;
LPVOID_ lpSecurityDescriptor;
BOOL_ bInheritHandle;
} SECURITY_ATTRIBUTES_, *PSECURITY_ATTRIBUTES_, *LPSECURITY_ATTRIBUTES_;
}
}
}
#endif // BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP
| nealkruis/kiva | vendor/boost-1.61.0/boost/detail/winapi/basic_types.hpp | C++ | gpl-3.0 | 5,732 |
/*
* drivers/video/tegra/host/nvhost_intr.h
*
* Tegra Graphics Host Interrupt Management
*
* Copyright (c) 2010-2012, NVIDIA Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __NVHOST_INTR_H
#define __NVHOST_INTR_H
#include <linux/kthread.h>
#include <linux/semaphore.h>
#include <linux/interrupt.h>
struct nvhost_channel;
enum nvhost_intr_action {
/**
* Perform cleanup after a submit has completed.
* 'data' points to a channel
*/
NVHOST_INTR_ACTION_SUBMIT_COMPLETE = 0,
/**
* Save a HW context.
* 'data' points to a context
*/
NVHOST_INTR_ACTION_CTXSAVE,
/**
* Wake up a task.
* 'data' points to a wait_queue_head_t
*/
NVHOST_INTR_ACTION_WAKEUP,
/**
* Wake up a interruptible task.
* 'data' points to a wait_queue_head_t
*/
NVHOST_INTR_ACTION_WAKEUP_INTERRUPTIBLE,
NVHOST_INTR_ACTION_COUNT
};
struct nvhost_intr;
struct nvhost_intr_syncpt {
struct nvhost_intr *intr;
u8 id;
u8 irq_requested;
u16 irq;
spinlock_t lock;
struct list_head wait_head;
char thresh_irq_name[12];
};
struct nvhost_intr {
struct nvhost_intr_syncpt *syncpt;
struct mutex mutex;
int host_general_irq;
bool host_general_irq_requested;
};
#define intr_to_dev(x) container_of(x, struct nvhost_master, intr)
#define intr_op(intr) (intr_to_dev(intr)->op.intr)
#define intr_syncpt_to_intr(is) (is->intr)
/**
* Schedule an action to be taken when a sync point reaches the given threshold.
*
* @id the sync point
* @thresh the threshold
* @action the action to take
* @data a pointer to extra data depending on action, see above
* @waiter waiter allocated with nvhost_intr_alloc_waiter - assumes ownership
* @ref must be passed if cancellation is possible, else NULL
*
* This is a non-blocking api.
*/
int nvhost_intr_add_action(struct nvhost_intr *intr, u32 id, u32 thresh,
enum nvhost_intr_action action, void *data,
void *waiter,
void **ref);
/**
* Allocate a waiter.
*/
void *nvhost_intr_alloc_waiter(void);
/**
* Unreference an action submitted to nvhost_intr_add_action().
* You must call this if you passed non-NULL as ref.
* @ref the ref returned from nvhost_intr_add_action()
*/
void nvhost_intr_put_ref(struct nvhost_intr *intr, void *ref);
int nvhost_intr_init(struct nvhost_intr *intr, u32 irq_gen, u32 irq_sync);
void nvhost_intr_deinit(struct nvhost_intr *intr);
void nvhost_intr_start(struct nvhost_intr *intr, u32 hz);
void nvhost_intr_stop(struct nvhost_intr *intr);
irqreturn_t nvhost_syncpt_thresh_fn(int irq, void *dev_id);
#endif
| OptiPop/kernel_asus_grouper | drivers/video/tegra/host/nvhost_intr.h | C | gpl-2.0 | 3,082 |
/*
* ext4_jbd2.h
*
* Written by Stephen C. Tweedie <sct@redhat.com>, 1999
*
* Copyright 1998--1999 Red Hat corp --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Ext4-specific journaling extensions.
*/
#ifndef _EXT4_JBD2_H
#define _EXT4_JBD2_H
#include <linux/fs.h>
#include <linux/jbd2.h>
#include "ext4.h"
#define EXT4_JOURNAL(inode) (EXT4_SB((inode)->i_sb)->s_journal)
/* Define the number of blocks we need to account to a transaction to
* modify one block of data.
*
* We may have to touch one inode, one bitmap buffer, up to three
* indirection blocks, the group and superblock summaries, and the data
* block to complete the transaction.
*
* For extents-enabled fs we may have to allocate and modify up to
* 5 levels of tree + root which are stored in the inode. */
#define EXT4_SINGLEDATA_TRANS_BLOCKS(sb) \
(EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS) \
? 27U : 8U)
/* Extended attribute operations touch at most two data buffers,
* two bitmap buffers, and two group summaries, in addition to the inode
* and the superblock, which are already accounted for. */
#define EXT4_XATTR_TRANS_BLOCKS 6U
/* Define the minimum size for a transaction which modifies data. This
* needs to take into account the fact that we may end up modifying two
* quota files too (one for the group, one for the user quota). The
* superblock only gets updated once, of course, so don't bother
* counting that again for the quota updates. */
#define EXT4_DATA_TRANS_BLOCKS(sb) (EXT4_SINGLEDATA_TRANS_BLOCKS(sb) + \
EXT4_XATTR_TRANS_BLOCKS - 2 + \
EXT4_MAXQUOTAS_TRANS_BLOCKS(sb))
/*
* Define the number of metadata blocks we need to account to modify data.
*
* This include super block, inode block, quota blocks and xattr blocks
*/
#define EXT4_META_TRANS_BLOCKS(sb) (EXT4_XATTR_TRANS_BLOCKS + \
EXT4_MAXQUOTAS_TRANS_BLOCKS(sb))
/* Delete operations potentially hit one directory's namespace plus an
* entire inode, plus arbitrary amounts of bitmap/indirection data. Be
* generous. We can grow the delete transaction later if necessary. */
#define EXT4_DELETE_TRANS_BLOCKS(sb) (2 * EXT4_DATA_TRANS_BLOCKS(sb) + 64)
/* Define an arbitrary limit for the amount of data we will anticipate
* writing to any given transaction. For unbounded transactions such as
* write(2) and truncate(2) we can write more than this, but we always
* start off at the maximum transaction size and grow the transaction
* optimistically as we go. */
#define EXT4_MAX_TRANS_DATA 64U
/* We break up a large truncate or write transaction once the handle's
* buffer credits gets this low, we need either to extend the
* transaction or to start a new one. Reserve enough space here for
* inode, bitmap, superblock, group and indirection updates for at least
* one block, plus two quota updates. Quota allocations are not
* needed. */
#define EXT4_RESERVE_TRANS_BLOCKS 12U
#define EXT4_INDEX_EXTRA_TRANS_BLOCKS 8
#ifdef CONFIG_QUOTA
/* Amount of blocks needed for quota update - we know that the structure was
* allocated so we need to update only data block */
#define EXT4_QUOTA_TRANS_BLOCKS(sb) (test_opt(sb, QUOTA) ? 1 : 0)
/* Amount of blocks needed for quota insert/delete - we do some block writes
* but inode, sb and group updates are done only once */
#define EXT4_QUOTA_INIT_BLOCKS(sb) (test_opt(sb, QUOTA) ? (DQUOT_INIT_ALLOC*\
(EXT4_SINGLEDATA_TRANS_BLOCKS(sb)-3)+3+DQUOT_INIT_REWRITE) : 0)
#define EXT4_QUOTA_DEL_BLOCKS(sb) (test_opt(sb, QUOTA) ? (DQUOT_DEL_ALLOC*\
(EXT4_SINGLEDATA_TRANS_BLOCKS(sb)-3)+3+DQUOT_DEL_REWRITE) : 0)
#else
#define EXT4_QUOTA_TRANS_BLOCKS(sb) 0
#define EXT4_QUOTA_INIT_BLOCKS(sb) 0
#define EXT4_QUOTA_DEL_BLOCKS(sb) 0
#endif
#define EXT4_MAXQUOTAS_TRANS_BLOCKS(sb) (MAXQUOTAS*EXT4_QUOTA_TRANS_BLOCKS(sb))
#define EXT4_MAXQUOTAS_INIT_BLOCKS(sb) (MAXQUOTAS*EXT4_QUOTA_INIT_BLOCKS(sb))
#define EXT4_MAXQUOTAS_DEL_BLOCKS(sb) (MAXQUOTAS*EXT4_QUOTA_DEL_BLOCKS(sb))
int
ext4_mark_iloc_dirty(handle_t *handle,
struct inode *inode,
struct ext4_iloc *iloc);
/*
* On success, We end up with an outstanding reference count against
* iloc->bh. This _must_ be cleaned up later.
*/
int ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
struct ext4_iloc *iloc);
int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode);
/*
* Wrapper functions with which ext4 calls into JBD.
*/
void ext4_journal_abort_handle(const char *caller, unsigned int line,
const char *err_fn,
struct buffer_head *bh, handle_t *handle, int err);
int __ext4_journal_get_write_access(const char *where, unsigned int line,
handle_t *handle, struct buffer_head *bh);
int __ext4_forget(const char *where, unsigned int line, handle_t *handle,
int is_metadata, struct inode *inode,
struct buffer_head *bh, ext4_fsblk_t blocknr);
int __ext4_journal_get_create_access(const char *where, unsigned int line,
handle_t *handle, struct buffer_head *bh);
int __ext4_handle_dirty_metadata(const char *where, unsigned int line,
handle_t *handle, struct inode *inode,
struct buffer_head *bh);
int __ext4_handle_dirty_super(const char *where, unsigned int line,
handle_t *handle, struct super_block *sb);
#define ext4_journal_get_write_access(handle, bh) \
__ext4_journal_get_write_access(__func__, __LINE__, (handle), (bh))
#define ext4_forget(handle, is_metadata, inode, bh, block_nr) \
__ext4_forget(__func__, __LINE__, (handle), (is_metadata), (inode), \
(bh), (block_nr))
#define ext4_journal_get_create_access(handle, bh) \
__ext4_journal_get_create_access(__func__, __LINE__, (handle), (bh))
#define ext4_handle_dirty_metadata(handle, inode, bh) \
__ext4_handle_dirty_metadata(__func__, __LINE__, (handle), (inode), \
(bh))
#define ext4_handle_dirty_super(handle, sb) \
__ext4_handle_dirty_super(__func__, __LINE__, (handle), (sb))
handle_t *ext4_journal_start_sb(struct super_block *sb, int nblocks);
int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle);
#define EXT4_NOJOURNAL_MAX_REF_COUNT ((unsigned long) 4096)
/* Note: Do not use this for NULL handles. This is only to determine if
* a properly allocated handle is using a journal or not. */
static inline int ext4_handle_valid(handle_t *handle)
{
if ((unsigned long)handle < EXT4_NOJOURNAL_MAX_REF_COUNT)
return 0;
return 1;
}
static inline void ext4_handle_sync(handle_t *handle)
{
if (ext4_handle_valid(handle))
handle->h_sync = 1;
}
static inline void ext4_handle_release_buffer(handle_t *handle,
struct buffer_head *bh)
{
if (ext4_handle_valid(handle))
jbd2_journal_release_buffer(handle, bh);
}
static inline int ext4_handle_is_aborted(handle_t *handle)
{
if (ext4_handle_valid(handle))
return is_handle_aborted(handle);
return 0;
}
static inline int ext4_handle_has_enough_credits(handle_t *handle, int needed)
{
if (ext4_handle_valid(handle) && handle->h_buffer_credits < needed)
return 0;
return 1;
}
static inline handle_t *ext4_journal_start(struct inode *inode, int nblocks)
{
return ext4_journal_start_sb(inode->i_sb, nblocks);
}
#define ext4_journal_stop(handle) \
__ext4_journal_stop(__func__, __LINE__, (handle))
static inline handle_t *ext4_journal_current_handle(void)
{
return journal_current_handle();
}
static inline int ext4_journal_extend(handle_t *handle, int nblocks)
{
if (ext4_handle_valid(handle))
return jbd2_journal_extend(handle, nblocks);
return 0;
}
static inline int ext4_journal_restart(handle_t *handle, int nblocks)
{
if (ext4_handle_valid(handle))
return jbd2_journal_restart(handle, nblocks);
return 0;
}
static inline int ext4_journal_blocks_per_page(struct inode *inode)
{
if (EXT4_JOURNAL(inode) != NULL)
return jbd2_journal_blocks_per_page(inode);
return 0;
}
static inline int ext4_journal_force_commit(journal_t *journal)
{
if (journal)
return jbd2_journal_force_commit(journal);
return 0;
}
static inline int ext4_jbd2_file_inode(handle_t *handle, struct inode *inode)
{
if (ext4_handle_valid(handle)) {
if (unlikely(EXT4_I(inode)->jinode == NULL)) {
/* Should never happen */
WARN(true, "inode #%lu has NULL jinode\n",
inode->i_ino);
return 0;
}
return jbd2_journal_file_inode(handle, EXT4_I(inode)->jinode);
}
return 0;
}
static inline void ext4_update_inode_fsync_trans(handle_t *handle,
struct inode *inode,
int datasync)
{
struct ext4_inode_info *ei = EXT4_I(inode);
if (ext4_handle_valid(handle)) {
ei->i_sync_tid = handle->h_transaction->t_tid;
if (datasync)
ei->i_datasync_tid = handle->h_transaction->t_tid;
}
}
/* super.c */
int ext4_force_commit(struct super_block *sb);
/*
* Ext4 inode journal modes
*/
#define EXT4_INODE_JOURNAL_DATA_MODE 0x01 /* journal data mode */
#define EXT4_INODE_ORDERED_DATA_MODE 0x02 /* ordered data mode */
#define EXT4_INODE_WRITEBACK_DATA_MODE 0x04 /* writeback data mode */
static inline int ext4_inode_journal_mode(struct inode *inode)
{
if (EXT4_JOURNAL(inode) == NULL)
return EXT4_INODE_WRITEBACK_DATA_MODE; /* writeback */
/* We do not support data journalling with delayed allocation */
if (!S_ISREG(inode->i_mode) ||
test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
return EXT4_INODE_JOURNAL_DATA_MODE; /* journal data */
if (ext4_test_inode_flag(inode, EXT4_INODE_JOURNAL_DATA) &&
!test_opt(inode->i_sb, DELALLOC))
return EXT4_INODE_JOURNAL_DATA_MODE; /* journal data */
if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
return EXT4_INODE_ORDERED_DATA_MODE; /* ordered */
if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
return EXT4_INODE_WRITEBACK_DATA_MODE; /* writeback */
else
BUG();
}
static inline int ext4_should_journal_data(struct inode *inode)
{
return ext4_inode_journal_mode(inode) & EXT4_INODE_JOURNAL_DATA_MODE;
}
static inline int ext4_should_order_data(struct inode *inode)
{
return ext4_inode_journal_mode(inode) & EXT4_INODE_ORDERED_DATA_MODE;
}
static inline int ext4_should_writeback_data(struct inode *inode)
{
return ext4_inode_journal_mode(inode) & EXT4_INODE_WRITEBACK_DATA_MODE;
}
/*
* This function controls whether or not we should try to go down the
* dioread_nolock code paths, which makes it safe to avoid taking
* i_mutex for direct I/O reads. This only works for extent-based
* files, and it doesn't work if data journaling is enabled, since the
* dioread_nolock code uses b_private to pass information back to the
* I/O completion handler, and this conflicts with the jbd's use of
* b_private.
*/
static inline int ext4_should_dioread_nolock(struct inode *inode)
{
if (!test_opt(inode->i_sb, DIOREAD_NOLOCK))
return 0;
if (!S_ISREG(inode->i_mode))
return 0;
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
return 0;
if (ext4_should_journal_data(inode))
return 0;
return 1;
}
#endif /* _EXT4_JBD2_H */
| manumanfred/kernel_omap | fs/ext4/ext4_jbd2.h | C | gpl-2.0 | 11,110 |
/*
* Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/stmp_device.h>
#include <asm/exception.h>
#include "irqchip.h"
#define HW_ICOLL_VECTOR 0x0000
#define HW_ICOLL_LEVELACK 0x0010
#define HW_ICOLL_CTRL 0x0020
#define HW_ICOLL_STAT_OFFSET 0x0070
#define HW_ICOLL_INTERRUPTn_SET(n) (0x0124 + (n) * 0x10)
#define HW_ICOLL_INTERRUPTn_CLR(n) (0x0128 + (n) * 0x10)
#define BM_ICOLL_INTERRUPTn_ENABLE 0x00000004
#define BV_ICOLL_LEVELACK_IRQLEVELACK__LEVEL0 0x1
#define ICOLL_NUM_IRQS 128
static void __iomem *icoll_base;
static struct irq_domain *icoll_domain;
static void icoll_ack_irq(struct irq_data *d)
{
/*
* The Interrupt Collector is able to prioritize irqs.
* Currently only level 0 is used. So acking can use
* BV_ICOLL_LEVELACK_IRQLEVELACK__LEVEL0 unconditionally.
*/
__raw_writel(BV_ICOLL_LEVELACK_IRQLEVELACK__LEVEL0,
icoll_base + HW_ICOLL_LEVELACK);
}
static void icoll_mask_irq(struct irq_data *d)
{
__raw_writel(BM_ICOLL_INTERRUPTn_ENABLE,
icoll_base + HW_ICOLL_INTERRUPTn_CLR(d->hwirq));
}
static void icoll_unmask_irq(struct irq_data *d)
{
__raw_writel(BM_ICOLL_INTERRUPTn_ENABLE,
icoll_base + HW_ICOLL_INTERRUPTn_SET(d->hwirq));
}
static struct irq_chip mxs_icoll_chip = {
.irq_ack = icoll_ack_irq,
.irq_mask = icoll_mask_irq,
.irq_unmask = icoll_unmask_irq,
};
asmlinkage void __exception_irq_entry icoll_handle_irq(struct pt_regs *regs)
{
u32 irqnr;
irqnr = __raw_readl(icoll_base + HW_ICOLL_STAT_OFFSET);
__raw_writel(irqnr, icoll_base + HW_ICOLL_VECTOR);
irqnr = irq_find_mapping(icoll_domain, irqnr);
handle_IRQ(irqnr, regs);
}
static int icoll_irq_domain_map(struct irq_domain *d, unsigned int virq,
irq_hw_number_t hw)
{
irq_set_chip_and_handler(virq, &mxs_icoll_chip, handle_level_irq);
set_irq_flags(virq, IRQF_VALID);
return 0;
}
static struct irq_domain_ops icoll_irq_domain_ops = {
.map = icoll_irq_domain_map,
.xlate = irq_domain_xlate_onecell,
};
static int __init icoll_of_init(struct device_node *np,
struct device_node *interrupt_parent)
{
icoll_base = of_iomap(np, 0);
WARN_ON(!icoll_base);
/*
* Interrupt Collector reset, which initializes the priority
* for each irq to level 0.
*/
stmp_reset_block(icoll_base + HW_ICOLL_CTRL);
icoll_domain = irq_domain_add_linear(np, ICOLL_NUM_IRQS,
&icoll_irq_domain_ops, NULL);
return icoll_domain ? 0 : -ENODEV;
}
IRQCHIP_DECLARE(mxs, "fsl,icoll", icoll_of_init);
| dperezde/little-penguin | linux-eudyptula/drivers/irqchip/irq-mxs.c | C | gpl-2.0 | 3,400 |
<?php
/**
* Exception for 503 Service Unavailable responses
*
* @package Requests
*/
/**
* Exception for 503 Service Unavailable responses
*
* @package Requests
*/
class Requests_Exception_HTTP_503 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 503;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Service Unavailable';
} | dexxtr/osbb-web-manager | www/wp-includes/Requests/Exception/HTTP/503.php | PHP | gpl-3.0 | 411 |
#include "reiserfs.h"
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/xattr.h>
#include <linux/slab.h>
#include "xattr.h"
#include <linux/security.h>
#include <asm/uaccess.h>
static int
security_get(struct dentry *dentry, const char *name, void *buffer, size_t size,
int handler_flags)
{
if (strlen(name) < sizeof(XATTR_SECURITY_PREFIX))
return -EINVAL;
if (IS_PRIVATE(dentry->d_inode))
return -EPERM;
return reiserfs_xattr_get(dentry->d_inode, name, buffer, size);
}
static int
security_set(struct dentry *dentry, const char *name, const void *buffer,
size_t size, int flags, int handler_flags)
{
if (strlen(name) < sizeof(XATTR_SECURITY_PREFIX))
return -EINVAL;
if (IS_PRIVATE(dentry->d_inode))
return -EPERM;
return reiserfs_xattr_set(dentry->d_inode, name, buffer, size, flags);
}
static size_t security_list(struct dentry *dentry, char *list, size_t list_len,
const char *name, size_t namelen, int handler_flags)
{
const size_t len = namelen + 1;
if (IS_PRIVATE(dentry->d_inode))
return 0;
if (list && len <= list_len) {
memcpy(list, name, namelen);
list[namelen] = '\0';
}
return len;
}
/* Initializes the security context for a new inode and returns the number
* of blocks needed for the transaction. If successful, reiserfs_security
* must be released using reiserfs_security_free when the caller is done. */
int reiserfs_security_init(struct inode *dir, struct inode *inode,
const struct qstr *qstr,
struct reiserfs_security_handle *sec)
{
int blocks = 0;
int error;
sec->name = NULL;
/* Don't add selinux attributes on xattrs - they'll never get used */
if (IS_PRIVATE(dir))
return 0;
error = security_old_inode_init_security(inode, dir, qstr, &sec->name,
&sec->value, &sec->length);
if (error) {
if (error == -EOPNOTSUPP)
error = 0;
sec->name = NULL;
sec->value = NULL;
sec->length = 0;
return error;
}
if (sec->length && reiserfs_xattrs_initialized(inode->i_sb)) {
blocks = reiserfs_xattr_jcreate_nblocks(inode) +
reiserfs_xattr_nblocks(inode, sec->length);
/* We don't want to count the directories twice if we have
* a default ACL. */
REISERFS_I(inode)->i_flags |= i_has_xattr_dir;
}
return blocks;
}
int reiserfs_security_write(struct reiserfs_transaction_handle *th,
struct inode *inode,
struct reiserfs_security_handle *sec)
{
int error;
if (strlen(sec->name) < sizeof(XATTR_SECURITY_PREFIX))
return -EINVAL;
error = reiserfs_xattr_set_handle(th, inode, sec->name, sec->value,
sec->length, XATTR_CREATE);
if (error == -ENODATA || error == -EOPNOTSUPP)
error = 0;
return error;
}
void reiserfs_security_free(struct reiserfs_security_handle *sec)
{
kfree(sec->name);
kfree(sec->value);
sec->name = NULL;
sec->value = NULL;
}
const struct xattr_handler reiserfs_xattr_security_handler = {
.prefix = XATTR_SECURITY_PREFIX,
.get = security_get,
.set = security_set,
.list = security_list,
};
| talnoah/android_kernel_htc_dlx | virt/fs/reiserfs/xattr_security.c | C | gpl-2.0 | 3,005 |
/* rc-main.c - Remote Controller core module
*
* Copyright (C) 2009-2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <media/rc-core.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/device.h>
#include "rc-core-priv.h"
/* Sizes are in bytes, 256 bytes allows for 32 entries on x64 */
#define IR_TAB_MIN_SIZE 256
#define IR_TAB_MAX_SIZE 8192
/* FIXME: IR_KEYPRESS_TIMEOUT should be protocol specific */
#define IR_KEYPRESS_TIMEOUT 250
/* Used to keep track of known keymaps */
static LIST_HEAD(rc_map_list);
static DEFINE_SPINLOCK(rc_map_lock);
static struct rc_map_list *seek_rc_map(const char *name)
{
struct rc_map_list *map = NULL;
spin_lock(&rc_map_lock);
list_for_each_entry(map, &rc_map_list, list) {
if (!strcmp(name, map->map.name)) {
spin_unlock(&rc_map_lock);
return map;
}
}
spin_unlock(&rc_map_lock);
return NULL;
}
struct rc_map *rc_map_get(const char *name)
{
struct rc_map_list *map;
map = seek_rc_map(name);
#ifdef MODULE
if (!map) {
int rc = request_module(name);
if (rc < 0) {
printk(KERN_ERR "Couldn't load IR keymap %s\n", name);
return NULL;
}
msleep(20); /* Give some time for IR to register */
map = seek_rc_map(name);
}
#endif
if (!map) {
printk(KERN_ERR "IR keymap %s not found\n", name);
return NULL;
}
printk(KERN_INFO "Registered IR keymap %s\n", map->map.name);
return &map->map;
}
EXPORT_SYMBOL_GPL(rc_map_get);
int rc_map_register(struct rc_map_list *map)
{
spin_lock(&rc_map_lock);
list_add_tail(&map->list, &rc_map_list);
spin_unlock(&rc_map_lock);
return 0;
}
EXPORT_SYMBOL_GPL(rc_map_register);
void rc_map_unregister(struct rc_map_list *map)
{
spin_lock(&rc_map_lock);
list_del(&map->list);
spin_unlock(&rc_map_lock);
}
EXPORT_SYMBOL_GPL(rc_map_unregister);
static struct rc_map_table empty[] = {
{ 0x2a, KEY_COFFEE },
};
static struct rc_map_list empty_map = {
.map = {
.scan = empty,
.size = ARRAY_SIZE(empty),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_EMPTY,
}
};
/**
* ir_create_table() - initializes a scancode table
* @rc_map: the rc_map to initialize
* @name: name to assign to the table
* @rc_type: ir type to assign to the new table
* @size: initial size of the table
* @return: zero on success or a negative error code
*
* This routine will initialize the rc_map and will allocate
* memory to hold at least the specified number of elements.
*/
static int ir_create_table(struct rc_map *rc_map,
const char *name, u64 rc_type, size_t size)
{
rc_map->name = name;
rc_map->rc_type = rc_type;
rc_map->alloc = roundup_pow_of_two(size * sizeof(struct rc_map_table));
rc_map->size = rc_map->alloc / sizeof(struct rc_map_table);
rc_map->scan = kmalloc(rc_map->alloc, GFP_KERNEL);
if (!rc_map->scan)
return -ENOMEM;
IR_dprintk(1, "Allocated space for %u keycode entries (%u bytes)\n",
rc_map->size, rc_map->alloc);
return 0;
}
/**
* ir_free_table() - frees memory allocated by a scancode table
* @rc_map: the table whose mappings need to be freed
*
* This routine will free memory alloctaed for key mappings used by given
* scancode table.
*/
static void ir_free_table(struct rc_map *rc_map)
{
rc_map->size = 0;
kfree(rc_map->scan);
rc_map->scan = NULL;
}
/**
* ir_resize_table() - resizes a scancode table if necessary
* @rc_map: the rc_map to resize
* @gfp_flags: gfp flags to use when allocating memory
* @return: zero on success or a negative error code
*
* This routine will shrink the rc_map if it has lots of
* unused entries and grow it if it is full.
*/
static int ir_resize_table(struct rc_map *rc_map, gfp_t gfp_flags)
{
unsigned int oldalloc = rc_map->alloc;
unsigned int newalloc = oldalloc;
struct rc_map_table *oldscan = rc_map->scan;
struct rc_map_table *newscan;
if (rc_map->size == rc_map->len) {
/* All entries in use -> grow keytable */
if (rc_map->alloc >= IR_TAB_MAX_SIZE)
return -ENOMEM;
newalloc *= 2;
IR_dprintk(1, "Growing table to %u bytes\n", newalloc);
}
if ((rc_map->len * 3 < rc_map->size) && (oldalloc > IR_TAB_MIN_SIZE)) {
/* Less than 1/3 of entries in use -> shrink keytable */
newalloc /= 2;
IR_dprintk(1, "Shrinking table to %u bytes\n", newalloc);
}
if (newalloc == oldalloc)
return 0;
newscan = kmalloc(newalloc, gfp_flags);
if (!newscan) {
IR_dprintk(1, "Failed to kmalloc %u bytes\n", newalloc);
return -ENOMEM;
}
memcpy(newscan, rc_map->scan, rc_map->len * sizeof(struct rc_map_table));
rc_map->scan = newscan;
rc_map->alloc = newalloc;
rc_map->size = rc_map->alloc / sizeof(struct rc_map_table);
kfree(oldscan);
return 0;
}
/**
* ir_update_mapping() - set a keycode in the scancode->keycode table
* @dev: the struct rc_dev device descriptor
* @rc_map: scancode table to be adjusted
* @index: index of the mapping that needs to be updated
* @keycode: the desired keycode
* @return: previous keycode assigned to the mapping
*
* This routine is used to update scancode->keycode mapping at given
* position.
*/
static unsigned int ir_update_mapping(struct rc_dev *dev,
struct rc_map *rc_map,
unsigned int index,
unsigned int new_keycode)
{
int old_keycode = rc_map->scan[index].keycode;
int i;
/* Did the user wish to remove the mapping? */
if (new_keycode == KEY_RESERVED || new_keycode == KEY_UNKNOWN) {
IR_dprintk(1, "#%d: Deleting scan 0x%04x\n",
index, rc_map->scan[index].scancode);
rc_map->len--;
memmove(&rc_map->scan[index], &rc_map->scan[index+ 1],
(rc_map->len - index) * sizeof(struct rc_map_table));
} else {
IR_dprintk(1, "#%d: %s scan 0x%04x with key 0x%04x\n",
index,
old_keycode == KEY_RESERVED ? "New" : "Replacing",
rc_map->scan[index].scancode, new_keycode);
rc_map->scan[index].keycode = new_keycode;
__set_bit(new_keycode, dev->input_dev->keybit);
}
if (old_keycode != KEY_RESERVED) {
/* A previous mapping was updated... */
__clear_bit(old_keycode, dev->input_dev->keybit);
/* ... but another scancode might use the same keycode */
for (i = 0; i < rc_map->len; i++) {
if (rc_map->scan[i].keycode == old_keycode) {
__set_bit(old_keycode, dev->input_dev->keybit);
break;
}
}
/* Possibly shrink the keytable, failure is not a problem */
ir_resize_table(rc_map, GFP_ATOMIC);
}
return old_keycode;
}
/**
* ir_establish_scancode() - set a keycode in the scancode->keycode table
* @dev: the struct rc_dev device descriptor
* @rc_map: scancode table to be searched
* @scancode: the desired scancode
* @resize: controls whether we allowed to resize the table to
* accommodate not yet present scancodes
* @return: index of the mapping containing scancode in question
* or -1U in case of failure.
*
* This routine is used to locate given scancode in rc_map.
* If scancode is not yet present the routine will allocate a new slot
* for it.
*/
static unsigned int ir_establish_scancode(struct rc_dev *dev,
struct rc_map *rc_map,
unsigned int scancode,
bool resize)
{
unsigned int i;
/*
* Unfortunately, some hardware-based IR decoders don't provide
* all bits for the complete IR code. In general, they provide only
* the command part of the IR code. Yet, as it is possible to replace
* the provided IR with another one, it is needed to allow loading
* IR tables from other remotes. So, we support specifying a mask to
* indicate the valid bits of the scancodes.
*/
if (dev->scanmask)
scancode &= dev->scanmask;
/* First check if we already have a mapping for this ir command */
for (i = 0; i < rc_map->len; i++) {
if (rc_map->scan[i].scancode == scancode)
return i;
/* Keytable is sorted from lowest to highest scancode */
if (rc_map->scan[i].scancode >= scancode)
break;
}
/* No previous mapping found, we might need to grow the table */
if (rc_map->size == rc_map->len) {
if (!resize || ir_resize_table(rc_map, GFP_ATOMIC))
return -1U;
}
/* i is the proper index to insert our new keycode */
if (i < rc_map->len)
memmove(&rc_map->scan[i + 1], &rc_map->scan[i],
(rc_map->len - i) * sizeof(struct rc_map_table));
rc_map->scan[i].scancode = scancode;
rc_map->scan[i].keycode = KEY_RESERVED;
rc_map->len++;
return i;
}
/**
* ir_setkeycode() - set a keycode in the scancode->keycode table
* @idev: the struct input_dev device descriptor
* @scancode: the desired scancode
* @keycode: result
* @return: -EINVAL if the keycode could not be inserted, otherwise zero.
*
* This routine is used to handle evdev EVIOCSKEY ioctl.
*/
static int ir_setkeycode(struct input_dev *idev,
const struct input_keymap_entry *ke,
unsigned int *old_keycode)
{
struct rc_dev *rdev = input_get_drvdata(idev);
struct rc_map *rc_map = &rdev->rc_map;
unsigned int index;
unsigned int scancode;
int retval = 0;
unsigned long flags;
spin_lock_irqsave(&rc_map->lock, flags);
if (ke->flags & INPUT_KEYMAP_BY_INDEX) {
index = ke->index;
if (index >= rc_map->len) {
retval = -EINVAL;
goto out;
}
} else {
retval = input_scancode_to_scalar(ke, &scancode);
if (retval)
goto out;
index = ir_establish_scancode(rdev, rc_map, scancode, true);
if (index >= rc_map->len) {
retval = -ENOMEM;
goto out;
}
}
*old_keycode = ir_update_mapping(rdev, rc_map, index, ke->keycode);
out:
spin_unlock_irqrestore(&rc_map->lock, flags);
return retval;
}
/**
* ir_setkeytable() - sets several entries in the scancode->keycode table
* @dev: the struct rc_dev device descriptor
* @to: the struct rc_map to copy entries to
* @from: the struct rc_map to copy entries from
* @return: -ENOMEM if all keycodes could not be inserted, otherwise zero.
*
* This routine is used to handle table initialization.
*/
static int ir_setkeytable(struct rc_dev *dev,
const struct rc_map *from)
{
struct rc_map *rc_map = &dev->rc_map;
unsigned int i, index;
int rc;
rc = ir_create_table(rc_map, from->name,
from->rc_type, from->size);
if (rc)
return rc;
IR_dprintk(1, "Allocated space for %u keycode entries (%u bytes)\n",
rc_map->size, rc_map->alloc);
for (i = 0; i < from->size; i++) {
index = ir_establish_scancode(dev, rc_map,
from->scan[i].scancode, false);
if (index >= rc_map->len) {
rc = -ENOMEM;
break;
}
ir_update_mapping(dev, rc_map, index,
from->scan[i].keycode);
}
if (rc)
ir_free_table(rc_map);
return rc;
}
/**
* ir_lookup_by_scancode() - locate mapping by scancode
* @rc_map: the struct rc_map to search
* @scancode: scancode to look for in the table
* @return: index in the table, -1U if not found
*
* This routine performs binary search in RC keykeymap table for
* given scancode.
*/
static unsigned int ir_lookup_by_scancode(const struct rc_map *rc_map,
unsigned int scancode)
{
int start = 0;
int end = rc_map->len - 1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (rc_map->scan[mid].scancode < scancode)
start = mid + 1;
else if (rc_map->scan[mid].scancode > scancode)
end = mid - 1;
else
return mid;
}
return -1U;
}
/**
* ir_getkeycode() - get a keycode from the scancode->keycode table
* @idev: the struct input_dev device descriptor
* @scancode: the desired scancode
* @keycode: used to return the keycode, if found, or KEY_RESERVED
* @return: always returns zero.
*
* This routine is used to handle evdev EVIOCGKEY ioctl.
*/
static int ir_getkeycode(struct input_dev *idev,
struct input_keymap_entry *ke)
{
struct rc_dev *rdev = input_get_drvdata(idev);
struct rc_map *rc_map = &rdev->rc_map;
struct rc_map_table *entry;
unsigned long flags;
unsigned int index;
unsigned int scancode;
int retval;
spin_lock_irqsave(&rc_map->lock, flags);
if (ke->flags & INPUT_KEYMAP_BY_INDEX) {
index = ke->index;
} else {
retval = input_scancode_to_scalar(ke, &scancode);
if (retval)
goto out;
index = ir_lookup_by_scancode(rc_map, scancode);
}
if (index < rc_map->len) {
entry = &rc_map->scan[index];
ke->index = index;
ke->keycode = entry->keycode;
ke->len = sizeof(entry->scancode);
memcpy(ke->scancode, &entry->scancode, sizeof(entry->scancode));
} else if (!(ke->flags & INPUT_KEYMAP_BY_INDEX)) {
/*
* We do not really know the valid range of scancodes
* so let's respond with KEY_RESERVED to anything we
* do not have mapping for [yet].
*/
ke->index = index;
ke->keycode = KEY_RESERVED;
} else {
retval = -EINVAL;
goto out;
}
retval = 0;
out:
spin_unlock_irqrestore(&rc_map->lock, flags);
return retval;
}
/**
* rc_g_keycode_from_table() - gets the keycode that corresponds to a scancode
* @dev: the struct rc_dev descriptor of the device
* @scancode: the scancode to look for
* @return: the corresponding keycode, or KEY_RESERVED
*
* This routine is used by drivers which need to convert a scancode to a
* keycode. Normally it should not be used since drivers should have no
* interest in keycodes.
*/
u32 rc_g_keycode_from_table(struct rc_dev *dev, u32 scancode)
{
struct rc_map *rc_map = &dev->rc_map;
unsigned int keycode;
unsigned int index;
unsigned long flags;
spin_lock_irqsave(&rc_map->lock, flags);
index = ir_lookup_by_scancode(rc_map, scancode);
keycode = index < rc_map->len ?
rc_map->scan[index].keycode : KEY_RESERVED;
spin_unlock_irqrestore(&rc_map->lock, flags);
if (keycode != KEY_RESERVED)
IR_dprintk(1, "%s: scancode 0x%04x keycode 0x%02x\n",
dev->input_name, scancode, keycode);
return keycode;
}
EXPORT_SYMBOL_GPL(rc_g_keycode_from_table);
/**
* ir_do_keyup() - internal function to signal the release of a keypress
* @dev: the struct rc_dev descriptor of the device
* @sync: whether or not to call input_sync
*
* This function is used internally to release a keypress, it must be
* called with keylock held.
*/
static void ir_do_keyup(struct rc_dev *dev, bool sync)
{
if (!dev->keypressed)
return;
IR_dprintk(1, "keyup key 0x%04x\n", dev->last_keycode);
input_report_key(dev->input_dev, dev->last_keycode, 0);
if (sync)
input_sync(dev->input_dev);
dev->keypressed = false;
}
/**
* rc_keyup() - signals the release of a keypress
* @dev: the struct rc_dev descriptor of the device
*
* This routine is used to signal that a key has been released on the
* remote control.
*/
void rc_keyup(struct rc_dev *dev)
{
unsigned long flags;
spin_lock_irqsave(&dev->keylock, flags);
ir_do_keyup(dev, true);
spin_unlock_irqrestore(&dev->keylock, flags);
}
EXPORT_SYMBOL_GPL(rc_keyup);
/**
* ir_timer_keyup() - generates a keyup event after a timeout
* @cookie: a pointer to the struct rc_dev for the device
*
* This routine will generate a keyup event some time after a keydown event
* is generated when no further activity has been detected.
*/
static void ir_timer_keyup(unsigned long cookie)
{
struct rc_dev *dev = (struct rc_dev *)cookie;
unsigned long flags;
/*
* ir->keyup_jiffies is used to prevent a race condition if a
* hardware interrupt occurs at this point and the keyup timer
* event is moved further into the future as a result.
*
* The timer will then be reactivated and this function called
* again in the future. We need to exit gracefully in that case
* to allow the input subsystem to do its auto-repeat magic or
* a keyup event might follow immediately after the keydown.
*/
spin_lock_irqsave(&dev->keylock, flags);
if (time_is_before_eq_jiffies(dev->keyup_jiffies))
ir_do_keyup(dev, true);
spin_unlock_irqrestore(&dev->keylock, flags);
}
/**
* rc_repeat() - signals that a key is still pressed
* @dev: the struct rc_dev descriptor of the device
*
* This routine is used by IR decoders when a repeat message which does
* not include the necessary bits to reproduce the scancode has been
* received.
*/
void rc_repeat(struct rc_dev *dev)
{
unsigned long flags;
spin_lock_irqsave(&dev->keylock, flags);
input_event(dev->input_dev, EV_MSC, MSC_SCAN, dev->last_scancode);
input_sync(dev->input_dev);
if (!dev->keypressed)
goto out;
dev->keyup_jiffies = jiffies + msecs_to_jiffies(IR_KEYPRESS_TIMEOUT);
mod_timer(&dev->timer_keyup, dev->keyup_jiffies);
out:
spin_unlock_irqrestore(&dev->keylock, flags);
}
EXPORT_SYMBOL_GPL(rc_repeat);
/**
* ir_do_keydown() - internal function to process a keypress
* @dev: the struct rc_dev descriptor of the device
* @scancode: the scancode of the keypress
* @keycode: the keycode of the keypress
* @toggle: the toggle value of the keypress
*
* This function is used internally to register a keypress, it must be
* called with keylock held.
*/
static void ir_do_keydown(struct rc_dev *dev, int scancode,
u32 keycode, u8 toggle)
{
bool new_event = !dev->keypressed ||
dev->last_scancode != scancode ||
dev->last_toggle != toggle;
if (new_event && dev->keypressed)
ir_do_keyup(dev, false);
input_event(dev->input_dev, EV_MSC, MSC_SCAN, scancode);
if (new_event && keycode != KEY_RESERVED) {
/* Register a keypress */
dev->keypressed = true;
dev->last_scancode = scancode;
dev->last_toggle = toggle;
dev->last_keycode = keycode;
IR_dprintk(1, "%s: key down event, "
"key 0x%04x, scancode 0x%04x\n",
dev->input_name, keycode, scancode);
input_report_key(dev->input_dev, keycode, 1);
}
input_sync(dev->input_dev);
}
/**
* rc_keydown() - generates input event for a key press
* @dev: the struct rc_dev descriptor of the device
* @scancode: the scancode that we're seeking
* @toggle: the toggle value (protocol dependent, if the protocol doesn't
* support toggle values, this should be set to zero)
*
* This routine is used to signal that a key has been pressed on the
* remote control.
*/
void rc_keydown(struct rc_dev *dev, int scancode, u8 toggle)
{
unsigned long flags;
u32 keycode = rc_g_keycode_from_table(dev, scancode);
spin_lock_irqsave(&dev->keylock, flags);
ir_do_keydown(dev, scancode, keycode, toggle);
if (dev->keypressed) {
dev->keyup_jiffies = jiffies + msecs_to_jiffies(IR_KEYPRESS_TIMEOUT);
mod_timer(&dev->timer_keyup, dev->keyup_jiffies);
}
spin_unlock_irqrestore(&dev->keylock, flags);
}
EXPORT_SYMBOL_GPL(rc_keydown);
/**
* rc_keydown_notimeout() - generates input event for a key press without
* an automatic keyup event at a later time
* @dev: the struct rc_dev descriptor of the device
* @scancode: the scancode that we're seeking
* @toggle: the toggle value (protocol dependent, if the protocol doesn't
* support toggle values, this should be set to zero)
*
* This routine is used to signal that a key has been pressed on the
* remote control. The driver must manually call rc_keyup() at a later stage.
*/
void rc_keydown_notimeout(struct rc_dev *dev, int scancode, u8 toggle)
{
unsigned long flags;
u32 keycode = rc_g_keycode_from_table(dev, scancode);
spin_lock_irqsave(&dev->keylock, flags);
ir_do_keydown(dev, scancode, keycode, toggle);
spin_unlock_irqrestore(&dev->keylock, flags);
}
EXPORT_SYMBOL_GPL(rc_keydown_notimeout);
static int ir_open(struct input_dev *idev)
{
struct rc_dev *rdev = input_get_drvdata(idev);
return rdev->open(rdev);
}
static void ir_close(struct input_dev *idev)
{
struct rc_dev *rdev = input_get_drvdata(idev);
if (rdev)
rdev->close(rdev);
}
/* class for /sys/class/rc */
static char *ir_devnode(struct device *dev, mode_t *mode)
{
return kasprintf(GFP_KERNEL, "rc/%s", dev_name(dev));
}
static struct class ir_input_class = {
.name = "rc",
.devnode = ir_devnode,
};
static struct {
u64 type;
char *name;
} proto_names[] = {
{ RC_TYPE_UNKNOWN, "unknown" },
{ RC_TYPE_RC5, "rc-5" },
{ RC_TYPE_NEC, "nec" },
{ RC_TYPE_RC6, "rc-6" },
{ RC_TYPE_JVC, "jvc" },
{ RC_TYPE_SONY, "sony" },
{ RC_TYPE_RC5_SZ, "rc-5-sz" },
{ RC_TYPE_LIRC, "lirc" },
{ RC_TYPE_OTHER, "other" },
};
#define PROTO_NONE "none"
/**
* show_protocols() - shows the current IR protocol(s)
* @device: the device descriptor
* @mattr: the device attribute struct (unused)
* @buf: a pointer to the output buffer
*
* This routine is a callback routine for input read the IR protocol type(s).
* it is trigged by reading /sys/class/rc/rc?/protocols.
* It returns the protocol names of supported protocols.
* Enabled protocols are printed in brackets.
*
* dev->lock is taken to guard against races between device
* registration, store_protocols and show_protocols.
*/
static ssize_t show_protocols(struct device *device,
struct device_attribute *mattr, char *buf)
{
struct rc_dev *dev = to_rc_dev(device);
u64 allowed, enabled;
char *tmp = buf;
int i;
/* Device is being removed */
if (!dev)
return -EINVAL;
mutex_lock(&dev->lock);
if (dev->driver_type == RC_DRIVER_SCANCODE) {
enabled = dev->rc_map.rc_type;
allowed = dev->allowed_protos;
} else if (dev->raw) {
enabled = dev->raw->enabled_protocols;
allowed = ir_raw_get_allowed_protocols();
} else {
mutex_unlock(&dev->lock);
return -ENODEV;
}
IR_dprintk(1, "allowed - 0x%llx, enabled - 0x%llx\n",
(long long)allowed,
(long long)enabled);
for (i = 0; i < ARRAY_SIZE(proto_names); i++) {
if (allowed & enabled & proto_names[i].type)
tmp += sprintf(tmp, "[%s] ", proto_names[i].name);
else if (allowed & proto_names[i].type)
tmp += sprintf(tmp, "%s ", proto_names[i].name);
}
if (tmp != buf)
tmp--;
*tmp = '\n';
mutex_unlock(&dev->lock);
return tmp + 1 - buf;
}
/**
* store_protocols() - changes the current IR protocol(s)
* @device: the device descriptor
* @mattr: the device attribute struct (unused)
* @buf: a pointer to the input buffer
* @len: length of the input buffer
*
* This routine is for changing the IR protocol type.
* It is trigged by writing to /sys/class/rc/rc?/protocols.
* Writing "+proto" will add a protocol to the list of enabled protocols.
* Writing "-proto" will remove a protocol from the list of enabled protocols.
* Writing "proto" will enable only "proto".
* Writing "none" will disable all protocols.
* Returns -EINVAL if an invalid protocol combination or unknown protocol name
* is used, otherwise @len.
*
* dev->lock is taken to guard against races between device
* registration, store_protocols and show_protocols.
*/
static ssize_t store_protocols(struct device *device,
struct device_attribute *mattr,
const char *data,
size_t len)
{
struct rc_dev *dev = to_rc_dev(device);
bool enable, disable;
const char *tmp;
u64 type;
u64 mask;
int rc, i, count = 0;
unsigned long flags;
ssize_t ret;
/* Device is being removed */
if (!dev)
return -EINVAL;
mutex_lock(&dev->lock);
if (dev->driver_type == RC_DRIVER_SCANCODE)
type = dev->rc_map.rc_type;
else if (dev->raw)
type = dev->raw->enabled_protocols;
else {
IR_dprintk(1, "Protocol switching not supported\n");
ret = -EINVAL;
goto out;
}
while ((tmp = strsep((char **) &data, " \n")) != NULL) {
if (!*tmp)
break;
if (*tmp == '+') {
enable = true;
disable = false;
tmp++;
} else if (*tmp == '-') {
enable = false;
disable = true;
tmp++;
} else {
enable = false;
disable = false;
}
if (!enable && !disable && !strncasecmp(tmp, PROTO_NONE, sizeof(PROTO_NONE))) {
tmp += sizeof(PROTO_NONE);
mask = 0;
count++;
} else {
for (i = 0; i < ARRAY_SIZE(proto_names); i++) {
if (!strcasecmp(tmp, proto_names[i].name)) {
tmp += strlen(proto_names[i].name);
mask = proto_names[i].type;
break;
}
}
if (i == ARRAY_SIZE(proto_names)) {
IR_dprintk(1, "Unknown protocol: '%s'\n", tmp);
ret = -EINVAL;
goto out;
}
count++;
}
if (enable)
type |= mask;
else if (disable)
type &= ~mask;
else
type = mask;
}
if (!count) {
IR_dprintk(1, "Protocol not specified\n");
ret = -EINVAL;
goto out;
}
if (dev->change_protocol) {
rc = dev->change_protocol(dev, type);
if (rc < 0) {
IR_dprintk(1, "Error setting protocols to 0x%llx\n",
(long long)type);
ret = -EINVAL;
goto out;
}
}
if (dev->driver_type == RC_DRIVER_SCANCODE) {
spin_lock_irqsave(&dev->rc_map.lock, flags);
dev->rc_map.rc_type = type;
spin_unlock_irqrestore(&dev->rc_map.lock, flags);
} else {
dev->raw->enabled_protocols = type;
}
IR_dprintk(1, "Current protocol(s): 0x%llx\n",
(long long)type);
ret = len;
out:
mutex_unlock(&dev->lock);
return ret;
}
static void rc_dev_release(struct device *device)
{
struct rc_dev *dev = to_rc_dev(device);
kfree(dev);
module_put(THIS_MODULE);
}
#define ADD_HOTPLUG_VAR(fmt, val...) \
do { \
int err = add_uevent_var(env, fmt, val); \
if (err) \
return err; \
} while (0)
static int rc_dev_uevent(struct device *device, struct kobj_uevent_env *env)
{
struct rc_dev *dev = to_rc_dev(device);
if (dev->rc_map.name)
ADD_HOTPLUG_VAR("NAME=%s", dev->rc_map.name);
if (dev->driver_name)
ADD_HOTPLUG_VAR("DRV_NAME=%s", dev->driver_name);
return 0;
}
/*
* Static device attribute struct with the sysfs attributes for IR's
*/
static DEVICE_ATTR(protocols, S_IRUGO | S_IWUSR,
show_protocols, store_protocols);
static struct attribute *rc_dev_attrs[] = {
&dev_attr_protocols.attr,
NULL,
};
static struct attribute_group rc_dev_attr_grp = {
.attrs = rc_dev_attrs,
};
static const struct attribute_group *rc_dev_attr_groups[] = {
&rc_dev_attr_grp,
NULL
};
static struct device_type rc_dev_type = {
.groups = rc_dev_attr_groups,
.release = rc_dev_release,
.uevent = rc_dev_uevent,
};
struct rc_dev *rc_allocate_device(void)
{
struct rc_dev *dev;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return NULL;
dev->input_dev = input_allocate_device();
if (!dev->input_dev) {
kfree(dev);
return NULL;
}
dev->input_dev->getkeycode = ir_getkeycode;
dev->input_dev->setkeycode = ir_setkeycode;
input_set_drvdata(dev->input_dev, dev);
spin_lock_init(&dev->rc_map.lock);
spin_lock_init(&dev->keylock);
mutex_init(&dev->lock);
setup_timer(&dev->timer_keyup, ir_timer_keyup, (unsigned long)dev);
dev->dev.type = &rc_dev_type;
dev->dev.class = &ir_input_class;
device_initialize(&dev->dev);
__module_get(THIS_MODULE);
return dev;
}
EXPORT_SYMBOL_GPL(rc_allocate_device);
void rc_free_device(struct rc_dev *dev)
{
if (dev) {
input_free_device(dev->input_dev);
put_device(&dev->dev);
}
}
EXPORT_SYMBOL_GPL(rc_free_device);
int rc_register_device(struct rc_dev *dev)
{
static atomic_t devno = ATOMIC_INIT(0);
struct rc_map *rc_map;
const char *path;
int rc;
if (!dev || !dev->map_name)
return -EINVAL;
rc_map = rc_map_get(dev->map_name);
if (!rc_map)
rc_map = rc_map_get(RC_MAP_EMPTY);
if (!rc_map || !rc_map->scan || rc_map->size == 0)
return -EINVAL;
set_bit(EV_KEY, dev->input_dev->evbit);
set_bit(EV_REP, dev->input_dev->evbit);
set_bit(EV_MSC, dev->input_dev->evbit);
set_bit(MSC_SCAN, dev->input_dev->mscbit);
if (dev->open)
dev->input_dev->open = ir_open;
if (dev->close)
dev->input_dev->close = ir_close;
/*
* Take the lock here, as the device sysfs node will appear
* when device_add() is called, which may trigger an ir-keytable udev
* rule, which will in turn call show_protocols and access either
* dev->rc_map.rc_type or dev->raw->enabled_protocols before it has
* been initialized.
*/
mutex_lock(&dev->lock);
dev->devno = (unsigned long)(atomic_inc_return(&devno) - 1);
dev_set_name(&dev->dev, "rc%ld", dev->devno);
dev_set_drvdata(&dev->dev, dev);
rc = device_add(&dev->dev);
if (rc)
goto out_unlock;
rc = ir_setkeytable(dev, rc_map);
if (rc)
goto out_dev;
dev->input_dev->dev.parent = &dev->dev;
memcpy(&dev->input_dev->id, &dev->input_id, sizeof(dev->input_id));
dev->input_dev->phys = dev->input_phys;
dev->input_dev->name = dev->input_name;
rc = input_register_device(dev->input_dev);
if (rc)
goto out_table;
/*
* Default delay of 250ms is too short for some protocols, especially
* since the timeout is currently set to 250ms. Increase it to 500ms,
* to avoid wrong repetition of the keycodes. Note that this must be
* set after the call to input_register_device().
*/
dev->input_dev->rep[REP_DELAY] = 500;
/*
* As a repeat event on protocols like RC-5 and NEC take as long as
* 110/114ms, using 33ms as a repeat period is not the right thing
* to do.
*/
dev->input_dev->rep[REP_PERIOD] = 125;
path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);
printk(KERN_INFO "%s: %s as %s\n",
dev_name(&dev->dev),
dev->input_name ? dev->input_name : "Unspecified device",
path ? path : "N/A");
kfree(path);
if (dev->driver_type == RC_DRIVER_IR_RAW) {
rc = ir_raw_event_register(dev);
if (rc < 0)
goto out_input;
}
mutex_unlock(&dev->lock);
if (dev->change_protocol) {
rc = dev->change_protocol(dev, rc_map->rc_type);
if (rc < 0)
goto out_raw;
}
IR_dprintk(1, "Registered rc%ld (driver: %s, remote: %s, mode %s)\n",
dev->devno,
dev->driver_name ? dev->driver_name : "unknown",
rc_map->name ? rc_map->name : "unknown",
dev->driver_type == RC_DRIVER_IR_RAW ? "raw" : "cooked");
return 0;
out_raw:
if (dev->driver_type == RC_DRIVER_IR_RAW)
ir_raw_event_unregister(dev);
out_input:
input_unregister_device(dev->input_dev);
dev->input_dev = NULL;
out_table:
ir_free_table(&dev->rc_map);
out_dev:
device_del(&dev->dev);
out_unlock:
if (mutex_is_locked(&dev->lock))
mutex_unlock(&dev->lock);
return rc;
}
EXPORT_SYMBOL_GPL(rc_register_device);
void rc_unregister_device(struct rc_dev *dev)
{
if (!dev)
return;
del_timer_sync(&dev->timer_keyup);
if (dev->driver_type == RC_DRIVER_IR_RAW)
ir_raw_event_unregister(dev);
input_unregister_device(dev->input_dev);
dev->input_dev = NULL;
ir_free_table(&dev->rc_map);
IR_dprintk(1, "Freed keycode table\n");
device_unregister(&dev->dev);
}
EXPORT_SYMBOL_GPL(rc_unregister_device);
/*
* Init/exit code for the module. Basically, creates/removes /sys/class/rc
*/
static int __init rc_core_init(void)
{
int rc = class_register(&ir_input_class);
if (rc) {
printk(KERN_ERR "rc_core: unable to register rc class\n");
return rc;
}
/* Initialize/load the decoders/keymap code that will be used */
ir_raw_init();
rc_map_register(&empty_map);
return 0;
}
static void __exit rc_core_exit(void)
{
class_unregister(&ir_input_class);
rc_map_unregister(&empty_map);
}
module_init(rc_core_init);
module_exit(rc_core_exit);
int rc_core_debug; /* ir_debug level (0,1,2) */
EXPORT_SYMBOL_GPL(rc_core_debug);
module_param_named(debug, rc_core_debug, int, 0644);
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
MODULE_LICENSE("GPL");
| kularny/GeniSys.Kernel | drivers/media/rc/rc-main.c | C | gpl-2.0 | 31,186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.