code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
---
layout: default
title: Approximate Visualization
whichOne: 0
label: 'approximate'
---
<div class="row">
<div id="visualization" class="col-md-12 "></div>
</div>
<div class="row">
<p>
As a reminder, you are interested in flights on <strong class="airline"></strong> and flights originating out of <strong class="state"></strong>.
<p>
<p>
You will be able to look at the questions after 10 seconds.
However, you will not be able to look at this visualization again once you clicked "Continue"!
</p>
<form id="nextCheckbox">
<div class="form-group">
<label>
<input disabled type="checkbox" required/> I have carefully looked at the visualization.
</label>
</div>
<div class="form-group col-md-12">
<input disabled type="submit" class="btn btn-primary" value="Continue">
</div>
</form>
</div>
<script>
$(function() {
addFocusStateAndAirline();
});
$('#nextCheckbox').submit(function(e) {
e.preventDefault();
window.location.replace('approximate_questions_first.html');
});
</script>
|
domoritz/bias-study
|
approximate_first.html
|
HTML
|
bsd-3-clause
| 1,138 |
//
// WWCardEditor.h
// WWCardEditor
//
// Created by Dan Grover on 6/19/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "WWCardEditorRow.h"
#import "NSColor+Extras.h"
@interface WWCardEditor : NSView {
BOOL needsLayout;
BOOL editMode;
NSMutableArray *_rows;
NSMutableDictionary *_rowNameIndex;
NSColor *keyLabelColor;
NSFont *keyLabelFont;
CGSize padding;
CGFloat rowSpacing;
CGSize focusRingPadding;
NSColor *backgroundColor;
NSColor *focusRingBorderColor;
NSColor *focusRingBackgroundColor;
}
@property(assign) BOOL editMode;
// Row manipulation
@property(retain,readonly) NSArray *rows;
- (void) addRow:(WWCardEditorRow *)row;
- (void) addRow:(WWCardEditorRow *)row atIndex:(NSUInteger)newRowIndex;
- (void) removeRowAtIndex:(NSUInteger)removeRowIndex;
- (void) removeAllRows;
- (NSDictionary *)rowsByName; // mostly here for bindings support
// Appearance
@property(retain) NSColor *keyLabelColor;
@property(retain) NSFont *keyLabelFont;
@property(retain) NSColor *backgroundColor;
@property(assign) CGSize padding;
@property(assign) CGFloat rowSpacing;
// Appearance: Focus Ring
@property(assign) CGSize focusRingPadding;
@property(retain) NSColor *focusRingBorderColor;
@property(retain) NSColor *focusRingBackgroundColor;
@end
|
dangrover/WWCardEditor
|
WWCardEditor.h
|
C
|
bsd-3-clause
| 1,315 |
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Date parser test — 1000<=x<=9999 and January<=y<=December and 1000<=z<=9999 — 4501/february/3509</title>
<script src="../date_test.js"></script>
<p>Failed (Script did not run)</p>
<script>
test_date_invalid("4501/february/3509", "Invalid Date")
</script>
</html>
|
operasoftware/presto-testo
|
core/features/dateParsing/TestCases/individual/SlashSeparator/938.html
|
HTML
|
bsd-3-clause
| 353 |
<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
/* @var $this \yii\web\View */
/* @var $content string */
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => '<img src='.Yii::$app->request->baseUrl.'/img/logo.png height="35px">',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
'encodeLabel' => false,
],
]);
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']],
Yii::$app->user->isGuest ?
['label' => 'Login', 'url' => ['/site/login']] :
['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']],
],
]);
NavBar::end();
?>
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<div class="container">
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© Kuliah Kita <?= date('Y') ?></p>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
|
yafithekid/itcc-yii
|
views/layouts/main.php
|
PHP
|
bsd-3-clause
| 2,209 |
<?php
namespace unid\view\Helper;
use Zend\Form\View\Helper\Form;
use Zend\Form\View\Helper\FormRow;
use Zend\View\Helper\AbstractHelper;
use Zend\View\Helper;
class BtnHelp extends AbstractHelper
{
public function __invoke($name_table = null)
{
}
}
|
dimajolkin/unid
|
module/unid/src/unid/View/Helper/BtnHelp.php
|
PHP
|
bsd-3-clause
| 264 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/chrome/performance_logger.h"
#include "base/compiler_specific.h"
#include "base/format_macros.h"
#include "base/json/json_reader.h"
#include "base/memory/scoped_vector.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/test/chromedriver/chrome/log.h"
#include "chrome/test/chromedriver/chrome/status.h"
#include "chrome/test/chromedriver/chrome/stub_devtools_client.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class FakeDevToolsClient : public StubDevToolsClient {
public:
explicit FakeDevToolsClient(const std::string& id)
: id_(id), listener_(NULL) {}
virtual ~FakeDevToolsClient() {}
std::string PopSentCommand() {
std::string command;
if (!sent_command_queue_.empty()) {
command = sent_command_queue_.front();
sent_command_queue_.pop_front();
}
return command;
}
Status TriggerEvent(const std::string& method) {
base::DictionaryValue empty_params;
return listener_->OnEvent(this, method, empty_params);
}
// Overridden from DevToolsClient:
virtual Status ConnectIfNecessary() OVERRIDE {
return listener_->OnConnected(this);
}
virtual Status SendCommandAndGetResult(
const std::string& method,
const base::DictionaryValue& params,
scoped_ptr<base::DictionaryValue>* result) OVERRIDE {
sent_command_queue_.push_back(method);
return Status(kOk);
}
virtual void AddListener(DevToolsEventListener* listener) OVERRIDE {
CHECK(!listener_);
listener_ = listener;
}
virtual const std::string& GetId() OVERRIDE {
return id_;
}
private:
const std::string id_; // WebView id.
std::list<std::string> sent_command_queue_; // Commands that were sent.
DevToolsEventListener* listener_; // The fake allows only one event listener.
};
struct LogEntry {
const base::Time timestamp;
const Log::Level level;
const std::string source;
const std::string message;
LogEntry(const base::Time& timestamp,
Log::Level level,
const std::string& source,
const std::string& message)
: timestamp(timestamp), level(level), source(source), message(message) {}
};
class FakeLog : public Log {
public:
virtual void AddEntryTimestamped(const base::Time& timestamp,
Level level,
const std::string& source,
const std::string& message) OVERRIDE;
const ScopedVector<LogEntry>& GetEntries() {
return entries_;
}
private:
ScopedVector<LogEntry> entries_;
};
void FakeLog::AddEntryTimestamped(const base::Time& timestamp,
Level level,
const std::string& source,
const std::string& message) {
entries_.push_back(new LogEntry(timestamp, level, source, message));
}
scoped_ptr<base::DictionaryValue> ParseDictionary(const std::string& json) {
std::string error;
scoped_ptr<base::Value> value(base::JSONReader::ReadAndReturnError(
json, base::JSON_PARSE_RFC, NULL, &error));
if (value == NULL) {
SCOPED_TRACE(json.c_str());
SCOPED_TRACE(error.c_str());
ADD_FAILURE();
return scoped_ptr<base::DictionaryValue>();
}
base::DictionaryValue* dict = NULL;
if (!value->GetAsDictionary(&dict)) {
SCOPED_TRACE("JSON object is not a dictionary");
ADD_FAILURE();
return scoped_ptr<base::DictionaryValue>();
}
return scoped_ptr<base::DictionaryValue>(dict->DeepCopy());
}
void ValidateLogEntry(const LogEntry *entry,
const std::string& expected_webview,
const std::string& expected_method) {
EXPECT_EQ(Log::kInfo, entry->level);
EXPECT_LT(0, entry->timestamp.ToTimeT());
scoped_ptr<base::DictionaryValue> message(ParseDictionary(entry->message));
std::string webview;
EXPECT_TRUE(message->GetString("webview", &webview));
EXPECT_EQ(expected_webview, webview);
std::string method;
EXPECT_TRUE(message->GetString("message.method", &method));
EXPECT_EQ(expected_method, method);
base::DictionaryValue* params;
EXPECT_TRUE(message->GetDictionary("message.params", ¶ms));
EXPECT_EQ(0u, params->size());
}
void ExpectEnableDomains(FakeDevToolsClient& client) {
EXPECT_EQ("Network.enable", client.PopSentCommand());
EXPECT_EQ("Page.enable", client.PopSentCommand());
EXPECT_EQ("Timeline.start", client.PopSentCommand());
EXPECT_TRUE(client.PopSentCommand().empty());
}
} // namespace
TEST(PerformanceLogger, OneWebView) {
FakeDevToolsClient client("webview-1");
FakeLog log;
PerformanceLogger logger(&log);
client.AddListener(&logger);
logger.OnConnected(&client);
ExpectEnableDomains(client);
ASSERT_EQ(kOk, client.TriggerEvent("Network.gaga").code());
ASSERT_EQ(kOk, client.TriggerEvent("Page.ulala").code());
// Ignore -- different domain.
ASSERT_EQ(kOk, client.TriggerEvent("Console.bad").code());
ASSERT_EQ(2u, log.GetEntries().size());
ValidateLogEntry(log.GetEntries()[0], "webview-1", "Network.gaga");
ValidateLogEntry(log.GetEntries()[1], "webview-1", "Page.ulala");
}
TEST(PerformanceLogger, TwoWebViews) {
FakeDevToolsClient client1("webview-1");
FakeDevToolsClient client2("webview-2");
FakeLog log;
PerformanceLogger logger(&log);
client1.AddListener(&logger);
client2.AddListener(&logger);
logger.OnConnected(&client1);
logger.OnConnected(&client2);
ExpectEnableDomains(client1);
ExpectEnableDomains(client2);
// OnConnected sends the enable command only to that client, not others.
client1.ConnectIfNecessary();
ExpectEnableDomains(client1);
EXPECT_TRUE(client2.PopSentCommand().empty());;
ASSERT_EQ(kOk, client1.TriggerEvent("Page.gaga1").code());
ASSERT_EQ(kOk, client2.TriggerEvent("Timeline.gaga2").code());
ASSERT_EQ(2u, log.GetEntries().size());
ValidateLogEntry(log.GetEntries()[0], "webview-1", "Page.gaga1");
ValidateLogEntry(log.GetEntries()[1], "webview-2", "Timeline.gaga2");
}
|
ChromiumWebApps/chromium
|
chrome/test/chromedriver/chrome/performance_logger_unittest.cc
|
C++
|
bsd-3-clause
| 6,173 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.4.7 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li id="current"><a href="classes.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li>
<form action="search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="classes.html"><span>Alphabetical List</span></a></li>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul></div>
<h1>X86ISA::Cmos Member List</h1>This is the complete list of members for <a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a>, including all inherited members.<p><table>
<tr class="memlist"><td><a class="el" href="classSimObject.html#99880551669bb51d749676f678b1dcc8">_params</a></td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#810db840bcb42bfe27b01844cf0f1535">address</a></td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classBasicPioDevice.html#8be07f328531a7ca5b7614fcb0561b6e">BasicPioDevice</a>(const Params *p, Addr size)</td><td><a class="el" href="classBasicPioDevice.html">BasicPioDevice</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#3edd16fe55d68f6610ea38ba8a2e0543">ckptCount</a></td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#a55994e6905bd7a5a739df8b748fe749">ckptMaxCount</a></td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#2ddcadfd3045221bee368bddb20a9f9f">ckptPrevCount</a></td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#7c1f64c925f158530be84323a503dbb7">clockEdge</a>(Cycles cycles=Cycles(0)) const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#96a2ae6db10010713f6c0752df74bba3">ClockedObject</a>(const ClockedObjectParams *p)</td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline, protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#3f0850d695e3722cdd7d33bbaf3e5f43">clockPeriod</a>() const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#d41c3b9f9b6b8637752ab71d69265e6e">Cmos</a>(const Params *p)</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#68726f5d7b8d0ed986338a2d09cdf720">create</a>(Checkpoint *cp, const std::string &section)</td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#2b4a36a0ae697fe2c7c1c493146d7626">curCycle</a>() const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#92b58a82b7a2bb4935f41bc4d46897b6">deschedule</a>(Event &event)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#6834e6eef71b36faddc8bbb34c3a7921">deschedule</a>(Event *event)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#ad86b785c0dca25037d8bb6dbab3969d">drain</a>(DrainManager *drainManger)</td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#c2b5f739cc6ae6bdb563763a1f3c40f9">Drainable</a>()</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#6173416423af6af1bfe17262be40b5ffd08d746efca2f68aeb28f73f94237603">Drained</a> enum value</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#6173416423af6af1bfe17262be40b5ffbd11bb9d2e9941029e08925c2a151162">Draining</a> enum value</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#795e610b1a9aeadc5b4e08b9f00f8ac6">drainResume</a>()</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#1615421c4ebad9c6625394d6c889914d">EventManager</a>(EventManager &em)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#7e1c3864ced0af1cd527168d9582809c">EventManager</a>(EventManager *em)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#ef6c70fb03067c32dcae627c25d92e7c">EventManager</a>(EventQueue *eq)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#e80b5045b34395c55d6c482335a4a0da">eventq</a></td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#35b83dad6cd0af3227f99d67445d1527">eventQueue</a>() const </td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#2d22556f4a5c932a267783fd33f4db79">find</a>(const char *name)</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#cb83f8dd8f412e23d09f1d390eaf13cf">frequency</a>() const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classBasicPioDevice.html#186dbf8f42c6825a0056726390d09e95">getAddrRanges</a>() const </td><td><a class="el" href="classBasicPioDevice.html">BasicPioDevice</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#0e5f525d2e1df1af3e87ce17530b40dc">getDrainState</a>() const </td><td><a class="el" href="classDrainable.html">Drainable</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classMemObject.html#a37deab2c27a8c2f8151ff679238fe30">getMasterPort</a>(const std::string &if_name, PortID idx=InvalidPortID)</td><td><a class="el" href="classMemObject.html">MemObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#b6f8b1c9e7c8239917c9b27254c5fe82">getProbeManager</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#55727db5fb51a8d39bf0cd7087b2c6a4">getSlavePort</a>(const std::string &if_name, PortID idx=InvalidPortID)</td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#34c2d498ef4b98bd3eed24723b8bad6b">init</a>()</td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#a16bbabf9a8b4ca9a6ecf36ca73e3590">initState</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#bd961733f4a33e83fbde246dba271b2d">latency</a></td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#d4e39678d8d748d0e774dfa97cbb7f33">loadState</a>(Checkpoint *cp)</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#ae461d54fc843a1e3570490b01e56945">memInvalidate</a>()</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td><code> [inline, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classMemObject.html#30a3a55dce17c5a579b76192bb9d70ca">MemObject</a>(const Params *params)</td><td><a class="el" href="classMemObject.html">MemObject</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#cf323efe6856218c6cdfde5b0ec3653d">memWriteback</a>()</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td><code> [inline, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#96c36bff06d98deb79d09e93652667ae">name</a>() const </td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [inline, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#23ac872f198ad03a95312016697de6b8">nameOut</a>(std::ostream &os)</td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#bc60ad53a35fe310f7c6a4bf43ae3d91">nameOut</a>(std::ostream &os, const std::string &_name)</td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#feec54486c377fa6d0825f9d24d64ab3">nextCycle</a>() const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#1e8f3e81d58b678473996cd624824b21">numRegs</a></td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [protected, static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classBasicPioDevice.html#652336b987a2686f6674ce3bf6378002">params</a>() const </td><td><a class="el" href="classBasicPioDevice.html">BasicPioDevice</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#10d86b78163445b9020ad7323033a6cb">Params</a> typedef</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classBasicPioDevice.html#338811b1320af1a601bef191177979ac">pioAddr</a></td><td><a class="el" href="classBasicPioDevice.html">BasicPioDevice</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classBasicPioDevice.html#d670b28b059714bd909327e2cedbab93">pioDelay</a></td><td><a class="el" href="classBasicPioDevice.html">BasicPioDevice</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#9455babd49d227f2bf00b334553534b9">PioDevice</a>(const Params *p)</td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#81c4d0791b19b64007a79efe336a65e8">pioPort</a></td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#943f3d8eaf2e9b90571c1f8d4ec74b98">PioPort</a> class</td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td><code> [friend]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classBasicPioDevice.html#99f22fb3bc4d87934cfafc3b768545cc">pioSize</a></td><td><a class="el" href="classBasicPioDevice.html">BasicPioDevice</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#bf6ce14730d90914a97468faefc6d42e">read</a>(PacketPtr pkt)</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#b13dc2de55336171c3c159097530dbac">readRegister</a>(uint8_t reg)</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#77a570384e5db3bdc4fd957b62099b46">regProbeListeners</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#d4ddb182591ccf26615cd14ac123cd99">regProbePoints</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#efabfaaabe68186a5f7de8db243e2b9a">regs</a></td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#fdfbd617cd603ccd8e19c3ceae507261">regStats</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#766c5f955dfa1609696955f075492687">reschedule</a>(Event &event, Tick when, bool always=false)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#9194adbdb2378d04a514caffc92f6f2d">reschedule</a>(Event *event, Tick when, bool always=false)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#73acf3e87bc8e85ca251209857ffb09c">resetClock</a>() const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline, protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#bca387b67afac2843f7039c1d800c5b4">resetStats</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#ae642461217164828e5e47d43a22168a">rtc</a></td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#6173416423af6af1bfe17262be40b5ff2cea28320073053047fb4cd4471b5075">Running</a> enum value</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#749a10828b2dd5017a2582960d04e400">schedule</a>(Event &event, Tick when)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#09998a01d7e18bfa8cc54295fdb2a4aa">schedule</a>(Event *event, Tick when)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#e2b10a6d95c9873ede8c4562cc5105be">Serializable</a>()</td><td><a class="el" href="classSerializable.html">Serializable</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#7814118403dd4df8a7ced1326358e00f">serialize</a>(std::ostream &os)</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#78ead9388d9add57a72b5a8bf2dddc87">serializeAll</a>(std::ostream &os)</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#2d8c2282a00cab12c4846f29be035efd">Serializable::serializeAll</a>(const std::string &cpt_dir)</td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classEventManager.html#72fbb95a44858e3542afec61007859da">setCurTick</a>(Tick newVal)</td><td><a class="el" href="classEventManager.html">EventManager</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#fce7a34e1fcacc71267a947a3feb941b">setDrainState</a>(State new_state)</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td><code> [inline, protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#3eba1a6dc1c54b6f154c07a08df3b297">SimObject</a>(const Params *_params)</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#15d30a398e82cab3686d2e9d54fd71a4">startup</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#6173416423af6af1bfe17262be40b5ff">State</a> enum name</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#e9a625f7038edc40a855f58b011bd2d4">sys</a></td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#0ed1c09106348a3fcd72ea19909256c1">ticksToCycles</a>(Tick t) const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#4b4b3f03c81f2fabb553277627be49d7">unserialize</a>(Checkpoint *cp, const std::string &section)</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#1f01655ee853d9b3f481a06428f1502b">unserializeGlobals</a>(Checkpoint *cp)</td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [static]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#6bd1f01b9f8ce80129cada1069819149">updateClockPeriod</a>() const </td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#cd174cdb339e8c6ba670f9a0608426e3">write</a>(PacketPtr pkt)</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classX86ISA_1_1Cmos.html#eb4eede9beb56df1d4a6605a508f57a0">writeRegister</a>(uint8_t reg, uint8_t val)</td><td><a class="el" href="classX86ISA_1_1Cmos.html">X86ISA::Cmos</a></td><td><code> [protected]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classClockedObject.html#54d224b94fea4994df25f320c5391300">~ClockedObject</a>()</td><td><a class="el" href="classClockedObject.html">ClockedObject</a></td><td><code> [inline, protected, virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classDrainable.html#c41cf77f0309d150245b592d5f7c3c01">~Drainable</a>()</td><td><a class="el" href="classDrainable.html">Drainable</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classPioDevice.html#8e3ba9811be53d4b534ad008996cf4c6">~PioDevice</a>()</td><td><a class="el" href="classPioDevice.html">PioDevice</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSerializable.html#aae29a43e8b1a24b0f107129b5af7e14">~Serializable</a>()</td><td><a class="el" href="classSerializable.html">Serializable</a></td><td><code> [virtual]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classSimObject.html#5ad9e70d2845434235780f39d95906f2">~SimObject</a>()</td><td><a class="el" href="classSimObject.html">SimObject</a></td><td><code> [virtual]</code></td></tr>
</table><hr size="1"><address style="align: right;"><small>
Generated on Fri Apr 17 12:42:25 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address>
</body>
</html>
|
wnoc-drexel/gem5-stable
|
src/doxygen/html/classX86ISA_1_1Cmos-members.html
|
HTML
|
bsd-3-clause
| 22,363 |
/*
* 2007 2013 Copyright Northwestern University
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
*/
#pragma once
#ifndef _AIMLib_Quantile_Class_
#define _AIMLib_Quantile_Class_
#include <string>
namespace aim_lib
{
class AIMLIB_API Quantile : public CharacteristicQuantification
{
public:
Quantile(void);
Quantile(const Quantile& quantile);
virtual ~Quantile(void);
Quantile& operator=(const Quantile& quantile);
virtual Quantile* Clone() const;
const QuantificationType GetQuantificationType() const;
int GetBins() const;
double GetMinValue() const;
double GetMaxValue() const;
int GetSelectedBin() const;
void SetBins(int newVal);
void SetMinValue(double minValue);
void SetMaxValue(double maxValue);
void SetSelectedBin(int selectedBin);
protected:
int _bins;
double _minValue;
double _maxValue;
int _selectedBin;
};
}
#endif // _AIMLib_Quantile_Class_
|
NCIP/annotation-and-image-markup
|
AIMToolkit_v4.0.0_rv44/source/AIMLib/AIMLib/entity/Quantile.h
|
C
|
bsd-3-clause
| 1,048 |
/**
* Created on: Jan 25, 2013
*/
package com.tubros.constraints.api
import org.junit.runner.RunWith
import org.scalacheck._
import org.scalatest.junit.JUnitRunner
/**
* The '''VariableNameSpec''' type exercises the
* [[com.tubros.constraints.api.VariableName]] abstraction. Since this is a
* fundamental (and simple) type, there's not a bunch to test.
*
* @author svickers
*
*/
@RunWith (classOf[JUnitRunner])
class VariableNameSpec
extends ProjectSpec
{
/// Class Imports
val nameGenerator = Gen.alphaStr;
"A VariableName" should "be creatable with only a Symbol" in
{
val name = VariableName ('x);
name shouldNot be (null);
}
it should "retain the symbolic name it was given" in
{
val name = VariableName ('a);
name.name shouldBe ("a");
}
it should "accept any valid Symbol" in
{
check (
Prop.forAll (nameGenerator) {
candidate =>
VariableName (Symbol (candidate)).name == candidate;
}
);
}
it should "be able to promote a Symbol" in
{
val converted : VariableName = 'anId;
converted should be (FastSymbol ("anId"));
}
}
|
osxhacker/smocs
|
smocs-api/src/test/scala/com/tubros/constraints/api/VariableNameSpec.scala
|
Scala
|
bsd-3-clause
| 1,109 |
package drum
import (
"fmt"
"path"
"testing"
)
func TestEncodeFile(t *testing.T) {
tData := []struct {
pat *Pattern
path string
}{
// Your everyday Dubstep beat
{
pat: &Pattern{
Version: "GoDrum-0.1.0",
Tempo: 140,
Tracks: []*Track{
{
ID: 0,
Name: "Kick",
Steps: [16]byte{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
},
{
ID: 1,
Name: "Snare",
Steps: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
},
{
ID: 2,
Name: "HiHat",
Steps: [16]byte{1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
},
},
},
path: "dubstep_pattern.splice",
},
{
pat: &Pattern{
Version: "GoDrum-0.1.0",
Tempo: 110,
Tracks: []*Track{
{
ID: 0,
Name: "kick",
Steps: [16]byte{1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0},
},
{
ID: 1,
Name: "snare",
Steps: [16]byte{0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0},
},
{
ID: 2,
Name: "hi-hat",
Steps: [16]byte{0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0},
},
},
},
path: "mombathon.splice",
},
}
for _, exp := range tData {
pth := path.Join("fixtures", exp.path)
if err := EncodeFile(pth, exp.pat); err != nil {
t.Fatalf("Something went wrong while encoding %s: %v", pth, err)
}
decoded, err := DecodeFile(pth)
if err != nil {
t.Fatalf("something went wrong while decoding %s: %v", pth, err)
}
if fmt.Sprint(decoded) != fmt.Sprint(exp.pat) {
t.Logf("decoded:\n%#v\n", fmt.Sprint(decoded))
t.Logf("expected:\n%#v\n", fmt.Sprint(exp.pat))
t.Fatalf("%s wasn't decoded as expect.\nGot:\n%s\nExpected:\n%s",
pth, decoded, exp.pat)
}
}
}
|
GoChallenge/GCSolutions
|
march15/normal/corey-powell/golang-challenge-1/encoder_test.go
|
GO
|
bsd-3-clause
| 1,777 |
#define SWITCH
#include "aabb.h"
extern inline AABB *
aabb(double x, double y, double z);
#include "type.c"
|
brokenshakles/Engineer
|
source/library/type/aabb.c
|
C
|
bsd-3-clause
| 111 |
package singhdas
import (
"crypto/elliptic"
"crypto/rand"
"github.com/ronperry/cryptoedge/eccutil"
"testing"
)
func Test_GenericRequest(t *testing.T) {
c := eccutil.SetCurve(elliptic.P256, rand.Reader, eccutil.Sha1Hash)
privkey, pubkey, err := c.GenerateKey()
if err != nil {
t.Fatalf("Error creating keys: %s", err)
}
signer := NewGenericBlindingServer(privkey, pubkey, c)
clientParams, serverParams, err := signer.GetParams()
if err != nil {
t.Errorf("Error occured throughout parameter creation: %s", err)
}
_, _ = clientParams, serverParams
}
func Test_GenericBlind(t *testing.T) {
msg := []byte("Message to be blinded")
c := eccutil.SetCurve(elliptic.P256, rand.Reader, eccutil.Sha1Hash)
privkey, pubkey, err := c.GenerateKey()
if err != nil {
t.Fatalf("Error creating keys: %s", err)
}
signer := NewGenericBlindingServer(privkey, pubkey, c)
client := NewGenericBlindingClient(pubkey, c)
clientParams, serverParams, err := signer.GetParams()
if err != nil {
t.Errorf("Error occured throughout parameter creation: %s", err)
}
cm := NewClearMessage(msg)
clientFactors, blindMessage, err := client.Blind(clientParams, cm)
if err != nil {
t.Errorf("Error occured throughout blinding: %s", err)
}
_, _, _, _, _ = clientParams, serverParams, client, clientFactors, blindMessage
_, _, _, _, _, _, _ = msg, client, clientParams, serverParams, cm, clientFactors, blindMessage
}
// func Test_GenericSign(t *testing.T) {
// msg := []byte("Message to be blinded")
// c := eccutil.SetCurve(elliptic.P256, rand.Reader, eccutil.Sha1Hash)
// privkey, pubkey, err := c.GenerateKey()
// if err != nil {
// t.Fatalf("Error creating keys: %s", err)
// }
// signer := NewGenericBlindingServer(privkey, pubkey, c)
// client := NewGenericBlindingClient(pubkey, c)
// clientParams, serverParams, err := signer.GetParams()
// if err != nil {
// t.Errorf("Error occured throughout parameter creation: %s", err)
// }
// cm := NewClearMessage(msg)
// clientFactors, blindMessage, err := client.Blind(clientParams, cm)
// if err != nil {
// t.Errorf("Error occured throughout blinding: %s", err)
// }
// blindsignature, err := signer.Sign(serverParams, blindMessage)
// if err != nil {
// t.Errorf("Error occured throughout signing: %s", err)
// }
// _, _, _, _, _ = clientParams, blindsignature, client, clientFactors, blindMessage
// }
// func Test_GenericUnBlind(t *testing.T) {
// msg := []byte("Message to be blinded")
// c := eccutil.SetCurve(elliptic.P256, rand.Reader, eccutil.Sha1Hash)
// privkey, pubkey, err := c.GenerateKey()
// if err != nil {
// t.Fatalf("Error creating keys: %s", err)
// }
// signer := NewGenericBlindingServer(privkey, pubkey, c)
// client := NewGenericBlindingClient(pubkey, c)
// clientParams, serverParams, err := signer.GetParams()
// if err != nil {
// t.Errorf("Error occured throughout parameter creation: %s", err)
// }
// cm := NewClearMessage(msg)
// clientFactors, blindMessage, err := client.Blind(clientParams, cm)
// if err != nil {
// t.Errorf("Error occured throughout blinding: %s", err)
// }
// blindsignature, err := signer.Sign(serverParams, blindMessage)
// if err != nil {
// t.Errorf("Error occured throughout signing: %s", err)
// }
// clearsig, clearmsg, err := client.Unblind(clientFactors, cm, blindsignature)
// if err != nil {
// t.Errorf("Error occured throughout unblinding: %s", err)
// }
// _, _, _, _, _ = clearsig, clearmsg, client, clientFactors, blindMessage
// }
// func Test_GenericVerify(t *testing.T) {
// msg := []byte("Message to be blinded")
// c := eccutil.SetCurve(elliptic.P256, rand.Reader, eccutil.Sha1Hash)
// privkey, pubkey, err := c.GenerateKey()
// if err != nil {
// t.Fatalf("Error creating keys: %s", err)
// }
// signer := NewGenericBlindingServer(privkey, pubkey, c)
// client := NewGenericBlindingClient(pubkey, c)
// clientParams, serverParams, err := signer.GetParams()
// if err != nil {
// t.Errorf("Error occured throughout parameter creation: %s", err)
// }
// cm := NewClearMessage(msg)
// clientFactors, blindMessage, err := client.Blind(clientParams, cm)
// if err != nil {
// t.Errorf("Error occured throughout blinding: %s", err)
// }
// blindsignature, err := signer.Sign(serverParams, blindMessage)
// if err != nil {
// t.Errorf("Error occured throughout signing: %s", err)
// }
// clearsig, clearmsg, err := client.Unblind(clientFactors, cm, blindsignature)
// if err != nil {
// t.Errorf("Error occured throughout unblinding: %s", err)
// }
// ok, err := client.Verify(clearsig, clearmsg)
// if err != nil {
// t.Errorf("Error occured throughout verify: %s", err)
// }
// if !ok {
// t.Error("Message does not verify")
// }
// _, _, _, _, _ = clearsig, clearmsg, client, clientFactors, blindMessage
// }
|
ronperry/cryptoedge
|
singhdas/generic_test.go
|
GO
|
bsd-3-clause
| 4,836 |
/********************************************************
*
* C register defines file
* Project: Secret Flow (secret_flow)
* Description: Secret Flow Switch
*
********************************************************/
#ifndef _REG_DEFINES_SECRET_FLOW_
#define _REG_DEFINES_SECRET_FLOW_
/* ========= Version Information ========= */
#define DEVICE_ID 3
#define DEVICE_MAJOR 1
#define DEVICE_MINOR 0
#define DEVICE_REVISION 1
#define DEVICE_PROJ_DIR "secret_flow"
#define DEVICE_PROJ_NAME "Secret Flow"
#define DEVICE_PROJ_DESC "Secret Flow Switch"
/* ========= Constants ========= */
// ===== File: lib/verilog/core/common/xml/global.xml =====
// Maximum number of phy ports
#define MAX_PHY_PORTS 4
// PCI address bus width
#define PCI_ADDR_WIDTH 32
// PCI data bus width
#define PCI_DATA_WIDTH 32
// PCI byte enable bus width
#define PCI_BE_WIDTH 4
// CPCI--CNET address bus width. This is byte addresses even though bottom bits are zero.
#define CPCI_CNET_ADDR_WIDTH 27
// CPCI--CNET data bus width
#define CPCI_CNET_DATA_WIDTH 32
// CPCI--Virtex address bus width. This is byte addresses even though bottom bits are zero.
#define CPCI_NF2_ADDR_WIDTH 27
// CPCI--Virtex data bus width
#define CPCI_NF2_DATA_WIDTH 32
// DMA data bus width
#define DMA_DATA_WIDTH 32
// DMA control bus width
#define DMA_CTRL_WIDTH 4
// CPCI debug bus width
#define CPCI_DEBUG_DATA_WIDTH 29
// SRAM address width
#define SRAM_ADDR_WIDTH 19
// SRAM data width
#define SRAM_DATA_WIDTH 36
// DRAM address width
#define DRAM_ADDR_WIDTH 24
// ===== File: lib/verilog/core/common/xml/nf_defines.xml =====
// Clock period of 125 MHz clock in ns
#define FAST_CLK_PERIOD 8
// Clock period of 62.5 MHz clock in ns
#define SLOW_CLK_PERIOD 16
// Header value used by the IO queues
#define IO_QUEUE_STAGE_NUM 0xff
// Data path data width
#define DATA_WIDTH 64
// Data path control width
#define CTRL_WIDTH 8
// ===== File: lib/verilog/core/output_queues/sram_rr_output_queues/xml/sram_rr_output_queues.xml =====
#define NUM_OUTPUT_QUEUES 8
#define OQ_DEFAULT_MAX_PKTS 0x7ffff
#define OQ_SRAM_PKT_CNT_WIDTH 19
#define OQ_SRAM_WORD_CNT_WIDTH 19
#define OQ_SRAM_BYTE_CNT_WIDTH 19
#define OQ_ENABLE_SEND_BIT_NUM 0
#define OQ_INITIALIZE_OQ_BIT_NUM 1
// ===== File: lib/verilog/core/utils/xml/device_id_reg.xml =====
// Total number of registers
#define DEV_ID_NUM_REGS 64
// Number of non string registers
#define DEV_ID_NON_STR_REGS 7
// Length of MD5 sum (bits)
#define DEV_ID_MD5SUM_LENGTH 128
// Project directory length (in words, not chars)
#define DEV_ID_PROJ_DIR_WORD_LEN 16
// Project directory length (in bytes/chars)
#define DEV_ID_PROJ_DIR_BYTE_LEN 64
// Project directory length (in bits)
#define DEV_ID_PROJ_DIR_BIT_LEN 512
// Project name length (in words, not chars)
#define DEV_ID_PROJ_NAME_WORD_LEN 16
// Project name length (in bytes/chars)
#define DEV_ID_PROJ_NAME_BYTE_LEN 64
// Project name length (in bits)
#define DEV_ID_PROJ_NAME_BIT_LEN 512
// Device description length (in words, not chars)
#define DEV_ID_PROJ_DESC_WORD_LEN 25
// Device description length (in bytes/chars)
#define DEV_ID_PROJ_DESC_BYTE_LEN 100
// Device description length (in bits)
#define DEV_ID_PROJ_DESC_BIT_LEN 800
// MD5 identifier (v1): MD5 sum of the string "device_id.v"
#define DEV_ID_MD5_VALUE_V1 0x4071736d8a603d2b4d55f62989a73c95
#define DEV_ID_MD5_VALUE_V1_0 0x4071736d
#define DEV_ID_MD5_VALUE_V1_1 0x8a603d2b
#define DEV_ID_MD5_VALUE_V1_2 0x4d55f629
#define DEV_ID_MD5_VALUE_V1_3 0x89a73c95
// MD5 identifier (v2): MD5 sum of the string "device_id.v:v2"
#define DEV_ID_MD5_VALUE_V2 0x5e461ffe439725c9279a22a1855f6c53
#define DEV_ID_MD5_VALUE_V2_0 0x5e461ffe
#define DEV_ID_MD5_VALUE_V2_1 0x439725c9
#define DEV_ID_MD5_VALUE_V2_2 0x279a22a1
#define DEV_ID_MD5_VALUE_V2_3 0x855f6c53
// Total number of registers (v1)
#define DEV_ID_NUM_REGS_V1 64
// Number of non string registers (v1)
#define DEV_ID_NON_STR_REGS_V1 7
// Project name length (v1: in words, not chars)
#define DEV_ID_PROJ_NAME_WORD_LEN_V1 25
// Project name length (v1: in bytes/chars)
#define DEV_ID_PROJ_NAME_BYTE_LEN_V1 100
// Project name length (v1: in bits)
#define DEV_ID_PROJ_NAME_BIT_LEN_V1 800
// ===== File: lib/verilog/core/io_queues/cpu_dma_queue/xml/cpu_dma_queue.xml =====
#define CPU_QUEUE_REGS_ENABLE 0x00000000
#define CPU_QUEUE_REGS_DISABLE 0x00000001
// ===== File: lib/verilog/core/io_queues/ethernet_queue/xml/ethernet_mac.xml =====
// TX queue disable bit
#define MAC_GRP_TX_QUEUE_DISABLE_BIT_NUM 0
// RX queue disable bit
#define MAC_GRP_RX_QUEUE_DISABLE_BIT_NUM 1
// Reset MAC bit
#define MAC_GRP_RESET_MAC_BIT_NUM 2
// MAC TX queue disable bit
#define MAC_GRP_MAC_DISABLE_TX_BIT_NUM 3
// MAC RX queue disable bit
#define MAC_GRP_MAC_DISABLE_RX_BIT_NUM 4
// MAC disable jumbo TX bit
#define MAC_GRP_MAC_DIS_JUMBO_TX_BIT_NUM 5
// MAC disable jumbo RX bit
#define MAC_GRP_MAC_DIS_JUMBO_RX_BIT_NUM 6
// MAC disable crc check disable bit
#define MAC_GRP_MAC_DIS_CRC_CHECK_BIT_NUM 7
// MAC disable crc generate bit
#define MAC_GRP_MAC_DIS_CRC_GEN_BIT_NUM 8
/* ========= Modules ========= */
// Module tags
#define CORE_BASE_ADDR 0x0000000
#define DEV_ID_BASE_ADDR 0x0400000
#define MDIO_BASE_ADDR 0x0440000
#define DMA_BASE_ADDR 0x0500000
#define MAC_GRP_0_BASE_ADDR 0x0600000
#define MAC_GRP_1_BASE_ADDR 0x0640000
#define MAC_GRP_2_BASE_ADDR 0x0680000
#define MAC_GRP_3_BASE_ADDR 0x06c0000
#define CPU_QUEUE_0_BASE_ADDR 0x0700000
#define CPU_QUEUE_1_BASE_ADDR 0x0740000
#define CPU_QUEUE_2_BASE_ADDR 0x0780000
#define CPU_QUEUE_3_BASE_ADDR 0x07c0000
#define SRAM_BASE_ADDR 0x1000000
#define UDP_BASE_ADDR 0x2000000
#define SECRET_FLOW_BASE_ADDR 0x2000000
#define SWITCH_OP_LUT_BASE_ADDR 0x2000100
#define IN_ARB_BASE_ADDR 0x2000200
#define OQ_BASE_ADDR 0x2001000
#define DRAM_BASE_ADDR 0x4000000
#define CPU_QUEUE_OFFSET 0x0040000
#define MAC_GRP_OFFSET 0x0040000
/* ========== Registers ========== */
// Name: device_id (DEV_ID)
// Description: Device identification
// File: lib/verilog/core/utils/xml/device_id_reg.xml
#define DEV_ID_MD5_0_REG 0x0400000
#define DEV_ID_MD5_1_REG 0x0400004
#define DEV_ID_MD5_2_REG 0x0400008
#define DEV_ID_MD5_3_REG 0x040000c
#define DEV_ID_DEVICE_ID_REG 0x0400010
#define DEV_ID_VERSION_REG 0x0400014
#define DEV_ID_CPCI_ID_REG 0x0400018
#define DEV_ID_PROJ_DIR_0_REG 0x040001c
#define DEV_ID_PROJ_DIR_1_REG 0x0400020
#define DEV_ID_PROJ_DIR_2_REG 0x0400024
#define DEV_ID_PROJ_DIR_3_REG 0x0400028
#define DEV_ID_PROJ_DIR_4_REG 0x040002c
#define DEV_ID_PROJ_DIR_5_REG 0x0400030
#define DEV_ID_PROJ_DIR_6_REG 0x0400034
#define DEV_ID_PROJ_DIR_7_REG 0x0400038
#define DEV_ID_PROJ_DIR_8_REG 0x040003c
#define DEV_ID_PROJ_DIR_9_REG 0x0400040
#define DEV_ID_PROJ_DIR_10_REG 0x0400044
#define DEV_ID_PROJ_DIR_11_REG 0x0400048
#define DEV_ID_PROJ_DIR_12_REG 0x040004c
#define DEV_ID_PROJ_DIR_13_REG 0x0400050
#define DEV_ID_PROJ_DIR_14_REG 0x0400054
#define DEV_ID_PROJ_DIR_15_REG 0x0400058
#define DEV_ID_PROJ_NAME_0_REG 0x040005c
#define DEV_ID_PROJ_NAME_1_REG 0x0400060
#define DEV_ID_PROJ_NAME_2_REG 0x0400064
#define DEV_ID_PROJ_NAME_3_REG 0x0400068
#define DEV_ID_PROJ_NAME_4_REG 0x040006c
#define DEV_ID_PROJ_NAME_5_REG 0x0400070
#define DEV_ID_PROJ_NAME_6_REG 0x0400074
#define DEV_ID_PROJ_NAME_7_REG 0x0400078
#define DEV_ID_PROJ_NAME_8_REG 0x040007c
#define DEV_ID_PROJ_NAME_9_REG 0x0400080
#define DEV_ID_PROJ_NAME_10_REG 0x0400084
#define DEV_ID_PROJ_NAME_11_REG 0x0400088
#define DEV_ID_PROJ_NAME_12_REG 0x040008c
#define DEV_ID_PROJ_NAME_13_REG 0x0400090
#define DEV_ID_PROJ_NAME_14_REG 0x0400094
#define DEV_ID_PROJ_NAME_15_REG 0x0400098
#define DEV_ID_PROJ_DESC_0_REG 0x040009c
#define DEV_ID_PROJ_DESC_1_REG 0x04000a0
#define DEV_ID_PROJ_DESC_2_REG 0x04000a4
#define DEV_ID_PROJ_DESC_3_REG 0x04000a8
#define DEV_ID_PROJ_DESC_4_REG 0x04000ac
#define DEV_ID_PROJ_DESC_5_REG 0x04000b0
#define DEV_ID_PROJ_DESC_6_REG 0x04000b4
#define DEV_ID_PROJ_DESC_7_REG 0x04000b8
#define DEV_ID_PROJ_DESC_8_REG 0x04000bc
#define DEV_ID_PROJ_DESC_9_REG 0x04000c0
#define DEV_ID_PROJ_DESC_10_REG 0x04000c4
#define DEV_ID_PROJ_DESC_11_REG 0x04000c8
#define DEV_ID_PROJ_DESC_12_REG 0x04000cc
#define DEV_ID_PROJ_DESC_13_REG 0x04000d0
#define DEV_ID_PROJ_DESC_14_REG 0x04000d4
#define DEV_ID_PROJ_DESC_15_REG 0x04000d8
#define DEV_ID_PROJ_DESC_16_REG 0x04000dc
#define DEV_ID_PROJ_DESC_17_REG 0x04000e0
#define DEV_ID_PROJ_DESC_18_REG 0x04000e4
#define DEV_ID_PROJ_DESC_19_REG 0x04000e8
#define DEV_ID_PROJ_DESC_20_REG 0x04000ec
#define DEV_ID_PROJ_DESC_21_REG 0x04000f0
#define DEV_ID_PROJ_DESC_22_REG 0x04000f4
#define DEV_ID_PROJ_DESC_23_REG 0x04000f8
#define DEV_ID_PROJ_DESC_24_REG 0x04000fc
// Name: mdio (MDIO)
// Description: MDIO interface
// File: lib/verilog/core/io/mdio/xml/mdio.xml
#define MDIO_PHY_0_CONTROL_REG 0x0440000
#define MDIO_PHY_0_STATUS_REG 0x0440004
#define MDIO_PHY_0_PHY_ID_HI_REG 0x0440008
#define MDIO_PHY_0_PHY_ID_LO_REG 0x044000c
#define MDIO_PHY_0_AUTONEGOTIATION_ADVERT_REG 0x0440010
#define MDIO_PHY_0_AUTONEG_LINK_PARTNER_BASE_PAGE_ABILITY_REG 0x0440014
#define MDIO_PHY_0_AUTONEG_EXPANSION_REG 0x0440018
#define MDIO_PHY_0_AUTONEG_NEXT_PAGE_TX_REG 0x044001c
#define MDIO_PHY_0_AUTONEG_LINK_PARTNER_RCVD_NEXT_PAGE_REG 0x0440020
#define MDIO_PHY_0_MASTER_SLAVE_CTRL_REG 0x0440024
#define MDIO_PHY_0_MASTER_SLAVE_STATUS_REG 0x0440028
#define MDIO_PHY_0_PSE_CTRL_REG 0x044002c
#define MDIO_PHY_0_PSE_STATUS_REG 0x0440030
#define MDIO_PHY_0_MMD_ACCESS_CTRL_REG 0x0440034
#define MDIO_PHY_0_MMD_ACCESS_STATUS_REG 0x0440038
#define MDIO_PHY_0_EXTENDED_STATUS_REG 0x044003c
#define MDIO_PHY_0_PHY_EXTENDED_CTRL_REG 0x0440040
#define MDIO_PHY_0_PHY_EXTENDED_STATUS_REG 0x0440044
#define MDIO_PHY_0_RX_ERROR_COUNT_REG 0x0440048
#define MDIO_PHY_0_FALSE_CARRIER_SENSE_COUNT_REG 0x044004c
#define MDIO_PHY_0_RX_NOT_OK_COUNT_REG 0x0440050
#define MDIO_PHY_0_EXPANSION_1_REG 0x0440054
#define MDIO_PHY_0_EXPANSION_2_REG 0x0440058
#define MDIO_PHY_0_EXPANSION_REG_ACCESS_REG 0x044005c
#define MDIO_PHY_0_SHADOW_18_REG 0x0440060
#define MDIO_PHY_0_AUX_STATUS_REG 0x0440064
#define MDIO_PHY_0_INT_STATUS_REG 0x0440068
#define MDIO_PHY_0_INT_MASK_REG 0x044006c
#define MDIO_PHY_0_SHADOW_1C_REG 0x0440070
#define MDIO_PHY_0_SHADOW_1D_REG 0x0440074
#define MDIO_PHY_0_TEST_REG 0x0440078
#define MDIO_PHY_0_RESERVED_REG 0x044007c
#define MDIO_PHY_1_CONTROL_REG 0x0440080
#define MDIO_PHY_1_STATUS_REG 0x0440084
#define MDIO_PHY_1_PHY_ID_HI_REG 0x0440088
#define MDIO_PHY_1_PHY_ID_LO_REG 0x044008c
#define MDIO_PHY_1_AUTONEGOTIATION_ADVERT_REG 0x0440090
#define MDIO_PHY_1_AUTONEG_LINK_PARTNER_BASE_PAGE_ABILITY_REG 0x0440094
#define MDIO_PHY_1_AUTONEG_EXPANSION_REG 0x0440098
#define MDIO_PHY_1_AUTONEG_NEXT_PAGE_TX_REG 0x044009c
#define MDIO_PHY_1_AUTONEG_LINK_PARTNER_RCVD_NEXT_PAGE_REG 0x04400a0
#define MDIO_PHY_1_MASTER_SLAVE_CTRL_REG 0x04400a4
#define MDIO_PHY_1_MASTER_SLAVE_STATUS_REG 0x04400a8
#define MDIO_PHY_1_PSE_CTRL_REG 0x04400ac
#define MDIO_PHY_1_PSE_STATUS_REG 0x04400b0
#define MDIO_PHY_1_MMD_ACCESS_CTRL_REG 0x04400b4
#define MDIO_PHY_1_MMD_ACCESS_STATUS_REG 0x04400b8
#define MDIO_PHY_1_EXTENDED_STATUS_REG 0x04400bc
#define MDIO_PHY_1_PHY_EXTENDED_CTRL_REG 0x04400c0
#define MDIO_PHY_1_PHY_EXTENDED_STATUS_REG 0x04400c4
#define MDIO_PHY_1_RX_ERROR_COUNT_REG 0x04400c8
#define MDIO_PHY_1_FALSE_CARRIER_SENSE_COUNT_REG 0x04400cc
#define MDIO_PHY_1_RX_NOT_OK_COUNT_REG 0x04400d0
#define MDIO_PHY_1_EXPANSION_1_REG 0x04400d4
#define MDIO_PHY_1_EXPANSION_2_REG 0x04400d8
#define MDIO_PHY_1_EXPANSION_REG_ACCESS_REG 0x04400dc
#define MDIO_PHY_1_SHADOW_18_REG 0x04400e0
#define MDIO_PHY_1_AUX_STATUS_REG 0x04400e4
#define MDIO_PHY_1_INT_STATUS_REG 0x04400e8
#define MDIO_PHY_1_INT_MASK_REG 0x04400ec
#define MDIO_PHY_1_SHADOW_1C_REG 0x04400f0
#define MDIO_PHY_1_SHADOW_1D_REG 0x04400f4
#define MDIO_PHY_1_TEST_REG 0x04400f8
#define MDIO_PHY_1_RESERVED_REG 0x04400fc
#define MDIO_PHY_2_CONTROL_REG 0x0440100
#define MDIO_PHY_2_STATUS_REG 0x0440104
#define MDIO_PHY_2_PHY_ID_HI_REG 0x0440108
#define MDIO_PHY_2_PHY_ID_LO_REG 0x044010c
#define MDIO_PHY_2_AUTONEGOTIATION_ADVERT_REG 0x0440110
#define MDIO_PHY_2_AUTONEG_LINK_PARTNER_BASE_PAGE_ABILITY_REG 0x0440114
#define MDIO_PHY_2_AUTONEG_EXPANSION_REG 0x0440118
#define MDIO_PHY_2_AUTONEG_NEXT_PAGE_TX_REG 0x044011c
#define MDIO_PHY_2_AUTONEG_LINK_PARTNER_RCVD_NEXT_PAGE_REG 0x0440120
#define MDIO_PHY_2_MASTER_SLAVE_CTRL_REG 0x0440124
#define MDIO_PHY_2_MASTER_SLAVE_STATUS_REG 0x0440128
#define MDIO_PHY_2_PSE_CTRL_REG 0x044012c
#define MDIO_PHY_2_PSE_STATUS_REG 0x0440130
#define MDIO_PHY_2_MMD_ACCESS_CTRL_REG 0x0440134
#define MDIO_PHY_2_MMD_ACCESS_STATUS_REG 0x0440138
#define MDIO_PHY_2_EXTENDED_STATUS_REG 0x044013c
#define MDIO_PHY_2_PHY_EXTENDED_CTRL_REG 0x0440140
#define MDIO_PHY_2_PHY_EXTENDED_STATUS_REG 0x0440144
#define MDIO_PHY_2_RX_ERROR_COUNT_REG 0x0440148
#define MDIO_PHY_2_FALSE_CARRIER_SENSE_COUNT_REG 0x044014c
#define MDIO_PHY_2_RX_NOT_OK_COUNT_REG 0x0440150
#define MDIO_PHY_2_EXPANSION_1_REG 0x0440154
#define MDIO_PHY_2_EXPANSION_2_REG 0x0440158
#define MDIO_PHY_2_EXPANSION_REG_ACCESS_REG 0x044015c
#define MDIO_PHY_2_SHADOW_18_REG 0x0440160
#define MDIO_PHY_2_AUX_STATUS_REG 0x0440164
#define MDIO_PHY_2_INT_STATUS_REG 0x0440168
#define MDIO_PHY_2_INT_MASK_REG 0x044016c
#define MDIO_PHY_2_SHADOW_1C_REG 0x0440170
#define MDIO_PHY_2_SHADOW_1D_REG 0x0440174
#define MDIO_PHY_2_TEST_REG 0x0440178
#define MDIO_PHY_2_RESERVED_REG 0x044017c
#define MDIO_PHY_3_CONTROL_REG 0x0440180
#define MDIO_PHY_3_STATUS_REG 0x0440184
#define MDIO_PHY_3_PHY_ID_HI_REG 0x0440188
#define MDIO_PHY_3_PHY_ID_LO_REG 0x044018c
#define MDIO_PHY_3_AUTONEGOTIATION_ADVERT_REG 0x0440190
#define MDIO_PHY_3_AUTONEG_LINK_PARTNER_BASE_PAGE_ABILITY_REG 0x0440194
#define MDIO_PHY_3_AUTONEG_EXPANSION_REG 0x0440198
#define MDIO_PHY_3_AUTONEG_NEXT_PAGE_TX_REG 0x044019c
#define MDIO_PHY_3_AUTONEG_LINK_PARTNER_RCVD_NEXT_PAGE_REG 0x04401a0
#define MDIO_PHY_3_MASTER_SLAVE_CTRL_REG 0x04401a4
#define MDIO_PHY_3_MASTER_SLAVE_STATUS_REG 0x04401a8
#define MDIO_PHY_3_PSE_CTRL_REG 0x04401ac
#define MDIO_PHY_3_PSE_STATUS_REG 0x04401b0
#define MDIO_PHY_3_MMD_ACCESS_CTRL_REG 0x04401b4
#define MDIO_PHY_3_MMD_ACCESS_STATUS_REG 0x04401b8
#define MDIO_PHY_3_EXTENDED_STATUS_REG 0x04401bc
#define MDIO_PHY_3_PHY_EXTENDED_CTRL_REG 0x04401c0
#define MDIO_PHY_3_PHY_EXTENDED_STATUS_REG 0x04401c4
#define MDIO_PHY_3_RX_ERROR_COUNT_REG 0x04401c8
#define MDIO_PHY_3_FALSE_CARRIER_SENSE_COUNT_REG 0x04401cc
#define MDIO_PHY_3_RX_NOT_OK_COUNT_REG 0x04401d0
#define MDIO_PHY_3_EXPANSION_1_REG 0x04401d4
#define MDIO_PHY_3_EXPANSION_2_REG 0x04401d8
#define MDIO_PHY_3_EXPANSION_REG_ACCESS_REG 0x04401dc
#define MDIO_PHY_3_SHADOW_18_REG 0x04401e0
#define MDIO_PHY_3_AUX_STATUS_REG 0x04401e4
#define MDIO_PHY_3_INT_STATUS_REG 0x04401e8
#define MDIO_PHY_3_INT_MASK_REG 0x04401ec
#define MDIO_PHY_3_SHADOW_1C_REG 0x04401f0
#define MDIO_PHY_3_SHADOW_1D_REG 0x04401f4
#define MDIO_PHY_3_TEST_REG 0x04401f8
#define MDIO_PHY_3_RESERVED_REG 0x04401fc
#define MDIO_PHY_GROUP_BASE_ADDR 0x0440000
#define MDIO_PHY_GROUP_INST_OFFSET 0x0000080
// Name: dma (DMA)
// Description: DMA transfer module
// File: lib/verilog/core/dma/xml/dma.xml
#define DMA_CTRL_REG 0x0500000
#define DMA_NUM_INGRESS_PKTS_REG 0x0500004
#define DMA_NUM_INGRESS_BYTES_REG 0x0500008
#define DMA_NUM_EGRESS_PKTS_REG 0x050000c
#define DMA_NUM_EGRESS_BYTES_REG 0x0500010
#define DMA_NUM_TIMEOUTS_REG 0x0500014
// Name: nf2_mac_grp (MAC_GRP_0)
// Description: Ethernet MAC group
// File: lib/verilog/core/io_queues/ethernet_queue/xml/ethernet_mac.xml
#define MAC_GRP_0_CONTROL_REG 0x0600000
#define MAC_GRP_0_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0600004
#define MAC_GRP_0_RX_QUEUE_NUM_PKTS_STORED_REG 0x0600008
#define MAC_GRP_0_RX_QUEUE_NUM_PKTS_DROPPED_FULL_REG 0x060000c
#define MAC_GRP_0_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x0600010
#define MAC_GRP_0_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x0600014
#define MAC_GRP_0_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x0600018
#define MAC_GRP_0_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x060001c
#define MAC_GRP_0_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0600020
#define MAC_GRP_0_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0600024
#define MAC_GRP_0_TX_QUEUE_NUM_PKTS_SENT_REG 0x0600028
#define MAC_GRP_0_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x060002c
#define MAC_GRP_0_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x0600030
// Name: nf2_mac_grp (MAC_GRP_1)
// Description: Ethernet MAC group
// File: lib/verilog/core/io_queues/ethernet_queue/xml/ethernet_mac.xml
#define MAC_GRP_1_CONTROL_REG 0x0640000
#define MAC_GRP_1_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0640004
#define MAC_GRP_1_RX_QUEUE_NUM_PKTS_STORED_REG 0x0640008
#define MAC_GRP_1_RX_QUEUE_NUM_PKTS_DROPPED_FULL_REG 0x064000c
#define MAC_GRP_1_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x0640010
#define MAC_GRP_1_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x0640014
#define MAC_GRP_1_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x0640018
#define MAC_GRP_1_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x064001c
#define MAC_GRP_1_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0640020
#define MAC_GRP_1_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0640024
#define MAC_GRP_1_TX_QUEUE_NUM_PKTS_SENT_REG 0x0640028
#define MAC_GRP_1_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x064002c
#define MAC_GRP_1_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x0640030
// Name: nf2_mac_grp (MAC_GRP_2)
// Description: Ethernet MAC group
// File: lib/verilog/core/io_queues/ethernet_queue/xml/ethernet_mac.xml
#define MAC_GRP_2_CONTROL_REG 0x0680000
#define MAC_GRP_2_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0680004
#define MAC_GRP_2_RX_QUEUE_NUM_PKTS_STORED_REG 0x0680008
#define MAC_GRP_2_RX_QUEUE_NUM_PKTS_DROPPED_FULL_REG 0x068000c
#define MAC_GRP_2_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x0680010
#define MAC_GRP_2_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x0680014
#define MAC_GRP_2_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x0680018
#define MAC_GRP_2_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x068001c
#define MAC_GRP_2_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0680020
#define MAC_GRP_2_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0680024
#define MAC_GRP_2_TX_QUEUE_NUM_PKTS_SENT_REG 0x0680028
#define MAC_GRP_2_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x068002c
#define MAC_GRP_2_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x0680030
// Name: nf2_mac_grp (MAC_GRP_3)
// Description: Ethernet MAC group
// File: lib/verilog/core/io_queues/ethernet_queue/xml/ethernet_mac.xml
#define MAC_GRP_3_CONTROL_REG 0x06c0000
#define MAC_GRP_3_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x06c0004
#define MAC_GRP_3_RX_QUEUE_NUM_PKTS_STORED_REG 0x06c0008
#define MAC_GRP_3_RX_QUEUE_NUM_PKTS_DROPPED_FULL_REG 0x06c000c
#define MAC_GRP_3_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x06c0010
#define MAC_GRP_3_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x06c0014
#define MAC_GRP_3_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x06c0018
#define MAC_GRP_3_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x06c001c
#define MAC_GRP_3_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x06c0020
#define MAC_GRP_3_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x06c0024
#define MAC_GRP_3_TX_QUEUE_NUM_PKTS_SENT_REG 0x06c0028
#define MAC_GRP_3_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x06c002c
#define MAC_GRP_3_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x06c0030
// Name: cpu_dma_queue (CPU_QUEUE_0)
// Description: CPU DMA queue
// File: lib/verilog/core/io_queues/cpu_dma_queue/xml/cpu_dma_queue.xml
#define CPU_QUEUE_0_CONTROL_REG 0x0700000
#define CPU_QUEUE_0_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0700004
#define CPU_QUEUE_0_RX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0700008
#define CPU_QUEUE_0_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x070000c
#define CPU_QUEUE_0_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x0700010
#define CPU_QUEUE_0_RX_QUEUE_NUM_UNDERRUNS_REG 0x0700014
#define CPU_QUEUE_0_RX_QUEUE_NUM_OVERRUNS_REG 0x0700018
#define CPU_QUEUE_0_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x070001c
#define CPU_QUEUE_0_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x0700020
#define CPU_QUEUE_0_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0700024
#define CPU_QUEUE_0_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0700028
#define CPU_QUEUE_0_TX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x070002c
#define CPU_QUEUE_0_TX_QUEUE_NUM_UNDERRUNS_REG 0x0700030
#define CPU_QUEUE_0_TX_QUEUE_NUM_OVERRUNS_REG 0x0700034
#define CPU_QUEUE_0_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x0700038
#define CPU_QUEUE_0_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x070003c
// Name: cpu_dma_queue (CPU_QUEUE_1)
// Description: CPU DMA queue
// File: lib/verilog/core/io_queues/cpu_dma_queue/xml/cpu_dma_queue.xml
#define CPU_QUEUE_1_CONTROL_REG 0x0740000
#define CPU_QUEUE_1_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0740004
#define CPU_QUEUE_1_RX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0740008
#define CPU_QUEUE_1_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x074000c
#define CPU_QUEUE_1_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x0740010
#define CPU_QUEUE_1_RX_QUEUE_NUM_UNDERRUNS_REG 0x0740014
#define CPU_QUEUE_1_RX_QUEUE_NUM_OVERRUNS_REG 0x0740018
#define CPU_QUEUE_1_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x074001c
#define CPU_QUEUE_1_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x0740020
#define CPU_QUEUE_1_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0740024
#define CPU_QUEUE_1_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0740028
#define CPU_QUEUE_1_TX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x074002c
#define CPU_QUEUE_1_TX_QUEUE_NUM_UNDERRUNS_REG 0x0740030
#define CPU_QUEUE_1_TX_QUEUE_NUM_OVERRUNS_REG 0x0740034
#define CPU_QUEUE_1_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x0740038
#define CPU_QUEUE_1_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x074003c
// Name: cpu_dma_queue (CPU_QUEUE_2)
// Description: CPU DMA queue
// File: lib/verilog/core/io_queues/cpu_dma_queue/xml/cpu_dma_queue.xml
#define CPU_QUEUE_2_CONTROL_REG 0x0780000
#define CPU_QUEUE_2_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0780004
#define CPU_QUEUE_2_RX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0780008
#define CPU_QUEUE_2_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x078000c
#define CPU_QUEUE_2_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x0780010
#define CPU_QUEUE_2_RX_QUEUE_NUM_UNDERRUNS_REG 0x0780014
#define CPU_QUEUE_2_RX_QUEUE_NUM_OVERRUNS_REG 0x0780018
#define CPU_QUEUE_2_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x078001c
#define CPU_QUEUE_2_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x0780020
#define CPU_QUEUE_2_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x0780024
#define CPU_QUEUE_2_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x0780028
#define CPU_QUEUE_2_TX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x078002c
#define CPU_QUEUE_2_TX_QUEUE_NUM_UNDERRUNS_REG 0x0780030
#define CPU_QUEUE_2_TX_QUEUE_NUM_OVERRUNS_REG 0x0780034
#define CPU_QUEUE_2_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x0780038
#define CPU_QUEUE_2_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x078003c
// Name: cpu_dma_queue (CPU_QUEUE_3)
// Description: CPU DMA queue
// File: lib/verilog/core/io_queues/cpu_dma_queue/xml/cpu_dma_queue.xml
#define CPU_QUEUE_3_CONTROL_REG 0x07c0000
#define CPU_QUEUE_3_RX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x07c0004
#define CPU_QUEUE_3_RX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x07c0008
#define CPU_QUEUE_3_RX_QUEUE_NUM_PKTS_DROPPED_BAD_REG 0x07c000c
#define CPU_QUEUE_3_RX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x07c0010
#define CPU_QUEUE_3_RX_QUEUE_NUM_UNDERRUNS_REG 0x07c0014
#define CPU_QUEUE_3_RX_QUEUE_NUM_OVERRUNS_REG 0x07c0018
#define CPU_QUEUE_3_RX_QUEUE_NUM_WORDS_PUSHED_REG 0x07c001c
#define CPU_QUEUE_3_RX_QUEUE_NUM_BYTES_PUSHED_REG 0x07c0020
#define CPU_QUEUE_3_TX_QUEUE_NUM_PKTS_IN_QUEUE_REG 0x07c0024
#define CPU_QUEUE_3_TX_QUEUE_NUM_PKTS_ENQUEUED_REG 0x07c0028
#define CPU_QUEUE_3_TX_QUEUE_NUM_PKTS_DEQUEUED_REG 0x07c002c
#define CPU_QUEUE_3_TX_QUEUE_NUM_UNDERRUNS_REG 0x07c0030
#define CPU_QUEUE_3_TX_QUEUE_NUM_OVERRUNS_REG 0x07c0034
#define CPU_QUEUE_3_TX_QUEUE_NUM_WORDS_PUSHED_REG 0x07c0038
#define CPU_QUEUE_3_TX_QUEUE_NUM_BYTES_PUSHED_REG 0x07c003c
// Name: SRAM (SRAM)
// Description: SRAM
// Name: secret_flow (SECRET_FLOW)
// Description: Registers for Secret Flow Module
// File: projects/secret_flow/include/secret_flow.xml
#define SECRET_FLOW_KEY_REG 0x2000000
// Name: learning_cam_switch (SWITCH_OP_LUT)
// Description: Output port lookup for learning switch
// File: lib/verilog/core/output_port_lookup/learning_cam_switch/xml/learning_cam_switch.xml
#define SWITCH_OP_LUT_PORTS_MAC_HI_REG 0x2000100
#define SWITCH_OP_LUT_MAC_LO_REG 0x2000104
#define SWITCH_OP_LUT_NUM_HITS_REG 0x2000108
#define SWITCH_OP_LUT_NUM_MISSES_REG 0x200010c
#define SWITCH_OP_LUT_MAC_LUT_RD_ADDR_REG 0x2000110
#define SWITCH_OP_LUT_MAC_LUT_WR_ADDR_REG 0x2000114
// Name: in_arb (IN_ARB)
// Description: Round-robin input arbiter
// File: lib/verilog/core/input_arbiter/rr_input_arbiter/xml/rr_input_arbiter.xml
#define IN_ARB_NUM_PKTS_SENT_REG 0x2000200
#define IN_ARB_LAST_PKT_WORD_0_HI_REG 0x2000204
#define IN_ARB_LAST_PKT_WORD_0_LO_REG 0x2000208
#define IN_ARB_LAST_PKT_CTRL_0_REG 0x200020c
#define IN_ARB_LAST_PKT_WORD_1_HI_REG 0x2000210
#define IN_ARB_LAST_PKT_WORD_1_LO_REG 0x2000214
#define IN_ARB_LAST_PKT_CTRL_1_REG 0x2000218
#define IN_ARB_STATE_REG 0x200021c
// Name: output_queues (OQ)
// Description: SRAM-based output queue using round-robin removal
// File: lib/verilog/core/output_queues/sram_rr_output_queues/xml/sram_rr_output_queues.xml
#define OQ_QUEUE_0_CTRL_REG 0x2001000
#define OQ_QUEUE_0_NUM_PKT_BYTES_STORED_REG 0x2001004
#define OQ_QUEUE_0_NUM_OVERHEAD_BYTES_STORED_REG 0x2001008
#define OQ_QUEUE_0_NUM_PKT_BYTES_REMOVED_REG 0x200100c
#define OQ_QUEUE_0_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001010
#define OQ_QUEUE_0_NUM_PKTS_STORED_REG 0x2001014
#define OQ_QUEUE_0_NUM_PKTS_DROPPED_REG 0x2001018
#define OQ_QUEUE_0_NUM_PKTS_REMOVED_REG 0x200101c
#define OQ_QUEUE_0_ADDR_LO_REG 0x2001020
#define OQ_QUEUE_0_ADDR_HI_REG 0x2001024
#define OQ_QUEUE_0_RD_ADDR_REG 0x2001028
#define OQ_QUEUE_0_WR_ADDR_REG 0x200102c
#define OQ_QUEUE_0_NUM_PKTS_IN_Q_REG 0x2001030
#define OQ_QUEUE_0_MAX_PKTS_IN_Q_REG 0x2001034
#define OQ_QUEUE_0_NUM_WORDS_IN_Q_REG 0x2001038
#define OQ_QUEUE_0_NUM_WORDS_LEFT_REG 0x200103c
#define OQ_QUEUE_0_FULL_THRESH_REG 0x2001040
#define OQ_QUEUE_1_CTRL_REG 0x2001200
#define OQ_QUEUE_1_NUM_PKT_BYTES_STORED_REG 0x2001204
#define OQ_QUEUE_1_NUM_OVERHEAD_BYTES_STORED_REG 0x2001208
#define OQ_QUEUE_1_NUM_PKT_BYTES_REMOVED_REG 0x200120c
#define OQ_QUEUE_1_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001210
#define OQ_QUEUE_1_NUM_PKTS_STORED_REG 0x2001214
#define OQ_QUEUE_1_NUM_PKTS_DROPPED_REG 0x2001218
#define OQ_QUEUE_1_NUM_PKTS_REMOVED_REG 0x200121c
#define OQ_QUEUE_1_ADDR_LO_REG 0x2001220
#define OQ_QUEUE_1_ADDR_HI_REG 0x2001224
#define OQ_QUEUE_1_RD_ADDR_REG 0x2001228
#define OQ_QUEUE_1_WR_ADDR_REG 0x200122c
#define OQ_QUEUE_1_NUM_PKTS_IN_Q_REG 0x2001230
#define OQ_QUEUE_1_MAX_PKTS_IN_Q_REG 0x2001234
#define OQ_QUEUE_1_NUM_WORDS_IN_Q_REG 0x2001238
#define OQ_QUEUE_1_NUM_WORDS_LEFT_REG 0x200123c
#define OQ_QUEUE_1_FULL_THRESH_REG 0x2001240
#define OQ_QUEUE_2_CTRL_REG 0x2001400
#define OQ_QUEUE_2_NUM_PKT_BYTES_STORED_REG 0x2001404
#define OQ_QUEUE_2_NUM_OVERHEAD_BYTES_STORED_REG 0x2001408
#define OQ_QUEUE_2_NUM_PKT_BYTES_REMOVED_REG 0x200140c
#define OQ_QUEUE_2_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001410
#define OQ_QUEUE_2_NUM_PKTS_STORED_REG 0x2001414
#define OQ_QUEUE_2_NUM_PKTS_DROPPED_REG 0x2001418
#define OQ_QUEUE_2_NUM_PKTS_REMOVED_REG 0x200141c
#define OQ_QUEUE_2_ADDR_LO_REG 0x2001420
#define OQ_QUEUE_2_ADDR_HI_REG 0x2001424
#define OQ_QUEUE_2_RD_ADDR_REG 0x2001428
#define OQ_QUEUE_2_WR_ADDR_REG 0x200142c
#define OQ_QUEUE_2_NUM_PKTS_IN_Q_REG 0x2001430
#define OQ_QUEUE_2_MAX_PKTS_IN_Q_REG 0x2001434
#define OQ_QUEUE_2_NUM_WORDS_IN_Q_REG 0x2001438
#define OQ_QUEUE_2_NUM_WORDS_LEFT_REG 0x200143c
#define OQ_QUEUE_2_FULL_THRESH_REG 0x2001440
#define OQ_QUEUE_3_CTRL_REG 0x2001600
#define OQ_QUEUE_3_NUM_PKT_BYTES_STORED_REG 0x2001604
#define OQ_QUEUE_3_NUM_OVERHEAD_BYTES_STORED_REG 0x2001608
#define OQ_QUEUE_3_NUM_PKT_BYTES_REMOVED_REG 0x200160c
#define OQ_QUEUE_3_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001610
#define OQ_QUEUE_3_NUM_PKTS_STORED_REG 0x2001614
#define OQ_QUEUE_3_NUM_PKTS_DROPPED_REG 0x2001618
#define OQ_QUEUE_3_NUM_PKTS_REMOVED_REG 0x200161c
#define OQ_QUEUE_3_ADDR_LO_REG 0x2001620
#define OQ_QUEUE_3_ADDR_HI_REG 0x2001624
#define OQ_QUEUE_3_RD_ADDR_REG 0x2001628
#define OQ_QUEUE_3_WR_ADDR_REG 0x200162c
#define OQ_QUEUE_3_NUM_PKTS_IN_Q_REG 0x2001630
#define OQ_QUEUE_3_MAX_PKTS_IN_Q_REG 0x2001634
#define OQ_QUEUE_3_NUM_WORDS_IN_Q_REG 0x2001638
#define OQ_QUEUE_3_NUM_WORDS_LEFT_REG 0x200163c
#define OQ_QUEUE_3_FULL_THRESH_REG 0x2001640
#define OQ_QUEUE_4_CTRL_REG 0x2001800
#define OQ_QUEUE_4_NUM_PKT_BYTES_STORED_REG 0x2001804
#define OQ_QUEUE_4_NUM_OVERHEAD_BYTES_STORED_REG 0x2001808
#define OQ_QUEUE_4_NUM_PKT_BYTES_REMOVED_REG 0x200180c
#define OQ_QUEUE_4_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001810
#define OQ_QUEUE_4_NUM_PKTS_STORED_REG 0x2001814
#define OQ_QUEUE_4_NUM_PKTS_DROPPED_REG 0x2001818
#define OQ_QUEUE_4_NUM_PKTS_REMOVED_REG 0x200181c
#define OQ_QUEUE_4_ADDR_LO_REG 0x2001820
#define OQ_QUEUE_4_ADDR_HI_REG 0x2001824
#define OQ_QUEUE_4_RD_ADDR_REG 0x2001828
#define OQ_QUEUE_4_WR_ADDR_REG 0x200182c
#define OQ_QUEUE_4_NUM_PKTS_IN_Q_REG 0x2001830
#define OQ_QUEUE_4_MAX_PKTS_IN_Q_REG 0x2001834
#define OQ_QUEUE_4_NUM_WORDS_IN_Q_REG 0x2001838
#define OQ_QUEUE_4_NUM_WORDS_LEFT_REG 0x200183c
#define OQ_QUEUE_4_FULL_THRESH_REG 0x2001840
#define OQ_QUEUE_5_CTRL_REG 0x2001a00
#define OQ_QUEUE_5_NUM_PKT_BYTES_STORED_REG 0x2001a04
#define OQ_QUEUE_5_NUM_OVERHEAD_BYTES_STORED_REG 0x2001a08
#define OQ_QUEUE_5_NUM_PKT_BYTES_REMOVED_REG 0x2001a0c
#define OQ_QUEUE_5_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001a10
#define OQ_QUEUE_5_NUM_PKTS_STORED_REG 0x2001a14
#define OQ_QUEUE_5_NUM_PKTS_DROPPED_REG 0x2001a18
#define OQ_QUEUE_5_NUM_PKTS_REMOVED_REG 0x2001a1c
#define OQ_QUEUE_5_ADDR_LO_REG 0x2001a20
#define OQ_QUEUE_5_ADDR_HI_REG 0x2001a24
#define OQ_QUEUE_5_RD_ADDR_REG 0x2001a28
#define OQ_QUEUE_5_WR_ADDR_REG 0x2001a2c
#define OQ_QUEUE_5_NUM_PKTS_IN_Q_REG 0x2001a30
#define OQ_QUEUE_5_MAX_PKTS_IN_Q_REG 0x2001a34
#define OQ_QUEUE_5_NUM_WORDS_IN_Q_REG 0x2001a38
#define OQ_QUEUE_5_NUM_WORDS_LEFT_REG 0x2001a3c
#define OQ_QUEUE_5_FULL_THRESH_REG 0x2001a40
#define OQ_QUEUE_6_CTRL_REG 0x2001c00
#define OQ_QUEUE_6_NUM_PKT_BYTES_STORED_REG 0x2001c04
#define OQ_QUEUE_6_NUM_OVERHEAD_BYTES_STORED_REG 0x2001c08
#define OQ_QUEUE_6_NUM_PKT_BYTES_REMOVED_REG 0x2001c0c
#define OQ_QUEUE_6_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001c10
#define OQ_QUEUE_6_NUM_PKTS_STORED_REG 0x2001c14
#define OQ_QUEUE_6_NUM_PKTS_DROPPED_REG 0x2001c18
#define OQ_QUEUE_6_NUM_PKTS_REMOVED_REG 0x2001c1c
#define OQ_QUEUE_6_ADDR_LO_REG 0x2001c20
#define OQ_QUEUE_6_ADDR_HI_REG 0x2001c24
#define OQ_QUEUE_6_RD_ADDR_REG 0x2001c28
#define OQ_QUEUE_6_WR_ADDR_REG 0x2001c2c
#define OQ_QUEUE_6_NUM_PKTS_IN_Q_REG 0x2001c30
#define OQ_QUEUE_6_MAX_PKTS_IN_Q_REG 0x2001c34
#define OQ_QUEUE_6_NUM_WORDS_IN_Q_REG 0x2001c38
#define OQ_QUEUE_6_NUM_WORDS_LEFT_REG 0x2001c3c
#define OQ_QUEUE_6_FULL_THRESH_REG 0x2001c40
#define OQ_QUEUE_7_CTRL_REG 0x2001e00
#define OQ_QUEUE_7_NUM_PKT_BYTES_STORED_REG 0x2001e04
#define OQ_QUEUE_7_NUM_OVERHEAD_BYTES_STORED_REG 0x2001e08
#define OQ_QUEUE_7_NUM_PKT_BYTES_REMOVED_REG 0x2001e0c
#define OQ_QUEUE_7_NUM_OVERHEAD_BYTES_REMOVED_REG 0x2001e10
#define OQ_QUEUE_7_NUM_PKTS_STORED_REG 0x2001e14
#define OQ_QUEUE_7_NUM_PKTS_DROPPED_REG 0x2001e18
#define OQ_QUEUE_7_NUM_PKTS_REMOVED_REG 0x2001e1c
#define OQ_QUEUE_7_ADDR_LO_REG 0x2001e20
#define OQ_QUEUE_7_ADDR_HI_REG 0x2001e24
#define OQ_QUEUE_7_RD_ADDR_REG 0x2001e28
#define OQ_QUEUE_7_WR_ADDR_REG 0x2001e2c
#define OQ_QUEUE_7_NUM_PKTS_IN_Q_REG 0x2001e30
#define OQ_QUEUE_7_MAX_PKTS_IN_Q_REG 0x2001e34
#define OQ_QUEUE_7_NUM_WORDS_IN_Q_REG 0x2001e38
#define OQ_QUEUE_7_NUM_WORDS_LEFT_REG 0x2001e3c
#define OQ_QUEUE_7_FULL_THRESH_REG 0x2001e40
#define OQ_QUEUE_GROUP_BASE_ADDR 0x2001000
#define OQ_QUEUE_GROUP_INST_OFFSET 0x0000200
// Name: DRAM (DRAM)
// Description: DRAM
/* ========== Bitmasks ========== */
// Type: oq_control
// File: lib/verilog/core/output_queues/sram_rr_output_queues/xml/sram_rr_output_queues.xml
// Part 1: bit positions
#define OQ_CONTROL_ENABLE_SEND_POS 0
#define OQ_CONTROL_INITIALIZE_OQ_POS 1
// Part 2: masks/values
#define OQ_CONTROL_ENABLE_SEND 0x1
#define OQ_CONTROL_INITIALIZE_OQ 0x2
// Type: dma_iface_ctrl
// Description: DMA interface control register
// File: lib/verilog/core/dma/xml/dma.xml
// Part 1: bit positions
#define DMA_IFACE_CTRL_DISABLE_POS 0
#define DMA_IFACE_CTRL_RESET_POS 1
// Part 2: masks/values
#define DMA_IFACE_CTRL_DISABLE 0x001
#define DMA_IFACE_CTRL_RESET 0x002
// Type: cpu_queue_control
// Description: DMA queue control register
// File: lib/verilog/core/io_queues/cpu_dma_queue/xml/cpu_dma_queue.xml
// Part 1: bit positions
#define CPU_QUEUE_CONTROL_TX_QUEUE_DISABLE_POS 0
#define CPU_QUEUE_CONTROL_RX_QUEUE_DISABLE_POS 1
// Part 2: masks/values
#define CPU_QUEUE_CONTROL_TX_QUEUE_DISABLE 0x001
#define CPU_QUEUE_CONTROL_RX_QUEUE_DISABLE 0x002
// Type: mii_ctrl
// Description: MII control register
// File: lib/verilog/core/io/mdio/xml/mdio.xml
// Part 1: bit positions
#define MII_CTRL_RESET_POS 15
#define MII_CTRL_INTERNAL_LOOPBACK_POS 14
#define MII_CTRL_SPEED_SEL_LO_POS 13
#define MII_CTRL_AUTONEG_ENABLE_POS 12
#define MII_CTRL_PWR_DOWN_POS 11
#define MII_CTRL_ISOLATE_POS 10
#define MII_CTRL_RESTART_AUTONEG_POS 9
#define MII_CTRL_DUPLEX_MODE_POS 8
#define MII_CTRL_COLLISION_TEST_EN_POS 7
#define MII_CTRL_SPEED_SEL_HI_POS 6
// Part 2: masks/values
#define MII_CTRL_RESET 0x8000
#define MII_CTRL_INTERNAL_LOOPBACK 0x4000
#define MII_CTRL_SPEED_SEL_LO 0x2000
#define MII_CTRL_AUTONEG_ENABLE 0x1000
#define MII_CTRL_PWR_DOWN 0x0800
#define MII_CTRL_ISOLATE 0x0400
#define MII_CTRL_RESTART_AUTONEG 0x0200
#define MII_CTRL_DUPLEX_MODE 0x0100
#define MII_CTRL_COLLISION_TEST_EN 0x0080
#define MII_CTRL_SPEED_SEL_HI 0x0040
// Type: mii_status
// Description: MII status register
// File: lib/verilog/core/io/mdio/xml/mdio.xml
// Part 1: bit positions
#define MII_STATUS_100BASE_T4_CAPABLE_POS 15
#define MII_STATUS_100BASE_X_FULL_DPLX_CAPABLE_POS 14
#define MII_STATUS_100BASE_X_HALF_DPLX_CAPABLE_POS 13
#define MII_STATUS_10BASE_T_FULL_DPLX_CAPABLE_POS 12
#define MII_STATUS_10BASE_T_HALF_DPLX_CAPABLE_POS 11
#define MII_STATUS_10BASE_T2_FULL_DPLX_CAPABLE_POS 10
#define MII_STATUS_10BASE_T2_HALF_DPLX_CAPABLE_POS 9
#define MII_STATUS_EXTENDED_STATUS_POS 8
#define MII_STATUS_MF_PREAMBLE_SUPPRESS_POS 6
#define MII_STATUS_AUTONEG_COMPLETE_POS 5
#define MII_STATUS_REMOTE_FAULT_POS 4
#define MII_STATUS_AUTONEG_ABILITY_POS 3
#define MII_STATUS_LINK_STATUS_POS 2
#define MII_STATUS_JABBER_DETECT_POS 1
#define MII_STATUS_EXTENDED_CAPABILITY_POS 0
// Part 2: masks/values
#define MII_STATUS_100BASE_T4_CAPABLE 0x8000
#define MII_STATUS_100BASE_X_FULL_DPLX_CAPABLE 0x4000
#define MII_STATUS_100BASE_X_HALF_DPLX_CAPABLE 0x2000
#define MII_STATUS_10BASE_T_FULL_DPLX_CAPABLE 0x1000
#define MII_STATUS_10BASE_T_HALF_DPLX_CAPABLE 0x0800
#define MII_STATUS_10BASE_T2_FULL_DPLX_CAPABLE 0x0400
#define MII_STATUS_10BASE_T2_HALF_DPLX_CAPABLE 0x0200
#define MII_STATUS_EXTENDED_STATUS 0x0100
#define MII_STATUS_MF_PREAMBLE_SUPPRESS 0x0040
#define MII_STATUS_AUTONEG_COMPLETE 0x0020
#define MII_STATUS_REMOTE_FAULT 0x0010
#define MII_STATUS_AUTONEG_ABILITY 0x0008
#define MII_STATUS_LINK_STATUS 0x0004
#define MII_STATUS_JABBER_DETECT 0x0002
#define MII_STATUS_EXTENDED_CAPABILITY 0x0001
// Type: mac_grp_control
// Description: MAC group control register
// File: lib/verilog/core/io_queues/ethernet_queue/xml/ethernet_mac.xml
// Part 1: bit positions
#define MAC_GRP_CONTROL_TX_QUEUE_DISABLE_POS 0
#define MAC_GRP_CONTROL_RX_QUEUE_DISABLE_POS 1
#define MAC_GRP_CONTROL_RESET_MAC_POS 2
#define MAC_GRP_CONTROL_MAC_DISABLE_TX_POS 3
#define MAC_GRP_CONTROL_MAC_DISABLE_RX_POS 4
#define MAC_GRP_CONTROL_MAC_DISABLE_JUMBO_TX_POS 5
#define MAC_GRP_CONTROL_MAC_DISABLE_JUMBO_RX_POS 6
#define MAC_GRP_CONTROL_MAC_DISABLE_CRC_CHECK_POS 7
#define MAC_GRP_CONTROL_MAC_DISABLE_CRC_GEN_POS 8
// Part 2: masks/values
#define MAC_GRP_CONTROL_TX_QUEUE_DISABLE 0x001
#define MAC_GRP_CONTROL_RX_QUEUE_DISABLE 0x002
#define MAC_GRP_CONTROL_RESET_MAC 0x004
#define MAC_GRP_CONTROL_MAC_DISABLE_TX 0x008
#define MAC_GRP_CONTROL_MAC_DISABLE_RX 0x010
#define MAC_GRP_CONTROL_MAC_DISABLE_JUMBO_TX 0x020
#define MAC_GRP_CONTROL_MAC_DISABLE_JUMBO_RX 0x040
#define MAC_GRP_CONTROL_MAC_DISABLE_CRC_CHECK 0x080
#define MAC_GRP_CONTROL_MAC_DISABLE_CRC_GEN 0x100
#endif
|
lucasbrasilino/secret_flow
|
lib/C/reg_defines_secret_flow.h
|
C
|
bsd-3-clause
| 44,013 |
// Copyright (c) 2012 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 "ui/views/controls/combobox/native_combobox_win.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "ui/base/events/event.h"
#include "ui/base/models/combobox_model.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/win/hwnd_util.h"
#include "ui/gfx/font.h"
#include "ui/native_theme/native_theme_win.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/combobox/native_combobox_views.h"
#include "ui/views/widget/widget.h"
namespace {
// Limit how small a combobox can be.
const int kMinComboboxWidth = 148;
// Add a couple extra pixels to the widths of comboboxes and combobox
// dropdowns so that text isn't too crowded.
const int kComboboxExtraPaddingX = 6;
} // namespace
namespace views {
////////////////////////////////////////////////////////////////////////////////
// NativeComboboxWin, public:
NativeComboboxWin::NativeComboboxWin(Combobox* combobox)
: combobox_(combobox),
content_width_(0) {
// Associates the actual HWND with the combobox so it is the one considered as
// having the focus (not the wrapper) when the HWND is focused directly (with
// a click for example).
set_focus_view(combobox);
}
NativeComboboxWin::~NativeComboboxWin() {
}
////////////////////////////////////////////////////////////////////////////////
// NativeComboboxWin, NativeComboboxWrapper implementation:
void NativeComboboxWin::UpdateFromModel() {
SendMessage(native_view(), CB_RESETCONTENT, 0, 0);
const gfx::Font& font = Combobox::GetFont();
int max_width = 0;
int num_items = combobox_->model()->GetItemCount();
for (int i = 0; i < num_items; ++i) {
string16 text = combobox_->model()->GetItemAt(i);
// Inserting the Unicode formatting characters if necessary so that the
// text is displayed correctly in right-to-left UIs.
base::i18n::AdjustStringForLocaleDirection(&text);
SendMessage(native_view(), CB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(UTF16ToWide(text).c_str()));
max_width = std::max(max_width, font.GetStringWidth(text));
}
content_width_ = max_width;
if (num_items > 0) {
SendMessage(native_view(), CB_SETCURSEL, combobox_->selected_index(), 0);
// Set the width for the drop down while accounting for the scrollbar and
// borders.
if (num_items > ComboBox_GetMinVisible(native_view()))
max_width += GetSystemMetrics(SM_CXVSCROLL);
// SM_CXEDGE would not be correct here, since the dropdown is flat, not 3D.
int kComboboxDropdownBorderSize = 1;
max_width += 2 * kComboboxDropdownBorderSize + kComboboxExtraPaddingX;
SendMessage(native_view(), CB_SETDROPPEDWIDTH, max_width, 0);
}
}
void NativeComboboxWin::UpdateSelectedIndex() {
// Note that we use CB_SETCURSEL and not CB_SELECTSTRING because on RTL
// locales the strings we get from our ComboBox::Model might be augmented
// with Unicode directionality marks before we insert them into the combobox
// and therefore we can not assume that the string we get from
// ui::ComboboxModel can be safely searched for and selected (which is what
// CB_SELECTSTRING does).
SendMessage(native_view(), CB_SETCURSEL, combobox_->selected_index(), 0);
}
void NativeComboboxWin::UpdateEnabled() {
SetEnabled(combobox_->enabled());
}
int NativeComboboxWin::GetSelectedIndex() const {
LRESULT selected_index = SendMessage(native_view(), CB_GETCURSEL, 0, 0);
return selected_index != CB_ERR ? selected_index : -1;
}
bool NativeComboboxWin::IsDropdownOpen() const {
return SendMessage(native_view(), CB_GETDROPPEDSTATE, 0, 0) != 0;
}
gfx::Size NativeComboboxWin::GetPreferredSize() {
COMBOBOXINFO cbi = { 0 };
cbi.cbSize = sizeof(cbi);
// Note: Don't use CB_GETCOMBOBOXINFO since that crashes on WOW64 systems
// when you have a global message hook installed.
GetComboBoxInfo(native_view(), &cbi);
gfx::Rect rect_item(cbi.rcItem);
gfx::Rect rect_button(cbi.rcButton);
gfx::Size border = ui::NativeThemeWin::instance()->GetThemeBorderSize(
ui::NativeThemeWin::MENULIST);
// The padding value of '3' is the xy offset from the corner of the control
// to the corner of rcItem. It does not seem to be queryable from the theme.
// It is consistent on all versions of Windows from 2K to Vista, and is
// invariant with respect to the combobox border size. We could conceivably
// get this number from rect_item.x, but it seems fragile to depend on
// position here, inside of the layout code.
const int kItemOffset = 3;
int item_to_button_distance = std::max(kItemOffset - border.width(), 0);
// The cx computation can be read as measuring from left to right.
int pref_width = std::max(kItemOffset + content_width_ +
kComboboxExtraPaddingX +
item_to_button_distance + rect_button.width() +
border.width(), kMinComboboxWidth);
// The two arguments to ::max below should be typically be equal.
int pref_height = std::max(rect_item.height() + 2 * kItemOffset,
rect_button.height() + 2 * border.height());
return gfx::Size(pref_width, pref_height);
}
View* NativeComboboxWin::GetView() {
return this;
}
void NativeComboboxWin::SetFocus() {
OnFocus();
}
bool NativeComboboxWin::HandleKeyPressed(const ui::KeyEvent& event) {
return false;
}
bool NativeComboboxWin::HandleKeyReleased(const ui::KeyEvent& event) {
return false;
}
void NativeComboboxWin::HandleFocus() {
}
void NativeComboboxWin::HandleBlur() {
}
gfx::NativeView NativeComboboxWin::GetTestingHandle() const {
return native_view();
}
////////////////////////////////////////////////////////////////////////////////
// NativeComboboxWin, NativeControlWin overrides:
bool NativeComboboxWin::ProcessMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) {
if (message == WM_COMMAND && HIWORD(w_param) == CBN_SELCHANGE) {
combobox_->SelectionChanged();
*result = 0;
return true;
}
return NativeControlWin::ProcessMessage(message, w_param, l_param, result);
}
void NativeComboboxWin::CreateNativeControl() {
// It's ok to add WS_VSCROLL. The scrollbar will show up only when necessary
// as long as we don't use CBS_DISABLENOSCROLL.
// See http://msdn.microsoft.com/en-us/library/7h63bxbe(VS.80).aspx
DWORD flags = WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
CBS_DROPDOWNLIST | WS_VSCROLL;
HWND control_hwnd = ::CreateWindowEx(GetAdditionalExStyle(), L"COMBOBOX", L"",
flags, 0, 0, width(), height(),
GetWidget()->GetNativeView(), NULL, NULL,
NULL);
ui::CheckWindowCreated(control_hwnd);
NativeControlCreated(control_hwnd);
}
void NativeComboboxWin::NativeControlCreated(HWND native_control) {
NativeControlWin::NativeControlCreated(native_control);
UpdateFont();
}
////////////////////////////////////////////////////////////////////////////////
// NativeComboboxWin, private:
void NativeComboboxWin::UpdateFont() {
HFONT font = Combobox::GetFont().GetNativeFont();
SendMessage(native_view(), WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE);
}
////////////////////////////////////////////////////////////////////////////////
// NativeComboboxWrapper, public:
// static
NativeComboboxWrapper* NativeComboboxWrapper::CreateWrapper(
Combobox* combobox) {
return new NativeComboboxViews(combobox);
}
} // namespace views
|
zcbenz/cefode-chromium
|
ui/views/controls/combobox/native_combobox_win.cc
|
C++
|
bsd-3-clause
| 7,843 |
<?php
/**
* index.php
*
* @author BeeCMS team <[email protected]>
* @link http://bee-cms.net
* @copyright 2015 INTFOM
* @package bee-cms.local
* @since 0.1
* Date: 02.09.2016
*/
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel bee\menu\models\MenuSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('bee\messages', 'Menus');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="menu-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('bee\messages', 'Create Menu'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'menu_id',
'zone_code',
'extension_id',
'menutype_id',
'menutype_name',
// 'menutype_params:ntext',
// 'menutype_is_published',
// 'menutype_is_removable',
// 'parent_id',
// 'title',
// 'subtitle',
// 'alias',
// 'component_path',
// 'query_params',
// 'link:ntext',
// 'image',
// 'params:ntext',
// 'zone_name',
// 'component_name',
// 'controller_name',
// 'action_name',
// 'ext_params:ntext',
// 'ext_is_published',
// 'component_is_published',
// 'is_home',
// 'is_menu_displayed',
// 'is_published',
// 'ordering',
// 'lft',
// 'rgt',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?></div>
|
OGreSiv/BeeCMS
|
libs/bee/menu/views/index.php
|
PHP
|
bsd-3-clause
| 1,766 |
hackerRSS
==========
A hacker news RSS feed generator
|
shanzi/hackerRSS
|
README.md
|
Markdown
|
bsd-3-clause
| 55 |
define(['lodash'], function(_) {
/**
* KeyboardGenerator
*
* Models a keyboard generator that knows how to generate
* keyboards of different sizes. When a new instance is created
* it automatically generates the specifications for the given
* keyboard size.
*
* @param {number} size The size of the keyboard
* @constructor
*/
var KeyboardGenerator = function(size) {
this.keySpecs = this.generate(size);
};
/**
* For each of the 12 keys in the octave [0-11], defines whether
* the key is white (true) or black (false).
*
* @property {object}
*/
KeyboardGenerator.keyIsWhite = {
0: true,
1: false,
2: true,
3: false,
4: true,
5: true,
6: false,
7: true,
8: false,
9: true,
10: false,
11: true
};
/**
* For each of supported keyboard sizes, defines the MIDI note
* number that should be assigned to the first key in the sequence.
*
* @property {object}
*/
KeyboardGenerator.startingNoteForSize = {
25: 48,
37: 48,
49: 36,
61: 36,
88: 21
};
/**
* Given the size, returns the starting MIDI note for the sequence.
*
* @param {number} size The size of the keyboard
* @return {number}
*/
KeyboardGenerator.prototype.startingNote = function(size) {
var startingNoteForSize = KeyboardGenerator.startingNoteForSize;
if(!(size in startingNoteForSize)) {
throw new Error("invalid keyboard size: " + size + " must be one of " + _.keys(startingNoteForSize).join(', '));
}
return startingNoteForSize[size];
};
/**
* Generates a sequence of key specifications for each key
* in the keyboard.
*
* @param {number} size The size of the keyboard
* @return {array}
*/
KeyboardGenerator.prototype.generate = function(size) {
var noteNumber = this.startingNote(size);
var keySpecs = [];
var index;
for(index = 0; index < size; index++, noteNumber++) {
keySpecs.push({
noteNumber: noteNumber,
pitch: noteNumber % 12,
isWhite: KeyboardGenerator.keyIsWhite[noteNumber % 12],
});
}
return keySpecs;
};
/**
* Returns the total number of "white" keys in the keyboard.
*
* @return {number}
*/
KeyboardGenerator.prototype.getNumWhiteKeys = function() {
return _.filter(_.pluck(this.keySpecs, 'isWhite')).length;
};
/**
* Returns the total number of keys in the keyboard.
*
* @return {number}
*/
KeyboardGenerator.prototype.getSize = function() {
return this.keySpecs.length;
};
return KeyboardGenerator;
});
|
Harvard-ATG/HarmonyLab
|
lab/static/js/src/models/keyboard_generator.js
|
JavaScript
|
bsd-3-clause
| 2,472 |
package org.easit.core.controllers.facebook;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.easit.dao.model.PSMetadata;
import org.springframework.social.MissingAuthorizationException;
import org.springframework.social.facebook.api.Album;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.Reference;
import org.springframework.social.facebook.api.Video;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class FacebookUserController {
private final Facebook facebook;
@Inject
public FacebookUserController(Facebook facebook) {
this.facebook = facebook;
}
@ExceptionHandler(MissingAuthorizationException.class)
public String handleAuthorizationException(Principal currentUser) {
return "redirect:/connect/facebook";
}
/*
* Show friend's wall
*/
@RequestMapping(value = "/facebook/friends/{userId}/wall", method = RequestMethod.GET)
public String showFeed(@PathVariable("userId") String userId, Model model, String offset) {
int int_offset = 0;
int listSize = 0;
if (offset != null) {
int_offset = Integer.valueOf(offset);
}
listSize = facebook.feedOperations().getFeed(userId).size();
model.addAttribute("userProf", facebook.userOperations().getUserProfile());
model.addAttribute("fuser", facebook.userOperations().getUserProfile(userId));
model.addAttribute("feed", facebook.feedOperations().getFeed(userId, int_offset, PSMetadata.FACEBOOK_LIMIT_RESULT));
model.addAttribute("offset", int_offset);
model.addAttribute("pageSize", listSize);
return "facebook/friend/wall";
}
/*
* Post to friend's wall
*/
@RequestMapping(value = "/facebook/friends/{userId}/wall", method = RequestMethod.POST)
public String postUpdate(@PathVariable("userId") String userId, String message) {
facebook.feedOperations().post(userId, message);
return "redirect:/facebook/friends/{userId}/wall";
}
/*
* Show friend's profile
*/
@RequestMapping(value = "/facebook/friends/{userId}/profile", method = RequestMethod.GET)
public String showProfile(@PathVariable("userId") String userId, Model model) {
model.addAttribute("userProf", facebook.userOperations().getUserProfile());
model.addAttribute("fuser", facebook.userOperations().getUserProfile(userId));
return "facebook/friend/profile";
}
/*
* Show friend's albums
*/
@RequestMapping(value = "/facebook/friends/{userId}/albums", method = RequestMethod.GET)
public String showAlbums(@PathVariable("userId") String userId, Model model, String offset) {
int int_offset = 0;
int listSize = 0;
if (offset != null) {
int_offset = Integer.valueOf(offset);
}
List<Album> albumList = facebook.mediaOperations().getAlbums(userId);
listSize = albumList.size();
model.addAttribute("fuser", facebook.userOperations().getUserProfile(userId));
model.addAttribute("falbums", albumList);
model.addAttribute("offset", int_offset);
model.addAttribute("pageSize", listSize);
return "facebook/friend/albums";
}
/*
* Show content of album
*/
@RequestMapping(value = "/facebook/friends/{userId}/albums/{albumId}", method = RequestMethod.GET)
public String showAlbum(@PathVariable("userId") String userId, @PathVariable("albumId") String albumId, Model model) {
model.addAttribute("fuser", facebook.userOperations().getUserProfile(userId));
model.addAttribute("falbum", facebook.mediaOperations().getAlbum(albumId));
model.addAttribute("fphotos", facebook.mediaOperations().getPhotos(albumId));
return "facebook/friend/albums/album";
}
/*
* Show friend's videos
*/
@RequestMapping(value = "/facebook/friends/{userId}/albums/videos", method = RequestMethod.GET)
public String showVideos(@PathVariable("userId") String userId, Model model, String offset) {
int int_offset = 0;
int listSize = 0;
if (offset != null) {
int_offset = Integer.valueOf(offset);
}
List<Video> videoList = facebook.mediaOperations().getVideos(userId);
listSize = videoList.size();
model.addAttribute("fvideos", videoList);
model.addAttribute("fuser", facebook.userOperations().getUserProfile(userId));
model.addAttribute("offset", int_offset);
model.addAttribute("pageSize", listSize);
return "facebook/friend/videos";
}
/*
* Show the selected video
*/
@RequestMapping(value = "/facebook/friends/{userId}/albums/videos/{videoId}", method = RequestMethod.GET)
public String showVideo(@PathVariable("videoId") String videoId, @PathVariable("userId") String userId, Model model) {
model.addAttribute(new UploadItem());
model.addAttribute("fvideo", facebook.mediaOperations().getVideo(videoId));
// model.addAttribute("comments",
// facebook.commentOperations().getComments(videoId));
model.addAttribute("fuser", facebook.userOperations().getUserProfile(userId));
return "facebook/friend/videos/video";
}
/*
* Show friends
*/
@RequestMapping(value = "/facebook/friends/{userId}/friends", method = RequestMethod.GET)
public String showFriends(@PathVariable("userId") String userId, Model model) {
List<Reference> users = facebook.friendOperations().getFriends(userId);
model.addAttribute("fuser", facebook.userOperations().getUserProfile(userId));
model.addAttribute("users", users);
model.addAttribute("areFriends", friendConnection(users, userId));
return "facebook/friend/users";
}
private List<Boolean> friendConnection(List<Reference> users, String userId) {
List<Boolean> areFriends = new ArrayList<Boolean>();
List<String> myFriends = facebook.friendOperations().getFriendIds();
for (Reference user : users) {
Boolean isFriend = false;
for (String friend : myFriends) {
if (friend.equals(user.getId()) || (friend.equals(userId))) {
isFriend = true;
break;
}
}
areFriends.add(isFriend);
}
return areFriends;
}
}
|
barcelonadigital/easit4all
|
core/src/main/java/org/easit/core/controllers/facebook/FacebookUserController.java
|
Java
|
bsd-3-clause
| 6,304 |
/*
* SimulatorTCP.h : part of the Mace toolkit for building distributed systems
*
* Copyright (c) 2011, Charles Killian, James W. Anderson, Karthik Nagaraj
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of the contributors, nor their associated universities
* or organizations may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*
* ----END-OF-LEGAL-STUFF---- */
#ifndef SIMULATOR_TCP_SERVICE_H
#define SIMULATOR_TCP_SERVICE_H
#include "SimNetwork.h"
#include "SimulatorTCPCommon.h"
namespace SimulatorTCP_namespace {
/**
* Simulator-specific reliable transport. Any new message events are queued in
* the pending events (SimTimeUtil) ordered by their calculated time of
* occurrence (in the future).
*/
class SimulatorTCPService : public SimulatorTCPCommonService {
public:
// SimulatorTCPService(uint32_t queue_size, uint16_t port, int node, bool messageErrors = false, int forwarder = -1)
// : SimulatorTCPCommonService(queue_size, port, node, messageErrors, forwarder),
SimulatorTCPService(uint16_t port = std::numeric_limits<uint16_t>::max(), int forwarder = -1)
: SimulatorTCPCommonService(port, forwarder, true),
net(SimNetwork::Instance()) {
net.registerHandler(getPort(), *this);
}
SimulatorTCPService(uint16_t port /*= std::numeric_limits<uint16_t>::max()*/, int forwarder /*= -1*/, bool shared)
: SimulatorTCPCommonService(port, forwarder, shared),
net(SimNetwork::Instance()) {
net.registerHandler(getPort(), *this);
}
~SimulatorTCPService() { }
bool route(const MaceKey& dest, const std::string& s, registration_uid_t registrationUid);
void addCTSEvent(int dest);
/// Add and remove FLUSHED event from the queue
void addFlushedEvent();
bool removeFlushedEvent();
void prepareDestNotReady(int node, uint64_t t);
int getNumFlows() const;
inline uint32_t getNetMessageId() {
return net.getMessageId();
}
inline SimulatorTransport* getNetTransport(int node, int port) {
return net.getTransport(node, port);
}
void netSignal(int source, int dest, int port, SimulatorTransport::TransportSignal sig) {
net.signal(source, dest, port, sig);
}
/// Simulator enqueues events as they are created
void enqueueEvent(int destNode) { }
/// Remove DEST_NOT_READY from event queue
bool removeDestNotReadyEvent(int other);
/// Remove message given SimulatorMessage equivalent
bool removeEventFromQueue(const SimulatorMessage& msg) const;
/// Remove any event that may be queued for the other node
void removeEvents(int other) const;
SimulatorMessage createMessageSourceReset(int other, uint32_t msgId);
SimulatorMessage createMessageBidiReadError(int other, uint32_t msgId);
BufferStatisticsPtr getStats(int node);
const BufferStatisticsPtr getStatistics(const MaceKey& peer, Connection::type d, registration_uid_t registrationUid);
private:
SimNetwork& net;
};
}
#endif // SIMULATOR_TCP_SERVICE_H
|
jojochuang/eventwave
|
application/simulator/SimulatorTCP.h
|
C
|
bsd-3-clause
| 4,437 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.regression.recursive_ls.RecursiveLSResults.aic — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.regression.recursive_ls.RecursiveLSResults.aicc" href="statsmodels.regression.recursive_ls.RecursiveLSResults.aicc.html" />
<link rel="prev" title="statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test_terms" href="statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test_terms.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.regression.recursive_ls.RecursiveLSResults.aic" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.1</span>
<span class="md-header-nav__topic"> statsmodels.regression.recursive_ls.RecursiveLSResults.aic </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../regression.html" class="md-tabs__link">Linear Regression</a></li>
<li class="md-tabs__item"><a href="statsmodels.regression.recursive_ls.RecursiveLSResults.html" class="md-tabs__link">statsmodels.regression.recursive_ls.RecursiveLSResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.1</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../regression.html" class="md-nav__link">Linear Regression</a>
</li>
<li class="md-nav__item">
<a href="../glm.html" class="md-nav__link">Generalized Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a>
</li>
<li class="md-nav__item">
<a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a>
</li>
<li class="md-nav__item">
<a href="../rlm.html" class="md-nav__link">Robust Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a>
</li>
<li class="md-nav__item">
<a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../anova.html" class="md-nav__link">ANOVA</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.regression.recursive_ls.RecursiveLSResults.aic.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-regression-recursive-ls-recursivelsresults-aic--page-root">statsmodels.regression.recursive_ls.RecursiveLSResults.aic<a class="headerlink" href="#generated-statsmodels-regression-recursive-ls-recursivelsresults-aic--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py attribute">
<dt id="statsmodels.regression.recursive_ls.RecursiveLSResults.aic">
<code class="sig-prename descclassname">RecursiveLSResults.</code><code class="sig-name descname">aic</code><a class="headerlink" href="#statsmodels.regression.recursive_ls.RecursiveLSResults.aic" title="Permalink to this definition">¶</a></dt>
<dd><p>(float) Akaike Information Criterion</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test_terms.html" title="statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test_terms"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test_terms </span>
</div>
</a>
<a href="statsmodels.regression.recursive_ls.RecursiveLSResults.aicc.html" title="statsmodels.regression.recursive_ls.RecursiveLSResults.aicc"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.regression.recursive_ls.RecursiveLSResults.aicc </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 29, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.12.1/generated/statsmodels.regression.recursive_ls.RecursiveLSResults.aic.html
|
HTML
|
bsd-3-clause
| 18,392 |
<?php
return [
'id' => 'ID',
'shop_id' => 'Shop ID',
'department_id' => 'Department ID',
'product_id' => 'Product ID',
'products_attributes_logistics_info_id' => 'Products Attributes Logistics Info ID',
'attributes_products_group_id' => 'Attributes Products Group ID',
'order_id' => 'Order ID',
'price' => 'Price',
'currency_id' => 'Currency ID',
'count' => 'Count',
'status_id' => 'Status ID',
'user_client_id' => 'User Client ID',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
|
Winkelor/yii2store
|
common/messages/en-US/orders_details.php
|
PHP
|
bsd-3-clause
| 567 |
from django.db import models
from django.utils import timezone
from indexed import Indexed
import datetime
import string
MAX_QUERY_STRING_LENGTH = 255
class Query(models.Model):
query_string = models.CharField(max_length=MAX_QUERY_STRING_LENGTH, unique=True)
def save(self, *args, **kwargs):
# Normalise query string
self.query_string = self.normalise_query_string(self.query_string)
super(Query, self).save(*args, **kwargs)
def add_hit(self, date=None):
if date is None:
date = timezone.now().date()
daily_hits, created = QueryDailyHits.objects.get_or_create(query=self, date=date)
daily_hits.hits = models.F('hits') + 1
daily_hits.save()
def __unicode__(self):
return self.query_string
@property
def hits(self):
hits = self.daily_hits.aggregate(models.Sum('hits'))['hits__sum']
return hits if hits else 0
@classmethod
def garbage_collect(cls):
"""
Deletes all Query records that have no daily hits or editors picks
"""
cls.objects.filter(daily_hits__isnull=True, editors_picks__isnull=True).delete()
@classmethod
def get(cls, query_string):
return cls.objects.get_or_create(query_string=cls.normalise_query_string(query_string))[0]
@classmethod
def get_most_popular(cls, date_since=None):
# TODO: Implement date_since
return cls.objects.filter(daily_hits__isnull=False).annotate(_hits=models.Sum('daily_hits__hits')).distinct().order_by('-_hits')
@staticmethod
def normalise_query_string(query_string):
# Truncate query string
if len(query_string) > MAX_QUERY_STRING_LENGTH:
query_string = query_string[:MAX_QUERY_STRING_LENGTH]
# Convert query_string to lowercase
query_string = query_string.lower()
# Strip punctuation characters
query_string = ''.join([c for c in query_string if c not in string.punctuation])
# Remove double spaces
query_string = ' '.join(query_string.split())
return query_string
class QueryDailyHits(models.Model):
query = models.ForeignKey(Query, db_index=True, related_name='daily_hits')
date = models.DateField()
hits = models.IntegerField(default=0)
@classmethod
def garbage_collect(cls):
"""
Deletes all QueryDailyHits records that are older than 7 days
"""
min_date = timezone.now().date() - datetime.timedelta(days=7)
cls.objects.filter(date__lt=min_date).delete()
class Meta:
unique_together = (
('query', 'date'),
)
class EditorsPick(models.Model):
query = models.ForeignKey(Query, db_index=True, related_name='editors_picks')
page = models.ForeignKey('wagtailcore.Page')
sort_order = models.IntegerField(null=True, blank=True, editable=False)
description = models.TextField(blank=True)
class Meta:
ordering = ('sort_order', )
# Used for tests
class SearchTest(models.Model, Indexed):
title = models.CharField(max_length=255)
content = models.TextField()
live = models.BooleanField(default=False)
indexed_fields = ("title", "content", "callable_indexed_field", "live")
def callable_indexed_field(self):
return "Callable"
class SearchTestChild(SearchTest):
extra_content = models.TextField()
indexed_fields = "extra_content"
|
helenwarren/pied-wagtail
|
wagtail/wagtailsearch/models.py
|
Python
|
bsd-3-clause
| 3,433 |
{/include file="simpla/common/header.html"/}
{/include file="simpla/common/left.html"/}
<div id="main-content">
<h2>欢迎您 {/$_adminname/}</h2>
<p id="page-intro">商品入库。带<font class="red"> * </font>为必填</p>
<div class="clear"></div>
<div class="content-box">
<div class="content-box-header">
<h3>商品入库</h3>
<ul class="content-box-tabs">
<li><a href="{/get_url rule="/purchase/index"/}">库存情况</a></li>
<li><a href="#tab1" class="default-tab">添加库存</a></li>
</ul>
<div class="clear"></div>
</div>
<div class="content-box-content">
<div class="tab-content default-tab" id="tab1">
<div class="form">
<form action="{/get_url rule='/purchase/purchase' data="ac=$ac"/}" method="post" id="js-form">
<fieldset class="clearfix">
<input type="hidden" name="goods_id" value="{/$goods.goods_id/}" />
{/if $goods.goods_name/}<p><label>商品名称:{/$goods.goods_name/}</label></p>{//if/}
<p><label><font class="red"> * </font>商品条形码:</label>
<input type="text" value="{/$goods.goods_sn/}" class="text-input small-input" name="goods_sn" id="goods_sn" /><span></span>
</p>
<p><label class="w80"><font class="red"> * </font>数量:</label>
<input type="text" value="" class="text-input min-input" name="in_num" id="in_num" /><span></span><br /><small>记重商品单位为千克</small>
</p>
<p><label class="w80"><font class="red"> * </font>进价:</label>
<span><input type="text" value="{/$goods.in_price/}" class="text-input min-input" name="in_price" id="in_price" />元</span>
</p>
<dt>
<input type="submit" name="" class="button" id="button" value="入库" />
</dt>
</fieldset>
</form>
</div>
</div>
</div>
</div>
{/include file="simpla/common/copy.html"/} </div>
{/include file="simpla/common/footer.html"/}
|
hVenus/bunny-erp-system
|
app/v/simpla/purchase/purchase.html
|
HTML
|
bsd-3-clause
| 2,144 |
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include "Node.hpp"
#include <iomanip>
namespace cuda
{
namespace JIT
{
class BinaryNode : public Node
{
private:
std::string m_op_str;
Node_ptr m_lhs, m_rhs;
int m_op;
public:
BinaryNode(const char *out_type_str, const char *name_str,
const std::string &op_str,
Node_ptr lhs, Node_ptr rhs, int op)
: Node(out_type_str, name_str),
m_op_str(op_str),
m_lhs(lhs),
m_rhs(rhs),
m_op(op)
{
}
bool isLinear(dim_type dims[4])
{
return m_lhs->isLinear(dims) && m_rhs->isLinear(dims);
}
void genParams(std::stringstream &kerStream,
std::stringstream &annStream, bool is_linear)
{
if (m_gen_param) return;
if (!(m_lhs->isGenParam())) m_lhs->genParams(kerStream, annStream, is_linear);
if (!(m_rhs->isGenParam())) m_rhs->genParams(kerStream, annStream, is_linear);
m_gen_param = true;
}
void genOffsets(std::stringstream &kerStream, bool is_linear)
{
if (m_gen_offset) return;
if (!(m_lhs->isGenOffset())) m_lhs->genOffsets(kerStream, is_linear);
if (!(m_rhs->isGenOffset())) m_rhs->genOffsets(kerStream, is_linear);
m_gen_offset = true;
}
void genKerName(std::stringstream &kerStream)
{
m_lhs->genKerName(kerStream);
m_rhs->genKerName(kerStream);
if (m_gen_name) return;
// Make the hex representation of enum part of the Kernel name
kerStream << "_" << std::setw(2) << std::setfill('0') << std::hex << m_op;
kerStream << std::setw(2) << std::setfill('0') << std::hex << m_lhs->getId();
kerStream << std::setw(2) << std::setfill('0') << std::hex << m_rhs->getId();
kerStream << std::setw(2) << std::setfill('0') << std::hex << m_id << std::dec;
m_gen_name = true;
}
void genFuncs(std::stringstream &kerStream, str_map_t &declStrs, bool is_linear)
{
if (m_gen_func) return;
if (!(m_lhs->isGenFunc())) m_lhs->genFuncs(kerStream, declStrs, is_linear);
if (!(m_rhs->isGenFunc())) m_rhs->genFuncs(kerStream, declStrs, is_linear);
std::stringstream declStream;
declStream << "declare " << m_type_str << " " << m_op_str
<< "(" << m_lhs->getTypeStr() << " , " << m_rhs->getTypeStr() << ")\n";
str_map_iter loc = declStrs.find(declStream.str());
if (loc == declStrs.end()) {
declStrs[declStream.str()] = true;
}
kerStream << "%val" << m_id << " = call "
<< m_type_str << " "
<< m_op_str << "("
<< m_lhs->getTypeStr() << " "
<< "%val" << m_lhs->getId() << ", "
<< m_rhs->getTypeStr() << " "
<< "%val" << m_rhs->getId() << ")\n";
m_gen_func = true;
}
int setId(int id)
{
if (m_set_id) return id;
id = m_lhs->setId(id);
id = m_rhs->setId(id);
m_id = id;
m_set_id = true;
return m_id + 1;
}
void getInfo(unsigned &len, unsigned &buf_count, unsigned &bytes)
{
if (m_set_id) return;
m_lhs->getInfo(len, buf_count, bytes);
m_rhs->getInfo(len, buf_count, bytes);
len++;
m_set_id = true;
return;
}
void resetFlags()
{
m_set_id = false;
m_gen_func = false;
m_gen_param = false;
m_gen_offset = false;
m_set_arg = false;
m_lhs->resetFlags();
m_rhs->resetFlags();
}
void setArgs(std::vector<void *> &args, bool is_linear)
{
if (m_set_arg) return;
m_lhs->setArgs(args, is_linear);
m_rhs->setArgs(args, is_linear);
m_set_arg = true;
}
};
}
}
|
glehmann/arrayfire
|
src/backend/cuda/JIT/BinaryNode.hpp
|
C++
|
bsd-3-clause
| 4,577 |
# -*- coding: utf-8 -*-
require './fib'
describe Fib do
describe "#at" do
let(:fib) { Fib.new }
context "with 1" do
it { fib.at(1).should == 0 }
end
context "with 7" do
it { fib.at(7).should == 8 }
end
context "with 0" do
it { expect { fib.at(0) }.to raise_error(RuntimeError) }
end
end
end
|
mochizukid/samples
|
ruby/BDD/fib_spec2.rb
|
Ruby
|
bsd-3-clause
| 346 |
<div class="project-container">
<div class="clear"></div>
<div class="project-info">
<div class="tag-project">TOOL DEVELOPER</div>
<div class="title-project">MATRIX CALCULATOR</div>
<div class="spacer"></div>
<div class="description">
<h2>General Overview</h2>
<p>
I started this project towards the end of my 1A term after I had almost completed my Linear Algebra and Digital Computation courses. I combined my knowledge from both of these courses (the matrix operations from Linear Algebra and the C++ knowledge from Digital Computation) to make a very useful matrix calculator that helped me solve comprehensive matrix operations quickly. It was a nice challenge and real life application after learning so much C++ and algebra over the semester. You can find the C++ code on my <a href="https://github.com/bhamodi/Matrix-Calculator" target="_blank">GitHub.</a>
</p>
<h2>Software</h2>
<p>
The algorithms that I used are fairly straightforward and I derived them by myself from my knowledge in Linear Algebra and matrix operations. There are still some matrix operations that are not implemented because of the algorithmic complexity such as inversing a matrix or finding the determinant. I hope to one day implement an efficient algorithm to handle these last few operations.
</p>
<h2>Current Plans</h2>
<p>
Since I have gained some Android and mobile development experience from my other projects, I revisited this calculator and I am currently in the process of porting it to Android. This will allow me to release a Matrix Calculator application that will help people compute their matrix operations.
</p>
</div>
</div>
</div>
<div class="clear"></div>
<div class="nav-arrows">
<div class="prev-button"></div>
<div class="close"></div>
<div class="next-button"></div>
</div>
|
bhamodi/bhamodi.github.io
|
project-01.html
|
HTML
|
bsd-3-clause
| 1,891 |
/**
* Automatically generated file. DO NOT MODIFY
*/
package com.openxcplatform.enabler;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.openxcplatform.enabler";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 6000004;
public static final String VERSION_NAME = "";
}
|
bibhrajit/openxc-androidStudio
|
enabler/build/generated/source/buildConfig/debug/com/openxcplatform/enabler/BuildConfig.java
|
Java
|
bsd-3-clause
| 462 |
<?php
namespace frontend\models;
use yii\db\Expression;
class nowCO extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName() {
return 'now_calls_operators';
}
public static function setCloseCard($data) {
return nowCO::updateAll(['is_answering' => 0 ],[ 'php_session_id' => $data['phpid']]);
}
public static function getJsonCallInfo($data) {
self::updateAll(['last_activity' => new Expression('NOW()')],['php_session_id'=>$data['phpid']]);
$callInfo = (new \yii\db\Query())
->select('nco.operator_id,
nco.phone_num,
nco.queue_num,
nco.is_ringing,
nco.is_answering,
nco.cid,
now() as server_time,
nco.uid,
rq.queue_url,
ro.add_info
')
->from('now_calls_operators nco')
->innerJoin('ref_operators ro', 'nco.operator_id = ro.operator_id')
->leftJoin('ref_queues rq', ' nco.queue_num = rq.queue_num')
->where( [ 'nco.php_session_id' => $data['phpid'] ] )
->createCommand();
$row = $callInfo->queryOne();
if (!$row) {
return [
'isL' => false
];
} else {
// %UID% , %CNUM% , %QNUM% , %PNUM%, %OID%
$queueURL = str_replace( '%UID%' , $row['uid'], $row['queue_url'] );
$queueURL = str_replace( '%OID%' , $row['add_info'], $queueURL );
$queueURL = str_replace( '%QNUM%' , $row['queue_num'], $queueURL );
$queueURL = str_replace( '%CNUM%' , $row['cid'], $queueURL );
$queueURL = str_replace( '%PNUM%' , $row['phone_num'], $queueURL );
return [
'isL' => true,
'aI' => $row['add_info'],
'oid' => $row['operator_id'],
'isR' => $row['is_ringing'],
'isA' => $row['is_answering'],
'pN' => $row['phone_num'],
'cN' => $row['cid'],
'qN' => $row['queue_num'],
'sT' => $row['server_time'],
'qU' => $queueURL,
'uid' => $row['uid']
];
}
}
}
|
predeinay/itwww
|
frontend/models/nowCO.php
|
PHP
|
bsd-3-clause
| 2,774 |
<?php
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use app\helpers\TimeHelper;
echo Nav::widget([
'options' => ['class' => 'nav nav-tabs'],
'items' => [
['label' => 'Buku Tabungan Hari Tua', 'url' => ['/manajerkeuangan/tabungan-hari-tua/listtabungan','startDate'=>TimeHelper::getBeginningYear(TimeHelper::getTodayDate()),'endDate'=>TimeHelper::getEndYear(TimeHelper::getTodayDate())]],
['label' => 'Transaksi Tabungan', 'url' => ['/manajerkeuangan/tabungan-hari-tua/add']],
],
]);
?>
|
vincentsthe/gema-radio
|
modules/manajerkeuangan/views/tabungan-hari-tua/_header.php
|
PHP
|
bsd-3-clause
| 555 |
/**************************************************************************
* Suite for benchmarking/testing curve operations for MSR ECClib
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* MIT License
*
* 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.
*
*
* Abstract: benchmarking/testing curve operations
*
* This software is based on the article by Joppe Bos, Craig Costello,
* Patrick Longa and Michael Naehrig, "Selecting elliptic curves for
* cryptography: an efficiency and security analysis", preprint available
* at http://eprint.iacr.org/2014/130.
***************************************************************************/
#include "msr_ecclib_priv.h"
#include "tests.h"
#if OS_TARGET == OS_WIN
#include <windows.h>
#endif
#include <stdio.h>
#include <malloc.h>
#ifdef ECCURVES_256
ECCRYPTO_STATUS ecc_test256_w(PCurveStaticData CurveData)
{ // Tests for curve numsp256d1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
dig n;
BOOL passed = TRUE;
point_jac_numsp256d1 P, R, complete_table[4] = {0};
dig k[ML_WORDS256], kk[ML_WORDS256];
point_numsp256d1 A, AA, B, BB, *T_fixed = NULL;
PCurveStruct JacCurve = {0};
printf("\n\nTESTING \n");
printf("--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp256d1, Weierstrass a=-3 curve over GF(2^256-189) \n\n");
// Curve initialization
JacCurve = ecc_curve_allocate(CurveData);
if (JacCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(JacCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (Weierstrass a=-3)
passed = TRUE;
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
for (n=0; n<ML_TEST_LOOPS; n++)
{
eccdouble_jac_numsp256d1(P, JacCurve); // 2*P
eccdouble_waff_256(A, JacCurve); // 2*A
}
eccnorm_numsp256d1(P, AA, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
if (passed==TRUE) printf(" Point doubling tests .................................................................... PASSED");
else { printf(" Point doubling tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// "Complete" point addition (Weierstrass a=-3)
passed = TRUE;
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
ecccopy_jac_numsp256d1(P, R);
eccdouble_jac_numsp256d1(P, JacCurve); // P = 2P
eccset_numsp256d1(AA, JacCurve);
eccdouble_waff_256(AA, JacCurve); // AA = 2A
for (n=0; n<ML_TEST_LOOPS; n++)
{
eccadd_jac_numsp256d1(R, P, JacCurve); // P = P+Q
eccadd_waff_256(A, AA, JacCurve); // AA = AA+A
}
eccnorm_numsp256d1(P, A, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
ecccopy_jac_numsp256d1(P, R);
fpneg256(JacCurve->prime, R->Y);
eccadd_jac_numsp256d1(R, P, JacCurve); // P+(-P)
if (ecc_is_infinity_jac_numsp256d1(P, JacCurve) == FALSE) passed=FALSE;
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, R);
ecczero_jac_numsp256d1(P); P->Y[0] = 1;
eccadd_jac_numsp256d1(R, P, JacCurve); // 0+R
eccnorm_numsp256d1(P, AA, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
ecczero_jac_numsp256d1(R); R->Y[0] = 1;
eccadd_jac_numsp256d1(R, P, JacCurve); // P+0
eccnorm_numsp256d1(P, AA, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
ecccopy_jac_numsp256d1(P, R);
eccadd_jac_numsp256d1(R, P, JacCurve); // P+P
eccnorm_numsp256d1(P, AA, JacCurve);
eccdouble_jac_numsp256d1(R, JacCurve); // 2P
eccnorm_numsp256d1(R, A, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
// Case of mixed addition
complete_table[0]->Y[0] = 1; // Initialize complete_table[0] with the point at infinity (0:1:0)
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, complete_table[1]); // Initialize complete_table[1] with A = (X_A:Y_A:1)
eccconvert_aff_to_jac_numsp256d1(A, P);
fpneg256(JacCurve->prime, P->Y);
eccadd_mixed_jac_numsp256d1(A, P, complete_table, JacCurve); // P+(-P)
if (ecc_is_infinity_jac_numsp256d1(P, JacCurve) == FALSE) passed=FALSE;
eccset_numsp256d1(A, JacCurve);
ecczero_jac_numsp256d1(P); P->Y[0] = 1;
eccadd_mixed_jac_numsp256d1(A, P, complete_table, JacCurve); // 0+R
eccnorm_numsp256d1(P, AA, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
ecccopy_jac_numsp256d1(P, R);
eccadd_mixed_jac_numsp256d1(A, P, complete_table, JacCurve); // P+P
eccnorm_numsp256d1(P, AA, JacCurve);
eccdouble_jac_numsp256d1(R, JacCurve); // 2P
eccnorm_numsp256d1(R, A, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp256d1(A, JacCurve);
eccset_numsp256d1(AA, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
eccdouble_jac_numsp256d1(P, JacCurve);
eccadd_mixed_jac_numsp256d1(A, P, complete_table, JacCurve); // P+2P
eccdouble_waff_256(AA, JacCurve);
eccadd_waff_256(A, AA, JacCurve); // P+2P
eccnorm_numsp256d1(P, A, JacCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
if (passed==TRUE) printf(" (Complete) point addition tests ......................................................... PASSED");
else { printf(" (Complete) point addition tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Variable-base scalar multiplication (Weierstrass a=-3)
eccset_numsp256d1(A, JacCurve);
for (n=0; n<ML_TEST_LOOPS; n++)
{
random256_test(k, JacCurve->order);
ecc_mul_waff_256(A, k, AA, JacCurve);
Status = ecc_scalar_mul_numsp256d1(A, k, B, JacCurve);
if (fpcompare256(AA->x,B->x)!=0 || fpcompare256(AA->y,B->y)!=0) { passed=FALSE; break; }
}
if (passed==TRUE) printf(" Variable-base scalar multiplication tests ............................................... PASSED");
else { printf(" Variable-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Fixed-base scalar multiplication (Weierstrass a=-3)
eccset_numsp256d1(A, JacCurve);
for (n=0; n<ML_TEST_LOOPS; n++)
{
random256_test(k, JacCurve->order);
ecc_mul_waff_256(A, k, AA, JacCurve);
T_fixed = ecc_allocate_precomp_numsp256d1(OP_FIXEDBASE, JacCurve);
ecc_precomp_fixed_numsp256d1(A, T_fixed, JacCurve);
Status = ecc_scalar_mul_fixed_numsp256d1(T_fixed, k, B, JacCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare256(AA->x,B->x)!=0 || fpcompare256(AA->y,B->y)!=0) { passed=FALSE; break; }
}
if (passed==TRUE) printf(" Fixed-base scalar multiplication tests .................................................. PASSED");
else { printf(" Fixed-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Double-scalar multiplication (Weierstrass a=-3)
passed = TRUE;
eccset_numsp256d1(A, JacCurve);
random256_test(k, JacCurve->order);
ecc_mul_waff_256(A, k, B, JacCurve); // Base points are A and B
for (n=0; n<ML_TEST_LOOPS; n++)
{
random256_test(k, JacCurve->order);
random256_test(kk, JacCurve->order);
ecc_mul_waff_256(A, k, AA, JacCurve);
ecc_mul_waff_256(B, kk, BB, JacCurve);
eccadd_waff_256(BB, AA, JacCurve);
T_fixed = ecc_allocate_precomp_numsp256d1(OP_DOUBLESCALAR, JacCurve);
ecc_precomp_dblmul_numsp256d1(A, T_fixed, JacCurve);
Status = ecc_double_scalar_mul_numsp256d1(T_fixed, k, B, kk, BB, JacCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare256(AA->x,BB->x)!=0 || fpcompare256(AA->y,BB->y)!=0) { passed=FALSE; break; }
}
if (passed==TRUE) printf(" Double-scalar multiplication tests ...................................................... PASSED");
else { printf(" Double-scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
cleanup:
if (passed == FALSE) {
Status = ECCRYPTO_ERROR_DURING_TEST;
}
ecc_curve_free(JacCurve);
return Status;
}
ECCRYPTO_STATUS ecc_test256_te(PCurveStaticData CurveData)
{ // Tests for curve numsp256t1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
dig n;
BOOL passed = TRUE;
point_numsp256t1 A, AA, U, V;
point_extproj_numsp256t1 P, R;
point_numsp256d1 PP, QQ, RR, UU, VV;
dig256 a, d, t1, t2, t3;
dig k[ML_WORDS256], kk[ML_WORDS256];
point_extaff_precomp_numsp256t1 *T_fixed = NULL;
PCurveStruct WeierstrassCurve = {0};
PCurveStruct TedCurve = {0};
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp256t1, twisted Edwards a=1 curve over GF(2^256-189) \n\n");
// Curve initialization
TedCurve = ecc_curve_allocate(CurveData);
if (TedCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(TedCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Weierstrass curve allocation
WeierstrassCurve = ecc_curve_allocate(CurveData);
if (WeierstrassCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
// Set Weierstrass curve isomorphic to TedCurve
fpcopy256(TedCurve->parameter1, a);
fpcopy256(TedCurve->parameter2, d);
fpzero256(t3); t3[0] = 14;
fpmul256(t3, d, t1);
fpmul256(t1, a, t1); // t1 = 14ad
fpsqr256(d, t2); // t2 = d^2
fpadd256(t1, t2, t2); // t2 = 14ad+d^2
fpsqr256(a, t3); // t3 = a^2
fpadd256(t2, t3, t2); // t2 = a^2+14ad+d^2
fpneg256(TedCurve->prime, t2); // t2 = -(a^2+14ad+d^2)
fpzero256(t1); t1[0] = 48;
fpinv256(t1); // t1 = 1/48
fpmul256(t1, t2, WeierstrassCurve->parameter1); // aW = -(a^2+14ad+d^2)/48
WeierstrassCurve->nbits = TedCurve->nbits;
WeierstrassCurve->rbits = TedCurve->rbits;
WeierstrassCurve->pbits = TedCurve->pbits;
// Point doubling (twisted Edwards a=1)
passed = TRUE;
eccset_numsp256t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp256t1(A, P);
ecc_numsp256t1_to_weierstrass(A, PP, TedCurve);
for (n=0; n<ML_TEST_LOOPS; n++)
{
eccdouble_extproj_numsp256t1(P, TedCurve); // 2*P
eccdouble_waff_256(PP, WeierstrassCurve); // 2*PP
}
eccnorm_numsp256t1(P, A, TedCurve);
ecc_weierstrass_to_numsp256t1(PP, AA, TedCurve);
if (fpcompare256(A->x,AA->x)!=0 || fpcompare256(A->y,AA->y)!=0) passed=FALSE;
if (passed==TRUE) printf(" Point doubling tests .................................................................... PASSED");
else { printf(" Point doubling tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Point addition (twisted Edwards a=1)
passed = TRUE;
eccset_numsp256t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp256t1(A, P);
ecccopy_extproj_numsp256t1(P, R);
eccdouble_extproj_numsp256t1(P, TedCurve); // P = 2P
eccset_numsp256t1(A, TedCurve);
ecc_numsp256t1_to_weierstrass(A, QQ, TedCurve);
ecc_numsp256t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_256(PP, WeierstrassCurve); // PP = 2P
for (n=0; n<ML_TEST_LOOPS; n++)
{
eccadd_extproj_numsp256t1(R, P, TedCurve); // P = P+Q
eccadd_waff_256(QQ, PP, WeierstrassCurve); // PP = PP+QQ
}
eccnorm_numsp256t1(P, A, TedCurve);
ecc_weierstrass_to_numsp256t1(PP, AA, TedCurve);
if (passed==TRUE) printf(" Point addition tests .................................................................... PASSED");
else { printf(" Point addition tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Variable-base scalar multiplication (twisted Edwards a=1)
eccset_numsp256t1(A, TedCurve);
ecc_numsp256t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_256(PP, WeierstrassCurve);
eccdouble_waff_256(PP, WeierstrassCurve);
for (n=0; n<ML_TEST_LOOPS; n++)
{
random256_test(k, TedCurve->order);
ecc_mul_waff_256(PP, k, RR, WeierstrassCurve);
Status = ecc_scalar_mul_numsp256t1(A, k, AA, TedCurve);
ecc_numsp256t1_to_weierstrass(AA, QQ, TedCurve);
if (fpcompare256(QQ->x,RR->x)!=0 || fpcompare256(QQ->y,RR->y)!=0) { passed=FALSE; break; }
}
if (passed==TRUE) printf(" Variable-base scalar multiplication tests ............................................... PASSED");
else { printf(" Variable-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Fixed-base scalar multiplication (twisted Edwards a=1)
eccset_numsp256t1(A, TedCurve);
ecc_numsp256t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_256(PP, WeierstrassCurve);
eccdouble_waff_256(PP, WeierstrassCurve);
for (n=0; n<ML_TEST_LOOPS; n++)
{
random256_test(k, TedCurve->order);
ecc_mul_waff_256(PP, k, RR, WeierstrassCurve);
T_fixed = ecc_allocate_precomp_numsp256t1(OP_FIXEDBASE, TedCurve);
ecc_precomp_fixed_numsp256t1(A, T_fixed, TedCurve);
Status = ecc_scalar_mul_fixed_numsp256t1(T_fixed, k, AA, TedCurve);
ecc_numsp256t1_to_weierstrass(AA, QQ, TedCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare256(QQ->x,RR->x)!=0 || fpcompare256(QQ->y,RR->y)!=0) { passed=FALSE; break; }
}
if (passed==TRUE) printf(" Fixed-base scalar multiplication tests .................................................. PASSED");
else { printf(" Fixed-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Double-scalar multiplication (twisted Edwards a=1)
passed = TRUE;
eccset_numsp256t1(A, TedCurve);
ecc_numsp256t1_to_weierstrass(A, PP, TedCurve);
random256_test(k, TedCurve->order);
ecc_mul_waff_256(PP, k, RR, WeierstrassCurve);
ecc_weierstrass_to_numsp256t1(RR, AA, TedCurve); // Base points are (A, AA) in twisted Edwards, (PP, RR) in Weierstrass
for (n=0; n<ML_TEST_LOOPS; n++)
{
random256_test(k, TedCurve->order);
random256_test(kk, TedCurve->order);
ecc_mul_waff_256(PP, k, UU, WeierstrassCurve);
ecc_mul_waff_256(RR, kk, VV, WeierstrassCurve);
eccadd_waff_256(VV, UU, WeierstrassCurve);
ecc_weierstrass_to_numsp256t1(UU, U, TedCurve);
T_fixed = ecc_allocate_precomp_numsp256t1(OP_DOUBLESCALAR, TedCurve);
ecc_precomp_dblmul_numsp256t1(A, T_fixed, TedCurve);
Status = ecc_double_scalar_mul_numsp256t1(T_fixed, k, AA, kk, V, TedCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare256(U->x,V->x)!=0 || fpcompare256(U->y,V->y)!=0) { passed=FALSE; break; }
}
if (passed==TRUE) printf(" Double-scalar multiplication tests ...................................................... PASSED");
else { printf(" Double-scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
cleanup:
if (passed == FALSE) {
Status = ECCRYPTO_ERROR_DURING_TEST;
}
ecc_curve_free(TedCurve);
ecc_curve_free(WeierstrassCurve);
return Status;
}
#endif
#ifdef ECCURVES_384
ECCRYPTO_STATUS ecc_test384_w(PCurveStaticData CurveData)
{ // Tests for curve numsp384d1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
dig n;
BOOL passed = TRUE;
point_jac_numsp384d1 P, R, complete_table[4] = {0};
dig k[ML_WORDS384], kk[ML_WORDS384];
point_numsp384d1 A, AA, B, BB, *T_fixed = NULL;
PCurveStruct JacCurve = {0};
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp384d1, Weierstrass a=-3 curve over GF(2^384-317) \n\n");
// Curve initialization
JacCurve = ecc_curve_allocate(CurveData);
if (JacCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(JacCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (Weierstrass a=-3)
passed = TRUE;
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccdouble_jac_numsp384d1(P, JacCurve); // 2*P
eccdouble_waff_384(A, JacCurve); // 2*A
}
eccnorm_numsp384d1(P, AA, JacCurve);
if (fpcompare384(A->x, AA->x) != 0 || fpcompare384(A->y, AA->y) != 0) passed = FALSE;
if (passed == TRUE) printf(" Point doubling tests .................................................................... PASSED");
else { printf(" Point doubling tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// "Complete" point addition (Weierstrass a=-3)
passed = TRUE;
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
ecccopy_jac_numsp384d1(P, R);
eccdouble_jac_numsp384d1(P, JacCurve); // P = 2P
eccset_numsp384d1(AA, JacCurve);
eccdouble_waff_384(AA, JacCurve); // AA = 2A
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccadd_jac_numsp384d1(R, P, JacCurve); // P = P+Q
eccadd_waff_384(A, AA, JacCurve); // AA = AA+A
}
eccnorm_numsp384d1(P, A, JacCurve);
if (fpcompare384(A->x, AA->x) != 0 || fpcompare384(A->y, AA->y) != 0) passed = FALSE;
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
ecccopy_jac_numsp384d1(P, R);
fpneg384(JacCurve->prime, R->Y);
eccadd_jac_numsp384d1(R, P, JacCurve); // P+(-P)
if (ecc_is_infinity_jac_numsp384d1(P, JacCurve) == FALSE) passed=FALSE;
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, R);
ecczero_jac_numsp384d1(P); P->Y[0] = 1;
eccadd_jac_numsp384d1(R, P, JacCurve); // 0+R
eccnorm_numsp384d1(P, AA, JacCurve);
if (fpcompare384(A->x,AA->x)!=0 || fpcompare384(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
ecczero_jac_numsp384d1(R); R->Y[0] = 1;
eccadd_jac_numsp384d1(R, P, JacCurve); // P+0
eccnorm_numsp384d1(P, AA, JacCurve);
if (fpcompare384(A->x,AA->x)!=0 || fpcompare384(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
ecccopy_jac_numsp384d1(P, R);
eccadd_jac_numsp384d1(R, P, JacCurve); // P+P
eccnorm_numsp384d1(P, AA, JacCurve);
eccdouble_jac_numsp384d1(R, JacCurve); // 2P
eccnorm_numsp384d1(R, A, JacCurve);
if (fpcompare384(A->x,AA->x)!=0 || fpcompare384(A->y,AA->y)!=0) passed=FALSE;
// Case of mixed addition
complete_table[0]->Y[0] = 1; // Initialize complete_table[0] with the point at infinity (0:1:0)
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, complete_table[1]); // Initialize complete_table[1] with A = (X_A:Y_A:1)
eccconvert_aff_to_jac_numsp384d1(A, P);
fpneg384(JacCurve->prime, P->Y);
eccadd_mixed_jac_numsp384d1(A, P, complete_table, JacCurve); // P+(-P)
if (ecc_is_infinity_jac_numsp384d1(P, JacCurve) == FALSE) passed=FALSE;
eccset_numsp384d1(A, JacCurve);
ecczero_jac_numsp384d1(P); P->Y[0] = 1;
eccadd_mixed_jac_numsp384d1(A, P, complete_table, JacCurve); // 0+R
eccnorm_numsp384d1(P, AA, JacCurve);
if (fpcompare384(A->x,AA->x)!=0 || fpcompare384(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
ecccopy_jac_numsp384d1(P, R);
eccadd_mixed_jac_numsp384d1(A, P, complete_table, JacCurve); // P+P
eccnorm_numsp384d1(P, AA, JacCurve);
eccdouble_jac_numsp384d1(R, JacCurve); // 2P
eccnorm_numsp384d1(R, A, JacCurve);
if (fpcompare384(A->x,AA->x)!=0 || fpcompare384(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp384d1(A, JacCurve);
eccset_numsp384d1(AA, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
eccdouble_jac_numsp384d1(P, JacCurve);
eccadd_mixed_jac_numsp384d1(A, P, complete_table, JacCurve); // P+2P
eccdouble_waff_384(AA, JacCurve);
eccadd_waff_384(A, AA, JacCurve); // P+2P
eccnorm_numsp384d1(P, A, JacCurve);
if (fpcompare384(A->x,AA->x)!=0 || fpcompare384(A->y,AA->y)!=0) passed=FALSE;
if (passed == TRUE) printf(" (Complete) point addition tests ......................................................... PASSED");
else { printf(" (Complete) point addition tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Variable-base scalar multiplication (Weierstrass a=-3)
eccset_numsp384d1(A, JacCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random384_test(k, JacCurve->order);
ecc_mul_waff_384(A, k, AA, JacCurve);
Status = ecc_scalar_mul_numsp384d1(A, k, B, JacCurve);
if (fpcompare384(AA->x, B->x) != 0 || fpcompare384(AA->y, B->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Variable-base scalar multiplication tests ............................................... PASSED");
else { printf(" Variable-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Fixed-base scalar multiplication (Weierstrass a=-3)
eccset_numsp384d1(A, JacCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random384_test(k, JacCurve->order);
ecc_mul_waff_384(A, k, AA, JacCurve);
T_fixed = ecc_allocate_precomp_numsp384d1(OP_FIXEDBASE, JacCurve);
ecc_precomp_fixed_numsp384d1(A, T_fixed, JacCurve);
Status = ecc_scalar_mul_fixed_numsp384d1(T_fixed, k, B, JacCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare384(AA->x, B->x) != 0 || fpcompare384(AA->y, B->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Fixed-base scalar multiplication tests .................................................. PASSED");
else { printf(" Fixed-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Double-scalar multiplication (Weierstrass a=-3)
passed = TRUE;
eccset_numsp384d1(A, JacCurve);
random384_test(k, JacCurve->order);
ecc_mul_waff_384(A, k, B, JacCurve); // Base points are A and B
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random384_test(k, JacCurve->order);
random384_test(kk, JacCurve->order);
ecc_mul_waff_384(A, k, AA, JacCurve);
ecc_mul_waff_384(B, kk, BB, JacCurve);
eccadd_waff_384(BB, AA, JacCurve);
T_fixed = ecc_allocate_precomp_numsp384d1(OP_DOUBLESCALAR, JacCurve);
ecc_precomp_dblmul_numsp384d1(A, T_fixed, JacCurve);
Status = ecc_double_scalar_mul_numsp384d1(T_fixed, k, B, kk, BB, JacCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare384(AA->x, BB->x) != 0 || fpcompare384(AA->y, BB->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Double-scalar multiplication tests ...................................................... PASSED");
else { printf(" Double-scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
cleanup:
if (passed == FALSE) {
Status = ECCRYPTO_ERROR_DURING_TEST;
}
ecc_curve_free(JacCurve);
return Status;
}
ECCRYPTO_STATUS ecc_test384_te(PCurveStaticData CurveData)
{ // Tests for curve numsp384t1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
dig n;
BOOL passed = TRUE;
point_numsp384t1 A, AA, U, V;
point_extproj_numsp384t1 P, R;
point_numsp384d1 PP, QQ, RR, UU, VV;
dig384 a, d, t1, t2, t3;
dig k[ML_WORDS384], kk[ML_WORDS384];
point_extaff_precomp_numsp384t1 *T_fixed = NULL;
PCurveStruct WeierstrassCurve = {0};
PCurveStruct TedCurve = {0};
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp384t1, twisted Edwards a=1 curve over GF(2^384-317) \n\n");
// Curve initialization
TedCurve = ecc_curve_allocate(CurveData);
if (TedCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(TedCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Weierstrass curve allocation
WeierstrassCurve = ecc_curve_allocate(CurveData);
if (WeierstrassCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
// Set Weierstrass curve isomorphic to TedCurve
fpcopy384(TedCurve->parameter1, a);
fpcopy384(TedCurve->parameter2, d);
fpzero384(t3); t3[0] = 14;
fpmul384(t3, d, t1);
fpmul384(t1, a, t1); // t1 = 14ad
fpsqr384(d, t2); // t2 = d^2
fpadd384(t1, t2, t2); // t2 = 14ad+d^2
fpsqr384(a, t3); // t3 = a^2
fpadd384(t2, t3, t2); // t2 = a^2+14ad+d^2
fpneg384(TedCurve->prime, t2); // t2 = -(a^2+14ad+d^2)
fpzero384(t1); t1[0] = 48;
fpinv384(t1); // t1 = 1/48
fpmul384(t1, t2, WeierstrassCurve->parameter1); // aW = -(a^2+14ad+d^2)/48
WeierstrassCurve->nbits = TedCurve->nbits;
WeierstrassCurve->rbits = TedCurve->rbits;
WeierstrassCurve->pbits = TedCurve->pbits;
// Point doubling (twisted Edwards a=1)
passed = TRUE;
eccset_numsp384t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp384t1(A, P);
ecc_numsp384t1_to_weierstrass(A, PP, TedCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccdouble_extproj_numsp384t1(P, TedCurve); // 2*P
eccdouble_waff_384(PP, WeierstrassCurve); // 2*PP
}
eccnorm_numsp384t1(P, A, TedCurve);
ecc_weierstrass_to_numsp384t1(PP, AA, TedCurve);
if (fpcompare384(A->x, AA->x) != 0 || fpcompare384(A->y, AA->y) != 0) passed = FALSE;
if (passed == TRUE) printf(" Point doubling tests .................................................................... PASSED");
else { printf(" Point doubling tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Point addition (twisted Edwards a=1)
passed = TRUE;
eccset_numsp384t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp384t1(A, P);
ecccopy_extproj_numsp384t1(P, R);
eccdouble_extproj_numsp384t1(P, TedCurve); // P = 2P
eccset_numsp384t1(A, TedCurve);
ecc_numsp384t1_to_weierstrass(A, QQ, TedCurve);
ecc_numsp384t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_384(PP, WeierstrassCurve); // PP = 2P
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccadd_extproj_numsp384t1(R, P, TedCurve); // P = P+Q
eccadd_waff_384(QQ, PP, WeierstrassCurve); // PP = PP+QQ
}
eccnorm_numsp384t1(P, A, TedCurve);
ecc_weierstrass_to_numsp384t1(PP, AA, TedCurve);
if (passed == TRUE) printf(" Point addition tests .................................................................... PASSED");
else { printf(" Point addition tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Variable-base scalar multiplication (twisted Edwards a=1)
eccset_numsp384t1(A, TedCurve);
ecc_numsp384t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_384(PP, WeierstrassCurve);
eccdouble_waff_384(PP, WeierstrassCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random384_test(k, TedCurve->order);
ecc_mul_waff_384(PP, k, RR, WeierstrassCurve);
Status = ecc_scalar_mul_numsp384t1(A, k, AA, TedCurve);
ecc_numsp384t1_to_weierstrass(AA, QQ, TedCurve);
if (fpcompare384(QQ->x, RR->x) != 0 || fpcompare384(QQ->y, RR->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Variable-base scalar multiplication tests ............................................... PASSED");
else { printf(" Variable-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Fixed-base scalar multiplication (twisted Edwards a=1)
eccset_numsp384t1(A, TedCurve);
ecc_numsp384t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_384(PP, WeierstrassCurve);
eccdouble_waff_384(PP, WeierstrassCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random384_test(k, TedCurve->order);
ecc_mul_waff_384(PP, k, RR, WeierstrassCurve);
T_fixed = ecc_allocate_precomp_numsp384t1(OP_FIXEDBASE, TedCurve);
ecc_precomp_fixed_numsp384t1(A, T_fixed, TedCurve);
Status = ecc_scalar_mul_fixed_numsp384t1(T_fixed, k, AA, TedCurve);
ecc_numsp384t1_to_weierstrass(AA, QQ, TedCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare384(QQ->x, RR->x) != 0 || fpcompare384(QQ->y, RR->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Fixed-base scalar multiplication tests .................................................. PASSED");
else { printf(" Fixed-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Double-scalar multiplication (twisted Edwards a=1)
passed = TRUE;
eccset_numsp384t1(A, TedCurve);
ecc_numsp384t1_to_weierstrass(A, PP, TedCurve);
random384_test(k, TedCurve->order);
ecc_mul_waff_384(PP, k, RR, WeierstrassCurve);
ecc_weierstrass_to_numsp384t1(RR, AA, TedCurve); // Base points are (A, AA) in twisted Edwards, (PP, RR) in Weierstrass
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random384_test(k, TedCurve->order);
random384_test(kk, TedCurve->order);
ecc_mul_waff_384(PP, k, UU, WeierstrassCurve);
ecc_mul_waff_384(RR, kk, VV, WeierstrassCurve);
eccadd_waff_384(VV, UU, WeierstrassCurve);
ecc_weierstrass_to_numsp384t1(UU, U, TedCurve);
T_fixed = ecc_allocate_precomp_numsp384t1(OP_DOUBLESCALAR, TedCurve);
ecc_precomp_dblmul_numsp384t1(A, T_fixed, TedCurve);
Status = ecc_double_scalar_mul_numsp384t1(T_fixed, k, AA, kk, V, TedCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare384(U->x, V->x) != 0 || fpcompare384(U->y, V->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Double-scalar multiplication tests ...................................................... PASSED");
else { printf(" Double-scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
cleanup:
if (passed == FALSE) {
Status = ECCRYPTO_ERROR_DURING_TEST;
}
ecc_curve_free(TedCurve);
ecc_curve_free(WeierstrassCurve);
return Status;
}
#endif
#ifdef ECCURVES_512
ECCRYPTO_STATUS ecc_test512_w(PCurveStaticData CurveData)
{ // Tests for curve numsp512d1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
dig n;
BOOL passed = TRUE;
point_jac_numsp512d1 P, R, complete_table[4] = {0};
dig k[ML_WORDS512], kk[ML_WORDS512];
point_numsp512d1 A, AA, B, BB, *T_fixed = NULL;
PCurveStruct JacCurve = {0};
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp512d1, Weierstrass a=-3 curve over GF(2^512-569) \n\n");
// Curve initialization
JacCurve = ecc_curve_allocate(CurveData);
if (JacCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(JacCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (Weierstrass a=-3)
passed = TRUE;
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccdouble_jac_numsp512d1(P, JacCurve); // 2*P
eccdouble_waff_512(A, JacCurve); // 2*A
}
eccnorm_numsp512d1(P, AA, JacCurve);
if (fpcompare512(A->x, AA->x) != 0 || fpcompare512(A->y, AA->y) != 0) passed = FALSE;
if (passed == TRUE) printf(" Point doubling tests .................................................................... PASSED");
else { printf(" Point doubling tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// "Complete" point addition (Weierstrass a=-3)
passed = TRUE;
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
ecccopy_jac_numsp512d1(P, R);
eccdouble_jac_numsp512d1(P, JacCurve); // P = 2P
eccset_numsp512d1(AA, JacCurve);
eccdouble_waff_512(AA, JacCurve); // AA = 2A
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccadd_jac_numsp512d1(R, P, JacCurve); // P = P+Q
eccadd_waff_512(A, AA, JacCurve); // AA = AA+A
}
eccnorm_numsp512d1(P, A, JacCurve);
if (fpcompare512(A->x, AA->x) != 0 || fpcompare512(A->y, AA->y) != 0) passed = FALSE;
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
ecccopy_jac_numsp512d1(P, R);
fpneg512(JacCurve->prime, R->Y);
eccadd_jac_numsp512d1(R, P, JacCurve); // P+(-P)
if (ecc_is_infinity_jac_numsp512d1(P, JacCurve) == FALSE) passed=FALSE;
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, R);
ecczero_jac_numsp512d1(P); P->Y[0] = 1;
eccadd_jac_numsp512d1(R, P, JacCurve); // 0+R
eccnorm_numsp512d1(P, AA, JacCurve);
if (fpcompare512(A->x,AA->x)!=0 || fpcompare512(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
ecczero_jac_numsp512d1(R); R->Y[0] = 1;
eccadd_jac_numsp512d1(R, P, JacCurve); // P+0
eccnorm_numsp512d1(P, AA, JacCurve);
if (fpcompare512(A->x,AA->x)!=0 || fpcompare512(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
ecccopy_jac_numsp512d1(P, R);
eccadd_jac_numsp512d1(R, P, JacCurve); // P+P
eccnorm_numsp512d1(P, AA, JacCurve);
eccdouble_jac_numsp512d1(R, JacCurve); // 2P
eccnorm_numsp512d1(R, A, JacCurve);
if (fpcompare512(A->x,AA->x)!=0 || fpcompare512(A->y,AA->y)!=0) passed=FALSE;
// Case of mixed addition
complete_table[0]->Y[0] = 1; // Initialize complete_table[0] with the point at infinity (0:1:0)
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, complete_table[1]); // Initialize complete_table[1] with A = (X_A:Y_A:1)
eccconvert_aff_to_jac_numsp512d1(A, P);
fpneg512(JacCurve->prime, P->Y);
eccadd_mixed_jac_numsp512d1(A, P, complete_table, JacCurve); // P+(-P)
if (ecc_is_infinity_jac_numsp512d1(P, JacCurve) == FALSE) passed=FALSE;
eccset_numsp512d1(A, JacCurve);
ecczero_jac_numsp512d1(P); P->Y[0] = 1;
eccadd_mixed_jac_numsp512d1(A, P, complete_table, JacCurve); // 0+R
eccnorm_numsp512d1(P, AA, JacCurve);
if (fpcompare512(A->x,AA->x)!=0 || fpcompare512(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
ecccopy_jac_numsp512d1(P, R);
eccadd_mixed_jac_numsp512d1(A, P, complete_table, JacCurve); // P+P
eccnorm_numsp512d1(P, AA, JacCurve);
eccdouble_jac_numsp512d1(R, JacCurve); // 2P
eccnorm_numsp512d1(R, A, JacCurve);
if (fpcompare512(A->x,AA->x)!=0 || fpcompare512(A->y,AA->y)!=0) passed=FALSE;
eccset_numsp512d1(A, JacCurve);
eccset_numsp512d1(AA, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
eccdouble_jac_numsp512d1(P, JacCurve);
eccadd_mixed_jac_numsp512d1(A, P, complete_table, JacCurve); // P+2P
eccdouble_waff_512(AA, JacCurve);
eccadd_waff_512(A, AA, JacCurve); // P+2P
eccnorm_numsp512d1(P, A, JacCurve);
if (fpcompare512(A->x,AA->x)!=0 || fpcompare512(A->y,AA->y)!=0) passed=FALSE;
if (passed == TRUE) printf(" (Complete) point addition tests ......................................................... PASSED");
else { printf(" (Complete) point addition tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Variable-base scalar multiplication (Weierstrass a=-3)
eccset_numsp512d1(A, JacCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random512_test(k, JacCurve->order);
ecc_mul_waff_512(A, k, AA, JacCurve);
Status = ecc_scalar_mul_numsp512d1(A, k, B, JacCurve);
if (fpcompare512(AA->x, B->x) != 0 || fpcompare512(AA->y, B->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Variable-base scalar multiplication tests ............................................... PASSED");
else { printf(" Variable-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Fixed-base scalar multiplication (Weierstrass a=-3)
eccset_numsp512d1(A, JacCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random512_test(k, JacCurve->order);
ecc_mul_waff_512(A, k, AA, JacCurve);
T_fixed = ecc_allocate_precomp_numsp512d1(OP_FIXEDBASE, JacCurve);
ecc_precomp_fixed_numsp512d1(A, T_fixed, JacCurve);
Status = ecc_scalar_mul_fixed_numsp512d1(T_fixed, k, B, JacCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare512(AA->x, B->x) != 0 || fpcompare512(AA->y, B->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Fixed-base scalar multiplication tests .................................................. PASSED");
else { printf(" Fixed-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Double-scalar multiplication (Weierstrass a=-3)
passed = TRUE;
eccset_numsp512d1(A, JacCurve);
random512_test(k, JacCurve->order);
ecc_mul_waff_512(A, k, B, JacCurve); // Base points are A and B
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random512_test(k, JacCurve->order);
random512_test(kk, JacCurve->order);
ecc_mul_waff_512(A, k, AA, JacCurve);
ecc_mul_waff_512(B, kk, BB, JacCurve);
eccadd_waff_512(BB, AA, JacCurve);
T_fixed = ecc_allocate_precomp_numsp512d1(OP_DOUBLESCALAR, JacCurve);
ecc_precomp_dblmul_numsp512d1(A, T_fixed, JacCurve);
Status = ecc_double_scalar_mul_numsp512d1(T_fixed, k, B, kk, BB, JacCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare512(AA->x, BB->x) != 0 || fpcompare512(AA->y, BB->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Double-scalar multiplication tests ...................................................... PASSED");
else { printf(" Double-scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
cleanup:
if (passed == FALSE) {
Status = ECCRYPTO_ERROR_DURING_TEST;
}
ecc_curve_free(JacCurve);
return Status;
}
ECCRYPTO_STATUS ecc_test512_te(PCurveStaticData CurveData)
{ // Tests for curve numsp512t1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
dig n;
BOOL passed = TRUE;
point_numsp512t1 A, AA, U, V;
point_extproj_numsp512t1 P, R;
point_numsp512d1 PP, QQ, RR, UU, VV;
dig512 a, d, t1, t2, t3;
dig k[ML_WORDS512], kk[ML_WORDS512];
point_extaff_precomp_numsp512t1 *T_fixed = NULL;
PCurveStruct WeierstrassCurve = {0};
PCurveStruct TedCurve = {0};
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp512t1, twisted Edwards a=1 curve over GF(2^512-569) \n\n");
// Curve initialization
TedCurve = ecc_curve_allocate(CurveData);
if (TedCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(TedCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Weierstrass curve allocation
WeierstrassCurve = ecc_curve_allocate(CurveData);
if (WeierstrassCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
// Set Weierstrass curve isomorphic to TedCurve
fpcopy512(TedCurve->parameter1, a);
fpcopy512(TedCurve->parameter2, d);
fpzero512(t3); t3[0] = 14;
fpmul512(t3, d, t1);
fpmul512(t1, a, t1); // t1 = 14ad
fpsqr512(d, t2); // t2 = d^2
fpadd512(t1, t2, t2); // t2 = 14ad+d^2
fpsqr512(a, t3); // t3 = a^2
fpadd512(t2, t3, t2); // t2 = a^2+14ad+d^2
fpneg512(TedCurve->prime, t2); // t2 = -(a^2+14ad+d^2)
fpzero512(t1); t1[0] = 48;
fpinv512(t1); // t1 = 1/48
fpmul512(t1, t2, WeierstrassCurve->parameter1); // aW = -(a^2+14ad+d^2)/48
WeierstrassCurve->nbits = TedCurve->nbits;
WeierstrassCurve->rbits = TedCurve->rbits;
WeierstrassCurve->pbits = TedCurve->pbits;
// Point doubling (twisted Edwards a=1)
passed = TRUE;
eccset_numsp512t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp512t1(A, P);
ecc_numsp512t1_to_weierstrass(A, PP, TedCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccdouble_extproj_numsp512t1(P, TedCurve); // 2*P
eccdouble_waff_512(PP, WeierstrassCurve); // 2*PP
}
eccnorm_numsp512t1(P, A, TedCurve);
ecc_weierstrass_to_numsp512t1(PP, AA, TedCurve);
if (fpcompare512(A->x, AA->x) != 0 || fpcompare512(A->y, AA->y) != 0) passed = FALSE;
if (passed == TRUE) printf(" Point doubling tests .................................................................... PASSED");
else { printf(" Point doubling tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Point addition (twisted Edwards a=1)
passed = TRUE;
eccset_numsp512t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp512t1(A, P);
ecccopy_extproj_numsp512t1(P, R);
eccdouble_extproj_numsp512t1(P, TedCurve); // P = 2P
eccset_numsp512t1(A, TedCurve);
ecc_numsp512t1_to_weierstrass(A, QQ, TedCurve);
ecc_numsp512t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_512(PP, WeierstrassCurve); // PP = 2P
for (n = 0; n<ML_TEST_LOOPS; n++)
{
eccadd_extproj_numsp512t1(R, P, TedCurve); // P = P+Q
eccadd_waff_512(QQ, PP, WeierstrassCurve); // PP = PP+QQ
}
eccnorm_numsp512t1(P, A, TedCurve);
ecc_weierstrass_to_numsp512t1(PP, AA, TedCurve);
if (passed == TRUE) printf(" Point addition tests .................................................................... PASSED");
else { printf(" Point addition tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Variable-base scalar multiplication (twisted Edwards a=1)
eccset_numsp512t1(A, TedCurve);
ecc_numsp512t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_512(PP, WeierstrassCurve);
eccdouble_waff_512(PP, WeierstrassCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random512_test(k, TedCurve->order);
ecc_mul_waff_512(PP, k, RR, WeierstrassCurve);
Status = ecc_scalar_mul_numsp512t1(A, k, AA, TedCurve);
ecc_numsp512t1_to_weierstrass(AA, QQ, TedCurve);
if (fpcompare512(QQ->x, RR->x) != 0 || fpcompare512(QQ->y, RR->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Variable-base scalar multiplication tests ............................................... PASSED");
else { printf(" Variable-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Fixed-base scalar multiplication (twisted Edwards a=1)
eccset_numsp512t1(A, TedCurve);
ecc_numsp512t1_to_weierstrass(A, PP, TedCurve);
eccdouble_waff_512(PP, WeierstrassCurve);
eccdouble_waff_512(PP, WeierstrassCurve);
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random512_test(k, TedCurve->order);
ecc_mul_waff_512(PP, k, RR, WeierstrassCurve);
T_fixed = ecc_allocate_precomp_numsp512t1(OP_FIXEDBASE, TedCurve);
ecc_precomp_fixed_numsp512t1(A, T_fixed, TedCurve);
Status = ecc_scalar_mul_fixed_numsp512t1(T_fixed, k, AA, TedCurve);
ecc_numsp512t1_to_weierstrass(AA, QQ, TedCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare512(QQ->x, RR->x) != 0 || fpcompare512(QQ->y, RR->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Fixed-base scalar multiplication tests .................................................. PASSED");
else { printf(" Fixed-base scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
// Double-scalar multiplication (twisted Edwards a=1)
passed = TRUE;
eccset_numsp512t1(A, TedCurve);
ecc_numsp512t1_to_weierstrass(A, PP, TedCurve);
random512_test(k, TedCurve->order);
ecc_mul_waff_512(PP, k, RR, WeierstrassCurve);
ecc_weierstrass_to_numsp512t1(RR, AA, TedCurve); // Base points are (A, AA) in twisted Edwards, (PP, RR) in Weierstrass
for (n = 0; n<ML_TEST_LOOPS; n++)
{
random512_test(k, TedCurve->order);
random512_test(kk, TedCurve->order);
ecc_mul_waff_512(PP, k, UU, WeierstrassCurve);
ecc_mul_waff_512(RR, kk, VV, WeierstrassCurve);
eccadd_waff_512(VV, UU, WeierstrassCurve);
ecc_weierstrass_to_numsp512t1(UU, U, TedCurve);
T_fixed = ecc_allocate_precomp_numsp512t1(OP_DOUBLESCALAR, TedCurve);
ecc_precomp_dblmul_numsp512t1(A, T_fixed, TedCurve);
Status = ecc_double_scalar_mul_numsp512t1(T_fixed, k, AA, kk, V, TedCurve);
if (T_fixed != NULL) {
free(T_fixed);
}
if (fpcompare512(U->x, V->x) != 0 || fpcompare512(U->y, V->y) != 0) { passed = FALSE; break; }
}
if (passed == TRUE) printf(" Double-scalar multiplication tests ...................................................... PASSED");
else { printf(" Double-scalar multiplication tests ... FAILED"); printf("\n"); goto cleanup; }
printf("\n");
cleanup:
if (passed == FALSE) {
Status = ECCRYPTO_ERROR_DURING_TEST;
}
ecc_curve_free(TedCurve);
ecc_curve_free(WeierstrassCurve);
return Status;
}
#endif
/****************** BENCHMARK TESTS *******************/
/******************************************************/
#ifdef ECCURVES_256
ECCRYPTO_STATUS ecc_run256_w(PCurveStaticData CurveData)
{ // Benchmarking for curve numsp256d1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
unsigned int n;
unsigned long long cycles, cycles1, cycles2;
point_jac_numsp256d1 P, R;
point_numsp256d1 A, AA, B;
dig k[ML_WORDS256], kk[ML_WORDS256];
point_numsp256d1 *T_fixed = NULL;
PCurveStruct JacCurve = {0};
#if OS_TARGET == OS_WIN
SetThreadAffinityMask(GetCurrentThread(), 1); // All threads are set to run in the same node
SetThreadPriority(GetCurrentThread(), 2); // Set to highest priority
#endif
printf("\n\nBENCHMARKING \n");
printf("--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp256d1, Weierstrass a=-3 curve over GF(2^256-189) \n\n");
// Curve initialization
JacCurve = ecc_curve_allocate(CurveData);
if (JacCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(JacCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (Weierstrass a=-3)
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
cycles = 0;
for (n=0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
eccdouble_jac_numsp256d1(P, JacCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
bench_print("Point doubling", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// "Complete" point addition (Weierstrass a=-3)
eccset_numsp256d1(A, JacCurve);
eccconvert_aff_to_jac_numsp256d1(A, P);
ecccopy_jac_numsp256d1(P, R);
eccdouble_jac_numsp256d1(P, JacCurve);
cycles = 0;
for (n=0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
eccadd_jac_numsp256d1(R, P, JacCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
bench_print("(Complete) point addition", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Variable-base scalar multiplication (Weierstrass a=-3)
eccset_numsp256d1(A, JacCurve);
random256_test(k, JacCurve->order);
cycles = 0;
for (n=0; n<ML_SHORT_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
ecc_scalar_mul_numsp256d1(A, k, AA, JacCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
bench_print("Variable-base scalar mul", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Fixed-base scalar multiplication (Weierstrass a=-3)
eccset_numsp256d1(A, JacCurve);
T_fixed = ecc_allocate_precomp_numsp256d1(OP_FIXEDBASE, JacCurve);
ecc_precomp_fixed_numsp256d1(A, T_fixed, JacCurve);
cycles = 0;
for (n=0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random256_test(k, JacCurve->order);
cycles1 = cpucycles();
ecc_scalar_mul_fixed_numsp256d1(T_fixed, k, AA, JacCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Fixed-base scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Double-scalar multiplication (Weierstrass a=-3)
eccset_numsp256d1(A, JacCurve);
random256_test(k, JacCurve->order);
ecc_mul_waff_256(A, k, AA, JacCurve); // Base points are A and AA
T_fixed = ecc_allocate_precomp_numsp256d1(OP_DOUBLESCALAR, JacCurve);
ecc_precomp_dblmul_numsp256d1(AA, T_fixed, JacCurve);
cycles = 0;
for (n=0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random256_test(k, JacCurve->order);
random256_test(kk, JacCurve->order);
cycles1 = cpucycles();
ecc_double_scalar_mul_numsp256d1(T_fixed, k, A, kk, B, JacCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Double-scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
cleanup:
ecc_curve_free(JacCurve);
return Status;
}
ECCRYPTO_STATUS ecc_run256_te(PCurveStaticData CurveData)
{ // Benchmarking for curve numsp256t1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
unsigned int n;
unsigned long long cycles, cycles1, cycles2;
point_numsp256t1 A, AA;
point_extproj_numsp256t1 P, R;
dig k[ML_WORDS256], kk[ML_WORDS256];
point_extaff_precomp_numsp256t1 *T_fixed = NULL;
PCurveStruct TedCurve = {0};
#if OS_TARGET == OS_WIN
SetThreadAffinityMask(GetCurrentThread(), 1); // All threads are set to run in the same node
SetThreadPriority(GetCurrentThread(), 2); // Set to highest priority
#endif
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp256t1, twisted Edwards a=1 curve over GF(2^256-189) \n\n");
// Curve initialization
TedCurve = ecc_curve_allocate(CurveData);
if (TedCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(TedCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (twisted Edwards a=1)
eccset_numsp256t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp256t1(A, P);
cycles = 0;
for (n=0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
eccdouble_extproj_numsp256t1(P, TedCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
bench_print("Point doubling", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Point addition (twisted Edwards a=1)
eccset_numsp256t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp256t1(A, P);
ecccopy_extproj_numsp256t1(P, R);
eccdouble_extproj_numsp256t1(P, TedCurve);
cycles = 0;
for (n=0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
eccadd_extproj_numsp256t1(R, P, TedCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
bench_print("(Complete) point addition", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Variable-base scalar multiplication (twisted Edwards a=1)
eccset_numsp256t1(A, TedCurve);
random256_test(k, TedCurve->order);
cycles = 0;
for (n=0; n<ML_SHORT_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
ecc_scalar_mul_numsp256t1(A, k, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
bench_print("Variable-base scalar mul", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Fixed-base scalar multiplication (twisted Edwards a=1)
eccset_numsp256t1(A, TedCurve);
T_fixed = ecc_allocate_precomp_numsp256t1(OP_FIXEDBASE, TedCurve);
ecc_precomp_fixed_numsp256t1(A, T_fixed, TedCurve);
cycles = 0;
for (n=0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random256_test(k, TedCurve->order);
cycles1 = cpucycles();
ecc_scalar_mul_fixed_numsp256t1(T_fixed, k, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Fixed-base scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Double-scalar multiplication (twisted Edwards a=1)
eccset_numsp256t1(A, TedCurve);
random256_test(k, TedCurve->order);
ecc_scalar_mul_numsp256t1(A, k, AA, TedCurve); // Base points are A and AA
T_fixed = ecc_allocate_precomp_numsp256t1(OP_DOUBLESCALAR, TedCurve);
ecc_precomp_dblmul_numsp256t1(AA, T_fixed, TedCurve);
cycles = 0;
for (n=0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random256_test(k, TedCurve->order);
random256_test(kk, TedCurve->order);
cycles1 = cpucycles();
ecc_double_scalar_mul_numsp256t1(T_fixed, k, A, kk, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Double-scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
cleanup:
ecc_curve_free(TedCurve);
return Status;
}
#endif
#ifdef ECCURVES_384
ECCRYPTO_STATUS ecc_run384_w(PCurveStaticData CurveData)
{ // Benchmarking for curve numsp384d1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
unsigned int n;
unsigned long long cycles, cycles1, cycles2;
point_jac_numsp384d1 P, R;
point_numsp384d1 A, AA, B;
dig k[ML_WORDS384], kk[ML_WORDS384];
point_numsp384d1 *T_fixed = NULL;
PCurveStruct JacCurve = {0};
#if OS_TARGET == OS_WIN
SetThreadAffinityMask(GetCurrentThread(), 1); // All threads are set to run in the same node
SetThreadPriority(GetCurrentThread(), 2); // Set to highest priority
#endif
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp384d1, Weierstrass a=-3 curve over GF(2^384-317) \n\n");
// Curve initialization
JacCurve = ecc_curve_allocate(CurveData);
if (JacCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(JacCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (Weierstrass a=-3)
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
cycles = 0;
for (n = 0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
eccdouble_jac_numsp384d1(P, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Point doubling", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// "Complete" point addition (Weierstrass a=-3)
eccset_numsp384d1(A, JacCurve);
eccconvert_aff_to_jac_numsp384d1(A, P);
ecccopy_jac_numsp384d1(P, R);
eccdouble_jac_numsp384d1(P, JacCurve);
cycles = 0;
for (n = 0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
eccadd_jac_numsp384d1(R, P, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("(Complete) point addition", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Variable-base scalar multiplication (Weierstrass a=-3)
eccset_numsp384d1(A, JacCurve);
random384_test(k, JacCurve->order);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
ecc_scalar_mul_numsp384d1(A, k, AA, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Variable-base scalar mul", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Fixed-base scalar multiplication (Weierstrass a=-3)
eccset_numsp384d1(A, JacCurve);
T_fixed = ecc_allocate_precomp_numsp384d1(OP_FIXEDBASE, JacCurve);
ecc_precomp_fixed_numsp384d1(A, T_fixed, JacCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random384_test(k, JacCurve->order);
cycles1 = cpucycles();
ecc_scalar_mul_fixed_numsp384d1(T_fixed, k, AA, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Fixed-base scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Double-scalar multiplication (Weierstrass a=-3)
eccset_numsp384d1(A, JacCurve);
random384_test(k, JacCurve->order);
ecc_mul_waff_384(A, k, AA, JacCurve); // Base points are A and AA
T_fixed = ecc_allocate_precomp_numsp384d1(OP_DOUBLESCALAR, JacCurve);
ecc_precomp_dblmul_numsp384d1(AA, T_fixed, JacCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random384_test(k, JacCurve->order);
random384_test(kk, JacCurve->order);
cycles1 = cpucycles();
ecc_double_scalar_mul_numsp384d1(T_fixed, k, A, kk, B, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Double-scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
cleanup:
ecc_curve_free(JacCurve);
return Status;
}
ECCRYPTO_STATUS ecc_run384_te(PCurveStaticData CurveData)
{ // Benchmarking for curve numsp384t1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
unsigned int n;
unsigned long long cycles, cycles1, cycles2;
point_numsp384t1 A, AA;
point_extproj_numsp384t1 P, R;
dig k[ML_WORDS384], kk[ML_WORDS384];
point_extaff_precomp_numsp384t1 *T_fixed = NULL;
PCurveStruct TedCurve = {0};
#if OS_TARGET == OS_WIN
SetThreadAffinityMask(GetCurrentThread(), 1); // All threads are set to run in the same node
SetThreadPriority(GetCurrentThread(), 2); // Set to highest priority
#endif
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp384t1, twisted Edwards a=1 curve over GF(2^384-317) \n\n");
// Curve initialization
TedCurve = ecc_curve_allocate(CurveData);
if (TedCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(TedCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (twisted Edwards a=1)
eccset_numsp384t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp384t1(A, P);
cycles = 0;
for (n = 0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
eccdouble_extproj_numsp384t1(P, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Point doubling", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Point addition (twisted Edwards a=1)
eccset_numsp384t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp384t1(A, P);
ecccopy_extproj_numsp384t1(P, R);
eccdouble_extproj_numsp384t1(P, TedCurve);
cycles = 0;
for (n=0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
eccadd_extproj_numsp384t1(R, P, TedCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
bench_print("(Complete) point addition", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Variable-base scalar multiplication (twisted Edwards a=1)
eccset_numsp384t1(A, TedCurve);
random384_test(k, TedCurve->order);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
ecc_scalar_mul_numsp384t1(A, k, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Variable-base scalar mul", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Fixed-base scalar multiplication (twisted Edwards a=1)
eccset_numsp384t1(A, TedCurve);
T_fixed = ecc_allocate_precomp_numsp384t1(OP_FIXEDBASE, TedCurve);
ecc_precomp_fixed_numsp384t1(A, T_fixed, TedCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random384_test(k, TedCurve->order);
cycles1 = cpucycles();
ecc_scalar_mul_fixed_numsp384t1(T_fixed, k, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles+(cycles2-cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Fixed-base scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Double-scalar multiplication (twisted Edwards a=1)
eccset_numsp384t1(A, TedCurve);
random384_test(k, TedCurve->order);
ecc_scalar_mul_numsp384t1(A, k, AA, TedCurve); // Base points are A and AA
T_fixed = ecc_allocate_precomp_numsp384t1(OP_DOUBLESCALAR, TedCurve);
ecc_precomp_dblmul_numsp384t1(AA, T_fixed, TedCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random384_test(k, TedCurve->order);
random384_test(kk, TedCurve->order);
cycles1 = cpucycles();
ecc_double_scalar_mul_numsp384t1(T_fixed, k, A, kk, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Double-scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
cleanup:
ecc_curve_free(TedCurve);
return Status;
}
#endif
#ifdef ECCURVES_512
ECCRYPTO_STATUS ecc_run512_w(PCurveStaticData CurveData)
{ // Benchmarking for curve numsp512d1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
unsigned int n;
unsigned long long cycles, cycles1, cycles2;
point_jac_numsp512d1 P, R;
point_numsp512d1 A, AA, B;
dig k[ML_WORDS512], kk[ML_WORDS512];
point_numsp512d1 *T_fixed = NULL;
PCurveStruct JacCurve = {0};
#if OS_TARGET == OS_WIN
SetThreadAffinityMask(GetCurrentThread(), 1); // All threads are set to run in the same node
SetThreadPriority(GetCurrentThread(), 2); // Set to highest priority
#endif
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp512d1, Weierstrass a=-3 curve over GF(2^512-569) \n\n");
// Curve initialization
JacCurve = ecc_curve_allocate(CurveData);
if (JacCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(JacCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (Weierstrass a=-3)
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
cycles = 0;
for (n = 0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
eccdouble_jac_numsp512d1(P, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Point doubling", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// "Complete" point addition (Weierstrass a=-3)
eccset_numsp512d1(A, JacCurve);
eccconvert_aff_to_jac_numsp512d1(A, P);
ecccopy_jac_numsp512d1(P, R);
eccdouble_jac_numsp512d1(P, JacCurve);
cycles = 0;
for (n = 0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
eccadd_jac_numsp512d1(R, P, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("(Complete) point addition", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Variable-base scalar multiplication (Weierstrass a=-3)
eccset_numsp512d1(A, JacCurve);
random512_test(k, JacCurve->order);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
ecc_scalar_mul_numsp512d1(A, k, AA, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Variable-base scalar mul", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Fixed-base scalar multiplication (Weierstrass a=-3)
eccset_numsp512d1(A, JacCurve);
T_fixed = ecc_allocate_precomp_numsp512d1(OP_FIXEDBASE, JacCurve);
ecc_precomp_fixed_numsp512d1(A, T_fixed, JacCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random512_test(k, JacCurve->order);
cycles1 = cpucycles();
ecc_scalar_mul_fixed_numsp512d1(T_fixed, k, AA, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Fixed-base scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Double-scalar multiplication (Weierstrass a=-3)
eccset_numsp512d1(A, JacCurve);
random512_test(k, JacCurve->order);
ecc_mul_waff_512(A, k, AA, JacCurve); // Base points are A and AA
T_fixed = ecc_allocate_precomp_numsp512d1(OP_DOUBLESCALAR, JacCurve);
ecc_precomp_dblmul_numsp512d1(AA, T_fixed, JacCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random512_test(k, JacCurve->order);
random512_test(kk, JacCurve->order);
cycles1 = cpucycles();
ecc_double_scalar_mul_numsp512d1(T_fixed, k, A, kk, B, JacCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Double-scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
cleanup:
ecc_curve_free(JacCurve);
return Status;
}
ECCRYPTO_STATUS ecc_run512_te(PCurveStaticData CurveData)
{ // Benchmarking for curve numsp512t1
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
unsigned int n;
unsigned long long cycles, cycles1, cycles2;
point_numsp512t1 A, AA;
point_extproj_numsp512t1 P, R;
dig k[ML_WORDS512], kk[ML_WORDS512];
point_extaff_precomp_numsp512t1 *T_fixed = NULL;
PCurveStruct TedCurve = {0};
#if OS_TARGET == OS_WIN
SetThreadAffinityMask(GetCurrentThread(), 1); // All threads are set to run in the same node
SetThreadPriority(GetCurrentThread(), 2); // Set to highest priority
#endif
printf("\n--------------------------------------------------------------------------------------------------------\n\n");
printf("Curve arithmetic: numsp512t1, twisted Edwards a=1 curve over GF(2^512-569) \n\n");
// Curve initialization
TedCurve = ecc_curve_allocate(CurveData);
if (TedCurve == NULL) {
Status = ECCRYPTO_ERROR_NO_MEMORY;
goto cleanup;
}
Status = ecc_curve_initialize(TedCurve, MEM_LARGE, NULL, CurveData);
if (Status != ECCRYPTO_SUCCESS) {
goto cleanup;
}
// Point doubling (twisted Edwards a=1)
eccset_numsp512t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp512t1(A, P);
cycles = 0;
for (n = 0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
eccdouble_extproj_numsp512t1(P, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Point doubling", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Point addition (twisted Edwards a=1)
eccset_numsp512t1(A, TedCurve);
eccconvert_aff_to_extproj_numsp512t1(A, P);
ecccopy_extproj_numsp512t1(P, R);
eccdouble_extproj_numsp512t1(P, TedCurve);
cycles = 0;
for (n = 0; n<ML_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
eccadd_extproj_numsp512t1(R, P, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("(Complete) point addition", cycles, ML_BENCH_LOOPS*10);
printf("\n");
// Variable-base scalar multiplication (twisted Edwards a=1)
eccset_numsp512t1(A, TedCurve);
random512_test(k, TedCurve->order);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
cycles1 = cpucycles();
ecc_scalar_mul_numsp512t1(A, k, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
bench_print("Variable-base scalar mul", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Fixed-base scalar multiplication (twisted Edwards a=1)
eccset_numsp512t1(A, TedCurve);
T_fixed = ecc_allocate_precomp_numsp512t1(OP_FIXEDBASE, TedCurve);
ecc_precomp_fixed_numsp512t1(A, T_fixed, TedCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random512_test(k, TedCurve->order);
cycles1 = cpucycles();
ecc_scalar_mul_fixed_numsp512t1(T_fixed, k, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Fixed-base scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
// Double-scalar multiplication (twisted Edwards a=1)
eccset_numsp512t1(A, TedCurve);
random512_test(k, TedCurve->order);
ecc_scalar_mul_numsp512t1(A, k, AA, TedCurve); // Base points are A and AA
T_fixed = ecc_allocate_precomp_numsp512t1(OP_DOUBLESCALAR, TedCurve);
ecc_precomp_dblmul_numsp512t1(AA, T_fixed, TedCurve);
cycles = 0;
for (n = 0; n<ML_SHORT_BENCH_LOOPS; n++)
{
random512_test(k, TedCurve->order);
random512_test(kk, TedCurve->order);
cycles1 = cpucycles();
ecc_double_scalar_mul_numsp512t1(T_fixed, k, A, kk, AA, TedCurve);
cycles2 = cpucycles();
cycles = cycles + (cycles2 - cycles1);
}
if (T_fixed != NULL) {
free(T_fixed);
}
bench_print("Double-scalar mul (memory model=MEM_LARGE)", cycles, ML_SHORT_BENCH_LOOPS);
printf("\n");
cleanup:
ecc_curve_free(TedCurve);
return Status;
}
#endif
int main()
{
const char* message = NULL;
ECCRYPTO_STATUS Status = ECCRYPTO_SUCCESS;
if (is_avx_supported() == FALSE) {
#ifdef AVX_SUPPORT
printf("\n SUPPORT FOR AVX CANNOT BE DETECTED BUT USER HAS ENABLED IT IN THE LIBRARY --- _AVX_ compiler flag must be disabled \n");
return FALSE;
#endif
} else {
#ifndef AVX_SUPPORT
printf("\n SUPPORT FOR AVX HAS BEEN DETECTED BUT USER HAS NOT ENABLED IT IN THE LIBRARY --- enabling _AVX_ compiler flag is recommended \n");
#endif
}
#ifdef ECCURVES_256
Status = ecc_test256_w(&curve_numsp256d1); // Test "numsp256d1", Weierstrass a=-3 curve with p = 2^256-189
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
Status = ecc_test256_te(&curve_numsp256t1); // Test "numsp256t1", twisted Edwards a=1 curve with p = 2^256-189
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
#endif
#ifdef ECCURVES_384
Status = ecc_test384_w(&curve_numsp384d1); // Test "numsp384d1", Weierstrass a=-3 curve with p = 2^384-317
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
Status = ecc_test384_te(&curve_numsp384t1); // Test "numsp384t1", twisted Edwards a=1 curve with p = 2^384-317
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
#endif
#ifdef ECCURVES_512
Status = ecc_test512_w(&curve_numsp512d1); // Test "numsp512d1", Weierstrass a=-3 curve with p = 2^512-569
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
Status = ecc_test512_te(&curve_numsp512t1); // Test "numsp512t1", twisted Edwards a=1 curve with p = 2^512-569
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
#endif
#ifdef ECCURVES_256
Status = ecc_run256_w(&curve_numsp256d1); // Benchmark "numsp256d1", Weierstrass a=-3 curve with p = 2^256-189
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
Status = ecc_run256_te(&curve_numsp256t1); // Benchmark "numsp256t1", twisted Edwards a=1 curve with p = 2^256-189
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
#endif
#ifdef ECCURVES_384
Status = ecc_run384_w(&curve_numsp384d1); // Benchmark "numsp384d1", Weierstrass a=-3 curve with p = 2^384-317
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
Status = ecc_run384_te(&curve_numsp384t1); // Benchmark "numsp384t1", twisted Edwards a=1 curve with p = 2^384-317
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
#endif
#ifdef ECCURVES_512
Status = ecc_run512_w(&curve_numsp512d1); // Benchmark "numsp512d1", Weierstrass a=-3 curve with p = 2^512-569
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
Status = ecc_run512_te(&curve_numsp512t1); // Benchmark "numsp512t1", twisted Edwards a=1 curve with p = 2^512-569
if (Status != ECCRYPTO_SUCCESS) {
message = ecc_get_error_message(Status);
printf("\n\n Error detected: %s \n\n", message);
return FALSE;
}
#endif
return TRUE;
}
|
GaloisInc/hacrypto
|
src/C/MSR_ECClib_v2.0/Tests/ecc_tests.c
|
C
|
bsd-3-clause
| 87,407 |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model frontend\models\EmailAddress */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Email Addresses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="email-address-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'person_id',
'live',
'type',
'email:email',
'note:ntext',
'user_id_created',
'date_entered',
'date_updated',
'ip_created',
'ip_updated',
],
]) ?>
</div>
|
elminero/contact_v4
|
frontend/views/email-address/view.php
|
PHP
|
bsd-3-clause
| 1,150 |
(function($)
{
$.Redactor.prototype.inlinestyle = function()
{
return {
langs: {
en: {
"style": "Style"
}
},
init: function()
{
var tags = {
"marked": {
title: "Marked",
args: ['mark']
},
"code": {
title: "Code",
args: ['code']
},
"sample": {
title: "Sample",
args: ['samp']
},
"variable": {
title: "Variable",
args: ['var']
},
"shortcut": {
title: "Shortcut",
args: ['kbd']
},
"cite": {
title: "Cite",
args: ['cite']
},
"sup": {
title: "Superscript",
args: ['abbr']
},
"sub": {
title: "Subscript",
args: ['sub']
}
};
var that = this;
var dropdown = {};
$.each(tags, function(i, s)
{
dropdown[i] = { title: s.title, func: 'inline.format', args: s.args };
});
var button = this.button.addAfter('format', 'inline', this.lang.get('style'));
this.button.addDropdown(button, dropdown);
}
};
};
})(jQuery);
|
unomena/django-redactor
|
redactor/static/redactor/js/inlinestyle.js
|
JavaScript
|
bsd-3-clause
| 1,060 |
/*
* @brief LPC18xx/43xx I2S driver
*
* @note
* Copyright(C) NXP Semiconductors, 2012
* All rights reserved.
*
* @par
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* LPC products. This software is supplied "AS IS" without any warranties of
* any kind, and NXP Semiconductors and its licensor disclaim any and
* all warranties, express or implied, including all implied warranties of
* merchantability, fitness for a particular purpose and non-infringement of
* intellectual property rights. NXP Semiconductors assumes no responsibility
* or liability for the use of the software, conveys no license or rights under any
* patent, copyright, mask work right, or any other intellectual property rights in
* or to any products. NXP Semiconductors reserves the right to make changes
* in the software without notification. NXP Semiconductors also makes no
* representation or warranty that such application will be suitable for the
* specified use without further testing or modification.
*
* @par
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, under NXP Semiconductors' and its
* licensor's relevant copyrights in the software, without fee, provided that it
* is used in conjunction with NXP Semiconductors microcontrollers. This
* copyright, permission, and disclaimer notice must appear in all copies of
* this code.
*/
#include "chip.h"
/*****************************************************************************
* Private types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Public types/enumerations/variables
****************************************************************************/
/*****************************************************************************
* Private functions
****************************************************************************/
/* Get divider value */
STATIC Status getClkDiv(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format, uint16_t *pxDiv, uint16_t *pyDiv, uint32_t *pN)
{
uint32_t pClk;
uint32_t x, y;
uint64_t divider;
uint16_t dif;
uint16_t xDiv = 0, yDiv = 0;
uint32_t N;
uint16_t err, ErrorOptimal = 0xFFFF;
pClk = Chip_Clock_GetRate(CLK_APB1_I2S);
/* divider is a fixed point number with 16 fractional bits */
divider = (((uint64_t) (format->SampleRate) * 2 * (format->WordWidth) * 2) << 16) / pClk;
/* find N that make x/y <= 1 -> divider <= 2^16 */
for (N = 64; N > 0; N--) {
if ((divider * N) < (1 << 16)) {
break;
}
}
if (N == 0) {
return ERROR;
}
divider *= N;
for (y = 255; y > 0; y--) {
x = y * divider;
if (x & (0xFF000000)) {
continue;
}
dif = x & 0xFFFF;
if (dif > 0x8000) {
err = 0x10000 - dif;
}
else {
err = dif;
}
if (err == 0) {
yDiv = y;
break;
}
else if (err < ErrorOptimal) {
ErrorOptimal = err;
yDiv = y;
}
}
xDiv = ((uint64_t) yDiv * (format->SampleRate) * 2 * (format->WordWidth) * N * 2) / pClk;
if (xDiv >= 256) {
xDiv = 0xFF;
}
if (xDiv == 0) {
xDiv = 1;
}
*pxDiv = xDiv;
*pyDiv = yDiv;
*pN = N;
return SUCCESS;
}
/*****************************************************************************
* Public functions
****************************************************************************/
/* Initialize the I2S interface */
void Chip_I2S_Init(LPC_I2S_T *pI2S)
{
Chip_Clock_Enable(CLK_APB1_I2S);
}
/* Shutdown I2S */
void Chip_I2S_DeInit(LPC_I2S_T *pI2S)
{
pI2S->DAI = 0x07E1;
pI2S->DAO = 0x87E1;
pI2S->IRQ = 0;
pI2S->TXMODE = 0;
pI2S->RXMODE = 0;
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_1] = 0;
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_2] = 0;
Chip_Clock_Disable(CLK_APB1_I2S);
}
/* Configure I2S for Audio Format input */
Status Chip_I2S_TxConfig(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format)
{
uint32_t temp;
uint16_t xDiv, yDiv;
uint32_t N;
if (getClkDiv(pI2S, format, &xDiv, &yDiv, &N) == ERROR) {
return ERROR;
}
temp = pI2S->DAO & (~(I2S_DAO_WORDWIDTH_MASK | I2S_DAO_MONO | I2S_DAO_SLAVE | I2S_DAO_WS_HALFPERIOD_MASK));
if (format->WordWidth <= 8) {
temp |= I2S_WORDWIDTH_8;
}
else if (format->WordWidth <= 16) {
temp |= I2S_WORDWIDTH_16;
}
else {
temp |= I2S_WORDWIDTH_32;
}
temp |= (format->ChannelNumber) == 1 ? I2S_MONO : I2S_STEREO;
temp |= I2S_MASTER_MODE;
temp |= I2S_DAO_WS_HALFPERIOD(format->WordWidth - 1);
pI2S->DAO = temp;
pI2S->TXMODE = I2S_TXMODE_CLKSEL(0);
pI2S->TXBITRATE = N - 1;
pI2S->TXRATE = yDiv | (xDiv << 8);
return SUCCESS;
}
/* Configure I2S for Audio Format input */
Status Chip_I2S_RxConfig(LPC_I2S_T *pI2S, I2S_AUDIO_FORMAT_T *format)
{
uint32_t temp;
uint16_t xDiv, yDiv;
uint32_t N;
if (getClkDiv(pI2S, format, &xDiv, &yDiv, &N) == ERROR) {
return ERROR;
}
temp = pI2S->DAI & (~(I2S_DAI_WORDWIDTH_MASK | I2S_DAI_MONO | I2S_DAI_SLAVE | I2S_DAI_WS_HALFPERIOD_MASK));
if (format->WordWidth <= 8) {
temp |= I2S_WORDWIDTH_8;
}
else if (format->WordWidth <= 16) {
temp |= I2S_WORDWIDTH_16;
}
else {
temp |= I2S_WORDWIDTH_32;
}
temp |= (format->ChannelNumber) == 1 ? I2S_MONO : I2S_STEREO;
temp |= I2S_MASTER_MODE;
temp |= I2S_DAI_WS_HALFPERIOD(format->WordWidth - 1);
pI2S->DAI = temp;
pI2S->RXMODE = I2S_RXMODE_CLKSEL(0);
pI2S->RXBITRATE = N - 1;
pI2S->RXRATE = yDiv | (xDiv << 8);
return SUCCESS;
}
/* Enable/Disable Interrupt with a specific FIFO depth */
void Chip_I2S_Int_TxCmd(LPC_I2S_T *pI2S, FunctionalState newState, uint8_t depth)
{
uint32_t temp;
depth &= 0x0F;
if (newState == ENABLE) {
temp = pI2S->IRQ & (~I2S_IRQ_TX_DEPTH_MASK);
pI2S->IRQ = temp | (I2S_IRQ_TX_DEPTH(depth));
pI2S->IRQ |= 0x02;
}
else {
pI2S->IRQ &= (~0x02);
}
}
/* Enable/Disable Interrupt with a specific FIFO depth */
void Chip_I2S_Int_RxCmd(LPC_I2S_T *pI2S, FunctionalState newState, uint8_t depth)
{
uint32_t temp;
depth &= 0x0F;
if (newState == ENABLE) {
temp = pI2S->IRQ & (~I2S_IRQ_RX_DEPTH_MASK);
pI2S->IRQ = temp | (I2S_IRQ_RX_DEPTH(depth));
pI2S->IRQ |= 0x01;
}
else {
pI2S->IRQ &= (~0x01);
}
}
/* Enable/Disable DMA with a specific FIFO depth */
void Chip_I2S_DMA_TxCmd(LPC_I2S_T *pI2S,
I2S_DMA_CHANNEL_T dmaNum,
FunctionalState newState,
uint8_t depth)
{
/* Enable/Disable I2S transmit*/
if (newState == ENABLE) {
/* Set FIFO Level */
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_1] &= ~(0x0F << 16);
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_1] |= depth << 16;
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_1] |= 0x02;
}
else {
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_1] &= ~0x02;
}
}
/* Enable/Disable DMA with a specific FIFO depth */
void Chip_I2S_DMA_RxCmd(LPC_I2S_T *pI2S,
I2S_DMA_CHANNEL_T dmaNum,
FunctionalState newState,
uint8_t depth)
{
/* Enable/Disable I2S Receive */
if (newState == ENABLE) {
/* Set FIFO Level */
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_2] &= ~(0x0F << 8);
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_2] |= depth << 8;
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_2] |= 0x01;
}
else {
pI2S->DMA[I2S_DMA_REQUEST_CHANNEL_2] &= ~0x01;
}
}
|
pridolfi/workspace
|
modules/lpc4337_m4/chip/src/i2s_18xx_43xx.c
|
C
|
bsd-3-clause
| 7,481 |
/*-
* Copyright (c) 2003 Matthew N. Dodd <[email protected]>
* 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 THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* $FreeBSD: src/sys/pci/agp_nvidia.c,v 1.2 2003/08/23 19:32:18 mdodd Exp $
*/
/*
* Written using information gleaned from the
* NVIDIA nForce/nForce2 AGPGART Linux Kernel Patch.
*/
#include "opt_bus.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/bus.h>
#include <sys/lock.h>
#if __FreeBSD_version < 500000
#include "opt_pci.h"
#endif
#if __FreeBSD_version > 500000
#include <sys/lockmgr.h>
#include <sys/mutex.h>
#include <sys/proc.h>
#endif
#include <dev/pci/pcivar.h>
#include <dev/pci/pcireg.h>
#include <pci/agppriv.h>
#include <pci/agpreg.h>
#include <vm/vm.h>
#include <vm/vm_object.h>
#include <vm/pmap.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>
#define NVIDIA_VENDORID 0x10de
#define NVIDIA_DEVICEID_NFORCE 0x01a4
#define NVIDIA_DEVICEID_NFORCE2 0x01e0
struct agp_nvidia_softc {
struct agp_softc agp;
u_int32_t initial_aperture; /* aperture size at startup */
struct agp_gatt * gatt;
device_t dev; /* AGP Controller */
device_t mc1_dev; /* Memory Controller */
device_t mc2_dev; /* Memory Controller */
device_t bdev; /* Bridge */
u_int32_t wbc_mask;
int num_dirs;
int num_active_entries;
off_t pg_offset;
};
static const char * agp_nvidia_match (device_t dev);
static int agp_nvidia_probe (device_t);
static int agp_nvidia_attach (device_t);
static int agp_nvidia_detach (device_t);
static u_int32_t agp_nvidia_get_aperture (device_t);
static int agp_nvidia_set_aperture (device_t, u_int32_t);
static int agp_nvidia_bind_page (device_t, int, vm_offset_t);
static int agp_nvidia_unbind_page (device_t, int);
static int nvidia_init_iorr (u_int32_t, u_int32_t);
static const char *
agp_nvidia_match (device_t dev)
{
if (pci_get_class(dev) != PCIC_BRIDGE ||
pci_get_subclass(dev) != PCIS_BRIDGE_HOST ||
pci_get_vendor(dev) != NVIDIA_VENDORID)
return (NULL);
switch (pci_get_device(dev)) {
case NVIDIA_DEVICEID_NFORCE:
return ("NVIDIA nForce AGP Controller");
case NVIDIA_DEVICEID_NFORCE2:
return ("NVIDIA nForce2 AGP Controller");
}
return ("NVIDIA Generic AGP Controller");
}
static int
agp_nvidia_probe (device_t dev)
{
const char *desc;
desc = agp_nvidia_match(dev);
if (desc) {
device_verbose(dev);
device_set_desc(dev, desc);
return (0);
}
return (ENXIO);
}
static int
agp_nvidia_attach (device_t dev)
{
struct agp_nvidia_softc *sc = device_get_softc(dev);
struct agp_gatt *gatt;
u_int32_t apbase;
u_int32_t aplimit;
u_int32_t temp;
int size;
int i;
int error;
switch (pci_get_device(dev)) {
case NVIDIA_DEVICEID_NFORCE:
sc->wbc_mask = 0x00010000;
break;
case NVIDIA_DEVICEID_NFORCE2:
sc->wbc_mask = 0x80000000;
break;
default:
sc->wbc_mask = 0;
break;
}
/* AGP Controller */
sc->dev = dev;
/* Memory Controller 1 */
sc->mc1_dev = pci_find_bsf(pci_get_bus(dev), 0, 1);
if (sc->mc1_dev == NULL) {
device_printf(dev,
"Unable to find NVIDIA Memory Controller 1.\n");
return (ENODEV);
}
/* Memory Controller 2 */
sc->mc2_dev = pci_find_bsf(pci_get_bus(dev), 0, 2);
if (sc->mc2_dev == NULL) {
device_printf(dev,
"Unable to find NVIDIA Memory Controller 2.\n");
return (ENODEV);
}
/* AGP Host to PCI Bridge */
sc->bdev = pci_find_bsf(pci_get_bus(dev), 30, 0);
if (sc->bdev == NULL) {
device_printf(dev,
"Unable to find NVIDIA AGP Host to PCI Bridge.\n");
return (ENODEV);
}
error = agp_generic_attach(dev);
if (error)
return (error);
sc->initial_aperture = AGP_GET_APERTURE(dev);
for (;;) {
gatt = agp_alloc_gatt(dev);
if (gatt)
break;
/*
* Probably contigmalloc failure. Try reducing the
* aperture so that the gatt size reduces.
*/
if (AGP_SET_APERTURE(dev, AGP_GET_APERTURE(dev) / 2))
goto fail;
}
sc->gatt = gatt;
apbase = rman_get_start(sc->agp.as_aperture);
aplimit = apbase + AGP_GET_APERTURE(dev) - 1;
pci_write_config(sc->mc2_dev, AGP_NVIDIA_2_APBASE, apbase, 4);
pci_write_config(sc->mc2_dev, AGP_NVIDIA_2_APLIMIT, aplimit, 4);
pci_write_config(sc->bdev, AGP_NVIDIA_3_APBASE, apbase, 4);
pci_write_config(sc->bdev, AGP_NVIDIA_3_APLIMIT, aplimit, 4);
error = nvidia_init_iorr(apbase, AGP_GET_APERTURE(dev));
if (error) {
device_printf(dev, "Failed to setup IORRs\n");
goto fail;
}
/* directory size is 64k */
size = AGP_GET_APERTURE(dev) / 1024 / 1024;
sc->num_dirs = size / 64;
sc->num_active_entries = (size == 32) ? 16384 : ((size * 1024) / 4);
sc->pg_offset = 0;
if (sc->num_dirs == 0) {
sc->num_dirs = 1;
sc->num_active_entries /= (64 / size);
sc->pg_offset = (apbase & (64 * 1024 * 1024 - 1) &
~(AGP_GET_APERTURE(dev) - 1)) / PAGE_SIZE;
}
/* (G)ATT Base Address */
for (i = 0; i < 8; i++) {
pci_write_config(sc->mc2_dev, AGP_NVIDIA_2_ATTBASE(i),
(sc->gatt->ag_physical +
(i % sc->num_dirs) * 64 * 1024),
4);
}
/* GTLB Control */
temp = pci_read_config(sc->mc2_dev, AGP_NVIDIA_2_GARTCTRL, 4);
pci_write_config(sc->mc2_dev, AGP_NVIDIA_2_GARTCTRL, temp | 0x11, 4);
/* GART Control */
temp = pci_read_config(sc->dev, AGP_NVIDIA_0_APSIZE, 4);
pci_write_config(sc->dev, AGP_NVIDIA_0_APSIZE, temp | 0x100, 4);
return (0);
fail:
agp_generic_detach(dev);
return (ENOMEM);
}
static int
agp_nvidia_detach (device_t dev)
{
struct agp_nvidia_softc *sc = device_get_softc(dev);
int error;
u_int32_t temp;
error = agp_generic_detach(dev);
if (error)
return (error);
/* GART Control */
temp = pci_read_config(sc->dev, AGP_NVIDIA_0_APSIZE, 4);
pci_write_config(sc->dev, AGP_NVIDIA_0_APSIZE, temp & ~(0x100), 4);
/* GTLB Control */
temp = pci_read_config(sc->mc2_dev, AGP_NVIDIA_2_GARTCTRL, 4);
pci_write_config(sc->mc2_dev, AGP_NVIDIA_2_GARTCTRL, temp & ~(0x11), 4);
/* Put the aperture back the way it started. */
AGP_SET_APERTURE(dev, sc->initial_aperture);
/* restore iorr for previous aperture size */
nvidia_init_iorr(rman_get_start(sc->agp.as_aperture),
sc->initial_aperture);
agp_free_gatt(sc->gatt);
return (0);
}
static u_int32_t
agp_nvidia_get_aperture(device_t dev)
{
u_int8_t key;
key = ffs(pci_read_config(dev, AGP_NVIDIA_0_APSIZE, 1) & 0x0f);
return (1 << (24 + (key ? key : 5)));
}
static int
agp_nvidia_set_aperture(device_t dev, u_int32_t aperture)
{
u_int8_t val;
u_int8_t key;
switch (aperture) {
case (512 * 1024 * 1024): key = 0; break;
case (256 * 1024 * 1024): key = 8; break;
case (128 * 1024 * 1024): key = 12; break;
case (64 * 1024 * 1024): key = 14; break;
case (32 * 1024 * 1024): key = 15; break;
default:
device_printf(dev, "Invalid aperture size (%dMb)\n",
aperture / 1024 / 1024);
return (EINVAL);
}
val = pci_read_config(dev, AGP_NVIDIA_0_APSIZE, 1);
pci_write_config(dev, AGP_NVIDIA_0_APSIZE, ((val & ~0x0f) | key), 1);
return (0);
}
static int
agp_nvidia_bind_page(device_t dev, int offset, vm_offset_t physical)
{
struct agp_nvidia_softc *sc = device_get_softc(dev);
u_int32_t index;
if (offset < 0 || offset >= (sc->gatt->ag_entries << AGP_PAGE_SHIFT))
return (EINVAL);
index = (sc->pg_offset + offset) >> AGP_PAGE_SHIFT;
sc->gatt->ag_virtual[index] = physical;
return (0);
}
static int
agp_nvidia_unbind_page(device_t dev, int offset)
{
struct agp_nvidia_softc *sc = device_get_softc(dev);
u_int32_t index;
if (offset < 0 || offset >= (sc->gatt->ag_entries << AGP_PAGE_SHIFT))
return (EINVAL);
index = (sc->pg_offset + offset) >> AGP_PAGE_SHIFT;
sc->gatt->ag_virtual[index] = 0;
return (0);
}
static int
agp_nvidia_flush_tlb (device_t dev, int offset)
{
struct agp_nvidia_softc *sc;
u_int32_t wbc_reg, temp;
int i;
sc = (struct agp_nvidia_softc *)device_get_softc(dev);
if (sc->wbc_mask) {
wbc_reg = pci_read_config(sc->mc1_dev, AGP_NVIDIA_1_WBC, 4);
wbc_reg |= sc->wbc_mask;
pci_write_config(sc->mc1_dev, AGP_NVIDIA_1_WBC, wbc_reg, 4);
/* Wait no more than 3 seconds. */
for (i = 0; i < 3000; i++) {
wbc_reg = pci_read_config(sc->mc1_dev,
AGP_NVIDIA_1_WBC, 4);
if ((sc->wbc_mask & wbc_reg) == 0)
break;
else
DELAY(1000);
}
if (i == 3000)
device_printf(dev,
"TLB flush took more than 3 seconds.\n");
}
/* Flush TLB entries. */
for(i = 0; i < 32 + 1; i++)
temp = sc->gatt->ag_virtual[i * PAGE_SIZE / sizeof(u_int32_t)];
for(i = 0; i < 32 + 1; i++)
temp = sc->gatt->ag_virtual[i * PAGE_SIZE / sizeof(u_int32_t)];
return (0);
}
#define SYSCFG 0xC0010010
#define IORR_BASE0 0xC0010016
#define IORR_MASK0 0xC0010017
#define AMD_K7_NUM_IORR 2
static int
nvidia_init_iorr(u_int32_t addr, u_int32_t size)
{
quad_t base, mask, sys;
u_int32_t iorr_addr, free_iorr_addr;
/* Find the iorr that is already used for the addr */
/* If not found, determine the uppermost available iorr */
free_iorr_addr = AMD_K7_NUM_IORR;
for(iorr_addr = 0; iorr_addr < AMD_K7_NUM_IORR; iorr_addr++) {
base = rdmsr(IORR_BASE0 + 2 * iorr_addr);
mask = rdmsr(IORR_MASK0 + 2 * iorr_addr);
if ((base & 0xfffff000ULL) == (addr & 0xfffff000))
break;
if ((mask & 0x00000800ULL) == 0)
free_iorr_addr = iorr_addr;
}
if (iorr_addr >= AMD_K7_NUM_IORR) {
iorr_addr = free_iorr_addr;
if (iorr_addr >= AMD_K7_NUM_IORR)
return (EINVAL);
}
base = (addr & ~0xfff) | 0x18;
mask = (0xfULL << 32) | ((~(size - 1)) & 0xfffff000) | 0x800;
wrmsr(IORR_BASE0 + 2 * iorr_addr, base);
wrmsr(IORR_MASK0 + 2 * iorr_addr, mask);
sys = rdmsr(SYSCFG);
sys |= 0x00100000ULL;
wrmsr(SYSCFG, sys);
return (0);
}
static device_method_t agp_nvidia_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, agp_nvidia_probe),
DEVMETHOD(device_attach, agp_nvidia_attach),
DEVMETHOD(device_detach, agp_nvidia_detach),
DEVMETHOD(device_shutdown, bus_generic_shutdown),
DEVMETHOD(device_suspend, bus_generic_suspend),
DEVMETHOD(device_resume, bus_generic_resume),
/* AGP interface */
DEVMETHOD(agp_get_aperture, agp_nvidia_get_aperture),
DEVMETHOD(agp_set_aperture, agp_nvidia_set_aperture),
DEVMETHOD(agp_bind_page, agp_nvidia_bind_page),
DEVMETHOD(agp_unbind_page, agp_nvidia_unbind_page),
DEVMETHOD(agp_flush_tlb, agp_nvidia_flush_tlb),
DEVMETHOD(agp_enable, agp_generic_enable),
DEVMETHOD(agp_alloc_memory, agp_generic_alloc_memory),
DEVMETHOD(agp_free_memory, agp_generic_free_memory),
DEVMETHOD(agp_bind_memory, agp_generic_bind_memory),
DEVMETHOD(agp_unbind_memory, agp_generic_unbind_memory),
{ 0, 0 }
};
static driver_t agp_nvidia_driver = {
"agp",
agp_nvidia_methods,
sizeof(struct agp_nvidia_softc),
};
static devclass_t agp_devclass;
DRIVER_MODULE(agp_nvidia, pci, agp_nvidia_driver, agp_devclass, 0, 0);
MODULE_DEPEND(agp_nvidia, agp, 1, 1, 1);
MODULE_DEPEND(agp_nvidia, pci, 1, 1, 1);
|
MarginC/kame
|
freebsd5/sys/pci/agp_nvidia.c
|
C
|
bsd-3-clause
| 12,031 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE364_Signal_Handler_Race_Condition__basic_06.c
Label Definition File: CWE364_Signal_Handler_Race_Condition__basic.label.xml
Template File: point-flaw-06.tmpl.c
*/
/*
* @description
* CWE: 364 Signal Handler Race Condition
* Sinks:
* GoodSink: Disable the signal handler while performing non-atomic operations
* BadSink : Do not disable the signal handler while performing non-atomic operations
* Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5)
*
* */
#include "std_testcase.h"
#include <signal.h>
typedef struct _structSigAtomic
{
sig_atomic_t val;
} structSigAtomic;
structSigAtomic *CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad = NULL;
structSigAtomic *CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood = NULL;
static void helperBad(int sig)
{
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad != NULL)
{
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad->val = 2;
}
}
static void helperGood(int sig)
{
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood != NULL)
{
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood->val = 2;
}
}
/* The variable below is declared "const", so a tool should be able
to identify that reads of this will always give its initialized
value. */
static const int STATIC_CONST_FIVE = 5;
#ifndef OMITBAD
void CWE364_Signal_Handler_Race_Condition__basic_06_bad()
{
if(STATIC_CONST_FIVE==5)
{
{
structSigAtomic *gStructSigAtomic = NULL;
signal(SIGINT, SIG_DFL);
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad != NULL)
{
free(CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad);
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad = NULL;
}
gStructSigAtomic = (structSigAtomic*)malloc(sizeof(structSigAtomic));
if (gStructSigAtomic == NULL) {exit(-1);}
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad = gStructSigAtomic;
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad->val = 1;
/* Assign CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad BEFORE
* calling 'signal', because pointer types are not (according to spec), atomic
* with respect to signals.
*
* In practice they are on most (all?) POSIX-y computers, but thems the
* rules
*/
signal(SIGINT, helperBad);
/* FLAW: This test, free, and set operation is not atomic, so if signal
* delivery occurs (for example) between the free and setting to NULL,
* the signal handler could corrupt the heap, cause an access violation,
* etc
*
* Technically, "CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad = 0" is not atomic on certain theoretical computer
* systems that don't actually exist, but this should trigger on
* theoretical as well as actual computer systems.
*/
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad != NULL)
{
free(CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad);
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicBad = NULL;
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good1() uses if(STATIC_CONST_FIVE!=5) instead of if(STATIC_CONST_FIVE==5) */
static void good1()
{
if(STATIC_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
structSigAtomic *gStructSigAtomic = NULL;
signal(SIGINT, SIG_DFL);
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood != NULL)
{
free(CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood);
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood = 0;
}
gStructSigAtomic = (structSigAtomic*)malloc(sizeof(structSigAtomic));
if (gStructSigAtomic == NULL) {exit(-1);}
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood = gStructSigAtomic;
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood->val = 1;
/* Assign CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood BEFORE
* calling 'signal', because pointer types are not (according to spec), atomic
* with respect to signals.
*
* In practice they are on most (all?) POSIX-y computers, but thems the
* rules
*/
signal(SIGINT, helperGood);
/* FIX: In this instance, the fix is to temporarily disable the signal
* handler while performing non-atomic operations. Another way would
* be to use sigprocmask or sigvec, or to restructure the signal handler
* to operate in a safe manner.
*/
signal(SIGINT, SIG_DFL);
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood != NULL)
{
free(CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood);
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood = NULL;
}
signal(SIGINT, helperGood);
}
}
}
/* good2() reverses the bodies in the if statement */
static void good2()
{
if(STATIC_CONST_FIVE==5)
{
{
structSigAtomic *gStructSigAtomic = NULL;
signal(SIGINT, SIG_DFL);
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood != NULL)
{
free(CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood);
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood = 0;
}
gStructSigAtomic = (structSigAtomic*)malloc(sizeof(structSigAtomic));
if (gStructSigAtomic == NULL) {exit(-1);}
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood = gStructSigAtomic;
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood->val = 1;
/* Assign CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood BEFORE
* calling 'signal', because pointer types are not (according to spec), atomic
* with respect to signals.
*
* In practice they are on most (all?) POSIX-y computers, but thems the
* rules
*/
signal(SIGINT, helperGood);
/* FIX: In this instance, the fix is to temporarily disable the signal
* handler while performing non-atomic operations. Another way would
* be to use sigprocmask or sigvec, or to restructure the signal handler
* to operate in a safe manner.
*/
signal(SIGINT, SIG_DFL);
if (CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood != NULL)
{
free(CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood);
CWE364_Signal_Handler_Race_Condition__basic_06StructSigAtomicGood = NULL;
}
signal(SIGINT, helperGood);
}
}
}
void CWE364_Signal_Handler_Race_Condition__basic_06_good()
{
good1();
good2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE364_Signal_Handler_Race_Condition__basic_06_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE364_Signal_Handler_Race_Condition__basic_06_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE364_Signal_Handler_Race_Condition/CWE364_Signal_Handler_Race_Condition__basic_06.c
|
C
|
bsd-3-clause
| 8,769 |
/* $OpenBSD: rand.h,v 1.20 2014/06/12 15:49:30 deraadt Exp $ */
/* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdlib.h>
#ifndef HEADER_RAND_H
#define HEADER_RAND_H
#include <openssl/opensslconf.h>
#include <openssl/ossl_typ.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Already defined in ossl_typ.h */
/* typedef struct rand_meth_st RAND_METHOD; */
struct rand_meth_st {
void (*seed)(const void *buf, int num);
int (*bytes)(unsigned char *buf, int num);
void (*cleanup)(void);
void (*add)(const void *buf, int num, double entropy);
int (*pseudorand)(unsigned char *buf, int num);
int (*status)(void);
};
int RAND_set_rand_method(const RAND_METHOD *meth);
const RAND_METHOD *RAND_get_rand_method(void);
#ifndef OPENSSL_NO_ENGINE
int RAND_set_rand_engine(ENGINE *engine);
#endif
RAND_METHOD *RAND_SSLeay(void);
void RAND_cleanup(void );
int RAND_bytes(unsigned char *buf, int num);
int RAND_pseudo_bytes(unsigned char *buf, int num);
void RAND_seed(const void *buf, int num);
void RAND_add(const void *buf, int num, double entropy);
int RAND_load_file(const char *file, long max_bytes);
int RAND_write_file(const char *file);
const char *RAND_file_name(char *file, size_t num);
int RAND_status(void);
int RAND_poll(void);
/* BEGIN ERROR CODES */
/* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
void ERR_load_RAND_strings(void);
/* Error codes for the RAND functions. (no longer used) */
/* Function codes. */
#define RAND_F_RAND_GET_RAND_METHOD 101
#define RAND_F_RAND_INIT_FIPS 102
#define RAND_F_SSLEAY_RAND_BYTES 100
/* Reason codes. */
#define RAND_R_DUAL_EC_DRBG_DISABLED 104
#define RAND_R_ERROR_INITIALISING_DRBG 102
#define RAND_R_ERROR_INSTANTIATING_DRBG 103
#define RAND_R_NO_FIPS_RANDOM_METHOD_SET 101
#define RAND_R_PRNG_NOT_SEEDED 100
#ifdef __cplusplus
}
#endif
#endif
|
GaloisInc/hacrypto
|
src/C/libressl/libressl-2.0.0/include/openssl/rand.h
|
C
|
bsd-3-clause
| 5,065 |
from __future__ import absolute_import, unicode_literals
import json
from dash.orgs.models import Org
from dash.utils import random_string
from django.core.cache import cache
from enum import Enum
class TaskType(Enum):
sync_contacts = 1
fetch_runs = 2
LAST_TASK_CACHE_KEY = 'org:%d:task_result:%s'
LAST_TASK_CACHE_TTL = 60 * 60 * 24 * 7 # 1 week
######################### Monkey patching for the Org class #########################
ORG_CONFIG_SECRET_TOKEN = 'secret_token'
ORG_CONFIG_CHAT_NAME_FIELD = 'chat_name_field'
def _org_get_secret_token(org):
return org.get_config(ORG_CONFIG_SECRET_TOKEN)
def _org_get_chat_name_field(org):
return org.get_config(ORG_CONFIG_CHAT_NAME_FIELD)
def _org_clean(org):
super(Org, org).clean()
# set config defaults
if not org.config:
org.config = json.dumps({ORG_CONFIG_SECRET_TOKEN: random_string(16).lower(),
ORG_CONFIG_CHAT_NAME_FIELD: 'chat_name'})
def _org_get_task_result(org, task_type):
result = cache.get(LAST_TASK_CACHE_KEY % (org.pk, task_type.name))
return json.loads(result) if result is not None else None
def _org_set_task_result(org, task_type, result):
cache.set(LAST_TASK_CACHE_KEY % (org.pk, task_type.name), json.dumps(result), LAST_TASK_CACHE_TTL)
Org.get_secret_token = _org_get_secret_token
Org.get_chat_name_field = _org_get_chat_name_field
Org.clean = _org_clean
Org.get_task_result = _org_get_task_result
Org.set_task_result = _org_set_task_result
|
rapidpro/chatpro
|
chatpro/orgs_ext/__init__.py
|
Python
|
bsd-3-clause
| 1,514 |
# ‹data-pipes›
A collection of invisble yet fabulous data access components, always returning immutable data structures, along with their schema in-band.
## Install the Polymer-CLI
First, make sure you have the [Polymer CLI](https://www.npmjs.com/package/polymer-cli) installed. Then run `polymer serve` to serve your element locally.
## Viewing Your Element
```
$ polymer serve
```
## Running Tests
```
$ polymer test
```
Your application is already set up to be tested via [web-component-tester](https://github.com/Polymer/web-component-tester). Run `polymer test` to run your application's test suite locally.
|
olange/data-pipes
|
README.md
|
Markdown
|
bsd-3-clause
| 625 |
using System;
namespace Konstruktor2
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class GeneratorMethodAttribute : Attribute
{
}
}
|
pragmatrix/Konstruktor2
|
Konstruktor2/Attributes/GeneratorMethodAttribute.cs
|
C#
|
bsd-3-clause
| 158 |
#http://www.gnu.org/prep/standards/html_node/Standard-Targets.html#Standard-Targets
all: build
./node_modules/node-pre-gyp:
npm install node-pre-gyp
./node_modules: ./node_modules/node-pre-gyp
npm install `node -e "console.log(Object.keys(require('./package.json').dependencies).join(' '))"` \
`node -e "console.log(Object.keys(require('./package.json').devDependencies).join(' '))"` --clang=1
build: ./node_modules
./node_modules/.bin/node-pre-gyp build --loglevel=silent --clang=1
debug: ./node_modules
./node_modules/.bin/node-pre-gyp build --debug --clang=1
verbose: ./node_modules
./node_modules/.bin/node-pre-gyp build --loglevel=verbose --clang=1
clean:
@rm -rf ./build
rm -rf lib/binding/
rm -rf ./test/tmp/*
echo > ./test/tmp/placeholder.txt
rm -rf ./node_modules/
grind:
valgrind --leak-check=full node node_modules/.bin/_mocha
rebuild:
@make clean
@make
ifndef only
test:
@PATH="./node_modules/mocha/bin:${PATH}" && NODE_PATH="./lib:$(NODE_PATH)" mocha -R spec
else
test:
@PATH="./node_modules/mocha/bin:${PATH}" && NODE_PATH="./lib:$(NODE_PATH)" mocha -R spec test/${only}.test.js
endif
check: test
.PHONY: test clean build
|
elaberge/node-zipfile
|
Makefile
|
Makefile
|
bsd-3-clause
| 1,164 |
package com.thaiopensource.relaxng.impl;
import com.thaiopensource.relaxng.match.MatchablePattern;
import com.thaiopensource.relaxng.match.Matcher;
public class MatchablePatternImpl implements MatchablePattern {
private final SchemaPatternBuilder spb;
private final Pattern start;
public MatchablePatternImpl(SchemaPatternBuilder spb, Pattern start) {
this.spb = spb;
this.start = start;
}
public Matcher createMatcher() {
return new PatternMatcher(start, new ValidatorPatternBuilder(spb));
}
}
|
evanchsa/jing-trang
|
mod/rng-validate/src/main/com/thaiopensource/relaxng/impl/MatchablePatternImpl.java
|
Java
|
bsd-3-clause
| 524 |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['BoxCox'] , ['PolyTrend'] , ['Seasonal_WeekOfYear'] , ['AR'] );
|
antoinecarme/pyaf
|
tests/model_control/detailed/transf_BoxCox/model_control_one_enabled_BoxCox_PolyTrend_Seasonal_WeekOfYear_AR.py
|
Python
|
bsd-3-clause
| 158 |
{% extends "base.html" %}
{% load i18n %}
{% load layout %}
{% load forms %}
{% block title %}{% trans "account" %} ‣ {% if edit %}{% trans "edit" %}{% else %}{% trans "create" %}{% endif %}{% endblock %}
{% block breadcrumbs %}
<a href="{% url nepal-account-summary %}">{% trans "account" %}</a>
‣
<a href="{% url nepal-account-edit form.instance.pk %}">{% trans "edit" %}</a>
‣
{% trans "webpack" %}
{% endblock %}
{% block content %}
<script type="text/javascript">
var rlimits = [];
rlimits['customers']= "{{rlimit.customers}}";
rlimits['domains'] = "{{rlimit.domains}}";
rlimits['sub_domains'] = "{{rlimit.sub_domains}}";
rlimits['webspace'] = "{{rlimit.webspace}}";
rlimits['traffic'] = "{{rlimit.traffic}}";
rlimits['mail_accounts'] = "{{rlimit.mail_accounts}}";
rlimits['mail_aliases'] = "{{rlimit.mail_aliases}}";
rlimits['ftp_accounts'] = "{{rlimit.ftp_accounts}}";
rlimits['databases'] = "{{rlimit.databases}}";
function onPackChange() {
values = $("#id_packselect").children("option:selected").val();
va = values.replace(/None/g,"").split(";");
$("#id_customers").val(va[0]);
$("#id_domains").val(va[1]);
$("#id_sub_domains").val(va[2]);
$("#id_webspace").val(va[3]);
$("#id_traffic").val(va[4]);
$("#id_mail_accounts").val(va[5]);
$("#id_mail_aliases").val(va[6]);
$("#id_ftp_accounts").val(va[7]);
$("#id_databases").val(va[8]);
/* trigger a checkLimits with a keyup event */
$("input[type='text']").keyup();
}
function checkLimits(e) {
/* see if keystroke is [0..9] # this might be different on IE O_o */
if ((e.which < 48 || e.which > 57) && e.which != 8)
return;
var f = $(e.target);
var id = f.attr("id");
var val = f.attr("value");
var lim = rlimits[id.substring(3)];
if (lim == "None")
return;
var dif = (lim - val);
if (dif > 0)
f.css("background","#ddffdd");
else
f.css("background","#ffdddd");
}
$(function() { $("select").change(onPackChange) });
$(function() { $("input[type='text']").keyup(checkLimits) });
</script>
<form id="resources-profile-edit" class="hcenter two-thirds" method="post" action=".">
{% info_box _("Use the form below to change resource limits. An empty value means unlimited.") %}
{% show_form %}
{% show_field form.profile %}
<tr class="field packselect">
<th scope="row">
<label for="id_packselect">{% trans "Resource pack" %}</label>
</th>
<td>
<select id="id_packselect">
<!-- XXX something like this would be good: <option value="...." selected="selected">-old-</option> -->
<option value=";;;;;;;;">none</option>
{% for pack in packs %}
<option value="{{pack.customers}};{{pack.domains}};{{pack.sub_domains}};{{pack.webspace}};{{pack.traffic}};{{pack.mail_accounts}};{{pack.mail_aliases}};{{pack.ftp_accounts}};{{pack.databases}}">{{ pack.name }}</option>
{% endfor %}
</select>
</td>
</tr>
{% if form.customers %}
{% show_field form.customers %}
{% endif %}
{% show_field form.domains %}
{% show_field form.sub_domains %}
{% show_field form.webspace %}
{% show_field form.traffic %}
{% show_field form.mail_accounts %}
{% show_field form.mail_aliases %}
{% show_field form.ftp_accounts %}
{% show_field form.databases %}
{% endshow_form %}
{% show_buttons %}
{% back_button _("Cancel") referer %}
{% submit_button _("Save Changes") %}
{% endshow_buttons %}
</form>
{% endblock %}
|
hollow/nepal
|
nepal/resources/templates/resources/profile_edit.html
|
HTML
|
bsd-3-clause
| 3,522 |
# -*- coding: utf-8 -*-
from django.core.cache.backends.locmem import LocMemCache
from django.test import SimpleTestCase
import time
from corehq.util.quickcache import quickcache, TieredCache, SkippableQuickCache, skippable_quickcache
from dimagi.utils import make_uuid
BUFFER = []
class CacheMock(LocMemCache):
def __init__(self, name, params):
self.name = name
super(CacheMock, self).__init__(name, params)
self.default_timeout = params["timeout"] # allow sub-second timeout
def get(self, key, default=None, version=None):
result = super(CacheMock, self).get(key, default, version)
if result is default:
BUFFER.append('{} miss'.format(self.name))
else:
BUFFER.append('{} hit'.format(self.name))
return result
class CacheMockWithSet(CacheMock):
def set(self, key, value, timeout=None, version=None):
super(CacheMockWithSet, self).set(key, value, timeout, version)
BUFFER.append('{} set'.format(self.name))
SHORT_TIME_UNIT = 0.01
_local_cache = CacheMock('local', {'timeout': SHORT_TIME_UNIT})
_shared_cache = CacheMock('shared', {'timeout': 2 * SHORT_TIME_UNIT})
_cache = TieredCache([_local_cache, _shared_cache])
_cache_with_set = CacheMockWithSet('cache', {'timeout': SHORT_TIME_UNIT})
class QuickcacheTest(SimpleTestCase):
def tearDown(self):
self.consume_buffer()
def consume_buffer(self):
result = list(BUFFER)
del BUFFER[:]
return result
def test_tiered_cache(self):
@quickcache([], cache=_cache)
def simple():
BUFFER.append('called')
return 'VALUE'
self.assertEqual(simple(), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local miss', 'shared miss', 'called'])
self.assertEqual(simple(), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local hit'])
# let the local cache expire
time.sleep(SHORT_TIME_UNIT)
self.assertEqual(simple(), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local miss', 'shared hit'])
# let the shared cache expire
time.sleep(SHORT_TIME_UNIT)
self.assertEqual(simple(), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local miss', 'shared miss', 'called'])
# and that this is again cached locally
self.assertEqual(simple(), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local hit'])
def test_vary_on(self):
@quickcache(['n'], cache=_cache)
def fib(n):
BUFFER.append(n)
if n < 2:
return 1
else:
return fib_r(n - 1) + fib_r(n - 2)
fib_r = fib
# [1, 1, 2, 3, 5, 8]
self.assertEqual(fib(5), 8)
self.assertEqual(self.consume_buffer(),
['local miss', 'shared miss', 5,
'local miss', 'shared miss', 4,
'local miss', 'shared miss', 3,
'local miss', 'shared miss', 2,
'local miss', 'shared miss', 1,
'local miss', 'shared miss', 0,
# fib(3/4/5) also ask for fib(1/2/3)
# so three cache hits
'local hit', 'local hit', 'local hit'])
def test_vary_on_attr(self):
class Item(object):
def __init__(self, id, name):
self.id = id
self.name = name
@quickcache(['self.id'], cache=_cache)
def get_name(self):
BUFFER.append('called method')
return self.name
@quickcache(['item.id'], cache=_cache)
def get_name(item):
BUFFER.append('called function')
return item.name
james = Item(1, 'james')
fred = Item(2, 'fred')
self.assertEqual(get_name(james), 'james')
self.assertEqual(self.consume_buffer(),
['local miss', 'shared miss', 'called function'])
self.assertEqual(get_name(fred), 'fred')
self.assertEqual(self.consume_buffer(),
['local miss', 'shared miss', 'called function'])
self.assertEqual(get_name(james), 'james')
self.assertEqual(self.consume_buffer(), ['local hit'])
self.assertEqual(get_name(fred), 'fred')
self.assertEqual(self.consume_buffer(), ['local hit'])
# this also works, and uses different keys
self.assertEqual(james.get_name(), 'james')
self.assertEqual(self.consume_buffer(),
['local miss', 'shared miss', 'called method'])
self.assertEqual(fred.get_name(), 'fred')
self.assertEqual(self.consume_buffer(),
['local miss', 'shared miss', 'called method'])
self.assertEqual(james.get_name(), 'james')
self.assertEqual(self.consume_buffer(), ['local hit'])
self.assertEqual(fred.get_name(), 'fred')
self.assertEqual(self.consume_buffer(), ['local hit'])
def test_bad_vary_on(self):
with self.assertRaisesRegexp(ValueError, 'cucumber'):
@quickcache(['cucumber'], cache=_cache)
def square(number):
return number * number
def test_weird_data(self):
@quickcache(['bytes'])
def encode(bytes):
return hash(bytes)
symbols = '!@#$%^&*():{}"?><.~`'
bytes = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09'
self.assertEqual(encode(symbols), hash(symbols))
self.assertEqual(encode(bytes), hash(bytes))
def test_lots_of_args(self):
@quickcache('abcdef')
def lots_of_args(a, b, c, d, e, f):
pass
# doesn't fail
lots_of_args(u"x", u"x", u"x", u"x", u"x", u"x")
key = lots_of_args.get_cache_key(u"x", u"x", u"x", u"x", u"x", u"x")
self.assertLess(len(key), 250)
# assert it's actually been hashed
self.assertEqual(
len(key), len('quickcache.lots_of_args.xxxxxxxx/H') + 32, key)
def test_really_long_function_name(self):
@quickcache([])
def aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa():
"""60 a's in a row"""
pass
# doesn't fail
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
key = (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
.get_cache_key())
self.assertEqual(
len(key), len('quickcache.' + 'a' * 40 + '...xxxxxxxx/'), key)
def test_vary_on_func(self):
def vary_on(data):
return [data['name']]
@quickcache(vary_on=vary_on)
def cached_fn(data):
pass
key = cached_fn.get_cache_key({'name': 'a1'})
self.assertRegexpMatches(key, 'quickcache.cached_fn.[a-z0-9]{8}/u[a-z0-9]{32}')
def test_unicode_string(self):
@quickcache(['name'], cache=_cache)
def by_name(name):
BUFFER.append('called')
return 'VALUE'
name_unicode = u'namé'
name_utf8 = name_unicode.encode('utf-8')
self.assertEqual(by_name(name_unicode), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local miss', 'shared miss', 'called'])
self.assertEqual(by_name(name_unicode), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local hit'])
self.assertEqual(by_name(name_utf8), 'VALUE')
self.assertEqual(self.consume_buffer(), ['local hit'])
def test_skippable(self):
@skippable_quickcache(['name'], cache=_cache_with_set, skip_arg='force')
def by_name(name, force=False):
BUFFER.append('called')
return 'VALUE'
name = 'name'
self.assertEqual(by_name(name), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache miss', 'called', 'cache set'])
self.assertEqual(by_name(name), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache hit'])
self.assertEqual(by_name(name, force=True), 'VALUE')
self.assertEqual(self.consume_buffer(), ['called', 'cache set'])
self.assertEqual(by_name(name), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache hit'])
def test_skippable_fn(self):
@skippable_quickcache(['name'], cache=_cache_with_set, skip_arg=lambda name: name == 'Ben')
def by_name(name, force=False):
BUFFER.append('called')
return 'VALUE'
name = 'name'
self.assertEqual(by_name(name), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache miss', 'called', 'cache set'])
self.assertEqual(by_name(name), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache hit'])
name = 'Ben'
self.assertEqual(by_name(name), 'VALUE')
self.assertEqual(self.consume_buffer(), ['called', 'cache set'])
self.assertEqual(by_name(name), 'VALUE')
self.assertEqual(self.consume_buffer(), ['called', 'cache set'])
def test_skippable_non_kwarg(self):
@skippable_quickcache(['name'], cache=_cache_with_set, skip_arg='skip_cache')
def by_name(name, skip_cache):
BUFFER.append('called')
return 'VALUE'
name = 'name'
self.assertEqual(by_name(name, False), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache miss', 'called', 'cache set'])
self.assertEqual(by_name(name, False), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache hit'])
self.assertEqual(by_name(name, True), 'VALUE')
self.assertEqual(self.consume_buffer(), ['called', 'cache set'])
self.assertEqual(by_name(name, False), 'VALUE')
self.assertEqual(self.consume_buffer(), ['cache hit'])
def test_skippable_validation(self):
# skip_arg not supplied
with self.assertRaises(ValueError):
@quickcache(['name'], helper_class=SkippableQuickCache)
def by_name(name, skip_cache=False):
return 'VALUE'
# skip_arg also in vary_on
with self.assertRaises(ValueError):
@skippable_quickcache(['name', 'skip_cache'], skip_arg='skip_cache')
def by_name(name, skip_cache=False):
return 'VALUE'
# skip_arg not in args
with self.assertRaises(ValueError):
@skippable_quickcache(['name'], skip_arg='missing')
def by_name(name):
return 'VALUE'
def test_dict_arg(self):
@quickcache(['dct'])
def return_random(dct):
return make_uuid()
value_1 = return_random({})
self.assertEqual(return_random({}), value_1)
value_2 = return_random({'abc': 123})
self.assertEqual(return_random({'abc': 123}), value_2)
self.assertNotEqual(value_2, value_1)
value_3 = return_random({'abc': 123, 'def': 456})
self.assertEqual(return_random({'abc': 123, 'def': 456}), value_3)
self.assertNotEqual(value_3, value_1)
self.assertNotEqual(value_3, value_2)
|
qedsoftware/commcare-hq
|
corehq/util/tests/test_quickcache.py
|
Python
|
bsd-3-clause
| 11,152 |
from dispatch import Spec, LinearSpecs, ListSpecs, review_and_launch
# WORK IN PROGRESS
# for kwargs in spec(): # Static
# result = func(**kwargs)
# spec.update(result)
# for arg_group in spec(): # Dynamic
# for args, kwargs in arg_group:
# result = func(*args, **kwargs)
def invoke(function, specifier):
for spec in next(specifier):
function(**spec)
def numeric_example(number):
print number
linspec = LinearSpecs('number', 1,5,steps=3, fp_precision=4)
invoke(numeric_example, linspec)
def greetings(time_of_day, person):
greeting = '%s %s!' % (time_of_day[1:-1], person[1:-1])
print greeting
times_of_day = ['Good morning', 'Afternoon']
people = ['Bob', 'John']
specifier = ListSpecs('time_of_day',times_of_day ) * ListSpecs('person',people)
invoke(greetings, specifier)
|
ioam/svn-history
|
dispatch/examples/basic/1-specifiers.py
|
Python
|
bsd-3-clause
| 874 |
/*L
Copyright SAIC
Distributed under the OSI-approved BSD 3-Clause License.
See http://ncip.github.com/cabio/LICENSE.txt for details.
L*/
create index ZSTG_GENCGID_ALIAS_lwr on ZSTG_GENE_GENEALIAS_CGID(lower(ALIAS)) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT;
--EXIT;
|
NCIP/cabio
|
software/cabio-database/scripts/sql_loader/no_longer_used/indexes/zstg_gene_genealias_cgid.lower.sql
|
SQL
|
bsd-3-clause
| 291 |
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/frame_generator.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "webrtc/base/checks.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
namespace webrtc {
namespace test {
namespace {
class ChromaGenerator : public FrameGenerator {
public:
ChromaGenerator(size_t width, size_t height)
: angle_(0.0), width_(width), height_(height) {
assert(width > 0);
assert(height > 0);
}
virtual I420VideoFrame* NextFrame() OVERRIDE {
frame_.CreateEmptyFrame(static_cast<int>(width_),
static_cast<int>(height_),
static_cast<int>(width_),
static_cast<int>((width_ + 1) / 2),
static_cast<int>((width_ + 1) / 2));
angle_ += 30.0;
uint8_t u = fabs(sin(angle_)) * 0xFF;
uint8_t v = fabs(cos(angle_)) * 0xFF;
memset(frame_.buffer(kYPlane), 0x80, frame_.allocated_size(kYPlane));
memset(frame_.buffer(kUPlane), u, frame_.allocated_size(kUPlane));
memset(frame_.buffer(kVPlane), v, frame_.allocated_size(kVPlane));
return &frame_;
}
private:
double angle_;
size_t width_;
size_t height_;
I420VideoFrame frame_;
};
class YuvFileGenerator : public FrameGenerator {
public:
YuvFileGenerator(std::vector<FILE*> files,
size_t width,
size_t height,
int frame_repeat_count)
: file_index_(0),
files_(files),
width_(width),
height_(height),
frame_size_(CalcBufferSize(kI420,
static_cast<int>(width_),
static_cast<int>(height_))),
frame_buffer_(new uint8_t[frame_size_]),
frame_display_count_(frame_repeat_count),
current_display_count_(0) {
assert(width > 0);
assert(height > 0);
assert(frame_repeat_count > 0);
}
virtual ~YuvFileGenerator() {
for (FILE* file : files_)
fclose(file);
}
virtual I420VideoFrame* NextFrame() OVERRIDE {
if (current_display_count_ == 0)
ReadNextFrame();
if (++current_display_count_ >= frame_display_count_)
current_display_count_ = 0;
// If this is the last repeatition of this frame, it's OK to use the
// original instance, otherwise use a copy.
if (current_display_count_ == frame_display_count_)
return &last_read_frame_;
temp_frame_copy_.CopyFrame(last_read_frame_);
return &temp_frame_copy_;
}
void ReadNextFrame() {
size_t bytes_read =
fread(frame_buffer_.get(), 1, frame_size_, files_[file_index_]);
if (bytes_read < frame_size_) {
// No more frames to read in this file, rewind and move to next file.
rewind(files_[file_index_]);
file_index_ = (file_index_ + 1) % files_.size();
bytes_read = fread(frame_buffer_.get(), 1, frame_size_,
files_[file_index_]);
assert(bytes_read >= frame_size_);
}
last_read_frame_.CreateEmptyFrame(
static_cast<int>(width_), static_cast<int>(height_),
static_cast<int>(width_), static_cast<int>((width_ + 1) / 2),
static_cast<int>((width_ + 1) / 2));
ConvertToI420(kI420, frame_buffer_.get(), 0, 0, static_cast<int>(width_),
static_cast<int>(height_), 0, kRotateNone, &last_read_frame_);
}
private:
size_t file_index_;
const std::vector<FILE*> files_;
const size_t width_;
const size_t height_;
const size_t frame_size_;
const rtc::scoped_ptr<uint8_t[]> frame_buffer_;
const int frame_display_count_;
int current_display_count_;
I420VideoFrame last_read_frame_;
I420VideoFrame temp_frame_copy_;
};
} // namespace
FrameGenerator* FrameGenerator::CreateChromaGenerator(size_t width,
size_t height) {
return new ChromaGenerator(width, height);
}
FrameGenerator* FrameGenerator::CreateFromYuvFile(
std::vector<std::string> filenames,
size_t width,
size_t height,
int frame_repeat_count) {
assert(!filenames.empty());
std::vector<FILE*> files;
for (const std::string& filename : filenames) {
FILE* file = fopen(filename.c_str(), "rb");
DCHECK(file != nullptr);
files.push_back(file);
}
return new YuvFileGenerator(files, width, height, frame_repeat_count);
}
} // namespace test
} // namespace webrtc
|
whxcctv/I-Love-Web_Rtc
|
test/frame_generator.cc
|
C++
|
bsd-3-clause
| 4,801 |
<!doctype html>
<html>
<head>
<title>Talk - Python, Inc. - PyGotham 2015</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../../../static/css/app.css">
<meta name="msapplication-TileColor" content="#182833">
<meta name="msapplication-TileImage" content="../../../static/img/metro-icon.png">
<link rel="apple-touch-icon-precomposed" href="../../../static/img/apple-touch-icon.png">
<link rel="icon" href="../../../static/img/favicon.png">
<script src="../../../static/bower_components/modernizr/modernizr.js"></script>
</head>
<body class="">
<nav class="top-bar" data-topbar data-options="mobile_show_parent_link: false">
<ul class="title-area">
<li class="name">
<h1><a href="../../../">PyGotham 2015</a></h1>
</li>
<li class="toggle-topbar menu-icon">
<a href="index.html#"><span>Menu</span></a>
</li>
</ul>
<section class="top-bar-section">
<ul class="right">
<li class="About has-dropdown">
<a href="index.html#">About</a>
<ul class="dropdown">
<li><a href="../../../about/code-of-conduct/">Code of Conduct</a></li>
<li><a href="../../../about/faq/">FAQ</a></li>
<li><a href="../../../about/privacy-policy/">Privacy Policy</a></li>
<li><a href="../../../about/social/">Social Event</a></li>
</ul>
</li>
<li class="Events has-dropdown">
<a href="index.html#">Events</a>
<ul class="dropdown">
<li><a href="../../">Talk List</a></li>
<li><a href="../../schedule/">Talk Schedule</a></li>
</ul>
</li>
<li class="Registration has-dropdown">
<a href="index.html#">Registration</a>
<ul class="dropdown">
<li><a href="../../../registration/information/">Information</a></li>
</ul>
</li>
<li class="Speaking has-dropdown">
<a href="index.html#">Speaking</a>
<ul class="dropdown">
<li><a href="../../call-for-proposals/">Call For Proposals</a></li>
</ul>
</li>
<li class="Sponsors has-dropdown">
<a href="index.html#">Sponsors</a>
<ul class="dropdown">
<li><a href="../../../sponsors/">Sponsors</a></li>
<li><a href="../../../sponsors/prospectus/">Sponsorship Prospectus</a></li>
</ul>
</li>
<li class="Venue has-dropdown">
<a href="index.html#">Venue</a>
<ul class="dropdown">
<li><a href="../../../about/venue/">Information</a></li>
</ul>
</li>
</ul>
</section>
</nav>
<div id="content">
<div class="row">
<h1>Python, Inc.</h1>
<small>09:00 AM - 09:45 AM on August 16, 2015, Room 701, Room 702, Room 704, Room 705</small>
<h4>
<a href="../../../speakers/profile/370/">
Jessica McKellar
</a>
</h4>
<dl>
<dt>Audience level:
<dd>novice
<dt>Watch:
<dd><a href="http://youtu.be/fhv-4QLGsso">http://youtu.be/fhv-4QLGsso</a>
</dl>
<h3>Description</h3>
<p>Open source communities and startups have some important properties in common. They are highly resource-constrained and must work to engage and retain users in a competitive and ever-changing market. How can open source communities apply startup best practices? In this talk, we take on the role of CEO of Python, Inc. and ask ourselves what actually matters for growing and sustaining an open source community.</p>
</div>
</div>
<footer>
<section class="credits">
PyGotham 2015 is a production of <a href="http://bigapplepy.org">Big Apple Py</a>.<br>
Design by <a href="http://www.jessiesima.com">Jessie Sima</a>. Hosting provided by <a href="http://www.rackspace.com">Rackspace</a>.<br>
Questions? Comments? Please contact <a href="mailto:[email protected]">[email protected]</a>.<br>
</section>
</footer>
<script src="../../../static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="../../../static/bower_components/foundation/js/foundation.min.js"></script>
<script src="../../../static/js/app.js"></script>
</body>
</html>
|
PyGotham/archives
|
2015.pygotham.org/talks/222/python-inc/index.html
|
HTML
|
bsd-3-clause
| 4,607 |
# Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic, option
class PipeMagic(Magic):
def __init__(self, *args, **kwargs):
super(PipeMagic, self).__init__(*args, **kwargs)
def cell_pipe(self, pipe_str):
"""
%%pipe FUNCTION1 | FUNCTION2 ...
The pipe cell will "pipe" the contents of a cell
through a series of function calls. All of the
functions must be defined in the language, and
the kernel must support the `do_function_direct`
method.
Example:
%%pipe f1 | f2 | f3
CELL CONTENTS
is the same as issuing:
f3(f2(f1("CELL CONTENTS")))
"""
functions = [function.strip() for function in pipe_str.split("|")]
self.retval = self.code
for function in functions:
self.retval = self.kernel.do_function_direct(function, self.retval)
self.evaluate = False
def post_process(self, retval):
return self.retval
def register_magics(kernel):
kernel.register_magics(PipeMagic)
def register_ipython_magics():
from IPython.core.magic import register_cell_magic
from IPython import get_ipython
@register_cell_magic
def pipe(line, cell):
"""
"""
ip = get_ipython()
functions = [function.strip() for function in line.split("|")]
retval = cell
for function in functions:
f = eval(function, ip.ns_table["user_global"])
retval = f(retval)
return retval
|
Calysto/metakernel
|
metakernel/magics/pipe_magic.py
|
Python
|
bsd-3-clause
| 1,611 |
#encoding: utf-8
# frozen_string_literal: true
module Puma
class UnsupportedOption < RuntimeError
end
# Every standard HTTP code mapped to the appropriate message. These are
# used so frequently that they are placed directly in Puma for easy
# access rather than Puma::Const itself.
# Every standard HTTP code mapped to the appropriate message.
# Generated with:
# curl -s https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv | \
# ruby -ne 'm = /^(\d{3}),(?!Unassigned|\(Unused\))([^,]+)/.match($_) and \
# puts "#{m[1]} => \x27#{m[2].strip}\x27,"'
HTTP_STATUS_CODES = {
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large',
414 => 'URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m A Teapot',
421 => 'Misdirected Request',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
451 => 'Unavailable For Legal Reasons',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
510 => 'Not Extended',
511 => 'Network Authentication Required'
}
# For some HTTP status codes the client only expects headers.
#
STATUS_WITH_NO_ENTITY_BODY = {
204 => true,
205 => true,
304 => true
}
# Frequently used constants when constructing requests or responses. Many times
# the constant just refers to a string with the same contents. Using these constants
# gave about a 3% to 10% performance improvement over using the strings directly.
#
# The constants are frozen because Hash#[]= when called with a String key dups
# the String UNLESS the String is frozen. This saves us therefore 2 object
# allocations when creating the env hash later.
#
# While Puma does try to emulate the CGI/1.2 protocol, it does not use the REMOTE_IDENT,
# REMOTE_USER, or REMOTE_HOST parameters since those are either a security problem or
# too taxing on performance.
module Const
PUMA_VERSION = VERSION = "5.0.0.beta1".freeze
CODE_NAME = "Spoony Bard".freeze
PUMA_SERVER_STRING = ['puma', PUMA_VERSION, CODE_NAME].join(' ').freeze
FAST_TRACK_KA_TIMEOUT = 0.2
# The default number of seconds for another request within a persistent
# session.
PERSISTENT_TIMEOUT = 20
# The default number of seconds to wait until we get the first data
# for the request
FIRST_DATA_TIMEOUT = 30
# How long to wait when getting some write blocking on the socket when
# sending data back
WRITE_TIMEOUT = 10
# How many requests to attempt inline before sending a client back to
# the reactor to be subject to normal ordering. The idea here is that
# we amortize the cost of going back to the reactor for a well behaved
# but very "greedy" client across 10 requests. This prevents a not
# well behaved client from monopolizing the thread forever.
MAX_FAST_INLINE = 10
# The original URI requested by the client.
REQUEST_URI= 'REQUEST_URI'.freeze
REQUEST_PATH = 'REQUEST_PATH'.freeze
QUERY_STRING = 'QUERY_STRING'.freeze
CONTENT_LENGTH = "CONTENT_LENGTH".freeze
PATH_INFO = 'PATH_INFO'.freeze
PUMA_TMP_BASE = "puma".freeze
ERROR_RESPONSE = {
# Indicate that we couldn't parse the request
400 => "HTTP/1.1 400 Bad Request\r\n\r\n".freeze,
# The standard empty 404 response for bad requests. Use Error4040Handler for custom stuff.
404 => "HTTP/1.1 404 Not Found\r\nConnection: close\r\nServer: Puma #{PUMA_VERSION}\r\n\r\nNOT FOUND".freeze,
# The standard empty 408 response for requests that timed out.
408 => "HTTP/1.1 408 Request Timeout\r\nConnection: close\r\nServer: Puma #{PUMA_VERSION}\r\n\r\n".freeze,
# Indicate that there was an internal error, obviously.
500 => "HTTP/1.1 500 Internal Server Error\r\n\r\n".freeze,
# A common header for indicating the server is too busy. Not used yet.
503 => "HTTP/1.1 503 Service Unavailable\r\n\r\nBUSY".freeze
}
# The basic max request size we'll try to read.
CHUNK_SIZE = 16 * 1024
# This is the maximum header that is allowed before a client is booted. The parser detects
# this, but we'd also like to do this as well.
MAX_HEADER = 1024 * (80 + 32)
# Maximum request body size before it is moved out of memory and into a tempfile for reading.
MAX_BODY = MAX_HEADER
REQUEST_METHOD = "REQUEST_METHOD".freeze
HEAD = "HEAD".freeze
# ETag is based on the apache standard of hex mtime-size-inode (inode is 0 on win32)
LINE_END = "\r\n".freeze
REMOTE_ADDR = "REMOTE_ADDR".freeze
HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR".freeze
HTTP_X_FORWARDED_SSL = "HTTP_X_FORWARDED_SSL".freeze
HTTP_X_FORWARDED_SCHEME = "HTTP_X_FORWARDED_SCHEME".freeze
HTTP_X_FORWARDED_PROTO = "HTTP_X_FORWARDED_PROTO".freeze
SERVER_NAME = "SERVER_NAME".freeze
SERVER_PORT = "SERVER_PORT".freeze
HTTP_HOST = "HTTP_HOST".freeze
PORT_80 = "80".freeze
PORT_443 = "443".freeze
LOCALHOST = "localhost".freeze
LOCALHOST_IP = "127.0.0.1".freeze
SERVER_PROTOCOL = "SERVER_PROTOCOL".freeze
HTTP_11 = "HTTP/1.1".freeze
SERVER_SOFTWARE = "SERVER_SOFTWARE".freeze
GATEWAY_INTERFACE = "GATEWAY_INTERFACE".freeze
CGI_VER = "CGI/1.2".freeze
STOP_COMMAND = "?".freeze
HALT_COMMAND = "!".freeze
RESTART_COMMAND = "R".freeze
RACK_INPUT = "rack.input".freeze
RACK_URL_SCHEME = "rack.url_scheme".freeze
RACK_AFTER_REPLY = "rack.after_reply".freeze
PUMA_SOCKET = "puma.socket".freeze
PUMA_CONFIG = "puma.config".freeze
PUMA_PEERCERT = "puma.peercert".freeze
HTTP = "http".freeze
HTTPS = "https".freeze
HTTPS_KEY = "HTTPS".freeze
HTTP_VERSION = "HTTP_VERSION".freeze
HTTP_CONNECTION = "HTTP_CONNECTION".freeze
HTTP_EXPECT = "HTTP_EXPECT".freeze
CONTINUE = "100-continue".freeze
HTTP_11_100 = "HTTP/1.1 100 Continue\r\n\r\n".freeze
HTTP_11_200 = "HTTP/1.1 200 OK\r\n".freeze
HTTP_10_200 = "HTTP/1.0 200 OK\r\n".freeze
CLOSE = "close".freeze
KEEP_ALIVE = "keep-alive".freeze
CONTENT_LENGTH2 = "content-length".freeze
CONTENT_LENGTH_S = "Content-Length: ".freeze
TRANSFER_ENCODING = "transfer-encoding".freeze
TRANSFER_ENCODING2 = "HTTP_TRANSFER_ENCODING".freeze
CONNECTION_CLOSE = "Connection: close\r\n".freeze
CONNECTION_KEEP_ALIVE = "Connection: Keep-Alive\r\n".freeze
TRANSFER_ENCODING_CHUNKED = "Transfer-Encoding: chunked\r\n".freeze
CLOSE_CHUNKED = "0\r\n\r\n".freeze
CHUNKED = "chunked".freeze
COLON = ": ".freeze
NEWLINE = "\n".freeze
HTTP_INJECTION_REGEX = /[\r\n]/.freeze
HIJACK_P = "rack.hijack?".freeze
HIJACK = "rack.hijack".freeze
HIJACK_IO = "rack.hijack_io".freeze
EARLY_HINTS = "rack.early_hints".freeze
# Mininum interval to checks worker health
WORKER_CHECK_INTERVAL = 5
end
end
|
looker/puma
|
lib/puma/const.rb
|
Ruby
|
bsd-3-clause
| 8,283 |
<?php namespace util;
use io\{IOException, File};
use io\streams\{InputStream, OutputStream, MemoryInputStream, FileInputStream, TextReader};
use lang\{FormatException, IllegalStateException, ElementNotFoundException};
/**
* An interface to property-files (aka "ini-files")
*
* Property-files syntax is easy.
* ```ini
* [section]
* key1=value
* key2="value"
* key3="value|value|value"
* key4="a:value|b:value"
* ; comment
*
* [section2]
* key=value
* ```
*
* @test xp://net.xp_framework.unittest.util.PropertyWritingTest
* @test xp://net.xp_framework.unittest.util.StringBasedPropertiesTest
* @test xp://net.xp_framework.unittest.util.FileBasedPropertiesTest
* @see php://parse_ini_file
*/
class Properties implements PropertyAccess {
private static $env;
public $_file, $_data;
private $expansion= null;
static function __static() {
self::$env= (new PropertyExpansion())->expand('env', 'getenv');
}
/** Creates a new properties instance from a given file */
public function __construct(string $filename= null) {
$this->_file= $filename;
}
/**
* Add expansion `${kind.X}` with a given expansion function `f(X)`
*
* @param string $kind
* @param [:var]|function(string): string $expansion
* @return self
*/
public function expanding($kind, $expansion) {
$this->expansion= $this->expansion ?: clone self::$env;
if ($expansion instanceof \ArrayAccess || (is_array($expansion) && 0 !== key($expansion))) {
$func= function($name) use($expansion) { return isset($expansion[$name]) ? $expansion[$name] : null; };
} else {
$func= cast($expansion, 'function(string): string');
}
$this->expansion->expand($kind, $func);
return $this;
}
/**
* Load from an input stream, e.g. a file
*
* @param io.streams.InputStream|io.Channel|string $in
* @param string $charset the charset the stream is encoded in or NULL to trigger autodetection by BOM
* @return self
* @throws io.IOException
* @throws lang.FormatException
*/
public function load($in, $charset= null): self {
$reader= new TextReader($in, $charset);
$expansion= $this->expansion ?: self::$env;
$this->_data= [];
$section= null;
while (null !== ($t= $reader->readLine())) {
$trimmedToken= trim($t);
if ('' === $trimmedToken) continue; // Empty lines
$c= $trimmedToken{0};
if (';' === $c || '#' === $c) { // One line comments
continue;
} else if ('[' === $c) {
if (false === ($p= strrpos($trimmedToken, ']'))) {
throw new FormatException('Unclosed section "'.$trimmedToken.'"');
}
$section= substr($trimmedToken, 1, $p- 1);
$this->_data[$section]= [];
} else if (false !== ($p= strpos($t, '='))) {
$key= trim(substr($t, 0, $p));
$value= ltrim(substr($t, $p+ 1));
if ('' === $value) {
// OK
} else if ('"' === $value{0}) { // Quoted strings
$quoted= substr($value, 1);
while (false === ($p= strrpos($quoted, '"'))) {
if (null === ($line= $reader->readLine())) break;
$quoted.= "\n".$line;
}
$value= $expansion->in(substr($quoted, 0, $p));
} else { // unquoted string
if (false !== ($p= strpos($value, ';'))) { // Comments at end of line
$value= substr($value, 0, $p);
}
$value= $expansion->in(rtrim($value));
}
// Arrays and maps: key[], key[0], key[assoc]
if (']' === substr($key, -1)) {
if (false === ($p= strpos($key, '['))) {
throw new FormatException('Invalid key "'.$key.'"');
}
$offset= substr($key, $p+ 1, -1);
$key= substr($key, 0, $p);
if (!isset($this->_data[$section][$key])) {
$this->_data[$section][$key]= [];
}
if ('' === $offset) {
$this->_data[$section][$key][]= $value;
} else {
$this->_data[$section][$key][$offset]= $value;
}
} else {
$this->_data[$section][$key]= $value;
}
} else if ('' !== trim($t)) {
throw new FormatException('Invalid line "'.$t.'"');
}
}
return $this;
}
/**
* Quote a value if necessary
*
* @param var $value
* @return string
*/
protected function quote($val) {
return is_string($val) ? '"'.$val.'"' : (string)$val;
}
/**
* Store to an output stream, e.g. a file
*
* @param io.streams.OutputStream out
* @throws io.IOException
*/
public function store(OutputStream $out) {
foreach (array_keys($this->_data) as $section) {
$out->write('['.$section."]\n");
foreach ($this->_data[$section] as $key => $val) {
if (';' == $key{0}) {
$out->write("\n; ".$val."\n");
} else if (is_array($val)) {
if (empty($val)) {
$out->write($key."=\n");
} else if (0 === key($val)) {
foreach ($val as $v) { $out->write($key.'[]='.$this->quote($v)."\n"); }
} else {
foreach ($val as $k => $v) { $out->write($key.'['.$k.']='.$this->quote($v)."\n"); }
}
} else {
$out->write($key.'='.$this->quote($val)."\n");
}
}
$out->write("\n");
}
}
/** Retrieves the file name containing the properties */
public function getFilename() { return $this->_file; }
/** Returns whether the property file exists */
public function exists(): bool { return file_exists($this->_file); }
/**
* Create the property file
*
* @return void
* @throws io.IOException if the property file could not be created
*/
public function create() {
if (null !== $this->_file) {
$fd= new File($this->_file);
$fd->open(File::WRITE);
$fd->close();
}
$this->_data= [];
}
/**
* Helper method that loads the data from the file if needed
*
* @param bool force default FALSE
* @throws io.IOException
*/
private function _load($force= false) {
if ($force || null === $this->_data) {
$this->load(new FileInputStream($this->_file));
}
}
/**
* Reload all data from the file
*
* @return void
*/
public function reset() {
$this->_load(true);
}
/** Returns sections */
public function sections(): \Traversable {
$this->_load();
foreach ($this->_data as $section => $_) {
yield $section;
}
}
/**
* Get the first configuration section
*
* @deprecated Use sections() iterator instead
* @see xp://util.Properties#getNextSection
* @return string the first section's name
*/
public function getFirstSection() {
$this->_load();
reset($this->_data);
return key($this->_data);
}
/**
* Get the next configuration section
*
* Example:
* <code>
* if ($section= $prop->getFirstSection()) do {
* var_dump($section, $prop->readSection($section));
* } while ($section= $prop->getNextSection());
* </code>
*
* @deprecated Use sections() iterator instead
* @see xp://util.Properties#getFirstSection
* @return var string section or FALSE if this was the last section
*/
public function getNextSection() {
$this->_load();
if (false === next($this->_data)) return false;
return key($this->_data);
}
/**
* Read an entire section into an array
*
* @param string name
* @param var[] default default [] what to return in case the section does not exist
* @return array
*/
public function readSection($name, $default= []) {
$this->_load();
return $this->_data[$name] ?? $default;
}
/**
* Read a value as string
*
* @param string section
* @param string key
* @param string default default '' what to return in case the section or key does not exist
* @return string
*/
public function readString($section, $key, $default= '') {
$this->_load();
return $this->_data[$section][$key] ?? $default;
}
/**
* Read a value as array
*
* @param string section
* @param string key
* @param var[] default default NULL what to return in case the section or key does not exist
* @return array
*/
public function readArray($section, $key, $default= []) {
$this->_load();
// New: key[]="a" or key[0]="a"
// Old: key="" (an empty array) or key="a|b|c"
if (!isset($this->_data[$section][$key])) {
return $default;
} else if (is_array($this->_data[$section][$key])) {
return $this->_data[$section][$key];
} else {
return '' == $this->_data[$section][$key] ? [] : explode('|', $this->_data[$section][$key]);
}
}
/**
* Read a value as maop
*
* @param string section
* @param string key
* @param [:var] default default NULL what to return in case the section or key does not exist
* @return [:var]
*/
public function readMap($section, $key, $default= null) {
$this->_load();
// New: key[color]="green" and key[make]="model"
// Old: key="color:green|make:model"
if (!isset($this->_data[$section][$key])) {
return $default;
} else if (is_array($this->_data[$section][$key])) {
return $this->_data[$section][$key];
} else if ('' === $this->_data[$section][$key]) {
return [];
} else {
$return= [];
foreach (explode('|', $this->_data[$section][$key]) as $val) {
if (strstr($val, ':')) {
list($k, $v)= explode(':', $val, 2);
$return[$k]= $v;
} else {
$return[]= $val;
}
}
return $return;
}
}
/**
* Read a value as range
*
* @param string section
* @param string key
* @param int[] default default NULL what to return in case the section or key does not exist
* @return array
*/
public function readRange($section, $key, $default= []) {
$this->_load();
if (!isset($this->_data[$section][$key])) return $default;
if (2 === sscanf($this->_data[$section][$key], '%d..%d', $min, $max)) {
return range($min, $max);
} else {
return [];
}
}
/**
* Read a value as integer
*
* @param string section
* @param string key
* @param int default default 0 what to return in case the section or key does not exist
* @return int
*/
public function readInteger($section, $key, $default= 0) {
$this->_load();
return isset($this->_data[$section][$key])
? intval($this->_data[$section][$key])
: $default
;
}
/**
* Read a value as float
*
* @param string section
* @param string key
* @param float default default 0.0 what to return in case the section or key does not exist
* @return float
*/
public function readFloat($section, $key, $default= 0.0) {
$this->_load();
return isset($this->_data[$section][$key])
? doubleval($this->_data[$section][$key])
: $default
;
}
/**
* Read a value as boolean
*
* @param string section
* @param string key
* @param bool default default FALSE what to return in case the section or key does not exist
* @return bool TRUE, when key is 1, 'on', 'yes' or 'true', FALSE otherwise
*/
public function readBool($section, $key, $default= false) {
$this->_load();
if (!isset($this->_data[$section][$key])) return $default;
return (
'1' === $this->_data[$section][$key] ||
0 === strncasecmp('yes', $this->_data[$section][$key], 3) ||
0 === strncasecmp('true', $this->_data[$section][$key], 4) ||
0 === strncasecmp('on', $this->_data[$section][$key], 2)
);
}
/**
* Returns whether a section exists
*
* @param string name
* @return bool
*/
public function hasSection($name) {
$this->_load();
return isset($this->_data[$name]);
}
/**
* Add a section
*
* @param string name
* @param bool overwrite default FALSE whether to overwrite existing sections
* @return string name
*/
public function writeSection($name, $overwrite= false) {
$this->_load();
if ($overwrite || !$this->hasSection($name)) $this->_data[$name]= [];
return $name;
}
/**
* Add a string (and the section, if necessary)
*
* @param string section
* @param string key
* @param string value
*/
public function writeString($section, $key, $value) {
$this->_load();
if (!$this->hasSection($section)) $this->_data[$section]= [];
$this->_data[$section][$key]= (string)$value;
}
/**
* Add a string (and the section, if necessary)
*
* @param string section
* @param string key
* @param int value
*/
public function writeInteger($section, $key, $value) {
$this->_load();
if (!$this->hasSection($section)) $this->_data[$section]= [];
$this->_data[$section][$key]= (int)$value;
}
/**
* Add a float (and the section, if necessary)
*
* @param string section
* @param string key
* @param float value
*/
public function writeFloat($section, $key, $value) {
$this->_load();
if (!$this->hasSection($section)) $this->_data[$section]= [];
$this->_data[$section][$key]= (float)$value;
}
/**
* Add a boolean (and the section, if necessary)
*
* @param string section
* @param string key
* @param bool value
*/
public function writeBool($section, $key, $value) {
$this->_load();
if (!$this->hasSection($section)) $this->_data[$section]= [];
$this->_data[$section][$key]= $value ? 'yes' : 'no';
}
/**
* Add an array string (and the section, if necessary)
*
* @param string section
* @param string key
* @param array value
*/
public function writeArray($section, $key, $value) {
$this->_load();
if (!$this->hasSection($section)) $this->_data[$section]= [];
$this->_data[$section][$key]= $value;
}
/**
* Add a map (and the section, if necessary)
*
* @param string section
* @param string key
* @param [:var] $value
*/
public function writeMap($section, $key, $value) {
$this->_load();
if (!$this->hasSection($section)) $this->_data[$section]= [];
$this->_data[$section][$key]= $value;
}
/**
* Add a comment (and the section, if necessary)
*
* @param string section
* @param string key
* @param string comment
*/
public function writeComment($section, $comment) {
$this->_load();
if (!$this->hasSection($section)) $this->_data[$section]= [];
$this->_data[$section][';'.sizeof($this->_data[$section])]= $comment;
}
/**
* Remove section completely
*
* @param string section
* @throws lang.IllegalStateException if given section does not exist
*/
public function removeSection($section) {
$this->_load();
if (!isset($this->_data[$section])) throw new IllegalStateException('Cannot remove nonexistant section "'.$section.'"');
unset($this->_data[$section]);
}
/**
* Remove key
*
* @param string section
* @param string key
* @throws lang.IllegalStateException if given key does not exist
*/
public function removeKey($section, $key) {
$this->_load();
if (!isset($this->_data[$section][$key])) throw new IllegalStateException('Cannot remove nonexistant key "'.$key.'" in "'.$section.'"');
unset($this->_data[$section][$key]);
}
/** Check if is equal to other object */
public function equals($cmp): bool {
if (!$cmp instanceof self) return false;
// If based on files, and both base on the same file, then they're equal
if (null === $this->_data && null === $cmp->_data) {
return $this->_file === $cmp->_file;
} else {
return Objects::equal($this->_data, $cmp->_data);
}
}
/** Creates hashcode */
public function hashCode(): string {
return $this->_file.serialize($this->_data);
}
/** Creates a string representation of this property file */
public function toString(): string {
return nameof($this).'('.$this->_file.')@{'.Objects::stringOf($this->_data).'}';
}
}
|
johannes85/core
|
src/main/php/util/Properties.class.php
|
PHP
|
bsd-3-clause
| 16,301 |
/*
/ _____) _ | |
( (____ _____ ____ _| |_ _____ ____| |__
\____ \| ___ | (_ _) ___ |/ ___) _ \
_____) ) ____| | | || |_| ____( (___| | | |
(______/|_____)_|_|_| \__)_____)\____)_| |_|
(C)2013 Semtech
Description: Default IRQ handlers
License: Revised BSD License, see LICENSE.TXT file include in the project
Maintainer: Miguel Luis and Gregory Cristian
*/
#include "board.h"
/*!
* \brief This function handles NMI exception.
* \param None
* \retval None
*/
void NMI_Handler( void )
{
}
/*!
* \brief This function handles Hard Fault exception.
* \param None
* \retval None
*/
#if defined( HARD_FAULT_HANDLER_ENABLED )
void HardFault_Handler_C( unsigned int *args )
{
volatile unsigned int stacked_r0;
volatile unsigned int stacked_r1;
volatile unsigned int stacked_r2;
volatile unsigned int stacked_r3;
volatile unsigned int stacked_r12;
volatile unsigned int stacked_lr;
volatile unsigned int stacked_pc;
volatile unsigned int stacked_psr;
stacked_r0 = ( ( unsigned long) args[0] );
stacked_r1 = ( ( unsigned long) args[1] );
stacked_r2 = ( ( unsigned long) args[2] );
stacked_r3 = ( ( unsigned long) args[3] );
stacked_r12 = ( ( unsigned long) args[4] );
stacked_lr = ( ( unsigned long) args[5] );
stacked_pc = ( ( unsigned long) args[6] );
stacked_psr = ( ( unsigned long) args[7] );
( void )stacked_r0;
( void )stacked_r1;
( void )stacked_r2;
( void )stacked_r3;
( void )stacked_r12;
( void )stacked_lr ;
( void )stacked_pc ;
( void )stacked_psr;
while( 1 );
}
#if defined(__CC_ARM)
__asm void HardFault_Handler(void)
{
TST LR, #4
ITE EQ
MRSEQ r0, MSP
MRSNE r0, PSP
B __cpp(HardFault_Handler_C)
}
#elif defined(__ICCARM__)
void HardFault_Handler(void)
{
__asm("TST LR, #4");
__asm("ITE EQ");
__asm("MRSEQ r0, MSP");
__asm("MRSNE r0, PSP");
__asm("B HardFault_Handler_C");
}
#elif defined(__GNUC__)
void HardFault_Handler(void)
{
__asm volatile( "TST LR, #4" );
__asm volatile( "ITE EQ" );
__asm volatile( "MRSEQ R0, MSP" );
__asm volatile( "MRSNE R0, PSP" );
__asm volatile( "B HardFault_Handler_C" );
}
#else
#warning Not supported compiler type
#endif
#endif
/*!
* \brief This function handles Memory Manage exception.
* \param None
* \retval None
*/
void MemManage_Handler( void )
{
/* Go to infinite loop when Memory Manage exception occurs */
while ( 1 )
{
}
}
/*!
* \brief This function handles Bus Fault exception.
* \param None
* \retval None
*/
void BusFault_Handler( void )
{
/* Go to infinite loop when Bus Fault exception occurs */
while ( 1 )
{
}
}
/*!
* \brief This function handles Usage Fault exception.
* \param None
* \retval None
*/
void UsageFault_Handler( void )
{
/* Go to infinite loop when Usage Fault exception occurs */
while ( 1 )
{
}
}
/*!
* \brief This function handles Debug Monitor exception.
* \param None
* \retval None
*/
void DebugMon_Handler( void )
{
}
|
reixd/LoRaMac-node
|
src/boards/mcu/stm32/sysIrqHandlers.c
|
C
|
bsd-3-clause
| 3,247 |
<link rel="import" href="../html/polymer.html">
<link rel="import" href="shared_vars_css.html">
<link rel="import" href="hidden_style_css.html">
<link rel="import" href="cr_icons_css.html">
<!-- Common styles for Material Design WebUI. Included directly in
settings_shared_css.html. -->
<dom-module id="cr-shared-style">
<template>
<style include="cr-hidden-style cr-icons">
html,
:host {
--scrollable-border-color: var(--google-grey-refresh-300);
}
@media (prefers-color-scheme: dark) {
html,
:host {
--scrollable-border-color: var(--google-grey-refresh-700);
}
}
[actionable] {
cursor: pointer;
}
/* Horizontal rule line. */
.hr {
border-top: var(--cr-separator-line);
}
iron-list.cr-separators > *:not([first]) {
border-top: var(--cr-separator-line);
}
[scrollable] {
border-color: transparent;
border-style: solid;
border-width: 1px 0;
overflow-y: auto;
}
[scrollable].is-scrolled {
border-top-color: var(--scrollable-border-color);
}
[scrollable].can-scroll:not(.scrolled-to-bottom) {
border-bottom-color: var(--scrollable-border-color);
}
[scrollable] iron-list > :not(.no-outline):focus,
[selectable]:focus,
[selectable] > :focus {
background-color: var(--cr-focused-item-color);
outline: none;
}
.scroll-container {
display: flex;
flex-direction: column;
min-height: 1px;
}
[selectable] > * {
cursor: pointer;
}
.cr-centered-card-container {
box-sizing: border-box;
display: block;
height: inherit;
margin: 0 auto;
max-width: var(--cr-centered-card-max-width);
min-width: 550px;
position: relative;
width: calc(100% * var(--cr-centered-card-width-percentage));
}
.cr-container-shadow {
box-shadow: inset 0 5px 6px -3px rgba(0, 0, 0, .4);
height: var(--cr-container-shadow-height);
left: 0;
margin: 0 0 var(--cr-container-shadow-margin);
opacity: 0;
pointer-events: none;
position: relative;
right: 0;
top: 0;
transition: opacity 500ms;
z-index: 1;
}
/** Styles for elements that implement the CrContainerShadowBehavior */
#cr-container-shadow-bottom {
margin-bottom: 0;
margin-top: var(--cr-container-shadow-margin);
transform: scaleY(-1);
}
#cr-container-shadow-top.has-shadow,
#cr-container-shadow-bottom.has-shadow {
opacity: var(--cr-container-shadow-max-opacity);
}
.cr-row {
align-items: center;
border-top: var(--cr-separator-line);
display: flex;
min-height: var(--cr-section-min-height);
padding: 0 var(--cr-section-padding);
}
.cr-row.first,
.cr-row.continuation {
border-top: none;
}
.cr-row-gap {
padding-inline-start: 16px;
}
.cr-button-gap {
margin-inline-start: 8px;
}
paper-tooltip {
--paper-tooltip: {
font-size: 92.31%; /* Effectively 12px if the host default is 13px. */
font-weight: 500;
max-width: 330px;
min-width: var(--paper-tooltip-min-width, 200px);
padding: var(--paper-tooltip-padding, 10px 8px);
}
}
/* Typography */
.cr-padded-text {
padding-block-end: var(--cr-section-vertical-padding);
padding-block-start: var(--cr-section-vertical-padding);
}
.cr-title-text {
color: var(--cr-title-text-color);
font-size: 107.6923%; /* Go to 14px from 13px. */
font-weight: 500;
}
.cr-secondary-text {
color: var(--cr-secondary-text-color);
font-weight: 400;
}
.cr-form-field-label {
color: var(--cr-form-field-label-color);
display: block;
font-size: var(--cr-form-field-label-font-size);
font-weight: 500;
letter-spacing: .4px;
line-height: var(--cr-form-field-label-line-height);
margin-bottom: 8px;
}
</style>
</template>
</dom-module>
|
endlessm/chromium-browser
|
ui/webui/resources/cr_elements/shared_style_css.html
|
HTML
|
bsd-3-clause
| 4,329 |
/*
Copyright (C) Intel Corp. 2006. All Rights Reserved.
Intel funded Tungsten Graphics (http://www.tungstengraphics.com) to
develop this 3D driver.
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 (including the
next paragraph) shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**********************************************************************/
/*
* Authors:
* Keith Whitwell <[email protected]>
*/
#include "brw_context.h"
#include "brw_wm.h"
/* Use these to force spilling so that that functionality can be
* tested with known-good examples rather than having to construct new
* tests.
*/
#define TEST_PAYLOAD_SPILLS 0
#define TEST_DST_SPILLS 0
static void spill_value(struct brw_wm_compile *c,
struct brw_wm_value *value);
static void prealloc_reg(struct brw_wm_compile *c,
struct brw_wm_value *value,
GLuint reg)
{
if (value->lastuse) {
/* Set nextuse to zero, it will be corrected by
* update_register_usage().
*/
c->pass2_grf[reg].value = value;
c->pass2_grf[reg].nextuse = 0;
value->resident = &c->pass2_grf[reg];
value->hw_reg = brw_vec8_grf(reg*2, 0);
if (TEST_PAYLOAD_SPILLS)
spill_value(c, value);
}
}
/* Initialize all the register values. Do the initial setup
* calculations for interpolants.
*/
static void init_registers( struct brw_wm_compile *c )
{
struct brw_context *brw = c->func.brw;
struct intel_context *intel = &brw->intel;
GLuint nr_interp_regs = 0;
GLuint i = 0;
GLuint j;
for (j = 0; j < c->grf_limit; j++)
c->pass2_grf[j].nextuse = BRW_WM_MAX_INSN;
for (j = 0; j < (c->nr_payload_regs + 1) / 2; j++)
prealloc_reg(c, &c->payload.depth[j], i++);
for (j = 0; j < c->nr_creg; j++)
prealloc_reg(c, &c->creg[j], i++);
if (intel->gen >= 6) {
for (unsigned int j = 0; j < FRAG_ATTRIB_MAX; j++) {
if (brw->fragment_program->Base.InputsRead & BITFIELD64_BIT(j)) {
nr_interp_regs++;
prealloc_reg(c, &c->payload.input_interp[j], i++);
}
}
} else {
for (j = 0; j < VERT_RESULT_MAX; j++) {
if (c->key.vp_outputs_written & BITFIELD64_BIT(j)) {
int fp_index;
if (j >= VERT_RESULT_VAR0)
fp_index = j - (VERT_RESULT_VAR0 - FRAG_ATTRIB_VAR0);
else if (j <= VERT_RESULT_TEX7)
fp_index = j;
else
fp_index = -1;
nr_interp_regs++;
if (fp_index >= 0)
prealloc_reg(c, &c->payload.input_interp[fp_index], i++);
}
}
assert(nr_interp_regs >= 1);
}
c->prog_data.first_curbe_grf = ALIGN(c->nr_payload_regs, 2);
c->prog_data.urb_read_length = nr_interp_regs * 2;
c->prog_data.curb_read_length = c->nr_creg * 2;
c->max_wm_grf = i * 2;
}
/* Update the nextuse value for each register in our file.
*/
static void update_register_usage(struct brw_wm_compile *c,
GLuint thisinsn)
{
GLuint i;
for (i = 1; i < c->grf_limit; i++) {
struct brw_wm_grf *grf = &c->pass2_grf[i];
/* Only search those which can change:
*/
if (grf->nextuse < thisinsn) {
const struct brw_wm_ref *ref = grf->value->lastuse;
/* Has last use of value been passed?
*/
if (ref->insn < thisinsn) {
grf->value->resident = 0;
grf->value = 0;
grf->nextuse = BRW_WM_MAX_INSN;
}
else {
/* Else loop through chain to update:
*/
while (ref->prevuse && ref->prevuse->insn >= thisinsn)
ref = ref->prevuse;
grf->nextuse = ref->insn;
}
}
}
}
static void spill_value(struct brw_wm_compile *c,
struct brw_wm_value *value)
{
/* Allocate a spill slot. Note that allocations start from 0x40 -
* the first slot is reserved to mean "undef" in brw_wm_emit.c
*/
if (!value->spill_slot) {
c->last_scratch += 0x40;
value->spill_slot = c->last_scratch;
}
/* The spill will be done in brw_wm_emit.c immediately after the
* value is calculated, so we can just take this reg without any
* further work.
*/
value->resident->value = NULL;
value->resident->nextuse = BRW_WM_MAX_INSN;
value->resident = NULL;
}
/* Search for contiguous region with the most distant nearest
* member. Free regs count as very distant.
*
* TODO: implement spill-to-reg so that we can rearrange discontigous
* free regs and then spill the oldest non-free regs in sequence.
* This would mean inserting instructions in this pass.
*/
static GLuint search_contiguous_regs(struct brw_wm_compile *c,
GLuint nr,
GLuint thisinsn)
{
struct brw_wm_grf *grf = c->pass2_grf;
GLuint furthest = 0;
GLuint reg = 0;
GLuint i, j;
/* Start search at 1: r0 is special and can't be used or spilled.
*/
for (i = 1; i < c->grf_limit && furthest < BRW_WM_MAX_INSN; i++) {
GLuint group_nextuse = BRW_WM_MAX_INSN;
for (j = 0; j < nr; j++) {
if (grf[i+j].nextuse < group_nextuse)
group_nextuse = grf[i+j].nextuse;
}
if (group_nextuse > furthest) {
furthest = group_nextuse;
reg = i;
}
}
assert(furthest != thisinsn);
/* Any non-empty regs will need to be spilled:
*/
for (j = 0; j < nr; j++)
if (grf[reg+j].value)
spill_value(c, grf[reg+j].value);
return reg;
}
static void alloc_contiguous_dest(struct brw_wm_compile *c,
struct brw_wm_value *dst[],
GLuint nr,
GLuint thisinsn)
{
GLuint reg = search_contiguous_regs(c, nr, thisinsn);
GLuint i;
for (i = 0; i < nr; i++) {
if (!dst[i]) {
/* Need to grab a dummy value in TEX case. Don't introduce
* it into the tracking scheme.
*/
dst[i] = &c->vreg[c->nr_vreg++];
}
else {
assert(!dst[i]->resident);
assert(c->pass2_grf[reg+i].nextuse != thisinsn);
c->pass2_grf[reg+i].value = dst[i];
c->pass2_grf[reg+i].nextuse = thisinsn;
dst[i]->resident = &c->pass2_grf[reg+i];
}
dst[i]->hw_reg = brw_vec8_grf((reg+i)*2, 0);
}
if ((reg+nr)*2 > c->max_wm_grf)
c->max_wm_grf = (reg+nr) * 2;
}
static void load_args(struct brw_wm_compile *c,
struct brw_wm_instruction *inst)
{
GLuint thisinsn = inst - c->instruction;
GLuint i,j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
struct brw_wm_ref *ref = inst->src[i][j];
if (ref) {
if (!ref->value->resident) {
/* Need to bring the value in from scratch space. The code for
* this will be done in brw_wm_emit.c, here we just do the
* register allocation and mark the ref as requiring a fill.
*/
GLuint reg = search_contiguous_regs(c, 1, thisinsn);
c->pass2_grf[reg].value = ref->value;
c->pass2_grf[reg].nextuse = thisinsn;
ref->value->resident = &c->pass2_grf[reg];
/* Note that a fill is required:
*/
ref->unspill_reg = reg*2;
}
/* Adjust the hw_reg to point at the value's current location:
*/
assert(ref->value == ref->value->resident->value);
ref->hw_reg.nr += (ref->value->resident - c->pass2_grf) * 2;
}
}
}
}
/* Step 3: Work forwards once again. Perform register allocations,
* taking into account instructions like TEX which require contiguous
* result registers. Where necessary spill registers to scratch space
* and reload later.
*/
void brw_wm_pass2( struct brw_wm_compile *c )
{
GLuint insn;
GLuint i;
init_registers(c);
for (insn = 0; insn < c->nr_insns; insn++) {
struct brw_wm_instruction *inst = &c->instruction[insn];
/* Update registers' nextuse values:
*/
update_register_usage(c, insn);
/* May need to unspill some args.
*/
load_args(c, inst);
/* Allocate registers to hold results:
*/
switch (inst->opcode) {
case OPCODE_TEX:
case OPCODE_TXB:
case OPCODE_TXP:
alloc_contiguous_dest(c, inst->dst, 4, insn);
break;
default:
for (i = 0; i < 4; i++) {
if (inst->writemask & (1<<i)) {
assert(inst->dst[i]);
alloc_contiguous_dest(c, &inst->dst[i], 1, insn);
}
}
break;
}
if (TEST_DST_SPILLS && inst->opcode != WM_PIXELXY) {
for (i = 0; i < 4; i++)
if (inst->dst[i])
spill_value(c, inst->dst[i]);
}
}
if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
brw_wm_print_program(c, "pass2");
}
c->state = PASS2_DONE;
if (unlikely(INTEL_DEBUG & DEBUG_WM)) {
brw_wm_print_program(c, "pass2/done");
}
}
|
ayoubg/gem5-graphics
|
Mesa-7.11.2_GPGPU-Sim/src/mesa/drivers/dri/i965/brw_wm_pass2.c
|
C
|
bsd-3-clause
| 9,402 |
This library contains generic serialization and deserialization functions
implemented using the [generics-sop][0] package for use with [aeson][1].
This is the development repository. For releases, look on [Hackage][2].
[0]: https://github.com/well-typed/generics-sop
[1]: https://hackage.haskell.org/package/aeson
[2]: https://hackage.haskell.org/package/json-sop
|
well-typed/json-sop
|
README.md
|
Markdown
|
bsd-3-clause
| 366 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\modules\setting\models\IdentitasKantorSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="identitas-kantor-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'kementerian') ?>
<?= $form->field($model, 'eseloni') ?>
<?= $form->field($model, 'kanwil') ?>
<?= $form->field($model, 'kppbc') ?>
<?php // echo $form->field($model, 'alamat1') ?>
<?php // echo $form->field($model, 'alamat2') ?>
<?php // echo $form->field($model, 'alamat3') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
ridhobc/sitampan
|
backend/modules/setting/views/identitas-kantor/_search.php
|
PHP
|
bsd-3-clause
| 959 |
package com.github.resource4j.objects.providers.events;
import com.github.resource4j.ResourceKey;
import com.github.resource4j.resources.context.ResourceResolutionContext;
import java.io.Serializable;
public class ResourceObjectRepositoryEvent implements Serializable {
private static final long serialVersionUID = 1;
private final String source;
private final ResourceObjectEventType type;
private final String name;
private final String key;
private final ResourceResolutionContext context;
public static ResourceObjectRepositoryEvent created(String source, String name, ResourceResolutionContext context) {
return new ResourceObjectRepositoryEvent(source, ResourceObjectEventType.CREATED, name, context);
}
public static ResourceObjectRepositoryEvent modified(String source, String name, ResourceResolutionContext context) {
return new ResourceObjectRepositoryEvent(source, ResourceObjectEventType.MODIFIED, name, context);
}
public static ResourceObjectRepositoryEvent deleted(String source, String name, ResourceResolutionContext context) {
return new ResourceObjectRepositoryEvent(source, ResourceObjectEventType.DELETED, name, context);
}
public static ResourceObjectRepositoryEvent valueSet(String source, ResourceKey key, ResourceResolutionContext context) {
return new ResourceObjectRepositoryEvent(source, ResourceObjectEventType.VALUE_SET, key, context);
}
public static ResourceObjectRepositoryEvent valueRemoved(String source, ResourceKey key, ResourceResolutionContext context) {
return new ResourceObjectRepositoryEvent(source, ResourceObjectEventType.VALUE_REMOVED, key, context);
}
public ResourceObjectRepositoryEvent(String source,
ResourceObjectEventType type,
String name,
ResourceResolutionContext context) {
this.source = source;
this.type = type;
this.name = name;
this.key = null;
this.context = context;
}
public ResourceObjectRepositoryEvent(String source,
ResourceObjectEventType type,
ResourceKey key,
ResourceResolutionContext context) {
this.source = source;
this.type = type;
this.name = key.getBundle();
this.key = key.getId();
this.context = context;
}
public String source() {
return source;
}
public ResourceObjectEventType type() {
return type;
}
public String objectName() {
return name;
}
public ResourceKey key() {
return ResourceKey.key(name, key);
}
public ResourceResolutionContext context() {
return context;
}
@Override
public String toString() {
return type + ":" + name + "@" + context;
}
}
|
resource4j/resource4j
|
core/src/main/java/com/github/resource4j/objects/providers/events/ResourceObjectRepositoryEvent.java
|
Java
|
bsd-3-clause
| 3,011 |
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/vcm_estimate_normals.h>
#include <cassert>
#include <vector>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Point_3<Kernel> Point_3;
typedef CGAL::Vector_3<Kernel> Vector_3;
typedef std::pair<Point_3, Vector_3> PointWithNormal;
int main (void) {
// Generate points on a plane
int k = 100;
double r = 10;
std::vector<PointWithNormal> points;
points.push_back(std::make_pair(Point_3(0, 0, 0), Vector_3(0, 0, 0)));
for (int i = 0; i < k; ++i) {
double theta = 2 * i * CGAL_PI / k;
points.push_back(std::make_pair(Point_3(r * cos(theta), r * sin(theta), 0),
Vector_3(0, 0, 0)));
}
// Estimate the normals using VCM
double R = 20;
vcm_estimate_normals(points.begin(), points.end(),
CGAL::First_of_pair_property_map<PointWithNormal>(),
CGAL::Second_of_pair_property_map<PointWithNormal>(),
R, 0.0);
std::cout << "Normal is " << points[0].second << std::endl;
// The normal at the origin should be (0, 0, 1)
double epsilon=2e-5;
assert(points[0].second.x() < epsilon && points[0].second.x() > -epsilon);
assert(points[0].second.y() < epsilon && points[0].second.y() > -epsilon);
assert(points[0].second.z() < 0 || (points[0].second.z() < 1+epsilon && points[0].second.z() > 1-epsilon));
assert(points[0].second.z() > 0 || (points[0].second.z() < -1+epsilon && points[0].second.z() > -1-epsilon));
return 0;
}
|
hlzz/dotfiles
|
graphics/cgal/Point_set_processing_3/test/Point_set_processing_3/vcm_plane_test.cpp
|
C++
|
bsd-3-clause
| 1,627 |
sum = 0
i = 1
File.open("022_names.txt").read.split(',').sort.each do |n|
n = n[1,n.length-2]
sum += i * n.split('').map {|l| l[0] - 'A'[0] + 1}.inject(0) {|s, l| s+l}
i += 1
end
puts sum
|
nikolasco/project_euler
|
022.rb
|
Ruby
|
bsd-3-clause
| 194 |
/*
* Copyright (c) 2015-2016, Lasse Farnung Laursen - http://www.lasselaursen.com
*
* This file is a part of SimplePose, and subject to the new and revised BSD license.
* Please see the LICENSE file for more information.
* All other rights reserved.
*/
#ifndef SIMPLEPOSE_TAGEVENT_H_INCLUDED
#define SIMPLEPOSE_TAGEVENT_H_INCLUDED
#include "cinder/app/Event.h"
#include "cinder/Signals.h"
#include "tag/Tag.h"
namespace SimplePose {
class TagEvent : public ci::app::Event {
public:
TagEvent();
TagEvent( TagId const& tagId ) :
mUpdatedTagId( tagId ) {};
TagId const getTagId() const { return mUpdatedTagId; }
private:
TagId const mUpdatedTagId;
};
typedef cinder::signals::Signal<bool( TagEvent& ), cinder::signals::CollectorWhile0<bool> > EventTag;
}
#endif // SIMPLEPOSE_TAGEVENT_H_INCLUDED
|
Gazoo101/Cinder-SimplePose
|
src/event/TagEvent.h
|
C
|
bsd-3-clause
| 857 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_07.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml
Template File: sources-sink-07.tmpl.c
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using malloc() and set data pointer to a small buffer
* GoodSource: Allocate using malloc() and set data pointer to a large buffer
* Sink: memcpy
* BadSink : Copy int64_t array to data using memcpy
* Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
*
* */
#include "std_testcase.h"
/* The variable below is not declared "const", but is never assigned
* any other value so a tool should be able to identify that reads of
* this will always give its initialized value.
*/
static int staticFive = 5;
#ifndef OMITBAD
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_07_bad()
{
int64_t * data;
data = NULL;
if(staticFive==5)
{
/* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = (int64_t *)malloc(50*sizeof(int64_t));
if (data == NULL) {exit(-1);}
}
{
int64_t source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int64_t));
printLongLongLine(data[0]);
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the staticFive==5 to staticFive!=5 */
static void goodG2B1()
{
int64_t * data;
data = NULL;
if(staticFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = (int64_t *)malloc(100*sizeof(int64_t));
if (data == NULL) {exit(-1);}
}
{
int64_t source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int64_t));
printLongLongLine(data[0]);
free(data);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
int64_t * data;
data = NULL;
if(staticFive==5)
{
/* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = (int64_t *)malloc(100*sizeof(int64_t));
if (data == NULL) {exit(-1);}
}
{
int64_t source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int64_t));
printLongLongLine(data[0]);
free(data);
}
}
void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_07_good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_07_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_07_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s08/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_07.c
|
C
|
bsd-3-clause
| 3,995 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Switch</title>
<link href="../../../themes/iphone/iphone.css" rel="stylesheet"/>
<script type="text/javascript" src="../../../../../dojo/dojo.js"
data-dojo-config="parseOnLoad: true"></script>
<style>
.color1 .duiSwitchBgLeft {
background: -webkit-gradient(linear, left top, left bottom, from(#28B159), to(#75FBAC), color-stop(0.5, #3FEB84), color-stop(0.5, #4CEE8E));
}
.color1 .duiSwitchBgRight {
background: -webkit-gradient(linear, left top, left bottom, from(#CECECE), to(#FDFDFD), color-stop(0.5, #EEEEEE), color-stop(0.5, #F8F8F8));
}
.color2 .duiSwitchBgLeft {
background: -webkit-gradient(linear, left top, left bottom, from(#FF9D00), to(#FFCE80), color-stop(0.5, #FFBB4D), color-stop(0.5, #FFC871));
}
.color2 .duiSwitchBgRight {
background: -webkit-gradient(linear, left top, left bottom, from(#CECECE), to(#FDFDFD), color-stop(0.5, #EEEEEE), color-stop(0.5, #F8F8F8));
}
.color1 .duiSwitchKnob,
.color2 .duiSwitchKnob {
background: -webkit-gradient(linear, left top, left bottom, from(#999999), to(#FAFAFA), color-stop(0.5, #BBBBBB), color-stop(0.5, #CACACA));
}
.float {
float: left;
margin-right: 10px;
}
.bold {
font-weight: bold;
}
</style>
<script language="JavaScript" type="text/javascript">
//dojo.require("dojo.parser"); // Use the lightweight parser.
dojo.require("dui/mobile/parser");
dojo.require("dui.mobile._base");
dojo.requireIf(!dojo.isWebKit, "dui/mobile/compat");
dojo.require("doh.runner");
</script>
<script type="text/javascript" src="Switch.js"></script>
</head>
<body style="padding:15px;visibility:visible">
<div data-dojo-type="dui/mobile/View" selected="true">
<div data-dojo-type="dui/mobile/RoundRect" shadow="true">
<span class="bold">Default Shape</span><br>
<div class="float" data-dojo-type="dui/mobile/Switch" value="off"></div>
<div data-dojo-type="dui/mobile/Switch" value="on" leftLabel="Start" rightLabel="Stop"></div>
</div>
<div data-dojo-type="dui/mobile/RoundRect" shadow="true">
<span class="bold">Round Shape 1</span><br>
<div class="duiSwRoundShape1 float" data-dojo-type="dui/mobile/Switch" value="off"></div>
<div class="duiSwRoundShape1 color1" data-dojo-type="dui/mobile/Switch" value="on" leftLabel="Start" rightLabel="Stop"></div>
</div>
<div data-dojo-type="dui/mobile/RoundRect" shadow="true">
<span class="bold">Round Shape 2</span><br>
<div class="duiSwRoundShape2 float" data-dojo-type="dui/mobile/Switch" value="off"></div>
<div class="duiSwRoundShape2 color2" data-dojo-type="dui/mobile/Switch" value="on" leftLabel="Start" rightLabel="Stop"></div>
</div>
<div data-dojo-type="dui/mobile/RoundRect" shadow="true">
<span class="bold">Arc Shape 1</span><br>
<div class="duiSwArcShape1 float" data-dojo-type="dui/mobile/Switch" value="off"></div>
<div class="duiSwArcShape1 color1" data-dojo-type="dui/mobile/Switch" value="on" leftLabel="Start" rightLabel="Stop"></div>
</div>
<div data-dojo-type="dui/mobile/RoundRect" shadow="true">
<span class="bold">Arc Shape 2</span><br>
<div class="duiSwArcShape2 float" data-dojo-type="dui/mobile/Switch" value="off"></div>
<div class="duiSwArcShape2 color2" data-dojo-type="dui/mobile/Switch" value="on" leftLabel="Start" rightLabel="Stop"></div>
</div>
</div>
</body>
</html>
|
asudoh/delite
|
mobile/tests/doh/switch/Switch.html
|
HTML
|
bsd-3-clause
| 3,680 |
// Copyright (c) 2013 CloudFlare, Inc.
// Circular buffer data structure.
//
// This implementation avoids memory allocations during push/pop
// operations. It supports nonblocking push (ie: old data gets
// evicted). You can pop an item from the top. You can access this
// data structure concurrently, using an internal guarding mutex lock.
//
// An item can get evicted when NBPush is called. During the call the
// buffer will try to call the Evict callback. If the callback is
// present the NBPush fun runs it and returns nil. Otherwise NBPush
// returns the evicted value or nil if there still is free space in
// the stack.
//
// This package exports three things:
// StackPusher interface
// StackGetter interface
// CircularBuffer structure
package circularbuffer
import (
"sync"
)
// An interface used to add things to the stack.
type StackPusher interface {
// Non-blocking push. Will evict items from the cache if there
// isn't enough space available.
NBPush(interface{}) interface{}
// Non-blocking push. Wil put item in the buffer only if there
// is free space.
NBOptionalPush(interface{}) interface{}
}
// An interface used to get items from the stack.
type StackGetter interface {
// Get an item from the beginning of the stack (oldest),
// blocking.
Get() interface{}
// Blocking pop an item from the end of the stack (newest),
// blocking.
Pop() interface{}
}
type CircularBuffer struct {
start uint // idx of first used cell
pos uint // idx of first unused cell
buffer []interface{}
size uint
avail chan bool // poor man's semaphore. len(avail) is always equal to (size + pos - start) % size
lock sync.Mutex
// Callback used by NBPush if an item needs to be evicted from
// the stack.
Evict func(v interface{})
}
// Create CircularBuffer object with a prealocated buffer of a given size.
func NewCircularBuffer(size uint) *CircularBuffer {
return &CircularBuffer{
buffer: make([]interface{}, size),
size: size,
avail: make(chan bool, size),
}
}
// Nonblocking push. If the Evict callback is not set returns the
// evicted item (if any), otherwise nil.
func (b *CircularBuffer) NBPush(v interface{}) interface{} {
var evictv interface{}
b.lock.Lock()
if b.buffer[b.pos] != nil {
panic("not nil")
}
b.buffer[b.pos] = v
b.pos = (b.pos + 1) % b.size
if b.pos == b.start {
// Remove old item from the bottom of the stack to
// free the space for the new one. This doesn't change
// the length of the stack, so no need to touch avail.
evictv = b.buffer[b.start]
b.buffer[b.start] = nil
b.start = (b.start + 1) % b.size
} else {
select {
case b.avail <- true:
default:
panic("Sending to avail channel must never block")
}
}
b.lock.Unlock()
if evictv != nil && b.Evict != nil {
// Outside the lock. User callback may in want to add
// an item to the stack.
b.Evict(evictv)
return nil
}
return evictv
}
// Nonblocking push. Push only if there is space. Otherwise evict v.
func (b *CircularBuffer) NBOptionalPush(v interface{}) interface{} {
var evictv interface{}
b.lock.Lock()
if b.buffer[b.pos] != nil {
panic("not nil")
}
if (b.start+b.size-1)%b.size == b.pos {
// evict v, don't change anything
evictv = v
} else {
// Plenty of space, just add as usual
b.buffer[b.pos] = v
b.pos = (b.pos + 1) % b.size
select {
case b.avail <- true:
default:
panic("Sending to avail channel must never block")
}
}
b.lock.Unlock()
if evictv != nil && b.Evict != nil {
// Outside the lock. User callback may in want to add
// an item to the stack.
b.Evict(evictv)
return nil
}
return evictv
}
// Get an item from the beginning of the queue (oldest), blocking.
func (b *CircularBuffer) Get() interface{} {
_ = <-b.avail
b.lock.Lock()
defer b.lock.Unlock()
if b.start == b.pos {
panic("Trying to get from empty buffer")
}
v := b.buffer[b.start]
b.buffer[b.start] = nil
b.start = (b.start + 1) % b.size
return v
}
// Blocking pop an item from the end of the queue (newest), blocking.
func (b *CircularBuffer) Pop() interface{} {
_ = <-b.avail
b.lock.Lock()
defer b.lock.Unlock()
if b.start == b.pos {
panic("Can't pop from empty buffer")
}
b.pos = (b.size + b.pos - 1) % b.size
v := b.buffer[b.pos]
b.buffer[b.pos] = nil
return v
}
// Empty Is the buffer empty?
func (b *CircularBuffer) Empty() bool {
// b.avail is a channel, no need for a lock
return len(b.avail) == 0
}
// Length of the buffer
func (b *CircularBuffer) Length() int {
// b.avail is a channel, no need for a lock
return len(b.avail)
}
|
cloudflare/golibs
|
circularbuffer/circularbuffer.go
|
GO
|
bsd-3-clause
| 4,591 |
/* $Id: interrupt.c,v 1.9 1999/01/10 12:35:38 dfr Exp $ */
/* $NetBSD: interrupt.c,v 1.23 1998/02/24 07:38:01 thorpej Exp $ */
/*
* Copyright (c) 1994, 1995, 1996 Carnegie-Mellon University.
* All rights reserved.
*
* Authors: Keith Bostic, Chris G. Demetriou
*
* Permission to use, copy, modify and distribute this software and
* its documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
* FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or [email protected]
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie the
* rights to redistribute these changes.
*/
/*
* Additional Copyright (c) 1997 by Matthew Jacob for NASA/Ames Research Center.
* Redistribute and modify at will, leaving only this additional copyright
* notice.
*/
#include <sys/cdefs.h> /* RCS ID & Copyright macro defns */
/* __KERNEL_RCSID(0, "$NetBSD: interrupt.c,v 1.23 1998/02/24 07:38:01 thorpej Exp $");*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/vmmeter.h>
#include <sys/bus.h>
#include <sys/malloc.h>
#include <machine/reg.h>
#include <machine/frame.h>
#include <machine/cpuconf.h>
#include <machine/bwx.h>
#include <machine/intr.h>
#ifdef EVCNT_COUNTERS
#include <sys/device.h>
struct evcnt clock_intr_evcnt; /* event counter for clock intrs. */
#else
#include <machine/intrcnt.h>
#endif
volatile int mc_expected, mc_received;
static void
dummy_perf(unsigned long vector, struct trapframe *framep)
{
printf("performance interrupt!\n");
}
void (*perf_irq)(unsigned long, struct trapframe *) = dummy_perf;
void
interrupt(a0, a1, a2, framep)
unsigned long a0, a1, a2;
struct trapframe *framep;
{
{
struct proc* p = curproc;
if (!p) p = &proc0;
if ((caddr_t) framep < (caddr_t) p->p_addr + 1024)
panic("possible stack overflow\n");
}
framep->tf_regs[FRAME_TRAPARG_A0] = a0;
framep->tf_regs[FRAME_TRAPARG_A1] = a1;
framep->tf_regs[FRAME_TRAPARG_A2] = a2;
switch (a0) {
case ALPHA_INTR_XPROC: /* interprocessor interrupt */
printf("interprocessor interrupt!\n");
break;
case ALPHA_INTR_CLOCK: /* clock interrupt */
cnt.v_intr++;
#ifdef EVCNT_COUNTERS
clock_intr_evcnt.ev_count++;
#else
intrcnt[INTRCNT_CLOCK]++;
#endif
if (platform.clockintr)
(*platform.clockintr)(framep);
break;
case ALPHA_INTR_ERROR: /* Machine Check or Correctable Error */
a0 = alpha_pal_rdmces();
if (platform.mcheck_handler)
(*platform.mcheck_handler)(a0, framep, a1, a2);
else
machine_check(a0, framep, a1, a2);
break;
case ALPHA_INTR_DEVICE: /* I/O device interrupt */
cnt.v_intr++;
if (platform.iointr)
(*platform.iointr)(framep, a1);
break;
case ALPHA_INTR_PERF: /* interprocessor interrupt */
perf_irq(a1, framep);
break;
case ALPHA_INTR_PASSIVE:
#if 0
printf("passive release interrupt vec 0x%lx (ignoring)\n", a1);
#endif
break;
default:
panic("unexpected interrupt: type 0x%lx vec 0x%lx a2 0x%lx\n",
a0, a1, a2);
/* NOTREACHED */
}
}
void
set_iointr(niointr)
void (*niointr) __P((void *, unsigned long));
{
if (platform.iointr)
panic("set iointr twice");
platform.iointr = niointr;
}
void
machine_check(mces, framep, vector, param)
unsigned long mces;
struct trapframe *framep;
unsigned long vector, param;
{
const char *type;
/* Make sure it's an error we know about. */
if ((mces & (ALPHA_MCES_MIP|ALPHA_MCES_SCE|ALPHA_MCES_PCE)) == 0) {
type = "fatal machine check or error (unknown type)";
goto fatal;
}
/* Machine checks. */
if (mces & ALPHA_MCES_MIP) {
/* If we weren't expecting it, then we punt. */
if (!mc_expected) {
type = "unexpected machine check";
goto fatal;
}
mc_expected = 0;
mc_received = 1;
}
/* System correctable errors. */
if (mces & ALPHA_MCES_SCE)
printf("Warning: received system correctable error.\n");
/* Processor correctable errors. */
if (mces & ALPHA_MCES_PCE)
printf("Warning: received processor correctable error.\n");
/* Clear pending machine checks and correctable errors */
alpha_pal_wrmces(mces);
return;
fatal:
/* Clear pending machine checks and correctable errors */
alpha_pal_wrmces(mces);
printf("\n");
printf("%s:\n", type);
printf("\n");
printf(" mces = 0x%lx\n", mces);
printf(" vector = 0x%lx\n", vector);
printf(" param = 0x%lx\n", param);
printf(" pc = 0x%lx\n", framep->tf_regs[FRAME_PC]);
printf(" ra = 0x%lx\n", framep->tf_regs[FRAME_RA]);
printf(" curproc = %p\n", curproc);
if (curproc != NULL)
printf(" pid = %d, comm = %s\n", curproc->p_pid,
curproc->p_comm);
printf("\n");
panic("machine check");
}
int
badaddr(addr, size)
void *addr;
size_t size;
{
return(badaddr_read(addr, size, NULL));
}
int
badaddr_read(addr, size, rptr)
void *addr;
size_t size;
void *rptr;
{
long rcpt;
/* Get rid of any stale machine checks that have been waiting. */
alpha_pal_draina();
/* Tell the trap code to expect a machine check. */
mc_received = 0;
mc_expected = 1;
/* Read from the test address, and make sure the read happens. */
alpha_mb();
switch (size) {
case sizeof (u_int8_t):
if (alpha_implver() == ALPHA_IMPLVER_EV5
&& alpha_amask(ALPHA_AMASK_BWX) == 0)
rcpt = ldbu((vm_offset_t)addr);
else
rcpt = *(volatile u_int8_t *)addr;
break;
case sizeof (u_int16_t):
if (alpha_implver() == ALPHA_IMPLVER_EV5
&& alpha_amask(ALPHA_AMASK_BWX) == 0)
rcpt = ldwu((vm_offset_t)addr);
else
rcpt = *(volatile u_int16_t *)addr;
break;
case sizeof (u_int32_t):
rcpt = *(volatile u_int32_t *)addr;
break;
case sizeof (u_int64_t):
rcpt = *(volatile u_int64_t *)addr;
break;
default:
panic("badaddr: invalid size (%ld)\n", size);
}
alpha_mb();
/* Make sure we took the machine check, if we caused one. */
alpha_pal_draina();
/* disallow further machine checks */
mc_expected = 0;
if (rptr) {
switch (size) {
case sizeof (u_int8_t):
*(volatile u_int8_t *)rptr = rcpt;
break;
case sizeof (u_int16_t):
*(volatile u_int16_t *)rptr = rcpt;
break;
case sizeof (u_int32_t):
*(volatile u_int32_t *)rptr = rcpt;
break;
case sizeof (u_int64_t):
*(volatile u_int64_t *)rptr = rcpt;
break;
}
}
/* Return non-zero (i.e. true) if it's a bad address. */
return (mc_received);
}
#define HASHVEC(vector) ((vector) % 31)
LIST_HEAD(alpha_intr_list, alpha_intr);
struct alpha_intr {
LIST_ENTRY(alpha_intr) list; /* chain handlers in this hash bucket */
int vector; /* vector to match */
driver_intr_t *intr; /* handler function */
void *arg; /* argument to handler */
volatile long *cntp; /* interrupt counter */
};
static struct alpha_intr_list alpha_intr_hash[31];
int alpha_setup_intr(int vector, driver_intr_t *intr, void *arg,
void **cookiep, volatile long *cntp)
{
int h = HASHVEC(vector);
struct alpha_intr *i;
int s;
i = malloc(sizeof(struct alpha_intr), M_DEVBUF, M_NOWAIT);
if (!i)
return ENOMEM;
i->vector = vector;
i->intr = intr;
i->arg = arg;
if (cntp)
i->cntp = cntp;
else
i->cntp = NULL;
s = splhigh();
LIST_INSERT_HEAD(&alpha_intr_hash[h], i, list);
splx(s);
*cookiep = i;
return 0;
}
int alpha_teardown_intr(void *cookie)
{
struct alpha_intr *i = cookie;
int s;
s = splhigh();
LIST_REMOVE(i, list);
splx(s);
free(i, M_DEVBUF);
return 0;
}
void
alpha_dispatch_intr(void *frame, unsigned long vector)
{
struct alpha_intr *i;
volatile long *cntp;
int h = HASHVEC(vector);
for (i = LIST_FIRST(&alpha_intr_hash[h]); i; i = LIST_NEXT(i, list))
if (i->vector == vector) {
if (cntp = i->cntp)
(*cntp) ++;
i->intr(i->arg);
}
}
|
MarginC/kame
|
freebsd3/sys/alpha/alpha/interrupt.c
|
C
|
bsd-3-clause
| 8,212 |
<?php
return array(
// This should be an array of module namespaces used in the application.
'modules' => array(
'Application',
'ZendDeveloperTools',
'ZfcBase',
'ZfcUser',
'DoctrineModule',
'DoctrineORMModule',
'ScnSocialAuth',
// Custom module
'User',
'Secret',
'Meeting',
'School',
),
// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => array(
// This should be an array of paths in which modules reside.
// If a string key is provided, the listener will consider that a module
// namespace, the value of that key the specific path to that module's
// Module class.
'module_paths' => array(
'./module',
'./vendor',
),
// An array of paths from which to glob configuration files after
// modules are loaded. These effectively override configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests.
//'config_cache_enabled' => $booleanValue,
// The key used to create the configuration cache file name.
//'config_cache_key' => $stringKey,
// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process.
//'module_map_cache_enabled' => $booleanValue,
// The key used to create the class map cache file name.
//'module_map_cache_key' => $stringKey,
// The path in which to cache merged configuration.
//'cache_dir' => $stringPath,
// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded.
// 'check_dependencies' => true,
),
// Used to create an own service manager. May contain one or more child arrays.
//'service_listener_options' => array(
// array(
// 'service_manager' => $stringServiceManagerName,
// 'config_key' => $stringConfigKey,
// 'interface' => $stringOptionalInterface,
// 'method' => $stringRequiredMethodName,
// ),
// )
// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => array(),
);
|
nazargulov/lingvoguide
|
config/application.config.php
|
PHP
|
bsd-3-clause
| 2,886 |
/* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#define BOOST_TEST_MAIN
#include "Tudat/JsonInterface/UnitTests/unitTestSupport.h"
#include "Tudat/JsonInterface/Propagation/referenceFrames.h"
namespace tudat
{
namespace unit_tests
{
#define INPUT( filename ) \
( json_interface::inputDirectory( ) / boost::filesystem::path( __FILE__ ).stem( ) / filename ).string( )
BOOST_AUTO_TEST_SUITE( test_json_referenceFrames )
// Test 1: aerodynamic reference frames
BOOST_AUTO_TEST_CASE( test_json_referenceFrames_aerodynamic )
{
BOOST_CHECK_EQUAL_ENUM( INPUT( "aerodynamic" ),
reference_frames::aerodynamicsReferenceFrames,
reference_frames::unsupportedAerodynamicsReferenceFrames );
}
// Test 2: aerodynamic reference frame angles
BOOST_AUTO_TEST_CASE( test_json_referenceFrames_aerodynamicAngles )
{
BOOST_CHECK_EQUAL_ENUM( INPUT( "aerodynamicAngles" ),
reference_frames::aerodynamicsReferenceFrameAngles,
reference_frames::unsupportedAerodynamicsReferenceFrameAngles );
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
|
Tudat/tudat
|
Tudat/JsonInterface/UnitTests/unitTestReferenceFrames.cpp
|
C++
|
bsd-3-clause
| 1,560 |
package gwlpr.protocol.loginserver.inbound;
import gwlpr.protocol.serialization.GWMessage;
/**
* Auto-generated by PacketCodeGen.
*
*/
public final class P050_Unknown
extends GWMessage
{
private long unknown1;
private String unknown2;
@Override
public short getHeader() {
return 50;
}
public long getUnknown1() {
return unknown1;
}
public String getUnknown2() {
return unknown2;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("P050_Unknown[");
sb.append("unknown1=").append(this.unknown1).append(",unknown2=").append(this.unknown2 .toString()).append("]");
return sb.toString();
}
}
|
GameRevision/GWLP-R
|
protocol/src/main/java/gwlpr/protocol/loginserver/inbound/P050_Unknown.java
|
Java
|
bsd-3-clause
| 727 |
#pragma once
#include "DAVAEngine.h"
namespace DAVA
{
class EditorHeightmap : public DAVA::Heightmap
{
static const DAVA::int32 MAX_EDITOR_HEIGHTMAP_SIZE = 512;
static const DAVA::int32 VALUE_NOT_CHANGED = 0;
static const DAVA::int32 VALUE_WAS_CHANGED = 1;
public:
EditorHeightmap(DAVA::Heightmap* heightmap);
virtual ~EditorHeightmap();
void HeghtWasChanged(const DAVA::Rect& changedRect);
void DrawRelativeRGBA(DAVA::Image* src, DAVA::int32 x, DAVA::int32 y, DAVA::int32 width, DAVA::int32 height, DAVA::float32 k);
void DrawAverageRGBA(DAVA::Image* mask, DAVA::int32 x, DAVA::int32 y, DAVA::int32 width, DAVA::int32 height, DAVA::float32 k);
void DrawAbsoluteRGBA(DAVA::Image* mask, DAVA::int32 x, DAVA::int32 y, DAVA::int32 width, DAVA::int32 height, DAVA::float32 time, DAVA::float32 dstHeight);
void DrawCopypasteRGBA(DAVA::Image* mask, const DAVA::Vector2& posFrom, const DAVA::Vector2& posTo, DAVA::int32 width, DAVA::int32 height, DAVA::float32 koef);
static void DrawCopypasteRGBA(DAVA::Image* src, DAVA::Image* dst, DAVA::Image* mask, const DAVA::Vector2& posFrom, const DAVA::Vector2& posTo, DAVA::int32 width, DAVA::int32 height);
static bool Clipping(DAVA::int32& srcOffset, DAVA::int32& dstOffset, DAVA::int32& dstX, DAVA::int32& dstY,
DAVA::int32 dstWidth, DAVA::int32 dstHeight, DAVA::int32& width, DAVA::int32& height,
DAVA::int32& yAddSrc, DAVA::int32& xAddDst, DAVA::int32& yAddDst);
protected:
void DownscaleOrClone();
void Downscale(DAVA::int32 newSize);
void Upscale();
void InitializeScalingTable(DAVA::int32 count);
void InitializeTableOfChanges();
DAVA::uint16 GetHeightValue(DAVA::int32 posX, DAVA::int32 posY, DAVA::int32 muliplier);
DAVA::uint16 GetVerticalValue(DAVA::int32 posY, DAVA::int32 muliplier);
DAVA::uint16 GetHorizontalValue(DAVA::int32 posX, DAVA::int32 muliplier);
void UpscaleValue(DAVA::int32 leftX, DAVA::int32 topY, DAVA::int32 muliplier);
protected:
Heightmap* savedHeightmap = nullptr;
DAVA::uint8* tableOfChanges = nullptr;
DAVA::float32* scalingTable = nullptr;
};
} // namespace DAVA
|
dava/dava.engine
|
Modules/REPlatform/Sources/REPlatform/Deprecated/EditorHeightmap.h
|
C
|
bsd-3-clause
| 2,195 |
/*-
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed
* to Berkeley by John Heidemann of the UCLA Ficus project.
*
* Source: * @(#)i405_init.c 2.10 92/04/27 UCLA Ficus project
*
* 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.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/kern/vfs_default.c 248029 2013-03-08 08:09:26Z kib $");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bio.h>
#include <sys/buf.h>
#include <sys/conf.h>
#include <sys/event.h>
#include <sys/kernel.h>
#include <sys/limits.h>
#include <sys/lock.h>
#include <sys/lockf.h>
#include <sys/malloc.h>
#include <sys/mount.h>
#include <sys/mutex.h>
#include <sys/namei.h>
#include <sys/fcntl.h>
#include <sys/unistd.h>
#include <sys/vnode.h>
#include <sys/dirent.h>
#include <sys/poll.h>
#include <security/mac/mac_framework.h>
#include <vm/vm.h>
#include <vm/vm_object.h>
#include <vm/vm_extern.h>
#include <vm/pmap.h>
#include <vm/vm_map.h>
#include <vm/vm_page.h>
#include <vm/vm_pager.h>
#include <vm/vnode_pager.h>
static int vop_nolookup(struct vop_lookup_args *);
static int vop_norename(struct vop_rename_args *);
static int vop_nostrategy(struct vop_strategy_args *);
static int get_next_dirent(struct vnode *vp, struct dirent **dpp,
char *dirbuf, int dirbuflen, off_t *off,
char **cpos, int *len, int *eofflag,
struct thread *td);
static int dirent_exists(struct vnode *vp, const char *dirname,
struct thread *td);
#define DIRENT_MINSIZE (sizeof(struct dirent) - (MAXNAMLEN+1) + 4)
static int vop_stdis_text(struct vop_is_text_args *ap);
static int vop_stdset_text(struct vop_set_text_args *ap);
static int vop_stdunset_text(struct vop_unset_text_args *ap);
static int vop_stdget_writecount(struct vop_get_writecount_args *ap);
static int vop_stdadd_writecount(struct vop_add_writecount_args *ap);
/*
* This vnode table stores what we want to do if the filesystem doesn't
* implement a particular VOP.
*
* If there is no specific entry here, we will return EOPNOTSUPP.
*
* Note that every filesystem has to implement either vop_access
* or vop_accessx; failing to do so will result in immediate crash
* due to stack overflow, as vop_stdaccess() calls vop_stdaccessx(),
* which calls vop_stdaccess() etc.
*/
struct vop_vector default_vnodeops = {
.vop_default = NULL,
.vop_bypass = VOP_EOPNOTSUPP,
.vop_access = vop_stdaccess,
.vop_accessx = vop_stdaccessx,
.vop_advise = vop_stdadvise,
.vop_advlock = vop_stdadvlock,
.vop_advlockasync = vop_stdadvlockasync,
.vop_advlockpurge = vop_stdadvlockpurge,
.vop_allocate = vop_stdallocate,
.vop_bmap = vop_stdbmap,
.vop_close = VOP_NULL,
.vop_fsync = VOP_NULL,
.vop_getpages = vop_stdgetpages,
.vop_getwritemount = vop_stdgetwritemount,
.vop_inactive = VOP_NULL,
.vop_ioctl = VOP_ENOTTY,
.vop_kqfilter = vop_stdkqfilter,
.vop_islocked = vop_stdislocked,
.vop_lock1 = vop_stdlock,
.vop_lookup = vop_nolookup,
.vop_open = VOP_NULL,
.vop_pathconf = VOP_EINVAL,
.vop_poll = vop_nopoll,
.vop_putpages = vop_stdputpages,
.vop_readlink = VOP_EINVAL,
.vop_rename = vop_norename,
.vop_revoke = VOP_PANIC,
.vop_strategy = vop_nostrategy,
.vop_unlock = vop_stdunlock,
.vop_vptocnp = vop_stdvptocnp,
.vop_vptofh = vop_stdvptofh,
.vop_unp_bind = vop_stdunp_bind,
.vop_unp_connect = vop_stdunp_connect,
.vop_unp_detach = vop_stdunp_detach,
.vop_is_text = vop_stdis_text,
.vop_set_text = vop_stdset_text,
.vop_unset_text = vop_stdunset_text,
.vop_get_writecount = vop_stdget_writecount,
.vop_add_writecount = vop_stdadd_writecount,
};
/*
* Series of placeholder functions for various error returns for
* VOPs.
*/
int
vop_eopnotsupp(struct vop_generic_args *ap)
{
/*
printf("vop_notsupp[%s]\n", ap->a_desc->vdesc_name);
*/
return (EOPNOTSUPP);
}
int
vop_ebadf(struct vop_generic_args *ap)
{
return (EBADF);
}
int
vop_enotty(struct vop_generic_args *ap)
{
return (ENOTTY);
}
int
vop_einval(struct vop_generic_args *ap)
{
return (EINVAL);
}
int
vop_enoent(struct vop_generic_args *ap)
{
return (ENOENT);
}
int
vop_null(struct vop_generic_args *ap)
{
return (0);
}
/*
* Helper function to panic on some bad VOPs in some filesystems.
*/
int
vop_panic(struct vop_generic_args *ap)
{
panic("filesystem goof: vop_panic[%s]", ap->a_desc->vdesc_name);
}
/*
* vop_std<something> and vop_no<something> are default functions for use by
* filesystems that need the "default reasonable" implementation for a
* particular operation.
*
* The documentation for the operations they implement exists (if it exists)
* in the VOP_<SOMETHING>(9) manpage (all uppercase).
*/
/*
* Default vop for filesystems that do not support name lookup
*/
static int
vop_nolookup(ap)
struct vop_lookup_args /* {
struct vnode *a_dvp;
struct vnode **a_vpp;
struct componentname *a_cnp;
} */ *ap;
{
*ap->a_vpp = NULL;
return (ENOTDIR);
}
/*
* vop_norename:
*
* Handle unlock and reference counting for arguments of vop_rename
* for filesystems that do not implement rename operation.
*/
static int
vop_norename(struct vop_rename_args *ap)
{
vop_rename_fail(ap);
return (EOPNOTSUPP);
}
/*
* vop_nostrategy:
*
* Strategy routine for VFS devices that have none.
*
* BIO_ERROR and B_INVAL must be cleared prior to calling any strategy
* routine. Typically this is done for a BIO_READ strategy call.
* Typically B_INVAL is assumed to already be clear prior to a write
* and should not be cleared manually unless you just made the buffer
* invalid. BIO_ERROR should be cleared either way.
*/
static int
vop_nostrategy (struct vop_strategy_args *ap)
{
printf("No strategy for buffer at %p\n", ap->a_bp);
vprint("vnode", ap->a_vp);
ap->a_bp->b_ioflags |= BIO_ERROR;
ap->a_bp->b_error = EOPNOTSUPP;
bufdone(ap->a_bp);
return (EOPNOTSUPP);
}
static int
get_next_dirent(struct vnode *vp, struct dirent **dpp, char *dirbuf,
int dirbuflen, off_t *off, char **cpos, int *len,
int *eofflag, struct thread *td)
{
int error, reclen;
struct uio uio;
struct iovec iov;
struct dirent *dp;
KASSERT(VOP_ISLOCKED(vp), ("vp %p is not locked", vp));
KASSERT(vp->v_type == VDIR, ("vp %p is not a directory", vp));
if (*len == 0) {
iov.iov_base = dirbuf;
iov.iov_len = dirbuflen;
uio.uio_iov = &iov;
uio.uio_iovcnt = 1;
uio.uio_offset = *off;
uio.uio_resid = dirbuflen;
uio.uio_segflg = UIO_SYSSPACE;
uio.uio_rw = UIO_READ;
uio.uio_td = td;
*eofflag = 0;
#ifdef MAC
error = mac_vnode_check_readdir(td->td_ucred, vp);
if (error == 0)
#endif
error = VOP_READDIR(vp, &uio, td->td_ucred, eofflag,
NULL, NULL);
if (error)
return (error);
*off = uio.uio_offset;
*cpos = dirbuf;
*len = (dirbuflen - uio.uio_resid);
if (*len == 0)
return (ENOENT);
}
dp = (struct dirent *)(*cpos);
reclen = dp->d_reclen;
*dpp = dp;
/* check for malformed directory.. */
if (reclen < DIRENT_MINSIZE)
return (EINVAL);
*cpos += reclen;
*len -= reclen;
return (0);
}
/*
* Check if a named file exists in a given directory vnode.
*/
static int
dirent_exists(struct vnode *vp, const char *dirname, struct thread *td)
{
char *dirbuf, *cpos;
int error, eofflag, dirbuflen, len, found;
off_t off;
struct dirent *dp;
struct vattr va;
KASSERT(VOP_ISLOCKED(vp), ("vp %p is not locked", vp));
KASSERT(vp->v_type == VDIR, ("vp %p is not a directory", vp));
found = 0;
error = VOP_GETATTR(vp, &va, td->td_ucred);
if (error)
return (found);
dirbuflen = DEV_BSIZE;
if (dirbuflen < va.va_blocksize)
dirbuflen = va.va_blocksize;
dirbuf = (char *)malloc(dirbuflen, M_TEMP, M_WAITOK);
off = 0;
len = 0;
do {
error = get_next_dirent(vp, &dp, dirbuf, dirbuflen, &off,
&cpos, &len, &eofflag, td);
if (error)
goto out;
if ((dp->d_type != DT_WHT) &&
!strcmp(dp->d_name, dirname)) {
found = 1;
goto out;
}
} while (len > 0 || !eofflag);
out:
free(dirbuf, M_TEMP);
return (found);
}
int
vop_stdaccess(struct vop_access_args *ap)
{
KASSERT((ap->a_accmode & ~(VEXEC | VWRITE | VREAD | VADMIN |
VAPPEND)) == 0, ("invalid bit in accmode"));
return (VOP_ACCESSX(ap->a_vp, ap->a_accmode, ap->a_cred, ap->a_td));
}
int
vop_stdaccessx(struct vop_accessx_args *ap)
{
int error;
accmode_t accmode = ap->a_accmode;
error = vfs_unixify_accmode(&accmode);
if (error != 0)
return (error);
if (accmode == 0)
return (0);
return (VOP_ACCESS(ap->a_vp, accmode, ap->a_cred, ap->a_td));
}
/*
* Advisory record locking support
*/
int
vop_stdadvlock(struct vop_advlock_args *ap)
{
struct vnode *vp;
struct ucred *cred;
struct vattr vattr;
int error;
vp = ap->a_vp;
cred = curthread->td_ucred;
vn_lock(vp, LK_SHARED | LK_RETRY);
error = VOP_GETATTR(vp, &vattr, cred);
VOP_UNLOCK(vp, 0);
if (error)
return (error);
return (lf_advlock(ap, &(vp->v_lockf), vattr.va_size));
}
int
vop_stdadvlockasync(struct vop_advlockasync_args *ap)
{
struct vnode *vp;
struct ucred *cred;
struct vattr vattr;
int error;
vp = ap->a_vp;
cred = curthread->td_ucred;
vn_lock(vp, LK_SHARED | LK_RETRY);
error = VOP_GETATTR(vp, &vattr, cred);
VOP_UNLOCK(vp, 0);
if (error)
return (error);
return (lf_advlockasync(ap, &(vp->v_lockf), vattr.va_size));
}
int
vop_stdadvlockpurge(struct vop_advlockpurge_args *ap)
{
struct vnode *vp;
vp = ap->a_vp;
lf_purgelocks(vp, &vp->v_lockf);
return (0);
}
/*
* vop_stdpathconf:
*
* Standard implementation of POSIX pathconf, to get information about limits
* for a filesystem.
* Override per filesystem for the case where the filesystem has smaller
* limits.
*/
int
vop_stdpathconf(ap)
struct vop_pathconf_args /* {
struct vnode *a_vp;
int a_name;
int *a_retval;
} */ *ap;
{
switch (ap->a_name) {
case _PC_NAME_MAX:
*ap->a_retval = NAME_MAX;
return (0);
case _PC_PATH_MAX:
*ap->a_retval = PATH_MAX;
return (0);
case _PC_LINK_MAX:
*ap->a_retval = LINK_MAX;
return (0);
case _PC_MAX_CANON:
*ap->a_retval = MAX_CANON;
return (0);
case _PC_MAX_INPUT:
*ap->a_retval = MAX_INPUT;
return (0);
case _PC_PIPE_BUF:
*ap->a_retval = PIPE_BUF;
return (0);
case _PC_CHOWN_RESTRICTED:
*ap->a_retval = 1;
return (0);
case _PC_VDISABLE:
*ap->a_retval = _POSIX_VDISABLE;
return (0);
default:
return (EINVAL);
}
/* NOTREACHED */
}
/*
* Standard lock, unlock and islocked functions.
*/
int
vop_stdlock(ap)
struct vop_lock1_args /* {
struct vnode *a_vp;
int a_flags;
char *file;
int line;
} */ *ap;
{
struct vnode *vp = ap->a_vp;
return (_lockmgr_args(vp->v_vnlock, ap->a_flags, VI_MTX(vp),
LK_WMESG_DEFAULT, LK_PRIO_DEFAULT, LK_TIMO_DEFAULT, ap->a_file,
ap->a_line));
}
/* See above. */
int
vop_stdunlock(ap)
struct vop_unlock_args /* {
struct vnode *a_vp;
int a_flags;
} */ *ap;
{
struct vnode *vp = ap->a_vp;
return (lockmgr(vp->v_vnlock, ap->a_flags | LK_RELEASE, VI_MTX(vp)));
}
/* See above. */
int
vop_stdislocked(ap)
struct vop_islocked_args /* {
struct vnode *a_vp;
} */ *ap;
{
return (lockstatus(ap->a_vp->v_vnlock));
}
/*
* Return true for select/poll.
*/
int
vop_nopoll(ap)
struct vop_poll_args /* {
struct vnode *a_vp;
int a_events;
struct ucred *a_cred;
struct thread *a_td;
} */ *ap;
{
return (poll_no_poll(ap->a_events));
}
/*
* Implement poll for local filesystems that support it.
*/
int
vop_stdpoll(ap)
struct vop_poll_args /* {
struct vnode *a_vp;
int a_events;
struct ucred *a_cred;
struct thread *a_td;
} */ *ap;
{
if (ap->a_events & ~POLLSTANDARD)
return (vn_pollrecord(ap->a_vp, ap->a_td, ap->a_events));
return (ap->a_events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
}
/*
* Return our mount point, as we will take charge of the writes.
*/
int
vop_stdgetwritemount(ap)
struct vop_getwritemount_args /* {
struct vnode *a_vp;
struct mount **a_mpp;
} */ *ap;
{
struct mount *mp;
/*
* XXX Since this is called unlocked we may be recycled while
* attempting to ref the mount. If this is the case or mountpoint
* will be set to NULL. We only have to prevent this call from
* returning with a ref to an incorrect mountpoint. It is not
* harmful to return with a ref to our previous mountpoint.
*/
mp = ap->a_vp->v_mount;
if (mp != NULL) {
vfs_ref(mp);
if (mp != ap->a_vp->v_mount) {
vfs_rel(mp);
mp = NULL;
}
}
*(ap->a_mpp) = mp;
return (0);
}
/* XXX Needs good comment and VOP_BMAP(9) manpage */
int
vop_stdbmap(ap)
struct vop_bmap_args /* {
struct vnode *a_vp;
daddr_t a_bn;
struct bufobj **a_bop;
daddr_t *a_bnp;
int *a_runp;
int *a_runb;
} */ *ap;
{
if (ap->a_bop != NULL)
*ap->a_bop = &ap->a_vp->v_bufobj;
if (ap->a_bnp != NULL)
*ap->a_bnp = ap->a_bn * btodb(ap->a_vp->v_mount->mnt_stat.f_iosize);
if (ap->a_runp != NULL)
*ap->a_runp = 0;
if (ap->a_runb != NULL)
*ap->a_runb = 0;
return (0);
}
int
vop_stdfsync(ap)
struct vop_fsync_args /* {
struct vnode *a_vp;
struct ucred *a_cred;
int a_waitfor;
struct thread *a_td;
} */ *ap;
{
struct vnode *vp = ap->a_vp;
struct buf *bp;
struct bufobj *bo;
struct buf *nbp;
int error = 0;
int maxretry = 1000; /* large, arbitrarily chosen */
bo = &vp->v_bufobj;
BO_LOCK(bo);
loop1:
/*
* MARK/SCAN initialization to avoid infinite loops.
*/
TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
bp->b_vflags &= ~BV_SCANNED;
bp->b_error = 0;
}
/*
* Flush all dirty buffers associated with a vnode.
*/
loop2:
TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
if ((bp->b_vflags & BV_SCANNED) != 0)
continue;
bp->b_vflags |= BV_SCANNED;
if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
if (ap->a_waitfor != MNT_WAIT)
continue;
if (BUF_LOCK(bp,
LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
BO_MTX(bo)) != 0) {
BO_LOCK(bo);
goto loop1;
}
BO_LOCK(bo);
}
BO_UNLOCK(bo);
KASSERT(bp->b_bufobj == bo,
("bp %p wrong b_bufobj %p should be %p",
bp, bp->b_bufobj, bo));
if ((bp->b_flags & B_DELWRI) == 0)
panic("fsync: not dirty");
if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) {
vfs_bio_awrite(bp);
} else {
bremfree(bp);
bawrite(bp);
}
BO_LOCK(bo);
goto loop2;
}
/*
* If synchronous the caller expects us to completely resolve all
* dirty buffers in the system. Wait for in-progress I/O to
* complete (which could include background bitmap writes), then
* retry if dirty blocks still exist.
*/
if (ap->a_waitfor == MNT_WAIT) {
bufobj_wwait(bo, 0, 0);
if (bo->bo_dirty.bv_cnt > 0) {
/*
* If we are unable to write any of these buffers
* then we fail now rather than trying endlessly
* to write them out.
*/
TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
if ((error = bp->b_error) == 0)
continue;
if (error == 0 && --maxretry >= 0)
goto loop1;
error = EAGAIN;
}
}
BO_UNLOCK(bo);
if (error == EAGAIN)
vprint("fsync: giving up on dirty", vp);
return (error);
}
/* XXX Needs good comment and more info in the manpage (VOP_GETPAGES(9)). */
int
vop_stdgetpages(ap)
struct vop_getpages_args /* {
struct vnode *a_vp;
vm_page_t *a_m;
int a_count;
int a_reqpage;
vm_ooffset_t a_offset;
} */ *ap;
{
return vnode_pager_generic_getpages(ap->a_vp, ap->a_m,
ap->a_count, ap->a_reqpage);
}
int
vop_stdkqfilter(struct vop_kqfilter_args *ap)
{
return vfs_kqfilter(ap);
}
/* XXX Needs good comment and more info in the manpage (VOP_PUTPAGES(9)). */
int
vop_stdputpages(ap)
struct vop_putpages_args /* {
struct vnode *a_vp;
vm_page_t *a_m;
int a_count;
int a_sync;
int *a_rtvals;
vm_ooffset_t a_offset;
} */ *ap;
{
return vnode_pager_generic_putpages(ap->a_vp, ap->a_m, ap->a_count,
ap->a_sync, ap->a_rtvals);
}
int
vop_stdvptofh(struct vop_vptofh_args *ap)
{
return (EOPNOTSUPP);
}
int
vop_stdvptocnp(struct vop_vptocnp_args *ap)
{
struct vnode *vp = ap->a_vp;
struct vnode **dvp = ap->a_vpp;
struct ucred *cred = ap->a_cred;
char *buf = ap->a_buf;
int *buflen = ap->a_buflen;
char *dirbuf, *cpos;
int i, error, eofflag, dirbuflen, flags, locked, len, covered;
off_t off;
ino_t fileno;
struct vattr va;
struct nameidata nd;
struct thread *td;
struct dirent *dp;
struct vnode *mvp;
i = *buflen;
error = 0;
covered = 0;
td = curthread;
if (vp->v_type != VDIR)
return (ENOENT);
error = VOP_GETATTR(vp, &va, cred);
if (error)
return (error);
VREF(vp);
locked = VOP_ISLOCKED(vp);
VOP_UNLOCK(vp, 0);
NDINIT_ATVP(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
"..", vp, td);
flags = FREAD;
error = vn_open_cred(&nd, &flags, 0, VN_OPEN_NOAUDIT, cred, NULL);
if (error) {
vn_lock(vp, locked | LK_RETRY);
return (error);
}
NDFREE(&nd, NDF_ONLY_PNBUF);
mvp = *dvp = nd.ni_vp;
if (vp->v_mount != (*dvp)->v_mount &&
((*dvp)->v_vflag & VV_ROOT) &&
((*dvp)->v_mount->mnt_flag & MNT_UNION)) {
*dvp = (*dvp)->v_mount->mnt_vnodecovered;
VREF(mvp);
VOP_UNLOCK(mvp, 0);
vn_close(mvp, FREAD, cred, td);
VREF(*dvp);
vn_lock(*dvp, LK_EXCLUSIVE | LK_RETRY);
covered = 1;
}
fileno = va.va_fileid;
dirbuflen = DEV_BSIZE;
if (dirbuflen < va.va_blocksize)
dirbuflen = va.va_blocksize;
dirbuf = (char *)malloc(dirbuflen, M_TEMP, M_WAITOK);
if ((*dvp)->v_type != VDIR) {
error = ENOENT;
goto out;
}
off = 0;
len = 0;
do {
/* call VOP_READDIR of parent */
error = get_next_dirent(*dvp, &dp, dirbuf, dirbuflen, &off,
&cpos, &len, &eofflag, td);
if (error)
goto out;
if ((dp->d_type != DT_WHT) &&
(dp->d_fileno == fileno)) {
if (covered) {
VOP_UNLOCK(*dvp, 0);
vn_lock(mvp, LK_EXCLUSIVE | LK_RETRY);
if (dirent_exists(mvp, dp->d_name, td)) {
error = ENOENT;
VOP_UNLOCK(mvp, 0);
vn_lock(*dvp, LK_EXCLUSIVE | LK_RETRY);
goto out;
}
VOP_UNLOCK(mvp, 0);
vn_lock(*dvp, LK_EXCLUSIVE | LK_RETRY);
}
i -= dp->d_namlen;
if (i < 0) {
error = ENOMEM;
goto out;
}
if (dp->d_namlen == 1 && dp->d_name[0] == '.') {
error = ENOENT;
} else {
bcopy(dp->d_name, buf + i, dp->d_namlen);
error = 0;
}
goto out;
}
} while (len > 0 || !eofflag);
error = ENOENT;
out:
free(dirbuf, M_TEMP);
if (!error) {
*buflen = i;
vref(*dvp);
}
if (covered) {
vput(*dvp);
vrele(mvp);
} else {
VOP_UNLOCK(mvp, 0);
vn_close(mvp, FREAD, cred, td);
}
vn_lock(vp, locked | LK_RETRY);
return (error);
}
int
vop_stdallocate(struct vop_allocate_args *ap)
{
#ifdef __notyet__
struct statfs sfs;
#endif
struct iovec aiov;
struct vattr vattr, *vap;
struct uio auio;
off_t fsize, len, cur, offset;
uint8_t *buf;
struct thread *td;
struct vnode *vp;
size_t iosize;
int error;
buf = NULL;
error = 0;
td = curthread;
vap = &vattr;
vp = ap->a_vp;
len = *ap->a_len;
offset = *ap->a_offset;
error = VOP_GETATTR(vp, vap, td->td_ucred);
if (error != 0)
goto out;
fsize = vap->va_size;
iosize = vap->va_blocksize;
if (iosize == 0)
iosize = BLKDEV_IOSIZE;
if (iosize > MAXPHYS)
iosize = MAXPHYS;
buf = malloc(iosize, M_TEMP, M_WAITOK);
#ifdef __notyet__
/*
* Check if the filesystem sets f_maxfilesize; if not use
* VOP_SETATTR to perform the check.
*/
error = VFS_STATFS(vp->v_mount, &sfs, td);
if (error != 0)
goto out;
if (sfs.f_maxfilesize) {
if (offset > sfs.f_maxfilesize || len > sfs.f_maxfilesize ||
offset + len > sfs.f_maxfilesize) {
error = EFBIG;
goto out;
}
} else
#endif
if (offset + len > vap->va_size) {
/*
* Test offset + len against the filesystem's maxfilesize.
*/
VATTR_NULL(vap);
vap->va_size = offset + len;
error = VOP_SETATTR(vp, vap, td->td_ucred);
if (error != 0)
goto out;
VATTR_NULL(vap);
vap->va_size = fsize;
error = VOP_SETATTR(vp, vap, td->td_ucred);
if (error != 0)
goto out;
}
for (;;) {
/*
* Read and write back anything below the nominal file
* size. There's currently no way outside the filesystem
* to know whether this area is sparse or not.
*/
cur = iosize;
if ((offset % iosize) != 0)
cur -= (offset % iosize);
if (cur > len)
cur = len;
if (offset < fsize) {
aiov.iov_base = buf;
aiov.iov_len = cur;
auio.uio_iov = &aiov;
auio.uio_iovcnt = 1;
auio.uio_offset = offset;
auio.uio_resid = cur;
auio.uio_segflg = UIO_SYSSPACE;
auio.uio_rw = UIO_READ;
auio.uio_td = td;
error = VOP_READ(vp, &auio, 0, td->td_ucred);
if (error != 0)
break;
if (auio.uio_resid > 0) {
bzero(buf + cur - auio.uio_resid,
auio.uio_resid);
}
} else {
bzero(buf, cur);
}
aiov.iov_base = buf;
aiov.iov_len = cur;
auio.uio_iov = &aiov;
auio.uio_iovcnt = 1;
auio.uio_offset = offset;
auio.uio_resid = cur;
auio.uio_segflg = UIO_SYSSPACE;
auio.uio_rw = UIO_WRITE;
auio.uio_td = td;
error = VOP_WRITE(vp, &auio, 0, td->td_ucred);
if (error != 0)
break;
len -= cur;
offset += cur;
if (len == 0)
break;
if (should_yield())
break;
}
out:
*ap->a_len = len;
*ap->a_offset = offset;
free(buf, M_TEMP);
return (error);
}
int
vop_stdadvise(struct vop_advise_args *ap)
{
struct vnode *vp;
off_t start, end;
int error, vfslocked;
vp = ap->a_vp;
switch (ap->a_advice) {
case POSIX_FADV_WILLNEED:
/*
* Do nothing for now. Filesystems should provide a
* custom method which starts an asynchronous read of
* the requested region.
*/
error = 0;
break;
case POSIX_FADV_DONTNEED:
/*
* Flush any open FS buffers and then remove pages
* from the backing VM object. Using vinvalbuf() here
* is a bit heavy-handed as it flushes all buffers for
* the given vnode, not just the buffers covering the
* requested range.
*/
error = 0;
vfslocked = VFS_LOCK_GIANT(vp->v_mount);
vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
if (vp->v_iflag & VI_DOOMED) {
VOP_UNLOCK(vp, 0);
VFS_UNLOCK_GIANT(vfslocked);
break;
}
vinvalbuf(vp, V_CLEANONLY, 0, 0);
if (vp->v_object != NULL) {
start = trunc_page(ap->a_start);
end = round_page(ap->a_end);
VM_OBJECT_LOCK(vp->v_object);
vm_object_page_cache(vp->v_object, OFF_TO_IDX(start),
OFF_TO_IDX(end));
VM_OBJECT_UNLOCK(vp->v_object);
}
VOP_UNLOCK(vp, 0);
VFS_UNLOCK_GIANT(vfslocked);
break;
default:
error = EINVAL;
break;
}
return (error);
}
int
vop_stdunp_bind(struct vop_unp_bind_args *ap)
{
ap->a_vp->v_socket = ap->a_socket;
return (0);
}
int
vop_stdunp_connect(struct vop_unp_connect_args *ap)
{
*ap->a_socket = ap->a_vp->v_socket;
return (0);
}
int
vop_stdunp_detach(struct vop_unp_detach_args *ap)
{
ap->a_vp->v_socket = NULL;
return (0);
}
static int
vop_stdis_text(struct vop_is_text_args *ap)
{
return ((ap->a_vp->v_vflag & VV_TEXT) != 0);
}
static int
vop_stdset_text(struct vop_set_text_args *ap)
{
ap->a_vp->v_vflag |= VV_TEXT;
return (0);
}
static int
vop_stdunset_text(struct vop_unset_text_args *ap)
{
ap->a_vp->v_vflag &= ~VV_TEXT;
return (0);
}
static int
vop_stdget_writecount(struct vop_get_writecount_args *ap)
{
*ap->a_writecount = ap->a_vp->v_writecount;
return (0);
}
static int
vop_stdadd_writecount(struct vop_add_writecount_args *ap)
{
ap->a_vp->v_writecount += ap->a_inc;
return (0);
}
/*
* vfs default ops
* used to fill the vfs function table to get reasonable default return values.
*/
int
vfs_stdroot (mp, flags, vpp)
struct mount *mp;
int flags;
struct vnode **vpp;
{
return (EOPNOTSUPP);
}
int
vfs_stdstatfs (mp, sbp)
struct mount *mp;
struct statfs *sbp;
{
return (EOPNOTSUPP);
}
int
vfs_stdquotactl (mp, cmds, uid, arg)
struct mount *mp;
int cmds;
uid_t uid;
void *arg;
{
return (EOPNOTSUPP);
}
int
vfs_stdsync(mp, waitfor)
struct mount *mp;
int waitfor;
{
struct vnode *vp, *mvp;
struct thread *td;
int error, lockreq, allerror = 0;
td = curthread;
lockreq = LK_EXCLUSIVE | LK_INTERLOCK;
if (waitfor != MNT_WAIT)
lockreq |= LK_NOWAIT;
/*
* Force stale buffer cache information to be flushed.
*/
loop:
MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
if (vp->v_bufobj.bo_dirty.bv_cnt == 0) {
VI_UNLOCK(vp);
continue;
}
if ((error = vget(vp, lockreq, td)) != 0) {
if (error == ENOENT) {
MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
goto loop;
}
continue;
}
error = VOP_FSYNC(vp, waitfor, td);
if (error)
allerror = error;
vput(vp);
}
return (allerror);
}
int
vfs_stdnosync (mp, waitfor)
struct mount *mp;
int waitfor;
{
return (0);
}
int
vfs_stdvget (mp, ino, flags, vpp)
struct mount *mp;
ino_t ino;
int flags;
struct vnode **vpp;
{
return (EOPNOTSUPP);
}
int
vfs_stdfhtovp (mp, fhp, flags, vpp)
struct mount *mp;
struct fid *fhp;
int flags;
struct vnode **vpp;
{
return (EOPNOTSUPP);
}
int
vfs_stdinit (vfsp)
struct vfsconf *vfsp;
{
return (0);
}
int
vfs_stduninit (vfsp)
struct vfsconf *vfsp;
{
return(0);
}
int
vfs_stdextattrctl(mp, cmd, filename_vp, attrnamespace, attrname)
struct mount *mp;
int cmd;
struct vnode *filename_vp;
int attrnamespace;
const char *attrname;
{
if (filename_vp != NULL)
VOP_UNLOCK(filename_vp, 0);
return (EOPNOTSUPP);
}
int
vfs_stdsysctl(mp, op, req)
struct mount *mp;
fsctlop_t op;
struct sysctl_req *req;
{
return (EOPNOTSUPP);
}
/* end of vfs default ops */
|
dcui/FreeBSD-9.3_kernel
|
sys/kern/vfs_default.c
|
C
|
bsd-3-clause
| 26,749 |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('core', parent_package, top_path)
config.add_subpackage('image')
config.add_subpackage('reference')
config.add_subpackage('transforms')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
yarikoptic/NiPy-OLD
|
nipy/core/setup.py
|
Python
|
bsd-3-clause
| 423 |
module Control.Applicative.Acme where
{- |
Application with the inverse lifting behavior of fmap.
Issue #1
-}
pamf :: Applicative f => f (a -> b) -> a -> f b
pamf f a = f <*> pure a
{- |
Operator version of pamf
Issue #1
-}
(>$<) :: Applicative f => f (a -> b) -> a -> f b
(>$<) = pamf
|
marcosdumay/acme-kitchen-sink
|
src/Control/Applicative/Acme.hs
|
Haskell
|
bsd-3-clause
| 290 |
from django.shortcuts import render
from cyder.base.views import cy_view, search_obj, table_update
def core_view(request, pk=None):
return cy_view(request, 'core/core_view.html', pk)
def core_search_obj(request):
return search_obj(request)
def core_table_update(request, pk, obj_type=None):
return table_update(request, pk, obj_type)
def core_index(request):
return render(request, 'core/core_index.html')
|
zeeman/cyder
|
cyder/core/views.py
|
Python
|
bsd-3-clause
| 431 |
<div class="row profile-account">
<div class="col-md-3">
<ul class="ver-inline-menu tabbable margin-bottom-10">
<li class="active">
<a data-toggle="tab" href="#tab_1-1">
<i class="fa fa-cog"></i>Nowe pudło</a>
<span class="after">
</span>
</li>
</ul>
</div>
<div class="col-md-9">
<form role="form" action="/warehouse/box_add" method="POST" id="add_box_form">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>Popraw błędy w formularzu</span>
</div>
<div class="tab-content">
<div id="tab_1-1" class="tab-pane active">
<div class="form-group">
<label class="control-label">Kategoria przechowywania
<span class="required" aria-required="true"> * </span>
</label>
<div class="input-icon right">
<select class="form-control" name="storage_category_id">
<option>-- Wybierz kategorię --</option>
<?php foreach ($storagecategories as $storagecategory):?>
<?php
echo "<option value=\"".$storagecategory->id."\">".$storagecategory->name."</option>";
?>
<?php endforeach;?>
</select>
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label">Data początku magazynowania
<span class="required" aria-required="true"> * </span>
</label>
<div class="input-group input-medium date date-picker margin-bottom-5" data-date-format="yyyy-mm-dd" >
<input type="text" class="form-control form-filter input-sm" readonly name="date_from" placeholder="Od">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button"><i class="fa fa-calendar"></i></button>
</span>
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label">Data końca magazynowania
<span class="required" aria-required="true"> * </span>
</label>
<div class="input-group input-medium date date-picker margin-bottom-5" data-date-format="yyyy-mm-dd" data-date-start-date="+0d">
<input type="text" class="form-control form-filter input-sm" readonly name="date_to" placeholder="Do" size="16">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button"><i class="fa fa-calendar"></i></button>
</span>
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label">Data odbioru
<span class="required" aria-required="true"> * </span>
</label>
<div class="input-group input-medium date date-picker margin-bottom-5" data-date-format="yyyy-mm-dd">
<input type="text" class="form-control form-filter input-sm" readonly name="date_reception" placeholder="Termin odbioru" size="16">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button"><i class="fa fa-calendar"></i></button>
</span>
</div>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label">Magazyn
<span class="required" aria-required="true"> * </span>
</label>
<div class="input-icon right">
<select class="form-control" name="warehouse_id">
<option>-- Wybierz magazyn --</option>
<?php foreach ($warehouses as $warehouse):?>
<?php
echo "<option value=\"".$warehouse->id."\">".$warehouse->name."</option>";
?>
<?php endforeach;?>
</select>
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label">Opis
</label>
<textarea class="form-control" name="description" placeholder="Opis pudła"></textarea>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label">Blokada
<span class="required" aria-required="true"> * </span>
</label>
<div class="checkbox-list">
<label class="checkbox-inline">
<input type="checkbox" name="lock" id="lock" value="1"> Tak </label>
<label class="checkbox-inline">
<input type="checkbox" name="lock" id="lock" value="0"> Nie </label>
</div>
</div>
<div class="form-group">
<label class="control-label">Kod kreskowy
</label>
<div class="input-icon">
<i class="fa fa-lock fa-fw"></i>
<input id="barcode" class="form-control" type="text" name="barcode" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label">Kod plomby nr 1
</label>
<div class="input-icon">
<i class="fa fa-lock fa-fw"></i>
<input id="seal" class="form-control" type="text" name="seal1" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label">Kod plomby nr 2
</label>
<div class="input-icon">
<i class="fa fa-lock fa-fw"></i>
<input id="seal" class="form-control" type="text" name="seal2" placeholder="">
</div>
</div>
<br/>
<br/>
<div class="margiv-top-10">
<a href="/warehouse/boxes" class="btn green" id="submit">
Zapisz zmiany</a>
<a href="/warehouse/boxes" class="btn default" id="cancel">
Anuluj</a>
</div>
</div>
</div>
</form>
</div>
<!--end col-md-9-->
|
yorg76/test
|
application/views/warehouse/box_add.php
|
PHP
|
bsd-3-clause
| 5,580 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'AccountType'
db.create_table('accounts_accounttype', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('path', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255)),
('depth', self.gf('django.db.models.fields.PositiveIntegerField')()),
('numchild', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('code', self.gf('django.db.models.fields.CharField')(max_length=128, unique=True, null=True, blank=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=128)),
))
db.send_create_signal('accounts', ['AccountType'])
# Adding model 'Account'
db.create_table('accounts_account', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=128, unique=True, null=True, blank=True)),
('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('account_type', self.gf('django.db.models.fields.related.ForeignKey')(related_name='accounts', null=True, to=orm['accounts.AccountType'])),
('code', self.gf('django.db.models.fields.CharField')(max_length=128, unique=True, null=True, blank=True)),
('primary_user', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='accounts', null=True, to=orm['auth.User'])),
('status', self.gf('django.db.models.fields.CharField')(default='Open', max_length=32)),
('credit_limit', self.gf('django.db.models.fields.DecimalField')(default='0.00', null=True, max_digits=12, decimal_places=2, blank=True)),
('balance', self.gf('django.db.models.fields.DecimalField')(default='0.00', null=True, max_digits=12, decimal_places=2)),
('start_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('end_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('product_range', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['offer.Range'], null=True, blank=True)),
('can_be_used_for_non_products', self.gf('django.db.models.fields.BooleanField')(default=True)),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal('accounts', ['Account'])
# Adding M2M table for field secondary_users on 'Account'
db.create_table('accounts_account_secondary_users', (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('account', models.ForeignKey(orm['accounts.account'], null=False)),
('user', models.ForeignKey(orm['auth.user'], null=False))
))
db.create_unique('accounts_account_secondary_users', ['account_id', 'user_id'])
# Adding model 'Transfer'
db.create_table('accounts_transfer', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('reference', self.gf('django.db.models.fields.CharField')(max_length=64, unique=True, null=True)),
('source', self.gf('django.db.models.fields.related.ForeignKey')(related_name='source_transfers', to=orm['accounts.Account'])),
('destination', self.gf('django.db.models.fields.related.ForeignKey')(related_name='destination_transfers', to=orm['accounts.Account'])),
('amount', self.gf('django.db.models.fields.DecimalField')(max_digits=12, decimal_places=2)),
('parent', self.gf('django.db.models.fields.related.ForeignKey')(related_name='related_transfers', null=True, to=orm['accounts.Transfer'])),
('merchant_reference', self.gf('django.db.models.fields.CharField')(max_length=128, null=True)),
('description', self.gf('django.db.models.fields.CharField')(max_length=256, null=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='transfers', null=True, to=orm['auth.User'])),
('username', self.gf('django.db.models.fields.CharField')(max_length=128)),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal('accounts', ['Transfer'])
# Adding model 'Transaction'
db.create_table('accounts_transaction', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('transfer', self.gf('django.db.models.fields.related.ForeignKey')(related_name='transactions', to=orm['accounts.Transfer'])),
('account', self.gf('django.db.models.fields.related.ForeignKey')(related_name='transactions', to=orm['accounts.Account'])),
('amount', self.gf('django.db.models.fields.DecimalField')(max_digits=12, decimal_places=2)),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal('accounts', ['Transaction'])
# Adding unique constraint on 'Transaction', fields ['transfer', 'account']
db.create_unique('accounts_transaction', ['transfer_id', 'account_id'])
# Adding model 'IPAddressRecord'
db.create_table('accounts_ipaddressrecord', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('ip_address', self.gf('django.db.models.fields.IPAddressField')(unique=True, max_length=15)),
('total_failures', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('consecutive_failures', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('date_last_failure', self.gf('django.db.models.fields.DateTimeField')(null=True)),
))
db.send_create_signal('accounts', ['IPAddressRecord'])
def backwards(self, orm):
# Removing unique constraint on 'Transaction', fields ['transfer', 'account']
db.delete_unique('accounts_transaction', ['transfer_id', 'account_id'])
# Deleting model 'AccountType'
db.delete_table('accounts_accounttype')
# Deleting model 'Account'
db.delete_table('accounts_account')
# Removing M2M table for field secondary_users on 'Account'
db.delete_table('accounts_account_secondary_users')
# Deleting model 'Transfer'
db.delete_table('accounts_transfer')
# Deleting model 'Transaction'
db.delete_table('accounts_transaction')
# Deleting model 'IPAddressRecord'
db.delete_table('accounts_ipaddressrecord')
models = {
'accounts.account': {
'Meta': {'object_name': 'Account'},
'account_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'accounts'", 'null': 'True', 'to': "orm['accounts.AccountType']"}),
'balance': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'null': 'True', 'max_digits': '12', 'decimal_places': '2'}),
'can_be_used_for_non_products': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'code': ('django.db.models.fields.CharField', [], {'max_length': '128', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'credit_limit': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'null': 'True', 'max_digits': '12', 'decimal_places': '2', 'blank': 'True'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'primary_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'accounts'", 'null': 'True', 'to': "orm['auth.User']"}),
'product_range': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['offer.Range']", 'null': 'True', 'blank': 'True'}),
'secondary_users': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'symmetrical': 'False', 'blank': 'True'}),
'start_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'Open'", 'max_length': '32'})
},
'accounts.accounttype': {
'Meta': {'object_name': 'AccountType'},
'code': ('django.db.models.fields.CharField', [], {'max_length': '128', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'depth': ('django.db.models.fields.PositiveIntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'numchild': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
'accounts.ipaddressrecord': {
'Meta': {'object_name': 'IPAddressRecord'},
'consecutive_failures': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_last_failure': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_address': ('django.db.models.fields.IPAddressField', [], {'unique': 'True', 'max_length': '15'}),
'total_failures': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
'accounts.transaction': {
'Meta': {'unique_together': "(('transfer', 'account'),)", 'object_name': 'Transaction'},
'account': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'transactions'", 'to': "orm['accounts.Account']"}),
'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', 'decimal_places': '2'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'transfer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'transactions'", 'to': "orm['accounts.Transfer']"})
},
'accounts.transfer': {
'Meta': {'ordering': "('-date_created',)", 'object_name': 'Transfer'},
'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', 'decimal_places': '2'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True'}),
'destination': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'destination_transfers'", 'to': "orm['accounts.Account']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'merchant_reference': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'related_transfers'", 'null': 'True', 'to': "orm['accounts.Transfer']"}),
'reference': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True'}),
'source': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'source_transfers'", 'to': "orm['accounts.Account']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'transfers'", 'null': 'True', 'to': "orm['auth.User']"}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [],
{'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [],
{'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'catalogue.attributeentity': {
'Meta': {'object_name': 'AttributeEntity'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}),
'type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'entities'", 'to': "orm['catalogue.AttributeEntityType']"})
},
'catalogue.attributeentitytype': {
'Meta': {'object_name': 'AttributeEntityType'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'})
},
'catalogue.attributeoption': {
'Meta': {'object_name': 'AttributeOption'},
'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['catalogue.AttributeOptionGroup']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'option': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'catalogue.attributeoptiongroup': {
'Meta': {'object_name': 'AttributeOptionGroup'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'catalogue.category': {
'Meta': {'ordering': "['full_name']", 'object_name': 'Category'},
'depth': ('django.db.models.fields.PositiveIntegerField', [], {}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'full_name': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'numchild': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'path': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '1024', 'db_index': 'True'})
},
'catalogue.option': {
'Meta': {'object_name': 'Option'},
'code': ('django.db.models.fields.SlugField', [], {'max_length': '128', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'Required'", 'max_length': '128'})
},
'catalogue.product': {
'Meta': {'ordering': "['-date_created']", 'object_name': 'Product'},
'attributes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['catalogue.ProductAttribute']", 'through': "orm['catalogue.ProductAttributeValue']", 'symmetrical': 'False'}),
'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['catalogue.Category']", 'through': "orm['catalogue.ProductCategory']", 'symmetrical': 'False'}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_discountable': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'variants'", 'null': 'True', 'to': "orm['catalogue.Product']"}),
'product_class': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.ProductClass']", 'null': 'True'}),
'product_options': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['catalogue.Option']", 'symmetrical': 'False', 'blank': 'True'}),
'recommended_products': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['catalogue.Product']", 'symmetrical': 'False', 'through': "orm['catalogue.ProductRecommendation']", 'blank': 'True'}),
'related_products': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'relations'", 'blank': 'True', 'to': "orm['catalogue.Product']"}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'db_index': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '128', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'upc': ('django.db.models.fields.CharField', [], {'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'})
},
'catalogue.productattribute': {
'Meta': {'ordering': "['code']", 'object_name': 'ProductAttribute'},
'code': ('django.db.models.fields.SlugField', [], {'max_length': '128', 'db_index': 'True'}),
'entity_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.AttributeEntityType']", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'option_group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.AttributeOptionGroup']", 'null': 'True', 'blank': 'True'}),
'product_class': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'attributes'", 'null': 'True', 'to': "orm['catalogue.ProductClass']"}),
'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'text'", 'max_length': '20'})
},
'catalogue.productattributevalue': {
'Meta': {'object_name': 'ProductAttributeValue'},
'attribute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.ProductAttribute']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'attribute_values'", 'to': "orm['catalogue.Product']"}),
'value_boolean': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'value_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'value_entity': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.AttributeEntity']", 'null': 'True', 'blank': 'True'}),
'value_float': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'value_integer': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'value_option': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.AttributeOption']", 'null': 'True', 'blank': 'True'}),
'value_richtext': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'value_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'catalogue.productcategory': {
'Meta': {'ordering': "['-is_canonical']", 'object_name': 'ProductCategory'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.Category']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_canonical': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.Product']"})
},
'catalogue.productclass': {
'Meta': {'ordering': "['name']", 'object_name': 'ProductClass'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'options': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['catalogue.Option']", 'symmetrical': 'False', 'blank': 'True'}),
'requires_shipping': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'})
},
'catalogue.productrecommendation': {
'Meta': {'object_name': 'ProductRecommendation'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'primary': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'primary_recommendations'", 'to': "orm['catalogue.Product']"}),
'ranking': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'recommendation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.Product']"})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'offer.range': {
'Meta': {'object_name': 'Range'},
'classes': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'classes'", 'blank': 'True', 'to': "orm['catalogue.ProductClass']"}),
'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'excluded_products': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'excludes'", 'blank': 'True', 'to': "orm['catalogue.Product']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'included_categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'includes'", 'blank': 'True', 'to': "orm['catalogue.Category']"}),
'included_products': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'includes'", 'blank': 'True', 'to': "orm['catalogue.Product']"}),
'includes_all_products': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'})
}
}
complete_apps = ['accounts']
|
machtfit/django-oscar-accounts
|
accounts/migrations/0001_initial.py
|
Python
|
bsd-3-clause
| 27,400 |
/*
This file is part of INDDGO.
Copyright (C) 2012, Oak Ridge National Laboratory
This product includes software produced by UT-Battelle, LLC under Contract No.
DE-AC05-00OR22725 with the Department of Energy.
This program is free software; you can redistribute it and/or modify
it under the terms of the New BSD 3-clause software license (LICENSE).
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
LICENSE for more details.
For more information please contact the INDDGO developers at:
[email protected]
*/
#ifndef _TD_TREE_H_
#define _TD_TREE_H_
#ifdef __PARALLEL__
#include <mpi.h>
#endif
#include "VertexWeightedGraph.h"
#include "TDTreeNode.h"
/**
* The TDTree class is used to represent a tree decomposition for a Graph.
*/
class TDTree
{
friend ostream &operator<<(ostream &, const TDTree &);
//friend class Graph::VertexWeightedGraph;
public:
TDTree(Graph::VertexWeightedGraph *); // Constructor given an input graph
TDTree(); // Default constructor
~TDTree(); // Destructor
// Copy constructor
TDTree(const TDTree& rhs);
// Assignment operator
TDTree& operator=(const TDTree& rhs);
/**
* The index of the root node in the tree.
*/
int root_node;
/**
* Boolean flag to indicated whether tree is rooted or not.
*/
bool rooted;
/**
* Roots the tree at node k. Reorders adj. lists so parent is first, followed by children.
*/
void root(int k);
/**
* Finds & sets a root node to minimize the maximum number of tables
* required to be stored at any given time (assuming no reconstruction is required).
* Reference: "Memory Requirements for Table Computations" by Aspvall et al.
* algorithm needs to be one of the following:
* TD_ROOT_ASPVALL - original tabreq() function assumes child tables are deleted sequentially due to DFS
* TD_ROOT_ALLCHILDREN - tries to account for all child tables needing to exist simultaneously to create parent.
*/
int root_mintables(int algorithm);
/**
* Pointer to the graph being decomposed
*/
Graph::VertexWeightedGraph *G;
/**
* Place for the file containing the graph G.
*/
char *graph_file;
/**
* A vector of pointers to TDTreeNodes that make up the graph.
* We use a vector instead of a list since we need
* quick access to node j in the tree. These pointers may be NULL if tree has been modified
* after creation, and tree_nodes.size() should never be used as a replacement for num_tree_nodes.
*/
vector<TDTreeNode *> tree_nodes;
/**
* Vector of G->n elements where "element i" is a list of the treenode
* indices whose bags contain node i from G.
*/
list<int> *node_locations;
/**
* The number of nodes in the tree.
*/
int num_tree_nodes;
/**
* Use this to keep track of DP progress.
*/
int num_tree_nodes_processed;
/**
* The number of leafs in the tree.
*/
int num_leafs;
/**
* True if the tree is nice, false otherwise.
*/
bool nice;
// Fills up the node_locations array by searching each tree node's bag
// for vertices
void record_node_locations();
// Constructs a tree decomposition using Gavril's algorithm
// with the provided elimination order
void construct_gavril(vector<int> *elim_order);
// Constructs a nice tree decomposition using Kloks' algorithm
// with the provided elimination order and tree-width
// Boolean indicates whether or not to push new node creation down the tree when
// possible when encountering a one-child node.
void construct_knice(vector<int> *elim_order, int k, bool descend_one);
//Construct a tree decomposition from supernodal elimination tree.
//FUTURE WORK: If elim_order is NULL, elimination order to be determined using methods in SuiteSparse
//specified by integer parmaeter using constants defined in GraphDecomposition.h
void construct_superetree(vector<int> *elim_order);
//Converts a given rooted tree decomposition into a nice TD of equal width.
void make_nice();
//helper functions for make_nice
int replace_by_join_tree(int old_node, int max_id);
int expand_symdiff(int old_node, int max_id);
//Tree refinement functions
void remove_duplicate_bags();
void remove_subset_bags();
void refine();
// Sorts all the members of the bags of T.
void sort_bags();
// Constructs a tree decomposition using Bodlaender-Koster's "Algorithm 2"
// with the provided elimination order
void construct_BK(vector<int> *elim_order);
// Finds the path between start and end in the tree
void find_path(int start, int end, list<int> *path);
void find_path(int start, int end, int *pred);
// Verifies that the decomposition is valid
bool verify();
// Verifies that the decomposition is nice
bool is_nice();
//Export the tree structure to a Grap.
Graph::Graph *export_tree();
// Writes the decomposition to a file in (an extended) DIMACS format
void write_DIMACS_file(const char *DIMACS_file);
void write_DIMACS_file(const char *DIMACS_file, bool preordered);
// Reads a decomposition from the file - returns the width
int read_DIMACS_file(const char *DIMACS_file);
// Writes the decomposition to a file for viewing via graphviz
void write_graphviz_file(bool spline, const char *GVIZ_file, int style);
void write_scored_graphviz_file(bool spline, const char *GVIZ_file, const vector<double>& color_vector, const double& max_color, const double& min_color,int style, const bool log_range=false);
void write_scored_graphviz_file(bool spline, const char *GVIZ_file, const vector<double>& color_vector, int style, const bool log_range=false);
// same as above, but highlights the subtree containing v.
void highlight_subtree_gviz(int v, const char *GVIZ_file, int style);
void highlight_subtree_scored_graphviz_file(int v, const char *GVIZ_file, const vector<double>& color_vector);
void highlight_subtree_scored_graphviz_file(int v, const char *GVIZ_file, const vector<double>& color_vector, const double max_color, const double min_color);
int compute_width();
int width, refined_width;
void pre_order_walk(vector<int> *walk);
void post_order_walk(vector<int> *walk);
void post_order_walk_DFS(vector<int> *walk);
int compute_table(int(*table_function)(TDTree *T, int k), int k);
int get_node_type(int k);
// Fills the TDTree S with the subtree containing the nodes whose indices are contained
// in the indices list. Returns false if there is an error (non-connected nodes, etc.), and
// returns true otherwise
bool create_subtree(list<int> *indices, TDTree *S);
// Resets to an empty tree
void clear();
// The number of 64-bit words in the masks contained in the TDTable
int num_mask_words;
/*
* For rooted tree decompositions only (fatal error if called on unrooted).
* Populates the vector B (which will be sized to equal the number of bags in the TD)
* with B[i] = the number of vertices in bag i which are also in the bags of at least 2 children of i.
* If i is a leaf, B[i] is the size of the bag (aka the width).
*/
int find_child_boundaries(vector<int> *B);
/*
* Deletes all the memory associated with the children of tree node k and sets
* the relevant pointers in the tree_node vector to NULL.
*/
void free_children(int k);
void free_table(int k);
void fill_bag_vecs();
/*
* Goes through the tree and removes all nodes from the list S from the bags
* of all tree nodes */
void refine_tree(list<int> *S);
class DP_info *info;
#ifdef __PARALLEL__
int size;
int rank;
int requester_rank;
int request_size;
int pool_size;
int msk_send_count;
int wgh_send_count;
int tnum;
int flag_recv_done;
int entries;
vector<int> *tbl_loc;
vector<int> *tbl_entries;
vector<int> *request_count;
vector<int> *rcount;
vector<int> *request_expect;
vector<int> *node_sizes;
vector<int> *iter_count;
vector<int> *nodes_with_tbl;
vector<MPI_Request> *requests;
vector<MPI_Request> *msk_send_requests;
vector<MPI_Request> *msk_recv_requests;
vector<MPI_Request> *wgh_send_requests;
vector<MPI_Request> *wgh_recv_requests;
vector<MPI_Request> *tbl_loc_requests;
vector<MPI_Request> *tbl_size_requests;
vector<MPI_Request> *compute_term_requests;
vector<MPI_Request> *storage_term_requests;
vector<MPI_Request> *child_free_requests;
vector< vector<unsigned long long> *> msk_send_pool;
vector< vector<unsigned long long> *> msk_recv_pool;
vector< vector<int> *> wgh_send_pool;
vector< vector<int> *> wgh_recv_pool;
vector<pthread_t> *threads;
vector<bigint_t *> *start_masks;
vector<bigint_t *> *end_masks;
vector<bigint_t> *indset_masks;
vector<int> *ind_wgh;
vector<int> *tbl_size;
bigint_t *iteration_counter;
int head_node;
int tmp;
int tblloc;
vector<int> compute_nodes;
vector<int> storage_nodes;
vector<int> *allnodes;
vector<int> *all_table_sizes;
int storage_nodes_size;
int compute_nodes_size;
int del_ch;
MPI_Comm *compute_nodes_comm;
#endif
void compute_parent_child_intersections(vector<int> *intersection_sizes);
//Find subtree "below" a vertex v in a rooted TD.
void compute_subtree(int v, list<int> *subtree);
void compute_subtree_vertices(int v, list<int> *vertex_list);
protected:
// Remove and add edges from the tree
bool remove_tree_edge(int u, int v);
bool add_tree_edge(int u, int v);
};
#endif
|
tdgoodrich/inddgo_pure
|
lib_treed/inc/TDTree.h
|
C
|
bsd-3-clause
| 9,409 |
package com.huskycode.jpaquery.persister;
import com.huskycode.jpaquery.types.db.Row;
/**
* Persist a row into the database based on a specific implementation.
*
* @author Varokas
*/
public interface RowPersister {
void save(Row row);
}
|
varokas/jpaQuery
|
src/main/java/com/huskycode/jpaquery/persister/RowPersister.java
|
Java
|
bsd-3-clause
| 247 |
# Changelog
## Unpublished
### 🛠 Breaking changes
### 🎉 New features
### 🐛 Bug fixes
## 9.1.0 — 2021-03-10
### 🎉 New features
- Updated Android build configuration to target Android 11 (added support for Android SDK 30). ([#11647](https://github.com/expo/expo/pull/11647) by [@bbarthec](https://github.com/bbarthec))
### 🐛 Bug fixes
- Remove peerDependencies and unimodulePeerDependencies from Expo modules. ([#11980](https://github.com/expo/expo/pull/11980) by [@brentvatne](https://github.com/brentvatne))
## 9.0.0 — 2021-01-15
### 🛠 Breaking changes
- Dropped support for iOS 10.0 ([#11344](https://github.com/expo/expo/pull/11344) by [@tsapeta](https://github.com/tsapeta))
## 8.5.0 — 2020-11-17
_This version does not introduce any user-facing changes._
## 8.4.0 — 2020-08-18
_This version does not introduce any user-facing changes._
## 8.3.0 — 2020-07-29
### 🐛 Bug fixes
- Fix incorrect `rowsAffected` value in result of `executeSql` method on iOS when deleting/updating cascadely. ([@9137](https://github.com/expo/expo/pull/9317) by [@mczernek](https://github.com/mczernek))
## 8.2.1 — 2020-05-29
### 🐛 Bug fixes
- Fixed support for using `expo-sqlite` on Web ([#8518](https://github.com/expo/expo/pull/8518) by [@sjchmiela](https://github.com/sjchmiela))
## 8.2.0 — 2020-05-27
_This version does not introduce any user-facing changes._
|
exponent/exponent
|
packages/expo-sqlite/CHANGELOG.md
|
Markdown
|
bsd-3-clause
| 1,407 |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import cgi
import jsonpickle
from django.utils import simplejson
from votuition.models import Vote
#import inspect
# Get an instance of a logger
import logging
from django.utils.log import getLogger
logger = getLogger('django')
logger.setLevel(logging.DEBUG)
LOG_INDENT = " "
@csrf_exempt
def vote(request, version):
""" get JSON for vote
"""
method_name = "vote"
logger.debug("%s starting..." % (method_name))
logger.debug("is_secure: [%s]" % request.is_secure())
if not request.is_secure():
error_msg = "ERROR: only https:// protocol allowed"
return __http_error_response__(error_msg)
# constants for query params
ip_address = ""
try:
ip_address = request.META['REMOTE_ADDR']
except Exception, e:
pass
logger.debug("IP: [%s]" % ip_address)
# dictionary for returning JSON results
ret_dict = dict()
ret_dict['status'] = "OK"
str_json = ""
logger.debug("parsing qeury string params...")
if request.method == 'POST':
# str_json = request.POST.items()
# str_pickle = cgi.escape(jsonpickle.encode(str_json))
logger.debug("POST items: [%s]" % (len(request.POST)))
if len(request.POST) != 1:
logger.warning("request.POST items not 1 but [%s]" % len(request.POST))
for key, value in request.POST.items():
str_json = key
logger.debug("%s converting JSON string [%s] to dictionary..." % (LOG_INDENT, str_json))
try:
pydict = simplejson.loads(str_json)
except Exception, e:
error_msg = "ERROR trying to convert JSON string to dictionary, most likely invalid JSON: [%s]" % (str_json)
return __http_error_response__(error_msg)
else:
error_msg = "ERROR request method: [%s] but only POST allowed" % (request.method)
return __http_error_response__(error_msg)
# populate db model
vote_record = Vote()
vote_record.ip = ip_address
# categories are not manadatory
try:
vote_record.categories = pydict['categories']
except Exception, e:
error_msg = "(%s): Error while trying to get categories from json data[%s], error: [%s]" % (method_name, str_json, e)
logger.warning(error_msg)
logger.warning("Setting categories to empty list..")
vote_record.categories = list()
vote_record.categories.append(unicode(""))
# mandatory fields - don't save if any missing / invalid
try:
vote_record.user_id = pydict['user_id']
vote_record.subject = pydict['subject']
vote_record.vote = pydict['vote']
except Exception, e:
error_msg = "(%s): Error while populating record with json data[%s], error: [%s]" % (method_name, str_json, e)
return __http_error_response__(error_msg)
logger.debug("trying to save datastore record...")
try:
vote_record.save()
except Exception, e:
error_msg = "(%s): Error while trying to save Vote record with json data[%s], error: [%s]" % (method_name, str_json, e)
return __http_error_response__(error_msg)
logger.debug("trying to save datastore record DONE")
ret_json = simplejson.dumps(ret_dict)
response = HttpResponse(status=200, content_type="application/json")
response.write(ret_json)
return response
def __http_error_response__(error_msg, type="json"):
# dictionary for returning error info in json
err_dictionary = dict()
logger.error(error_msg)
response = HttpResponse(status=500, content_type="application/json")
err_dictionary["error_msg"] = error_msg
ret_json_error = simplejson.dumps(err_dictionary)
response.write(ret_json_error)
return response
@csrf_exempt
def index(request):
if request.method == 'POST':
post = request.POST
# raw = request.raw_post_data
# remote_media_id = post.get("video_id", "")
else:
return HttpResponse("Hello, world. You're at the index.")
|
andrew-szymanski/gae_django
|
api/handlers.py
|
Python
|
bsd-3-clause
| 4,169 |
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef ProxyUtils_DEFINED
#define ProxyUtils_DEFINED
#include "include/private/GrTypesPriv.h"
#include "src/gpu/GrImageInfo.h"
#include "src/gpu/GrPipeline.h"
#include "src/gpu/GrTextureProxy.h"
class GrProgramInfo;
namespace sk_gpu_test {
/** Makes a texture proxy containing the passed in color data. */
sk_sp<GrTextureProxy> MakeTextureProxyFromData(GrContext*,
GrRenderable,
GrSurfaceOrigin,
const GrImageInfo&,
const void* data,
size_t rowBytes);
GrProgramInfo* CreateProgramInfo(const GrCaps*,
SkArenaAlloc*,
const GrSurfaceProxyView* dstView,
GrAppliedClip&&,
const GrXferProcessor::DstProxyView& dstProxyView,
GrGeometryProcessor*, SkBlendMode,
GrPrimitiveType,
GrPipeline::InputFlags flags = GrPipeline::InputFlags::kNone,
const GrUserStencilSettings* stencil =
&GrUserStencilSettings::kUnused);
} // namespace sk_gpu_test
#endif
|
HalCanary/skia-hc
|
tools/gpu/ProxyUtils.h
|
C
|
bsd-3-clause
| 1,557 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/tools/quic_server.h"
#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
#include "net/third_party/quiche/src/quic/core/quic_epoll_alarm_factory.h"
#include "net/third_party/quiche/src/quic/core/quic_epoll_connection_helper.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_port_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_test_loopback.h"
#include "net/third_party/quiche/src/quic/test_tools/crypto_test_utils.h"
#include "net/third_party/quiche/src/quic/test_tools/mock_quic_dispatcher.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_server_peer.h"
#include "net/third_party/quiche/src/quic/tools/quic_memory_cache_backend.h"
#include "net/third_party/quiche/src/quic/tools/quic_simple_crypto_server_stream_helper.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
namespace quic {
namespace test {
using ::testing::_;
namespace {
class MockQuicSimpleDispatcher : public QuicSimpleDispatcher {
public:
MockQuicSimpleDispatcher(
const QuicConfig* config,
const QuicCryptoServerConfig* crypto_config,
QuicVersionManager* version_manager,
std::unique_ptr<QuicConnectionHelperInterface> helper,
std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper,
std::unique_ptr<QuicAlarmFactory> alarm_factory,
QuicSimpleServerBackend* quic_simple_server_backend)
: QuicSimpleDispatcher(config,
crypto_config,
version_manager,
std::move(helper),
std::move(session_helper),
std::move(alarm_factory),
quic_simple_server_backend,
kQuicDefaultConnectionIdLength) {}
~MockQuicSimpleDispatcher() override = default;
MOCK_METHOD(void, OnCanWrite, (), (override));
MOCK_METHOD(bool, HasPendingWrites, (), (const, override));
MOCK_METHOD(bool, HasChlosBuffered, (), (const, override));
MOCK_METHOD(void, ProcessBufferedChlos, (size_t), (override));
};
class TestQuicServer : public QuicServer {
public:
TestQuicServer()
: QuicServer(crypto_test_utils::ProofSourceForTesting(),
&quic_simple_server_backend_) {}
~TestQuicServer() override = default;
MockQuicSimpleDispatcher* mock_dispatcher() { return mock_dispatcher_; }
protected:
QuicDispatcher* CreateQuicDispatcher() override {
mock_dispatcher_ = new MockQuicSimpleDispatcher(
&config(), &crypto_config(), version_manager(),
std::unique_ptr<QuicEpollConnectionHelper>(
new QuicEpollConnectionHelper(epoll_server(),
QuicAllocator::BUFFER_POOL)),
std::unique_ptr<QuicCryptoServerStreamBase::Helper>(
new QuicSimpleCryptoServerStreamHelper()),
std::unique_ptr<QuicEpollAlarmFactory>(
new QuicEpollAlarmFactory(epoll_server())),
&quic_simple_server_backend_);
return mock_dispatcher_;
}
MockQuicSimpleDispatcher* mock_dispatcher_ = nullptr;
QuicMemoryCacheBackend quic_simple_server_backend_;
};
class QuicServerEpollInTest : public QuicTest {
public:
QuicServerEpollInTest()
: port_(QuicPickServerPortForTestsOrDie()),
server_address_(TestLoopback(), port_) {}
void StartListening() {
server_.CreateUDPSocketAndListen(server_address_);
server_address_ = QuicSocketAddress(server_address_.host(), server_.port());
ASSERT_TRUE(QuicServerPeer::SetSmallSocket(&server_));
if (!server_.overflow_supported()) {
QUIC_LOG(WARNING) << "Overflow not supported. Not testing.";
return;
}
}
protected:
int port_;
QuicSocketAddress server_address_;
TestQuicServer server_;
};
// Tests that if dispatcher has CHLOs waiting for connection creation, EPOLLIN
// event should try to create connections for them. And set epoll mask with
// EPOLLIN if there are still CHLOs remaining at the end of epoll event.
TEST_F(QuicServerEpollInTest, ProcessBufferedCHLOsOnEpollin) {
// Given an EPOLLIN event, try to create session for buffered CHLOs. In first
// event, dispatcher can't create session for all of CHLOs. So listener should
// register another EPOLLIN event by itself. Even without new packet arrival,
// the rest CHLOs should be process in next epoll event.
StartListening();
bool more_chlos = true;
MockQuicSimpleDispatcher* dispatcher_ = server_.mock_dispatcher();
DCHECK(dispatcher_ != nullptr);
EXPECT_CALL(*dispatcher_, OnCanWrite()).Times(testing::AnyNumber());
EXPECT_CALL(*dispatcher_, ProcessBufferedChlos(_)).Times(2);
EXPECT_CALL(*dispatcher_, HasPendingWrites()).Times(testing::AnyNumber());
// Expect there are still CHLOs buffered after 1st event. But not any more
// after 2nd event.
EXPECT_CALL(*dispatcher_, HasChlosBuffered())
.WillOnce(testing::Return(true))
.WillOnce(
DoAll(testing::Assign(&more_chlos, false), testing::Return(false)));
// Send a packet to trigger epoll event.
int fd = socket(
AddressFamilyUnderTest() == IpAddressFamily::IP_V4 ? AF_INET : AF_INET6,
SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP);
ASSERT_LT(0, fd);
char buf[1024];
memset(buf, 0, QUICHE_ARRAYSIZE(buf));
sockaddr_storage storage = server_address_.generic_address();
int rc = sendto(fd, buf, QUICHE_ARRAYSIZE(buf), 0,
reinterpret_cast<sockaddr*>(&storage), sizeof(storage));
if (rc < 0) {
QUIC_DLOG(INFO) << errno << " " << strerror(errno);
}
while (more_chlos) {
server_.WaitForEvents();
}
}
class QuicServerDispatchPacketTest : public QuicTest {
public:
QuicServerDispatchPacketTest()
: crypto_config_("blah",
QuicRandom::GetInstance(),
crypto_test_utils::ProofSourceForTesting(),
KeyExchangeSource::Default()),
version_manager_(AllSupportedVersions()),
dispatcher_(
&config_,
&crypto_config_,
&version_manager_,
std::unique_ptr<QuicEpollConnectionHelper>(
new QuicEpollConnectionHelper(&eps_,
QuicAllocator::BUFFER_POOL)),
std::unique_ptr<QuicCryptoServerStreamBase::Helper>(
new QuicSimpleCryptoServerStreamHelper()),
std::unique_ptr<QuicEpollAlarmFactory>(
new QuicEpollAlarmFactory(&eps_)),
&quic_simple_server_backend_) {
dispatcher_.InitializeWithWriter(new QuicDefaultPacketWriter(1234));
}
void DispatchPacket(const QuicReceivedPacket& packet) {
QuicSocketAddress client_addr, server_addr;
dispatcher_.ProcessPacket(server_addr, client_addr, packet);
}
protected:
QuicConfig config_;
QuicCryptoServerConfig crypto_config_;
QuicVersionManager version_manager_;
QuicEpollServer eps_;
QuicMemoryCacheBackend quic_simple_server_backend_;
MockQuicDispatcher dispatcher_;
};
TEST_F(QuicServerDispatchPacketTest, DispatchPacket) {
// clang-format off
unsigned char valid_packet[] = {
// public flags (8 byte connection_id)
0x3C,
// connection_id
0x10, 0x32, 0x54, 0x76,
0x98, 0xBA, 0xDC, 0xFE,
// packet number
0xBC, 0x9A, 0x78, 0x56,
0x34, 0x12,
// private flags
0x00
};
// clang-format on
QuicReceivedPacket encrypted_valid_packet(
reinterpret_cast<char*>(valid_packet), QUICHE_ARRAYSIZE(valid_packet),
QuicTime::Zero(), false);
EXPECT_CALL(dispatcher_, ProcessPacket(_, _, _)).Times(1);
DispatchPacket(encrypted_valid_packet);
}
} // namespace
} // namespace test
} // namespace quic
|
endlessm/chromium-browser
|
net/third_party/quiche/src/quic/tools/quic_server_test.cc
|
C++
|
bsd-3-clause
| 8,269 |
# -*- coding: utf-8 -*-
"""Factories to help in tests."""
from factory import PostGenerationMethodCall, Sequence
from factory.alchemy import SQLAlchemyModelFactory
from www.database import db
from www.user.models import User
class BaseFactory(SQLAlchemyModelFactory):
"""Base factory."""
class Meta:
"""Factory configuration."""
abstract = True
sqlalchemy_session = db.session
class UserFactory(BaseFactory):
"""User factory."""
username = Sequence(lambda n: 'user{0}'.format(n))
email = Sequence(lambda n: 'user{0}@example.com'.format(n))
password = PostGenerationMethodCall('set_password', 'example')
active = True
class Meta:
"""Factory configuration."""
model = User
|
devchild/infinity
|
tests/factories.py
|
Python
|
bsd-3-clause
| 753 |
/* $FreeBSD: releng/9.3/sys/fs/msdosfs/denode.h 203822 2010-02-13 11:34:25Z kib $ */
/* $NetBSD: denode.h,v 1.25 1997/11/17 15:36:28 ws Exp $ */
/*-
* Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
* Copyright (C) 1994, 1995, 1997 TooLs GmbH.
* All rights reserved.
* Original code by Paul Popelka ([email protected]) (see below).
*
* 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by TooLs GmbH.
* 4. The name of TooLs GmbH may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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.
*/
/*-
* Written by Paul Popelka ([email protected])
*
* You can do anything you want with this software, just don't say you wrote
* it, and don't remove this notice.
*
* This software is provided "as is".
*
* The author supplies this software to be publicly redistributed on the
* understanding that the author is not responsible for the correct
* functioning of this software in any circumstances and is not liable for
* any damages caused by this software.
*
* October 1992
*/
/*
* This is the pc filesystem specific portion of the vnode structure.
*
* To describe a file uniquely the de_dirclust, de_diroffset, and
* de_StartCluster fields are used.
*
* de_dirclust contains the cluster number of the directory cluster
* containing the entry for a file or directory.
* de_diroffset is the index into the cluster for the entry describing
* a file or directory.
* de_StartCluster is the number of the first cluster of the file or directory.
*
* Now to describe the quirks of the pc filesystem.
* - Clusters 0 and 1 are reserved.
* - The first allocatable cluster is 2.
* - The root directory is of fixed size and all blocks that make it up
* are contiguous.
* - Cluster 0 refers to the root directory when it is found in the
* startcluster field of a directory entry that points to another directory.
* - Cluster 0 implies a 0 length file when found in the start cluster field
* of a directory entry that points to a file.
* - You can't use the cluster number 0 to derive the address of the root
* directory.
* - Multiple directory entries can point to a directory. The entry in the
* parent directory points to a child directory. Any directories in the
* child directory contain a ".." entry that points back to the parent.
* The child directory itself contains a "." entry that points to itself.
* - The root directory does not contain a "." or ".." entry.
* - Directory entries for directories are never changed once they are created
* (except when removed). The size stays 0, and the last modification time
* is never changed. This is because so many directory entries can point to
* the physical clusters that make up a directory. It would lead to an
* update nightmare.
* - The length field in a directory entry pointing to a directory contains 0
* (always). The only way to find the end of a directory is to follow the
* cluster chain until the "last cluster" marker is found.
*
* My extensions to make this house of cards work. These apply only to the in
* memory copy of the directory entry.
* - A reference count for each denode will be kept since dos doesn't keep such
* things.
*/
/*
* Internal pseudo-offset for (nonexistent) directory entry for the root
* dir in the root dir
*/
#define MSDOSFSROOT_OFS 0x1fffffff
/*
* The fat cache structure. fc_fsrcn is the filesystem relative cluster
* number that corresponds to the file relative cluster number in this
* structure (fc_frcn).
*/
struct fatcache {
u_long fc_frcn; /* file relative cluster number */
u_long fc_fsrcn; /* filesystem relative cluster number */
};
/*
* The fat entry cache as it stands helps make extending files a "quick"
* operation by avoiding having to scan the fat to discover the last
* cluster of the file. The cache also helps sequential reads by
* remembering the last cluster read from the file. This also prevents us
* from having to rescan the fat to find the next cluster to read. This
* cache is probably pretty worthless if a file is opened by multiple
* processes.
*/
#define FC_SIZE 3 /* number of entries in the cache */
#define FC_LASTMAP 0 /* entry the last call to pcbmap() resolved
* to */
#define FC_LASTFC 1 /* entry for the last cluster in the file */
#define FC_NEXTTOLASTFC 2 /* entry for a close to the last cluster in
* the file */
#define FCE_EMPTY 0xffffffff /* doesn't represent an actual cluster # */
/*
* Set a slot in the fat cache.
*/
#define fc_setcache(dep, slot, frcn, fsrcn) \
(dep)->de_fc[(slot)].fc_frcn = (frcn); \
(dep)->de_fc[(slot)].fc_fsrcn = (fsrcn);
/*
* This is the in memory variant of a dos directory entry. It is usually
* contained within a vnode.
*/
struct denode {
struct vnode *de_vnode; /* addr of vnode we are part of */
u_long de_flag; /* flag bits */
u_long de_dirclust; /* cluster of the directory file containing this entry */
u_long de_diroffset; /* offset of this entry in the directory cluster */
u_long de_fndoffset; /* offset of found dir entry */
int de_fndcnt; /* number of slots before de_fndoffset */
long de_refcnt; /* reference count */
struct msdosfsmount *de_pmp; /* addr of our mount struct */
u_char de_Name[12]; /* name, from DOS directory entry */
u_char de_Attributes; /* attributes, from directory entry */
u_char de_LowerCase; /* NT VFAT lower case flags */
u_char de_CHun; /* Hundredth of second of CTime*/
u_short de_CTime; /* creation time */
u_short de_CDate; /* creation date */
u_short de_ADate; /* access date */
u_short de_MTime; /* modification time */
u_short de_MDate; /* modification date */
u_long de_StartCluster; /* starting cluster of file */
u_long de_FileSize; /* size of file in bytes */
struct fatcache de_fc[FC_SIZE]; /* fat cache */
u_quad_t de_modrev; /* Revision level for lease. */
u_int64_t de_inode; /* Inode number (really byte offset of direntry) */
};
/*
* Values for the de_flag field of the denode.
*/
#define DE_UPDATE 0x0004 /* Modification time update request */
#define DE_CREATE 0x0008 /* Creation time update */
#define DE_ACCESS 0x0010 /* Access time update */
#define DE_MODIFIED 0x0020 /* Denode has been modified */
#define DE_RENAME 0x0040 /* Denode is in the process of being renamed */
/*
* Transfer directory entries between internal and external form.
* dep is a struct denode * (internal form),
* dp is a struct direntry * (external form).
*/
#define DE_INTERNALIZE32(dep, dp) \
((dep)->de_StartCluster |= getushort((dp)->deHighClust) << 16)
#define DE_INTERNALIZE(dep, dp) \
(bcopy((dp)->deName, (dep)->de_Name, 11), \
(dep)->de_Attributes = (dp)->deAttributes, \
(dep)->de_LowerCase = (dp)->deLowerCase, \
(dep)->de_CHun = (dp)->deCHundredth, \
(dep)->de_CTime = getushort((dp)->deCTime), \
(dep)->de_CDate = getushort((dp)->deCDate), \
(dep)->de_ADate = getushort((dp)->deADate), \
(dep)->de_MTime = getushort((dp)->deMTime), \
(dep)->de_MDate = getushort((dp)->deMDate), \
(dep)->de_StartCluster = getushort((dp)->deStartCluster), \
(dep)->de_FileSize = getulong((dp)->deFileSize), \
(FAT32((dep)->de_pmp) ? DE_INTERNALIZE32((dep), (dp)) : 0))
#define DE_EXTERNALIZE(dp, dep) \
(bcopy((dep)->de_Name, (dp)->deName, 11), \
(dp)->deAttributes = (dep)->de_Attributes, \
(dp)->deLowerCase = (dep)->de_LowerCase, \
(dp)->deCHundredth = (dep)->de_CHun, \
putushort((dp)->deCTime, (dep)->de_CTime), \
putushort((dp)->deCDate, (dep)->de_CDate), \
putushort((dp)->deADate, (dep)->de_ADate), \
putushort((dp)->deMTime, (dep)->de_MTime), \
putushort((dp)->deMDate, (dep)->de_MDate), \
putushort((dp)->deStartCluster, (dep)->de_StartCluster), \
putulong((dp)->deFileSize, \
((dep)->de_Attributes & ATTR_DIRECTORY) ? 0 : (dep)->de_FileSize), \
putushort((dp)->deHighClust, (dep)->de_StartCluster >> 16))
#ifdef _KERNEL
#define VTODE(vp) ((struct denode *)(vp)->v_data)
#define DETOV(de) ((de)->de_vnode)
#define DETIMES(dep, acc, mod, cre) do { \
if ((dep)->de_flag & DE_UPDATE) { \
(dep)->de_flag |= DE_MODIFIED; \
timespec2fattime((mod), 0, &(dep)->de_MDate, \
&(dep)->de_MTime, NULL); \
(dep)->de_Attributes |= ATTR_ARCHIVE; \
} \
if ((dep)->de_pmp->pm_flags & MSDOSFSMNT_NOWIN95) { \
(dep)->de_flag &= ~(DE_UPDATE | DE_CREATE | DE_ACCESS); \
break; \
} \
if ((dep)->de_flag & DE_ACCESS) { \
u_int16_t adate; \
\
timespec2fattime((acc), 0, &adate, NULL, NULL); \
if (adate != (dep)->de_ADate) { \
(dep)->de_flag |= DE_MODIFIED; \
(dep)->de_ADate = adate; \
} \
} \
if ((dep)->de_flag & DE_CREATE) { \
timespec2fattime((cre), 0, &(dep)->de_CDate, \
&(dep)->de_CTime, &(dep)->de_CHun); \
(dep)->de_flag |= DE_MODIFIED; \
} \
(dep)->de_flag &= ~(DE_UPDATE | DE_CREATE | DE_ACCESS); \
} while (0)
/*
* This overlays the fid structure (see mount.h)
*/
struct defid {
u_short defid_len; /* length of structure */
u_short defid_pad; /* force long alignment */
u_int32_t defid_dirclust; /* cluster this dir entry came from */
u_int32_t defid_dirofs; /* offset of entry within the cluster */
#if 0
u_int32_t defid_gen; /* generation number */
#endif
};
extern struct vop_vector msdosfs_vnodeops;
int msdosfs_lookup(struct vop_cachedlookup_args *);
int msdosfs_inactive(struct vop_inactive_args *);
int msdosfs_reclaim(struct vop_reclaim_args *);
/*
* Internal service routine prototypes.
*/
int deget(struct msdosfsmount *, u_long, u_long, struct denode **);
int uniqdosname(struct denode *, struct componentname *, u_char *);
int findwin95(struct denode *);
int readep(struct msdosfsmount *pmp, u_long dirclu, u_long dirofs, struct buf **bpp, struct direntry **epp);
int readde(struct denode *dep, struct buf **bpp, struct direntry **epp);
int deextend(struct denode *dep, u_long length, struct ucred *cred);
int fillinusemap(struct msdosfsmount *pmp);
void reinsert(struct denode *dep);
int dosdirempty(struct denode *dep);
int createde(struct denode *dep, struct denode *ddep, struct denode **depp, struct componentname *cnp);
int deupdat(struct denode *dep, int waitfor);
int removede(struct denode *pdep, struct denode *dep);
int detrunc(struct denode *dep, u_long length, int flags, struct ucred *cred, struct thread *td);
int doscheckpath( struct denode *source, struct denode *target);
#endif /* _KERNEL */
|
dcui/FreeBSD-9.3_kernel
|
sys/fs/msdosfs/denode.h
|
C
|
bsd-3-clause
| 11,841 |
// vim: tabstop=2 shiftwidth=2
package main
import (
"bufio"
"encoding/binary"
"crypto/rsa"
"encoding/base64"
"os"
"strconv"
"strings"
"math/big"
"fmt"
)
type pubinfo struct {
name string // Remailer Shortname
//address is the next field in pubring but we'll use this as the key
keyid string // 16 Byte Mixmaster KeyID
version string // Mixmaster version
caps string // Remailer capstring
keylen uint16 // Stated key length
pk rsa.PublicKey // RSA Public Key
latent int // Latency (minutes)
uptime int // Uptime (10ths of a %)
}
func import_mlist2(filename string, pub map[string]pubinfo, xref map[string]string) (count int) {
var err error
f, err := os.Open(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
scanner := bufio.NewScanner(f)
var elements []string
var line string //Each line in mlist2.txt
var rem_name string //Remailer name in stats
var rem_addy string //Remailer address from xref
var lat []string //Latency hours:minutes
var lathrs int //Latent Hours
var latmin int //Latent Minutes
var exists bool //Test for presence of remailer in xref
stat_phase := 0
count = 0
/* Stat phases are:
0 Expecting long string of dashes
*/
for scanner.Scan() {
line = scanner.Text()
switch stat_phase {
case 0:
// Expecting dashes
if strings.HasPrefix(line, "----------") {
stat_phase = 1
}
case 1:
// Expecting stats
line = strings.Split(line, "%")[0]
elements = strings.Fields(line)
if len(elements) == 5 {
rem_name = elements[0]
_, exists = xref[rem_name]
if exists {
rem_addy = xref[rem_name]
// Element 2 is Latency in the format (hrs:mins)
lat = strings.Split(elements[2], ":")
if lat[0] == "" {
lathrs = 0
} else {
lathrs, err = strconv.Atoi(lat[0])
if err != nil {
fmt.Fprintf(os.Stderr, "%s: Invalid latent hours\n", rem_name)
continue
}
if lathrs < 0 || lathrs > 99 {
fmt.Fprintf(os.Stderr, "%s: Latent hours out of range\n", rem_name)
continue
}
}
latmin, err = strconv.Atoi(lat[1])
if err != nil {
fmt.Fprintf(os.Stderr, "%s: Invalid latent minutes\n", rem_name)
continue
}
if latmin < 0 || latmin > 59 {
fmt.Fprintf(os.Stderr, "%s: Latent minutes out of range\n", rem_name)
continue
}
// Element 4 is Uptime in format (xxx.xx)
uptmp, err := strconv.ParseFloat(elements[4], 32)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: Invalid uptime\n", rem_name)
continue
}
if uptmp < 0 || uptmp > 100 {
fmt.Fprintf(os.Stderr, "%s: Uptime out of range\n", rem_name)
continue
}
tmp := pub[rem_addy]
tmp.latent = (lathrs * 60) + latmin
tmp.uptime = int(uptmp * 10)
pub[rem_addy] = tmp
count += 1 // Increment count of processed remailers
} else {
fmt.Fprintf(os.Stderr, "%s: Unknown remailer\n", rem_name)
}
} else {
stat_phase = 2
}
case 2:
// Reserved for future mlist2.txt processing
break
}
}
return
}
func import_pubring(filename string) (pub map[string]pubinfo,
xref map[string]string) {
var err error
// pub = map of pubring structs
pub = make(map[string]pubinfo)
// xref = map of shortnames to addresses
xref = make(map[string]string)
f, err := os.Open(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
scanner := bufio.NewScanner(f)
var elements []string
var num_elements int
var line string //Each line within pubring.mix
var addy string //Remailer's address (The map key)
var rem *pubinfo //A specific remailer's pubring struct
var key_length int //The stated Public Key length
var keyblock string
var keydata []byte
key_phase := 0
/* Key phases are:
0 Expecting header line
1 Expecting Begin cutmark
2 Expecting Keyid line
3 Expecting key length line
4 In keyblock
5 Got End cutmark
*/
for scanner.Scan() {
line = scanner.Text()
switch key_phase {
case 0:
// Expecting key header line
elements = strings.Split(line, " ")
num_elements = len(elements)
// Elements of 5 or 7 indicate a remailer header line in pubring.mix
if (num_elements == 5 || num_elements == 7) {
rem = new(pubinfo)
rem.name = elements[0]
rem.keyid = elements[2]
rem.version = elements[3]
rem.caps = elements[4]
addy = elements[1]
xref[elements[0]] = addy
key_phase = 1
}
case 1:
// Expecting Begin cutmark
if line == "-----Begin Mix Key-----" {
key_phase = 2
}
case 2:
// Expecting Keyid line
if line == rem.keyid {
key_phase = 3
} else {
// Corrupt keyblock - header keyid doesn't match keyid in block
key_phase = 0
continue
}
key_length = 0
case 3:
// Expecting key length line
key_length, err = strconv.Atoi(line)
if err != nil {
// The keyblock is corrupt so reset key_phase and look for another
key_phase = 0
continue
}
keyblock = ""
key_phase = 4
case 4:
//In Keyblock
if line == "-----End Mix Key-----" {
keydata, err = base64.StdEncoding.DecodeString(keyblock)
// encoded_keylen is the first 2 Bytes of the keyblock
encoded_keylen := binary.LittleEndian.Uint16(keydata[0:2])
if err != nil {
// Invalid base64 data in keyblock
key_phase = 0
continue
}
if len(keydata) != key_length {
// Keyblock length doesn't match stated key length
key_phase = 0
continue
}
if int((encoded_keylen / 4) + 2) != key_length {
// Keyblock length differs from encoded (2 Byte) key length
key_phase = 0
continue
}
rem.keylen = encoded_keylen
// Cut between N and E: (1024 / 8) + 2 = 130
midpoint := (encoded_keylen / 8) + 2
rem.pk.N = bytes_to_bigint(keydata[2:midpoint])
rem.pk.E = bytes_to_int(keydata[midpoint:])
pub[addy] = *rem
key_phase = 0
} else {
keyblock += line
}
}
}
return
}
func bytes_to_bigint(b []byte) (acc *big.Int) {
acc = new(big.Int)
acc.SetBytes(b)
return
}
func bytes_to_int(b []byte) (i int) {
bigint := bytes_to_bigint(b)
i = int(bigint.Uint64())
return
}
|
crooks/gomix
|
pubring.go
|
GO
|
bsd-3-clause
| 6,160 |
# -*- coding: utf-8 -*-
# django imports
from django.urls import path, include
# devilry imports
from devilry.devilry_group.cradmin_instances import crinstance_admin
from devilry.devilry_group.cradmin_instances import crinstance_examiner
from devilry.devilry_group.cradmin_instances import crinstance_student
urlpatterns = [
path('student/', include(crinstance_student.StudentCrInstance.urls())),
path('examiner/', include(crinstance_examiner.ExaminerCrInstance.urls())),
path('admin/', include(crinstance_admin.AdminCrInstance.urls())),
]
|
devilry/devilry-django
|
devilry/devilry_group/urls.py
|
Python
|
bsd-3-clause
| 555 |
{% load i18n %}
{% if field.is_hidden %}
{{ field }}
{% else %}
<div class="control-group{% if field.errors %} error{% endif %}">
<label class="control-label" for="id_{{ field.name }}">{{ field.label }} {% if field.field.required %}<span class="red"> *</span>{% endif %}</label>
<div class="controls">
{{ field }}
{% if field.help_text %}
<br /><span class="help-inline">{{ field.help_text }}</span>
{% endif %}
{% if field.errors %}
<br /><span class="help-inline">{{ field.errors }}</span>
{% endif %}
</div>
</div>
{% endif %}
|
aazhbd/medical_info01
|
templates/_horizontal_field.html
|
HTML
|
bsd-3-clause
| 657 |
module IAU2000.Table53.Multipliers (multipliers) where
import Numeric.Units.Dimensional.Prelude
import qualified Prelude
import IAU2000.Table53.LunisolarMultipliers
import IAU2000.Table53.PlanetaryMultipliers
-- | Returns the series of fundamental argument multipliers. The multipliers
-- are on the order [m10,m11,m12,m13,m14,m1,m2,m3,m4,m5,m6,m7,m8,m9] where
-- the indices correspond to those of the fundamental arguments on page 46
-- of [3]. For the luni-solar terms (the first 678 terms in the series) only
-- m10 through m14 are provided.
multipliers :: Fractional a => [[Dimensionless a]]
multipliers = lunisolarMultipliers ++ planetaryMultipliers
|
bjornbm/astro-tables
|
IAU2000/Table53/Multipliers.hs
|
Haskell
|
bsd-3-clause
| 658 |
// Copyright 2015 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 "chromecast/renderer/media/hole_frame_factory.h"
#include "base/bind.h"
#include "base/location.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "media/base/video_frame.h"
#include "media/renderers/gpu_video_accelerator_factories.h"
namespace chromecast {
namespace media {
HoleFrameFactory::HoleFrameFactory(
::media::GpuVideoAcceleratorFactories* gpu_factories)
: gpu_factories_(gpu_factories), texture_(0), image_id_(0) {
if (gpu_factories_) {
scoped_ptr<::media::GpuVideoAcceleratorFactories::ScopedGLContextLock> lock(
gpu_factories_->GetGLContextLock());
CHECK(lock);
gpu::gles2::GLES2Interface* gl = lock->ContextGL();
gl->GenTextures(1, &texture_);
gl->BindTexture(GL_TEXTURE_2D, texture_);
image_id_ = gl->CreateGpuMemoryBufferImageCHROMIUM(1, 1, GL_RGBA,
GL_READ_WRITE_CHROMIUM);
if (image_id_) {
gl->BindTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id_);
gl->GenMailboxCHROMIUM(mailbox_.name);
gl->ProduceTextureDirectCHROMIUM(texture_, GL_TEXTURE_2D, mailbox_.name);
sync_token_ = gpu::SyncToken(gl->InsertSyncPointCHROMIUM());
}
}
}
HoleFrameFactory::~HoleFrameFactory() {
if (texture_) {
scoped_ptr<::media::GpuVideoAcceleratorFactories::ScopedGLContextLock> lock(
gpu_factories_->GetGLContextLock());
CHECK(lock);
gpu::gles2::GLES2Interface* gl = lock->ContextGL();
gl->BindTexture(GL_TEXTURE_2D, texture_);
if (image_id_)
gl->ReleaseTexImage2DCHROMIUM(GL_TEXTURE_2D, image_id_);
gl->DeleteTextures(1, &texture_);
if (image_id_)
gl->DestroyImageCHROMIUM(image_id_);
}
}
scoped_refptr<::media::VideoFrame> HoleFrameFactory::CreateHoleFrame(
const gfx::Size& size) {
if (texture_ && image_id_) {
scoped_refptr<::media::VideoFrame> frame =
::media::VideoFrame::WrapNativeTexture(
::media::PIXEL_FORMAT_XRGB,
gpu::MailboxHolder(mailbox_, sync_token_, GL_TEXTURE_2D),
::media::VideoFrame::ReleaseMailboxCB(),
size, // coded_size
gfx::Rect(size), // visible rect
size, // natural size
base::TimeDelta()); // timestamp
frame->metadata()->SetBoolean(::media::VideoFrameMetadata::ALLOW_OVERLAY,
true);
return frame;
} else {
// This case is needed for audio-only devices.
return ::media::VideoFrame::CreateBlackFrame(gfx::Size(1, 1));
}
}
} // namespace media
} // namespace chromecast
|
Bysmyyr/chromium-crosswalk
|
chromecast/renderer/media/hole_frame_factory.cc
|
C++
|
bsd-3-clause
| 2,803 |
{% load staticfiles %}
<!doctype html>
<html lang="en">
<head>
<title>Horseradish</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<style>
h1 { margin: 0 0 1em 0; }
.nav-tabs { margin-bottom: 1em; }
.the-image { display: block; margin-bottom: 3em; max-width: 100%; }
.modal textarea { border: 1px solid #ccc; border-radius: 3px; height: 200px; margin-top: 1em; width: 100%; }
.img-controls { text-align: right; margin-bottom: 1em; }
.photo-list img { margin-bottom: 0.3em; }
.paginator { text-align: center; }
div[role=main] { margin-bottom: 30px; }
.tag-list {
-webkit-column-count: 6;
-moz-column-count: 6;
column-count: 6;
}
.qa { margin: 4em 0; }
#dropzone {
text-align: center;
color: #999;
padding: 4em 0;
margin: 0 0 2em 0;
}
.dropready {
box-shadow: 0 0 5px #468CC8;
}
</style>
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<a class="navbar-brand" href="/"><span class="glyphicon glyphicon-picture"></span> Horseradish</a>
</div>
{% if request.user.is_authenticated %}
<ul class="nav navbar-nav navbar-right">
<li><a href="{% url 'photolib.tag_list' %}"><span class="glyphicon glyphicon-tags"></span> Tags</a></li>
<li><a href="{% url 'photolib.image_upload' %}"><span class="glyphicon glyphicon-cloud-upload"></span> Upload</a></li>
<li>
<form class="navbar-form" role="search" action="/search/" method="get">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="q" value="{% if query %}{{ query }}{% endif %}">
</div>
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span></button>
</form>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-cog"></span><b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="{% url 'horseradish.help' %}"><span class="glyphicon glyphicon-question-sign"></span> Help</a></li>
<li class="divider"></li>
<li><a href="/logout/"><span class="glyphicon glyphicon-log-out"></span> Log Out</a></li>
</ul>
</li>
</ul>
{% endif %}
</nav>
<div role="main" class="container">
{% block content %}{% endblock %}
</div>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
{% block js %}{% endblock %}
</body>
</html>
|
sunlightlabs/horseradish
|
horseradish/templates/base.html
|
HTML
|
bsd-3-clause
| 2,645 |
<?php
/**
* This file is part of the Zimbra API in PHP library.
*
* © Nguyen Van Nguyen <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zimbra\Mail\Struct;
use Zimbra\Struct\Base;
/**
* NewSearchFolderSpec struct class
*
* @package Zimbra
* @subpackage Mail
* @category Struct
* @author Nguyen Van Nguyen - [email protected]
* @copyright Copyright © 2013 by Nguyen Van Nguyen.
*/
class NewSearchFolderSpec extends Base
{
/**
* Constructor method for NewSearchFolderSpec
* @param string $name Name
* @param string $query Query
* @param string $types Search types
* @param string $sortBy Sort by
* @param string $f Flags
* @param int $color Color numeric; range 0-127; defaults to 0 if not present; client can display only 0-7
* @param string $l Parent folder ID
* @return self
*/
public function __construct(
$name,
$query,
$types = null,
$sortBy = null,
$f = null,
$color = null,
$l = null
)
{
parent::__construct();
$this->property('name', trim($name));
$this->property('query', trim($query));
if(null !== $types)
{
$this->property('types', trim($types));
}
if(null !== $sortBy)
{
$this->property('sortBy', trim($sortBy));
}
if(null !== $f)
{
$this->property('f', trim($f));
}
if(null !== $color)
{
$color = (int) $color;
$this->property('color', ($color > 0 && $color < 128) ? $color : 0);
}
if(null !== $l)
{
$this->property('l', trim($l));
}
}
/**
* Gets or sets name
*
* @param string $name
* @return string|self
*/
public function name($name = null)
{
if(null === $name)
{
return $this->property('name');
}
return $this->property('name', trim($name));
}
/**
* Gets or sets query
*
* @param string $query
* @return string|self
*/
public function query($query = null)
{
if(null === $query)
{
return $this->property('query');
}
return $this->property('query', trim($query));
}
/**
* Gets or sets types
*
* @param string $types
* @return string|self
*/
public function types($types = null)
{
if(null === $types)
{
return $this->property('types');
}
return $this->property('types', trim($types));
}
/**
* Gets or sets sortBy
*
* @param string $sortBy
* @return string|self
*/
public function sortBy($sortBy = null)
{
if(null === $sortBy)
{
return $this->property('sortBy');
}
return $this->property('sortBy', trim($sortBy));
}
/**
* Gets or sets f
*
* @param string $f
* @return string|self
*/
public function f($f = null)
{
if(null === $f)
{
return $this->property('f');
}
return $this->property('f', trim($f));
}
/**
* Gets or sets color
*
* @param int $color
* @return int|self
*/
public function color($color = null)
{
if(null === $color)
{
return $this->property('color');
}
return $this->property('color', ($color > 0 && $color < 128) ? $color : 0);
}
/**
* Gets or sets l
*
* @param string $l
* @return string|self
*/
public function l($l = null)
{
if(null === $l)
{
return $this->property('l');
}
return $this->property('l', trim($l));
}
/**
* Returns the array representation of this class
*
* @param string $name
* @return array
*/
public function toArray($name = 'search')
{
return parent::toArray($name);
}
/**
* Method returning the xml representative this class
*
* @param string $name
* @return SimpleXML
*/
public function toXml($name = 'search')
{
return parent::toXml($name);
}
}
|
malaleche/api-zimbra
|
src/Zimbra/Mail/Struct/NewSearchFolderSpec.php
|
PHP
|
bsd-3-clause
| 4,405 |
//========================================================================
// GLFW 3.1 Wayland - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2014 Jonas Ådahl <[email protected]>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include <linux/input.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-client.h>
#include <wayland-cursor.h>
#include "xkb_unicode.h"
static void pointerHandleEnter(void* data,
struct wl_pointer* pointer,
uint32_t serial,
struct wl_surface* surface,
wl_fixed_t sx,
wl_fixed_t sy)
{
_GLFWwindow* window = wl_surface_get_user_data(surface);
_glfw.wl.pointerSerial = serial;
_glfw.wl.pointerFocus = window;
_glfwPlatformSetCursor(window, window->wl.currentCursor);
_glfwInputCursorEnter(window, GL_TRUE);
}
static void pointerHandleLeave(void* data,
struct wl_pointer* pointer,
uint32_t serial,
struct wl_surface* surface)
{
_GLFWwindow* window = _glfw.wl.pointerFocus;
if (!window)
return;
_glfw.wl.pointerSerial = serial;
_glfw.wl.pointerFocus = NULL;
_glfwInputCursorEnter(window, GL_FALSE);
}
static void pointerHandleMotion(void* data,
struct wl_pointer* pointer,
uint32_t time,
wl_fixed_t sx,
wl_fixed_t sy)
{
_GLFWwindow* window = _glfw.wl.pointerFocus;
if (!window)
return;
if (window->cursorMode == GLFW_CURSOR_DISABLED)
{
/* TODO */
_glfwInputError(GLFW_PLATFORM_ERROR,
"Wayland: GLFW_CURSOR_DISABLED not supported");
return;
}
_glfwInputCursorMotion(window,
wl_fixed_to_double(sx),
wl_fixed_to_double(sy));
}
static void pointerHandleButton(void* data,
struct wl_pointer* wl_pointer,
uint32_t serial,
uint32_t time,
uint32_t button,
uint32_t state)
{
_GLFWwindow* window = _glfw.wl.pointerFocus;
int glfwButton;
if (!window)
return;
/* Makes left, right and middle 0, 1 and 2. Overall order follows evdev
* codes. */
glfwButton = button - BTN_LEFT;
_glfwInputMouseClick(window,
glfwButton,
state == WL_POINTER_BUTTON_STATE_PRESSED
? GLFW_PRESS
: GLFW_RELEASE,
_glfw.wl.xkb.modifiers);
}
static void pointerHandleAxis(void* data,
struct wl_pointer* wl_pointer,
uint32_t time,
uint32_t axis,
wl_fixed_t value)
{
_GLFWwindow* window = _glfw.wl.pointerFocus;
double scroll_factor;
double x, y;
if (!window)
return;
/* Wayland scroll events are in pointer motion coordinate space (think
* two finger scroll). The factor 10 is commonly used to convert to
* "scroll step means 1.0. */
scroll_factor = 1.0/10.0;
switch (axis)
{
case WL_POINTER_AXIS_HORIZONTAL_SCROLL:
x = wl_fixed_to_double(value) * scroll_factor;
y = 0.0;
break;
case WL_POINTER_AXIS_VERTICAL_SCROLL:
x = 0.0;
y = wl_fixed_to_double(value) * scroll_factor;
break;
default:
break;
}
_glfwInputScroll(window, x, y);
}
static const struct wl_pointer_listener pointerListener = {
pointerHandleEnter,
pointerHandleLeave,
pointerHandleMotion,
pointerHandleButton,
pointerHandleAxis,
};
static void keyboardHandleKeymap(void* data,
struct wl_keyboard* keyboard,
uint32_t format,
int fd,
uint32_t size)
{
struct xkb_keymap* keymap;
struct xkb_state* state;
char* mapStr;
if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1)
{
close(fd);
return;
}
mapStr = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
if (mapStr == MAP_FAILED) {
close(fd);
return;
}
keymap = xkb_map_new_from_string(_glfw.wl.xkb.context,
mapStr,
XKB_KEYMAP_FORMAT_TEXT_V1,
0);
munmap(mapStr, size);
close(fd);
if (!keymap)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"Wayland: Failed to compile keymap");
return;
}
state = xkb_state_new(keymap);
if (!state)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"Wayland: Failed to create XKB state");
xkb_map_unref(keymap);
return;
}
xkb_keymap_unref(_glfw.wl.xkb.keymap);
xkb_state_unref(_glfw.wl.xkb.state);
_glfw.wl.xkb.keymap = keymap;
_glfw.wl.xkb.state = state;
_glfw.wl.xkb.control_mask =
1 << xkb_map_mod_get_index(_glfw.wl.xkb.keymap, "Control");
_glfw.wl.xkb.alt_mask =
1 << xkb_map_mod_get_index(_glfw.wl.xkb.keymap, "Mod1");
_glfw.wl.xkb.shift_mask =
1 << xkb_map_mod_get_index(_glfw.wl.xkb.keymap, "Shift");
_glfw.wl.xkb.super_mask =
1 << xkb_map_mod_get_index(_glfw.wl.xkb.keymap, "Mod4");
}
static void keyboardHandleEnter(void* data,
struct wl_keyboard* keyboard,
uint32_t serial,
struct wl_surface* surface,
struct wl_array* keys)
{
_GLFWwindow* window = wl_surface_get_user_data(surface);
_glfw.wl.keyboardFocus = window;
_glfwInputWindowFocus(window, GL_TRUE);
}
static void keyboardHandleLeave(void* data,
struct wl_keyboard* keyboard,
uint32_t serial,
struct wl_surface* surface)
{
_GLFWwindow* window = _glfw.wl.keyboardFocus;
if (!window)
return;
_glfw.wl.keyboardFocus = NULL;
_glfwInputWindowFocus(window, GL_FALSE);
}
static int toGLFWKeyCode(uint32_t key)
{
switch (key)
{
case KEY_GRAVE: return GLFW_KEY_GRAVE_ACCENT;
case KEY_1: return GLFW_KEY_1;
case KEY_2: return GLFW_KEY_2;
case KEY_3: return GLFW_KEY_3;
case KEY_4: return GLFW_KEY_4;
case KEY_5: return GLFW_KEY_5;
case KEY_6: return GLFW_KEY_6;
case KEY_7: return GLFW_KEY_7;
case KEY_8: return GLFW_KEY_8;
case KEY_9: return GLFW_KEY_9;
case KEY_0: return GLFW_KEY_0;
case KEY_MINUS: return GLFW_KEY_MINUS;
case KEY_EQUAL: return GLFW_KEY_EQUAL;
case KEY_Q: return GLFW_KEY_Q;
case KEY_W: return GLFW_KEY_W;
case KEY_E: return GLFW_KEY_E;
case KEY_R: return GLFW_KEY_R;
case KEY_T: return GLFW_KEY_T;
case KEY_Y: return GLFW_KEY_Y;
case KEY_U: return GLFW_KEY_U;
case KEY_I: return GLFW_KEY_I;
case KEY_O: return GLFW_KEY_O;
case KEY_P: return GLFW_KEY_P;
case KEY_LEFTBRACE: return GLFW_KEY_LEFT_BRACKET;
case KEY_RIGHTBRACE: return GLFW_KEY_RIGHT_BRACKET;
case KEY_A: return GLFW_KEY_A;
case KEY_S: return GLFW_KEY_S;
case KEY_D: return GLFW_KEY_D;
case KEY_F: return GLFW_KEY_F;
case KEY_G: return GLFW_KEY_G;
case KEY_H: return GLFW_KEY_H;
case KEY_J: return GLFW_KEY_J;
case KEY_K: return GLFW_KEY_K;
case KEY_L: return GLFW_KEY_L;
case KEY_SEMICOLON: return GLFW_KEY_SEMICOLON;
case KEY_APOSTROPHE: return GLFW_KEY_APOSTROPHE;
case KEY_Z: return GLFW_KEY_Z;
case KEY_X: return GLFW_KEY_X;
case KEY_C: return GLFW_KEY_C;
case KEY_V: return GLFW_KEY_V;
case KEY_B: return GLFW_KEY_B;
case KEY_N: return GLFW_KEY_N;
case KEY_M: return GLFW_KEY_M;
case KEY_COMMA: return GLFW_KEY_COMMA;
case KEY_DOT: return GLFW_KEY_PERIOD;
case KEY_SLASH: return GLFW_KEY_SLASH;
case KEY_BACKSLASH: return GLFW_KEY_BACKSLASH;
case KEY_ESC: return GLFW_KEY_ESCAPE;
case KEY_TAB: return GLFW_KEY_TAB;
case KEY_LEFTSHIFT: return GLFW_KEY_LEFT_SHIFT;
case KEY_RIGHTSHIFT: return GLFW_KEY_RIGHT_SHIFT;
case KEY_LEFTCTRL: return GLFW_KEY_LEFT_CONTROL;
case KEY_RIGHTCTRL: return GLFW_KEY_RIGHT_CONTROL;
case KEY_LEFTALT: return GLFW_KEY_LEFT_ALT;
case KEY_RIGHTALT: return GLFW_KEY_RIGHT_ALT;
case KEY_LEFTMETA: return GLFW_KEY_LEFT_SUPER;
case KEY_RIGHTMETA: return GLFW_KEY_RIGHT_SUPER;
case KEY_MENU: return GLFW_KEY_MENU;
case KEY_NUMLOCK: return GLFW_KEY_NUM_LOCK;
case KEY_CAPSLOCK: return GLFW_KEY_CAPS_LOCK;
case KEY_PRINT: return GLFW_KEY_PRINT_SCREEN;
case KEY_SCROLLLOCK: return GLFW_KEY_SCROLL_LOCK;
case KEY_PAUSE: return GLFW_KEY_PAUSE;
case KEY_DELETE: return GLFW_KEY_DELETE;
case KEY_BACKSPACE: return GLFW_KEY_BACKSPACE;
case KEY_ENTER: return GLFW_KEY_ENTER;
case KEY_HOME: return GLFW_KEY_HOME;
case KEY_END: return GLFW_KEY_END;
case KEY_PAGEUP: return GLFW_KEY_PAGE_UP;
case KEY_PAGEDOWN: return GLFW_KEY_PAGE_DOWN;
case KEY_INSERT: return GLFW_KEY_INSERT;
case KEY_LEFT: return GLFW_KEY_LEFT;
case KEY_RIGHT: return GLFW_KEY_RIGHT;
case KEY_DOWN: return GLFW_KEY_DOWN;
case KEY_UP: return GLFW_KEY_UP;
case KEY_F1: return GLFW_KEY_F1;
case KEY_F2: return GLFW_KEY_F2;
case KEY_F3: return GLFW_KEY_F3;
case KEY_F4: return GLFW_KEY_F4;
case KEY_F5: return GLFW_KEY_F5;
case KEY_F6: return GLFW_KEY_F6;
case KEY_F7: return GLFW_KEY_F7;
case KEY_F8: return GLFW_KEY_F8;
case KEY_F9: return GLFW_KEY_F9;
case KEY_F10: return GLFW_KEY_F10;
case KEY_F11: return GLFW_KEY_F11;
case KEY_F12: return GLFW_KEY_F12;
case KEY_F13: return GLFW_KEY_F13;
case KEY_F14: return GLFW_KEY_F14;
case KEY_F15: return GLFW_KEY_F15;
case KEY_F16: return GLFW_KEY_F16;
case KEY_F17: return GLFW_KEY_F17;
case KEY_F18: return GLFW_KEY_F18;
case KEY_F19: return GLFW_KEY_F19;
case KEY_F20: return GLFW_KEY_F20;
case KEY_F21: return GLFW_KEY_F21;
case KEY_F22: return GLFW_KEY_F22;
case KEY_F23: return GLFW_KEY_F23;
case KEY_F24: return GLFW_KEY_F24;
case KEY_KPSLASH: return GLFW_KEY_KP_DIVIDE;
case KEY_KPDOT: return GLFW_KEY_KP_MULTIPLY;
case KEY_KPMINUS: return GLFW_KEY_KP_SUBTRACT;
case KEY_KPPLUS: return GLFW_KEY_KP_ADD;
case KEY_KP0: return GLFW_KEY_KP_0;
case KEY_KP1: return GLFW_KEY_KP_1;
case KEY_KP2: return GLFW_KEY_KP_2;
case KEY_KP3: return GLFW_KEY_KP_3;
case KEY_KP4: return GLFW_KEY_KP_4;
case KEY_KP5: return GLFW_KEY_KP_5;
case KEY_KP6: return GLFW_KEY_KP_6;
case KEY_KP7: return GLFW_KEY_KP_7;
case KEY_KP8: return GLFW_KEY_KP_8;
case KEY_KP9: return GLFW_KEY_KP_9;
case KEY_KPCOMMA: return GLFW_KEY_KP_DECIMAL;
case KEY_KPEQUAL: return GLFW_KEY_KP_EQUAL;
case KEY_KPENTER: return GLFW_KEY_KP_ENTER;
default: return GLFW_KEY_UNKNOWN;
}
}
static void keyboardHandleKey(void* data,
struct wl_keyboard* keyboard,
uint32_t serial,
uint32_t time,
uint32_t key,
uint32_t state)
{
uint32_t code, num_syms;
long cp;
int keyCode;
int action;
const xkb_keysym_t *syms;
_GLFWwindow* window = _glfw.wl.keyboardFocus;
if (!window)
return;
keyCode = toGLFWKeyCode(key);
action = state == WL_KEYBOARD_KEY_STATE_PRESSED
? GLFW_PRESS : GLFW_RELEASE;
_glfwInputKey(window, keyCode, key, action,
_glfw.wl.xkb.modifiers);
code = key + 8;
num_syms = xkb_key_get_syms(_glfw.wl.xkb.state, code, &syms);
if (num_syms == 1)
{
cp = _glfwKeySym2Unicode(syms[0]);
if (cp != -1)
{
const int mods = _glfw.wl.xkb.modifiers;
const int plain = !(mods & (GLFW_MOD_CONTROL | GLFW_MOD_ALT));
_glfwInputChar(window, cp, mods, plain);
}
}
}
static void keyboardHandleModifiers(void* data,
struct wl_keyboard* keyboard,
uint32_t serial,
uint32_t modsDepressed,
uint32_t modsLatched,
uint32_t modsLocked,
uint32_t group)
{
xkb_mod_mask_t mask;
unsigned int modifiers = 0;
if (!_glfw.wl.xkb.keymap)
return;
xkb_state_update_mask(_glfw.wl.xkb.state,
modsDepressed,
modsLatched,
modsLocked,
0,
0,
group);
mask = xkb_state_serialize_mods(_glfw.wl.xkb.state,
XKB_STATE_DEPRESSED |
XKB_STATE_LATCHED);
if (mask & _glfw.wl.xkb.control_mask)
modifiers |= GLFW_MOD_CONTROL;
if (mask & _glfw.wl.xkb.alt_mask)
modifiers |= GLFW_MOD_ALT;
if (mask & _glfw.wl.xkb.shift_mask)
modifiers |= GLFW_MOD_SHIFT;
if (mask & _glfw.wl.xkb.super_mask)
modifiers |= GLFW_MOD_SUPER;
_glfw.wl.xkb.modifiers = modifiers;
}
static const struct wl_keyboard_listener keyboardListener = {
keyboardHandleKeymap,
keyboardHandleEnter,
keyboardHandleLeave,
keyboardHandleKey,
keyboardHandleModifiers,
};
static void seatHandleCapabilities(void* data,
struct wl_seat* seat,
enum wl_seat_capability caps)
{
if ((caps & WL_SEAT_CAPABILITY_POINTER) && !_glfw.wl.pointer)
{
_glfw.wl.pointer = wl_seat_get_pointer(seat);
wl_pointer_add_listener(_glfw.wl.pointer, &pointerListener, NULL);
}
else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && _glfw.wl.pointer)
{
wl_pointer_destroy(_glfw.wl.pointer);
_glfw.wl.pointer = NULL;
}
if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !_glfw.wl.keyboard)
{
_glfw.wl.keyboard = wl_seat_get_keyboard(seat);
wl_keyboard_add_listener(_glfw.wl.keyboard, &keyboardListener, NULL);
}
else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && _glfw.wl.keyboard)
{
wl_keyboard_destroy(_glfw.wl.keyboard);
_glfw.wl.keyboard = NULL;
}
}
static const struct wl_seat_listener seatListener = {
seatHandleCapabilities
};
static void registryHandleGlobal(void* data,
struct wl_registry* registry,
uint32_t name,
const char* interface,
uint32_t version)
{
if (strcmp(interface, "wl_compositor") == 0)
{
_glfw.wl.compositor =
wl_registry_bind(registry, name, &wl_compositor_interface, 1);
}
else if (strcmp(interface, "wl_shm") == 0)
{
_glfw.wl.shm =
wl_registry_bind(registry, name, &wl_shm_interface, 1);
}
else if (strcmp(interface, "wl_shell") == 0)
{
_glfw.wl.shell =
wl_registry_bind(registry, name, &wl_shell_interface, 1);
}
else if (strcmp(interface, "wl_output") == 0)
{
_glfwAddOutput(name, version);
}
else if (strcmp(interface, "wl_seat") == 0)
{
if (!_glfw.wl.seat)
{
_glfw.wl.seat =
wl_registry_bind(registry, name, &wl_seat_interface, 1);
wl_seat_add_listener(_glfw.wl.seat, &seatListener, NULL);
}
}
}
static void registryHandleGlobalRemove(void *data,
struct wl_registry *registry,
uint32_t name)
{
}
static const struct wl_registry_listener registryListener = {
registryHandleGlobal,
registryHandleGlobalRemove
};
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
int _glfwPlatformInit(void)
{
_glfw.wl.display = wl_display_connect(NULL);
if (!_glfw.wl.display)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"Wayland: Failed to connect to display");
return GL_FALSE;
}
_glfw.wl.registry = wl_display_get_registry(_glfw.wl.display);
wl_registry_add_listener(_glfw.wl.registry, ®istryListener, NULL);
_glfw.wl.monitors = calloc(4, sizeof(_GLFWmonitor*));
_glfw.wl.monitorsSize = 4;
_glfw.wl.xkb.context = xkb_context_new(0);
if (!_glfw.wl.xkb.context)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"Wayland: Failed to initialize xkb context");
return GL_FALSE;
}
// Sync so we got all registry objects
wl_display_roundtrip(_glfw.wl.display);
// Sync so we got all initial output events
wl_display_roundtrip(_glfw.wl.display);
if (!_glfwInitContextAPI())
return GL_FALSE;
_glfwInitTimer();
_glfwInitJoysticks();
if (_glfw.wl.pointer && _glfw.wl.shm)
{
_glfw.wl.cursorTheme = wl_cursor_theme_load(NULL, 32, _glfw.wl.shm);
if (!_glfw.wl.cursorTheme)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"Wayland: Unable to load default cursor theme\n");
return GL_FALSE;
}
_glfw.wl.defaultCursor =
wl_cursor_theme_get_cursor(_glfw.wl.cursorTheme, "left_ptr");
if (!_glfw.wl.defaultCursor)
{
_glfwInputError(GLFW_PLATFORM_ERROR,
"Wayland: Unable to load default left pointer\n");
return GL_FALSE;
}
_glfw.wl.cursorSurface =
wl_compositor_create_surface(_glfw.wl.compositor);
}
return GL_TRUE;
}
void _glfwPlatformTerminate(void)
{
_glfwTerminateContextAPI();
if (_glfw.wl.cursorTheme)
wl_cursor_theme_destroy(_glfw.wl.cursorTheme);
if (_glfw.wl.cursorSurface)
wl_surface_destroy(_glfw.wl.cursorSurface);
if (_glfw.wl.registry)
wl_registry_destroy(_glfw.wl.registry);
if (_glfw.wl.display)
wl_display_flush(_glfw.wl.display);
if (_glfw.wl.display)
wl_display_disconnect(_glfw.wl.display);
}
const char* _glfwPlatformGetVersionString(void)
{
const char* version = _GLFW_VERSION_NUMBER " Wayland EGL "
#if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
" clock_gettime"
#endif
#if defined(_GLFW_BUILD_DLL)
" shared"
#endif
;
return version;
}
|
azul3d/native-glfw
|
glfw/src/wl_init.c
|
C
|
bsd-3-clause
| 21,783 |
// Copyright 2020 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.
#ifndef COMPONENTS_PERMISSIONS_CONTEXTS_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_H_
#define COMPONENTS_PERMISSIONS_CONTEXTS_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_H_
#include "build/build_config.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/permissions/permission_context_base.h"
namespace webrtc {
class MediaStreamDeviceEnumerator;
} // namespace webrtc
namespace permissions {
// Manage user permissions that only control camera movement (pan, tilt, and
// zoom). Those permissions are automatically reset when the "regular" camera
// permission is blocked or reset.
class CameraPanTiltZoomPermissionContext
: public permissions::PermissionContextBase {
public:
// Delegate which allows embedders to modify the logic of this permission
// context.
class Delegate {
public:
virtual ~Delegate() = default;
// Allows the delegate to override the context's
// GetPermissionStatusInternal() logic. If this returns true, the base
// context's GetPermissionStatusInternal() will not be called.
virtual bool GetPermissionStatusInternal(
const GURL& requesting_origin,
const GURL& embedding_origin,
ContentSetting* content_setting_result) = 0;
};
// Constructs a CameraPanTiltZoomPermissionContext for |browser_context|. Note
// that the passed in |device_enumerator| must outlive |this|.
CameraPanTiltZoomPermissionContext(
content::BrowserContext* browser_context,
std::unique_ptr<Delegate> delegate,
const webrtc::MediaStreamDeviceEnumerator* device_enumerator);
~CameraPanTiltZoomPermissionContext() override;
CameraPanTiltZoomPermissionContext(
const CameraPanTiltZoomPermissionContext&) = delete;
CameraPanTiltZoomPermissionContext& operator=(
const CameraPanTiltZoomPermissionContext&) = delete;
private:
// PermissionContextBase
void RequestPermission(
content::WebContents* web_contents,
const permissions::PermissionRequestID& id,
const GURL& requesting_frame_origin,
bool user_gesture,
permissions::BrowserPermissionCallback callback) override;
ContentSetting GetPermissionStatusInternal(
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const GURL& embedding_origin) const override;
bool IsRestrictedToSecureOrigins() const override;
// content_settings::Observer
void OnContentSettingChanged(
const ContentSettingsPattern& primary_pattern,
const ContentSettingsPattern& secondary_pattern,
ContentSettingsTypeSet content_type_set) override;
// Returns true if at least one video capture device has PTZ capabilities.
// Otherwise returns false.
bool HasAvailableCameraPtzDevices() const;
std::unique_ptr<Delegate> delegate_;
HostContentSettingsMap* host_content_settings_map_;
bool updating_camera_ptz_permission_ = false;
bool updating_mediastream_camera_permission_ = false;
// Enumerates available media devices. Must outlive |this|.
const webrtc::MediaStreamDeviceEnumerator* const device_enumerator_;
};
} // namespace permissions
#endif // COMPONENTS_PERMISSIONS_CONTEXTS_CAMERA_PAN_TILT_ZOOM_PERMISSION_CONTEXT_H_
|
scheib/chromium
|
components/permissions/contexts/camera_pan_tilt_zoom_permission_context.h
|
C
|
bsd-3-clause
| 3,395 |
<?php
use frontend\modules\catalog\assets\CatalogCardAsset;
use frontend\assets\GoogleMapsAsset;
Yii::$app->assetManager->forceCopy = true;
CatalogCardAsset::register($this);
GoogleMapsAsset::register($this);
?>
<div id="map">
</div>
|
baranov-nt/ektscp
|
frontend/modules/catalog/views/default/_map.php
|
PHP
|
bsd-3-clause
| 237 |
<?php
namespace app\controllers;
use app\forms\LoginForm;
use app\forms\RegisterForm;
use app\forms\UserForm;
use app\models\User;
use yii\base\Exception;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\HttpException;
use yii\web\IdentityInterface;
class UserController extends Controller {
public function behaviors() {
return [
'access' => [ 'class' => AccessControl::className(),
'except' => [ 'login', 'register', 'logout' ],
'rules' => [
[ 'allow' => true, 'actions' => [ 'edit', 'update', 'create', 'delete' ], 'roles' => [ 'USER_WRITE' ] ],
[ 'allow' => true, 'actions' => [ 'list', 'vk' ], 'roles' => [ 'USER_READ' ] ]
]
],
];
}
public function actionList() {
return $this->render('list', [
'model' => new UserForm([ 'scenario' => 'site.user.create' ])
]);
}
public function actionEdit() {
if (!$id = \Yii::$app->getRequest()->getQueryParam('id')) {
return $this->redirect([ 'user/list' ]);
}
else if (!$ar = User::find()->where([ 'id' => $id ])->one()) {
return $this->redirect([ 'user/list' ]);
}
return $this->render('edit', [
'model' => new UserForm([ 'scenario' => 'site.user.update', 'password' => '' ] + $ar->getAttributes())
]);
}
public function actionCreate() {
$form = new UserForm([ 'scenario' => 'site.user.create' ]);
if (!$form->load(\Yii::$app->getRequest()->getBodyParams())) {
\Yii::$app->getSession()->setFlash('danger', 'Невозможно загрузить форму');
return $this->redirect([ 'user/list' ]);
}
else if (!$form->validate()) {
\Yii::$app->getSession()->setFlash('danger', 'Произошли ошибки при валидации формы');
return $this->redirect([ 'user/list' ]);
}
$ar = new User();
$ar->setAttributes($form->getAttributes(), false);
$ar->setAttribute('password', \Yii::$app->getSecurity()->generatePasswordHash(
$ar->getAttribute('password')
));
$ar->save();
\Yii::$app->getSession()->setFlash('success', 'Пользователь успешно создан');
return $this->redirect([ 'user/list' ]);
}
public function actionUpdate() {
$form = new UserForm([ 'scenario' => 'site.user.update' ]);
if (!$form->load(\Yii::$app->getRequest()->getBodyParams())) {
\Yii::$app->getSession()->setFlash('danger', 'Невозможно загрузить форму');
return $this->redirect([ 'user/list' ]);
}
else if (!$form->validate()) {
\Yii::$app->getSession()->setFlash('danger', 'Произошли ошибки при валидации формы');
return $this->redirect([ 'user/list' ]);
}
else if (!$ar = User::find()->where([ 'id' => $form->id ])->one()) {
\Yii::$app->getSession()->setFlash('danger', 'Невозможно загрузить модель');
return $this->redirect([ 'user/list' ]);
}
if (!empty($form->password)) {
$form->password = \Yii::$app->getSecurity()->generatePasswordHash($form->password);
} else {
$form->password = $ar->getAttribute('password');
}
$ar->setAttributes($form->getAttributes(), false);
$ar->setAttribute('id', $ar->getOldAttribute('id'));
$ar->save();
\Yii::$app->getSession()->setFlash('success', 'Пользователь успешно изменен');
return $this->redirect([ 'user/list' ]);
}
public function actionDelete() {
User::deleteAll([ 'id' => $id = \Yii::$app->getRequest()->getQueryParam('id') ]);
\Yii::$app->getSession()->setFlash('success', 'Пользователь успешно удален');
return $this->redirect([ 'user/list' ]);
}
public function actionRegister() {
$model = new RegisterForm();
if (!$model->load(\Yii::$app->getRequest()->getBodyParams())) {
\Yii::$app->getSession()->setFlash('danger', 'Невозможно загрузить клиентскую форму');
$this->goBack();
}
else if (!$model->validate()) {
\Yii::$app->getSession()->setFlash('danger', 'Произошли ошибки при валидации формы');
$this->goBack();
}
$user = new User();
$user->setAttributes($model->getAttributes(), false);
$user->setAttribute('role_id', 1);
$user->setAttribute("password", \Yii::$app->getSecurity()->generatePasswordHash($user->getAttribute("password")));
$user->save();
\Yii::$app->getSession()->setFlash('success', 'Пользователь успешно зарегистрировался');
$this->redirect([ '/' ]);
}
public function actionLogin() {
$model = new LoginForm();
if (!$model->load(\Yii::$app->getRequest()->getBodyParams())) {
\Yii::$app->getSession()->setFlash('danger', 'Невозможно загрузить клиентскую форму');
return $this->redirect([ '/' ]);
}
else if (!$model->validate()) {
\Yii::$app->getSession()->setFlash('danger', 'Произошли ошибки при валидации формы');
return $this->redirect([ '/' ]);
}
else if (!$user = User::find()->where([ 'login' => $model->login ])->one()) {
\Yii::$app->getSession()->setFlash('danger', 'Неверный логин или пароль');
return $this->redirect([ '/' ]);
}
else if (!\Yii::$app->getSecurity()->validatePassword($model->password, $user->getAttribute('password'))) {
\Yii::$app->getSession()->setFlash('danger', 'Неверный логин или пароль');
return $this->redirect([ '/' ]);
}
/* @var $user IdentityInterface */
\Yii::$app->getUser()->login($user);
return $this->goHome();
}
public function actionLogout() {
\Yii::$app->getUser()->logout();
$this->goHome();
}
}
|
pancake123/R3D
|
controllers/UserController.php
|
PHP
|
bsd-3-clause
| 5,613 |
// Copyright 2016 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.
#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_PROTOCOL_HANDLERS_HANDLER_H_
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_PROTOCOL_HANDLERS_HANDLER_H_
#include <string>
#include "base/scoped_observation.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h"
#include "chrome/browser/web_applications/app_registrar_observer.h"
#include "chrome/browser/web_applications/web_app_id.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "content/public/common/custom_handlers/protocol_handler.h"
////////////////////////////////////////////////////////////////////////////////
// ProtocolHandlersHandler
// Listen for changes to protocol handlers registrations.
// This get triggered whenever a user allows or disallows a specific website or
// application to handle clicks on a link with a specified protocol (i.e.
// mailto: -> Gmail).
namespace base {
class DictionaryValue;
}
using content::ProtocolHandler;
namespace settings {
class ProtocolHandlersHandler : public SettingsPageUIHandler,
public ProtocolHandlerRegistry::Observer,
public web_app::AppRegistrarObserver {
public:
explicit ProtocolHandlersHandler(Profile* profile);
ProtocolHandlersHandler(const ProtocolHandlersHandler&) = delete;
ProtocolHandlersHandler& operator=(const ProtocolHandlersHandler&) = delete;
~ProtocolHandlersHandler() override;
// SettingsPageUIHandler:
void OnJavascriptAllowed() override;
void OnJavascriptDisallowed() override;
void RegisterMessages() override;
// ProtocolHandlerRegistry::Observer:
void OnProtocolHandlerRegistryChanged() override;
// web_app::AppRegistrarObserver:
void OnWebAppUninstalled(const web_app::AppId& app_id) override;
void OnWebAppProtocolSettingsChanged() override;
private:
// Called to fetch the state of the protocol handlers. If the full list of
// handlers is not needed, consider HandleObserveProtocolHandlersEnabledState
// instead.
void HandleObserveProtocolHandlers(const base::ListValue* args);
// Called to begin updates to the handlers enabled status. This is a subset
// (lighter alternative) of HandleObserveProtocolHandlers. There's no need to
// call this function if HandleObserveProtocolHandlers is called.
void HandleObserveProtocolHandlersEnabledState(const base::ListValue* args);
// Notifies the JS side whether the handlers are enabled or not.
void SendHandlersEnabledValue();
// Called when the user toggles whether custom handlers are enabled.
void HandleSetHandlersEnabled(const base::ListValue* args);
// Called when the user sets a new default handler for a protocol.
void HandleSetDefault(const base::ListValue* args);
// Parses a ProtocolHandler out of the arguments passed back from the view.
// |args| is a list of [protocol, url].
ProtocolHandler ParseHandlerFromArgs(const base::ListValue* args) const;
// Returns a JSON object describing the set of protocol handlers for the
// given protocol.
void GetHandlersForProtocol(const std::string& protocol,
base::DictionaryValue* value);
// Returns a JSON list of the ignored protocol handlers.
void GetIgnoredHandlers(base::ListValue* handlers);
// Called when the JS PasswordManager object is initialized.
void UpdateHandlerList();
// Remove a handler.
// |args| is a list of [protocol, url].
void HandleRemoveHandler(const base::ListValue* args);
ProtocolHandlerRegistry* GetProtocolHandlerRegistry();
base::ScopedObservation<ProtocolHandlerRegistry,
ProtocolHandlerRegistry::Observer>
registry_observation_{this};
// Web App Protocol Handler specific functions:
// Called to fetch the state of the app protocol handlers.
void HandleObserveAppProtocolHandlers(base::Value::ConstListView args);
// Parses an App ProtocolHandler out of |args|, which is a list of [protocol,
// url, app_id].
content::ProtocolHandler ParseAppHandlerFromArgs(
base::Value::ConstListView args) const;
// Returns a DictionaryValue describing the set of app protocol handlers for
// the given |protocol| in the given |handlers| list.
std::unique_ptr<base::DictionaryValue> GetAppHandlersForProtocol(
const std::string& protocol,
ProtocolHandlerRegistry::ProtocolHandlerList handlers);
// Called when OnWebAppProtocolSettingsChanged() is notified or on page load.
void UpdateAllAllowedLaunchProtocols();
// Called when OnWebAppProtocolSettingsChanged() is notified or on page load.
void UpdateAllDisallowedLaunchProtocols();
// Remove an approved app handler.
// |args| is a list of [protocol, url, app_id].
void HandleRemoveAllowedAppHandler(base::Value::ConstListView args);
// Remove a disallowed app handler.
// |args| is a list of [protocol, url, app_id].
void HandleRemoveDisallowedAppHandler(base::Value::ConstListView args);
Profile* const profile_;
web_app::WebAppProvider* const web_app_provider_;
base::ScopedObservation<web_app::WebAppRegistrar,
web_app::AppRegistrarObserver>
app_observation_{this};
};
} // namespace settings
#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_PROTOCOL_HANDLERS_HANDLER_H_
|
scheib/chromium
|
chrome/browser/ui/webui/settings/protocol_handlers_handler.h
|
C
|
bsd-3-clause
| 5,560 |
/*
* Carrot2 project.
*
* Copyright (C) 2002-2015, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.text.suffixtree;
import com.carrotsearch.hppc.IntArrayList;
import com.carrotsearch.hppc.LongIntScatterMap;
import com.carrotsearch.hppc.cursors.LongIntCursor;
/**
* Builds a suffix tree (or generalized suffix tree) on a sequence of any integers (or
* objects that can be represented as unique integers). A direct implementation of Esko
* Ukkonen's algorithm, but optimized for Java to use primitive data types instead of
* objects (or boxed types).
*
* @see "E. Ukkonen, On-line construction of suffix trees, Algorithmica, 1995, volume 14, number 3, pages 249-260."
*/
public final class SuffixTree
{
/** A constant to represent invalid suffix link from a state. */
private final static int NO_SUFFIX_LINK = Integer.MIN_VALUE;
/**
* Leaf state marker in {@link #states}.
*/
private final static int LEAF_STATE = -1;
/**
* Marker for the state's last edge in {@link #transitions}.
*/
public final static int NO_EDGE = -1;
/**
* Root state's identifier (constant).
*/
private final static int ROOT_STATE = 1;
/**
* The input sequence of integers.
*/
final ISequence sequence;
/**
* Cached size of {@link #sequence}.
*/
private final int inputSize;
/**
* States array indexed by state number. Values in this array are:
* <ul>
* <li>at build time, the suffix pointer (state pointer),</li>
* <li>after the tree is built, the first edge from a given state (edge pointer).</li>
* </ul>
*/
private IntArrayList states = new IntArrayList();
/**
* A hash map of transitions (edges) between states in the suffix tree. The map is
* keyed by a combination of state (upper 32 bits) and symbol (lower 32 bits). The
* value is an index in the transitions array.
*/
private final LongIntScatterMap transitions_map = new LongIntScatterMap();
/**
* An array of all transitions.
*
* @see #addTransition(int, int, int)
* @see #reuseTransition(int, int, int, int, int)
*/
private final IntArrayList transitions = new IntArrayList();
/**
* Variables used during tree construction. See Ukkonen's algorithm for details.
*/
private int s, k, i;
private boolean end_point;
/**
* Head state and root state.
*/
private final int head, root;
/**
* Default transition from head to the root.
*/
private final int root_transition;
/**
* Number of integers per single transition.
*/
private final int slots_per_transition;
/**
* State callback or <code>null</code>.
*
* @see IStateCallback
*/
private final IStateCallback newStateCallback;
/**
* A callback invoked when new states are added to the tree.
*/
public interface IStateCallback
{
void newState(int state, int position);
}
/**
* Progress callback is invoked when iterating forward through the input sequence
* elements.
*/
public interface IProgressCallback
{
void next(int pos);
}
/**
* Visitor interface for traversals.
*
* @see VisitorAdapter
*/
public interface IVisitor
{
/**
* Invoked before <code>state</code> is descended into.
*
* @return Returning <code>false</code> omits the subtree of <code>state</code>.
* {@link #post(int)} is not invoked for this state if skipped.
*/
public boolean pre(int state);
/**
* Invoked after <code>state</code> is fully traversed.
*
* @param state Identifier of the completed state.
*/
public void post(int state);
/**
* Invoked when an edge is visited.
*
* @return Returning <code>false</code> skips the traversal of
* <code>toState</code>.
*/
public boolean edge(int fromState, int toState, int startIndex, int endIndex);
}
/**
* Empty implementation recursively walking the entire suffix tree.
*/
public static class VisitorAdapter implements IVisitor
{
public boolean pre(int state)
{
return true;
}
public void post(int state)
{
}
public boolean edge(int fromState, int toState, int startIndex, int endIndex)
{
return true;
}
}
/**
* Build a suffix tree for a given input sequence of symbols.
*/
public SuffixTree(ISequence sequence, IStateCallback newStateCallback,
final IProgressCallback progressCallback)
{
this.sequence = sequence;
this.newStateCallback = newStateCallback;
// Prepare initial conditions.
head = createState();
root = createState();
setSuffixLink(root, head);
assert ROOT_STATE == root;
addTransition(root, 0, 0);
slots_per_transition = transitions.size();
root_transition = 0;
// Build the tree.
s = root;
inputSize = sequence.size();
for (k = i = 1; i <= inputSize; i++)
{
if (progressCallback != null) progressCallback.next(i - 1);
update();
canonize(s, k, i);
}
// Connect edges from a single state to speed up iterators.
for (int i = states.size() - 1; i >= 0; i--)
states.set(i, LEAF_STATE);
for (LongIntCursor c : transitions_map)
{
final int g = c.value;
final int state = (int) (c.key >>> 32);
final int prev = states.get(state);
if (prev != LEAF_STATE)
{
transitions.set(g + 3, prev);
}
states.set(state, g);
}
}
/**
* Update subroutine of the suffix tree building algorithm.
*/
private final void update()
{
int oldr = root;
while (true)
{
int r = testAndSplit(i - 1, i);
if (end_point) break;
createTransition(r, i, inputSize, createNewState(i));
if (oldr != root) setSuffixLink(oldr, r);
oldr = r;
canonize(getSuffixLink(s), k, i - 1);
}
if (oldr != root) setSuffixLink(oldr, s);
}
/**
* Test and split subroutine of the suffix tree building algorithm.
*/
private final int testAndSplit(int p, int ti)
{
if (k <= p)
{
final int g = findTransition(s, k);
assert g >= 0;
final int gk = transitions.get(g + 1);
final int gj = transitions.get(g + 2);
final int gs = transitions.get(g);
if (sequence.objectAt(ti - 1) == sequence.objectAt(gk + p - k))
{
end_point = true;
return s;
}
else
{
final int r = createNewState(gk + p - k);
reuseTransition(removeTransition(s, k), s, gk, gk + p - k, r);
createTransition(r, gk + p - k + 1, gj, gs);
end_point = false;
return r;
}
}
else
{
end_point = findTransition(s, ti) >= 0;
return s;
}
}
/**
* Canonization subroutine of the suffix tree building algorithm.
*/
private void canonize(int s, int k, int p)
{
if (p >= k)
{
int g = findTransition(s, k);
int d;
while (g >= 0 && (d = transitions.get(g + 2) - transitions.get(g + 1)) <= p - k)
{
k = k + d + 1;
s = transitions.get(g);
if (k <= p) g = findTransition(s, k);
}
}
this.s = s;
this.k = k;
}
/*
*
*/
private void setSuffixLink(int fromState, int toState)
{
states.set(fromState, toState);
}
/*
*
*/
private int getSuffixLink(int s)
{
final int ts = this.states.get(s);
assert ts != NO_SUFFIX_LINK;
return ts;
}
/**
* Add a new state to the tree, calling external callback if requested.
*/
private final int createNewState(int position)
{
final int state = createState();
if (newStateCallback != null)
{
newStateCallback.newState(state, position);
}
return state;
}
/**
* Adds a new state to the list of {@link #states}.
*/
private final int createState()
{
final int state = states.size();
states.add(NO_SUFFIX_LINK);
return state;
}
/**
* Create a transition from state <code>s</code> to state <code>ts</code>, labeled
* with symbols between <code>k</code> and <code>p</code> (1-based, inclusive).
*/
private final void createTransition(int s, int k, int p, int ts)
{
assert k > 0 && p > 0;
final int transition = addTransition(ts, k, p);
transitions_map.put(asLong(s, sequence.objectAt(k - 1)), transition);
}
/**
* Reuse an existing transition slot to store a transition from state <code>s</code>
* to state <code>ts</code>, labeled with symbols between <code>k</code> and
* <code>p</code> (1-based, inclusive).
*/
private final void reuseTransition(int transition, int s, int k, int p, int ts)
{
assert k > 0 && p > 0;
transitions.set(transition, ts);
transitions.set(transition + 1, k);
transitions.set(transition + 2, p);
transitions_map.put(asLong(s, sequence.objectAt(k - 1)), transition);
}
/**
* Adds a transition to state <code>ts</code>, labeled with symbols between
* <code>k</code> and <code>p</code> (1-based, inclusive), but does not add hash map
* entry (for internal use).
*/
private final int addTransition(int ts, int k, int p)
{
final int transition = transitions.size();
transitions.add(ts);
transitions.add(k);
transitions.add(p);
transitions.add(NO_EDGE);
return transition;
}
/**
* Find a transition from state <code>s</code>, labeled with symbol at index
* <code>k - 1</code> in the input sequence.
*/
private final int findTransition(int s, int k)
{
return s == head ? root_transition : findEdge(s, sequence.objectAt(k - 1));
}
/**
* Remove the transition from state <code>s</code>, labeled with symbol at index
* <code>k - 1</code> and return its slot in the transitions array.
*/
private int removeTransition(int s, int k)
{
assert s != head;
return transitions_map.remove(asLong(s, sequence.objectAt(k - 1)));
}
/**
* Make a <code>long</code> from two integers.
*/
private final static long asLong(int i1, int i2)
{
return ((long) i1) << 32 | (i2 & 0xffffffffL);
}
/**
* @return Return the number of transitions (edges) in the tree.
*/
public final int getTransitionsCount()
{
return (this.transitions.size() / slots_per_transition) - 1;
}
/**
* @return Return the number of states in the tree.
*/
public final int getStatesCount()
{
return this.states.size() - 1;
}
/**
* @return <code>true</code> if this suffix tree has a path from the root state to a
* leaf state corresponding to a given sequence of objects. This indicates the
* input sequence had a suffix identical to <code>sequence</code>.
*/
public boolean containsSuffix(ISequence seq)
{
int state = root;
int i = 0;
while (true)
{
// Find an edge leaving the current state marked with symbol sequence[i].
final int edge = findEdge(state, seq.objectAt(i));
if (edge < 0)
{
// Different characters on explicit state.
return false;
}
// Follow the edge, checking symbols on the way.
int j = getStartIndex(edge);
final int m = getEndIndex(edge) + 1;
for (;i < seq.size() && j < m; j++, i++)
{
if (seq.objectAt(i) != this.sequence.objectAt(j))
{
// Different characters on implicit state.
return false;
}
}
if (i == seq.size())
{
// End of input sequence must be aligned with the tree's leaf state.
return j == inputSize;
}
// Follow to the child state.
state = getToState(edge);
}
}
/**
* Walks the states and edges of the suffix tree, depth-first.
*/
public final void visit(final IVisitor visitor)
{
visitState(root, visitor);
}
/**
* Start visiting from a given state.
*/
public final void visitState(final int state, final IVisitor visitor)
{
if (visitor.pre(state))
{
int edge = firstEdge(state);
while (edge != NO_EDGE)
{
final int toState = transitions.get(edge);
if (visitor.edge(state, toState, getStartIndex(edge), getEndIndex(edge)))
{
visitState(toState, visitor);
}
edge = nextEdge(edge);
}
visitor.post(state);
}
}
/**
* For procedural traversals (not visitors).
*/
public int getRootState()
{
return root;
}
/**
* Check if <code>state</code> is a leaf (has no outgoing edges).
*/
public final boolean isLeaf(int state)
{
return this.states.get(state) == LEAF_STATE;
}
/**
* Returns the index of the first edge from a given state or {@link #NO_EDGE} if a
* given state has no edges. Does not perform any sanity check on the input state.
*/
public final int firstEdge(int state)
{
return states.get(state);
}
/**
* Returns the index of the next edge (sibling) or {@link #NO_EDGE} if
* <code>edge</code> is the last edge in its state.
*/
public final int nextEdge(int edge)
{
return transitions.get(edge + 3);
}
/**
* Find a transition from state <code>state</code>, labeled with a given symbol.
* {@link #NO_EDGE} is returned if there is no such edge.
*/
public final int findEdge(int state, int symbol)
{
return transitions_map.getOrDefault(asLong(state, symbol), NO_EDGE);
}
/**
* Returns the target state for a given edge.
*/
public int getToState(int edge)
{
return transitions.get(edge);
}
/**
* Returns the edge label's start index (inclusive).
*/
public int getStartIndex(int edge)
{
return transitions.get(edge + 1) - 1;
}
/**
* Returns the edge label's end index (inclusive).
*/
public int getEndIndex(int edge)
{
return transitions.get(edge + 2) - 1;
}
}
|
MjAbuz/carrot2
|
core/carrot2-algorithm-stc/src/org/carrot2/text/suffixtree/SuffixTree.java
|
Java
|
bsd-3-clause
| 15,553 |
// Copyright (c) 2012 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.
#ifndef CHROME_BROWSER_FILE_SELECT_HELPER_H_
#define CHROME_BROWSER_FILE_SELECT_HELPER_H_
#include <map>
#include <memory>
#include <vector>
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/scoped_observation.h"
#include "build/build_config.h"
#include "components/safe_browsing/buildflags.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_observer.h"
#include "content/public/browser/web_contents_observer.h"
#include "net/base/directory_lister.h"
#include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#if BUILDFLAG(FULL_SAFE_BROWSING)
#include "chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.h"
#endif
class Profile;
namespace content {
class FileSelectListener;
class WebContents;
}
namespace ui {
struct SelectedFileInfo;
}
// This class handles file-selection requests coming from renderer processes.
// It implements both the initialisation and listener functions for
// file-selection dialogs.
//
// Since FileSelectHelper listens to observations of a widget, it needs to live
// on and be destroyed on the UI thread. References to FileSelectHelper may be
// passed on to other threads.
class FileSelectHelper : public base::RefCountedThreadSafe<
FileSelectHelper,
content::BrowserThread::DeleteOnUIThread>,
public ui::SelectFileDialog::Listener,
public content::WebContentsObserver,
public content::RenderWidgetHostObserver,
private net::DirectoryLister::DirectoryListerDelegate {
public:
FileSelectHelper(const FileSelectHelper&) = delete;
FileSelectHelper& operator=(const FileSelectHelper&) = delete;
// Show the file chooser dialog.
static void RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params);
// Enumerates all the files in directory.
static void EnumerateDirectory(
content::WebContents* tab,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path);
private:
friend class base::RefCountedThreadSafe<FileSelectHelper>;
friend class base::DeleteHelper<FileSelectHelper>;
friend class FileSelectHelperContactsAndroid;
friend struct content::BrowserThread::DeleteOnThread<
content::BrowserThread::UI>;
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, IsAcceptTypeValid);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, ZipPackage);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, GetSanitizedFileName);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, LastSelectedDirectory);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
ContentAnalysisCompletionCallback_NoFiles);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
ContentAnalysisCompletionCallback_OneOKFile);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
ContentAnalysisCompletionCallback_TwoOKFiles);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
ContentAnalysisCompletionCallback_TwoBadFiles);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest,
ContentAnalysisCompletionCallback_OKBadFiles);
FRIEND_TEST_ALL_PREFIXES(FileSelectHelperTest, GetFileTypesFromAcceptType);
explicit FileSelectHelper(Profile* profile);
~FileSelectHelper() override;
void RunFileChooser(content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
blink::mojom::FileChooserParamsPtr params);
void GetFileTypesInThreadPool(blink::mojom::FileChooserParamsPtr params);
void GetSanitizedFilenameOnUIThread(
blink::mojom::FileChooserParamsPtr params);
#if BUILDFLAG(FULL_SAFE_BROWSING)
void CheckDownloadRequestWithSafeBrowsing(
const base::FilePath& default_path,
blink::mojom::FileChooserParamsPtr params);
void ProceedWithSafeBrowsingVerdict(const base::FilePath& default_path,
blink::mojom::FileChooserParamsPtr params,
bool allowed_by_safe_browsing);
#endif
void RunFileChooserOnUIThread(const base::FilePath& default_path,
blink::mojom::FileChooserParamsPtr params);
// Cleans up and releases this instance. This must be called after the last
// callback is received from the file chooser dialog.
void RunFileChooserEnd();
// SelectFileDialog::Listener overrides.
void FileSelected(const base::FilePath& path,
int index,
void* params) override;
void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file,
int index,
void* params) override;
void MultiFilesSelected(const std::vector<base::FilePath>& files,
void* params) override;
void MultiFilesSelectedWithExtraInfo(
const std::vector<ui::SelectedFileInfo>& files,
void* params) override;
void FileSelectionCanceled(void* params) override;
// content::RenderWidgetHostObserver overrides.
void RenderWidgetHostDestroyed(
content::RenderWidgetHost* widget_host) override;
// content::WebContentsObserver overrides.
void RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) override;
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
void WebContentsDestroyed() override;
void EnumerateDirectoryImpl(
content::WebContents* tab,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path);
// Kicks off a new directory enumeration.
void StartNewEnumeration(const base::FilePath& path);
// net::DirectoryLister::DirectoryListerDelegate overrides.
void OnListFile(
const net::DirectoryLister::DirectoryListerData& data) override;
void OnListDone(int error) override;
void LaunchConfirmationDialog(
const base::FilePath& path,
std::vector<ui::SelectedFileInfo> selected_files);
// Cleans up and releases this instance. This must be called after the last
// callback is received from the enumeration code.
void EnumerateDirectoryEnd();
#if defined(OS_MAC)
// Must be called from a MayBlock() task. Each selected file that is a package
// will be zipped, and the zip will be passed to the render view host in place
// of the package.
void ProcessSelectedFilesMac(const std::vector<ui::SelectedFileInfo>& files);
// Saves the paths of |zipped_files| for later deletion. Passes |files| to the
// render view host.
void ProcessSelectedFilesMacOnUIThread(
const std::vector<ui::SelectedFileInfo>& files,
const std::vector<base::FilePath>& zipped_files);
// Zips the package at |path| into a temporary destination. Returns the
// temporary destination, if the zip was successful. Otherwise returns an
// empty path.
static base::FilePath ZipPackage(const base::FilePath& path);
#endif // defined(OS_MAC)
// This function is the start of a call chain that may or may not be async
// depending on the platform and features enabled. The call to this method
// is made after the user has chosen the file(s) in the UI in order to
// process and filter the list before returning the final result to the
// caller. The call chain is as follows:
//
// ConvertToFileChooserFileInfoList: converts a vector of SelectedFileInfo
// into a vector of FileChooserFileInfoPtr and then calls
// PerformContentAnalysisIfNeeded(). On chromeos, the conversion is
// performed asynchronously.
//
// PerformContentAnalysisIfNeeded: if the deep scanning feature is
// enabled and it is determined by enterprise policy that scans are required,
// starts the scans and sets ContentAnalysisCompletionCallback() as the async
// callback. If deep scanning is not enabled or is not supported on the
// platform, this function calls NotifyListenerAndEnd() directly.
//
// ContentAnalysisCompletionCallback: processes the results of the deep scan.
// Any files that did not pass the scan are removed from the list. Ends by
// calling NotifyListenerAndEnd().
//
// NotifyListenerAndEnd: Informs the listener of the final list of files to
// use and performs any required cleanup.
//
// Because the state of the web contents may change at each asynchronous
// step, calls are make to AbortIfWebContentsDestroyed() to check if, for
// example, the tab has been closed or the contents navigated. In these
// cases the file selection is aborted and the state cleaned up.
void ConvertToFileChooserFileInfoList(
const std::vector<ui::SelectedFileInfo>& files);
// Checks to see if scans are required for the specified files.
void PerformContentAnalysisIfNeeded(
std::vector<blink::mojom::FileChooserFileInfoPtr> list);
#if BUILDFLAG(FULL_SAFE_BROWSING)
// Callback used to receive the results of a content analysis scan.
void ContentAnalysisCompletionCallback(
std::vector<blink::mojom::FileChooserFileInfoPtr> list,
const enterprise_connectors::ContentAnalysisDelegate::Data& data,
const enterprise_connectors::ContentAnalysisDelegate::Result& result);
#endif
// Finish the PerformContentAnalysisIfNeeded() handling after the
// deep scanning checks have been performed. Deep scanning may change the
// list of files chosen by the user, so the list of files passed here may be
// a subset of of the files passed to PerformContentAnalysisIfNeeded().
void NotifyListenerAndEnd(
std::vector<blink::mojom::FileChooserFileInfoPtr> list);
// Schedules the deletion of the files in |temporary_files_| and clears the
// vector.
void DeleteTemporaryFiles();
// Cleans up when the initiator of the file chooser is no longer valid.
void CleanUp();
// Calls RunFileChooserEnd() if the webcontents was destroyed. Returns true
// if the file chooser operation shouldn't proceed.
bool AbortIfWebContentsDestroyed();
void SetFileSelectListenerForTesting(
scoped_refptr<content::FileSelectListener> listener);
void DontAbortOnMissingWebContentsForTesting();
// Helper method to get allowed extensions for select file dialog from
// the specified accept types as defined in the spec:
// http://whatwg.org/html/number-state.html#attr-input-accept
// |accept_types| contains only valid lowercased MIME types or file extensions
// beginning with a period (.).
static std::unique_ptr<ui::SelectFileDialog::FileTypeInfo>
GetFileTypesFromAcceptType(const std::vector<std::u16string>& accept_types);
// Check the accept type is valid. It is expected to be all lower case with
// no whitespace.
static bool IsAcceptTypeValid(const std::string& accept_type);
// Get a sanitized filename suitable for use as a default filename. The
// suggested filename coming over the IPC may contain invalid characters or
// may result in a filename that's reserved on the current platform.
//
// If |suggested_path| is empty, the return value is also empty.
//
// If |suggested_path| is non-empty, but can't be safely converted to UTF-8,
// or is entirely lost during the sanitization process (e.g. because it
// consists entirely of invalid characters), it's replaced with a default
// filename.
//
// Otherwise, returns |suggested_path| with any invalid characters will be
// replaced with a suitable replacement character.
static base::FilePath GetSanitizedFileName(
const base::FilePath& suggested_path);
// Profile used to set/retrieve the last used directory.
Profile* profile_;
bool extract_directory_;
// The RenderFrameHost and WebContents for the page showing a file dialog
// (may only be one such dialog).
content::RenderFrameHost* render_frame_host_;
content::WebContents* web_contents_;
// |listener_| receives the result of the FileSelectHelper.
scoped_refptr<content::FileSelectListener> listener_;
// Dialog box used for choosing files to upload from file form fields.
scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
std::unique_ptr<ui::SelectFileDialog::FileTypeInfo> select_file_types_;
// The type of file dialog last shown. This is SELECT_NONE if an
// instance is created through the public EnumerateDirectory().
ui::SelectFileDialog::Type dialog_type_;
// The mode of file dialog last shown.
blink::mojom::FileChooserParams::Mode dialog_mode_;
// The enumeration root directory for EnumerateDirectory() and
// RunFileChooser with kUploadFolder.
base::FilePath base_dir_;
// Maintain an active directory enumeration. These could come from the file
// select dialog or from drag-and-drop of directories. There could not be
// more than one going on at a time.
struct ActiveDirectoryEnumeration;
std::unique_ptr<ActiveDirectoryEnumeration> directory_enumeration_;
base::ScopedObservation<content::RenderWidgetHost,
content::RenderWidgetHostObserver>
observation_{this};
// Temporary files only used on OSX. This class is responsible for deleting
// these files when they are no longer needed.
std::vector<base::FilePath> temporary_files_;
// Set to false in unit tests since there is no WebContents.
bool abort_on_missing_web_contents_in_tests_ = true;
};
#endif // CHROME_BROWSER_FILE_SELECT_HELPER_H_
|
nwjs/chromium.src
|
chrome/browser/file_select_helper.h
|
C
|
bsd-3-clause
| 13,939 |
//
// Copyright 2002 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ExtensionBehavior.h: Extension name enumeration and data structures for storing extension
// behavior.
#ifndef COMPILER_TRANSLATOR_EXTENSIONBEHAVIOR_H_
#define COMPILER_TRANSLATOR_EXTENSIONBEHAVIOR_H_
#include <map>
namespace sh
{
enum class TExtension
{
UNDEFINED, // Special value used to indicate no extension.
ARB_texture_rectangle,
ANGLE_texture_multisample,
ARM_shader_framebuffer_fetch,
EXT_blend_func_extended,
EXT_draw_buffers,
EXT_frag_depth,
EXT_geometry_shader,
EXT_shader_framebuffer_fetch,
EXT_shader_texture_lod,
EXT_YUV_target,
NV_EGL_stream_consumer_external,
NV_shader_framebuffer_fetch,
OES_EGL_image_external,
OES_EGL_image_external_essl3,
OES_standard_derivatives,
OES_texture_storage_multisample_2d_array,
OES_texture_3D,
OVR_multiview,
OVR_multiview2,
ANGLE_multi_draw,
ANGLE_base_vertex_base_instance
};
enum TBehavior
{
EBhRequire,
EBhEnable,
EBhWarn,
EBhDisable,
EBhUndefined
};
const char *GetExtensionNameString(TExtension extension);
TExtension GetExtensionByName(const char *extension);
const char *GetBehaviorString(TBehavior b);
// Mapping between extension id and behavior.
typedef std::map<TExtension, TBehavior> TExtensionBehavior;
bool IsExtensionEnabled(const TExtensionBehavior &extBehavior, TExtension extension);
} // namespace sh
#endif // COMPILER_TRANSLATOR_EXTENSIONBEHAVIOR_H_
|
youtube/cobalt
|
third_party/angle/src/compiler/translator/ExtensionBehavior.h
|
C
|
bsd-3-clause
| 1,624 |
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="../../support/github-web/physcomp.css" />
<title>Smart Machines: Overview</title>
</head>
<body>
<h2>Smart Machines: Overview</h2>
<p>This section is about encoding <em>behavior</em> in machines, where
behavior is loosely interpreted as the response of a machine to a varying
environment in order to achieve an implicit goal. At the limit, this
encompasses all of robotics. However, machines can achieve their smarts
through many means including physical form which passively interacts with
the world, mechanical action which responds to forces, and computational
models which span complexity from simple reflex reactivity to detailed
world models.</p>
<h3>Takeaway Lessons</h3>
<p>Machines have parts which move relative to each other; the elements or
surfaces where relative motion occurs are <em>bearings</em> and serve the
functions of controlling relative motion and friction. These can be
rolling-contact devices such as <em>ball bearings</em> in which small
steel balls roll between concentric surfaces, but many common bearings
are <em>plain bearings</em> in which two surfaces simply slide over each
other. Even a book sliding on a table can be considered to be using a
planar sliding bearing formed by the book jacket and the smooth table: the
shape constrains motion to the plane, and the smooth materials limit
friction.</p>
<p>The common types of bearing components we will use are <em>bushings</em>
and ball bearings. Bushings are plain bearings made from a low-friction
material such as bronze.</p>
<p>The key principles of shaft bearing design are to consider the <em>radial
force</em> acting perpendicular to the shaft, the <em>axial force</em>
(or <em>thrust</em>) acting along the shaft, the <em>bending
moments</em> induced by the loads, and the <em>torque</em> carried by
the shaft.</p>
<p>Most ball bearings have limits on the moments they can support, so a good
rule of thumb is to <em>always use bearings in pairs</em> such that the
shaft bending moments are counted by radial forces.</p>
<p>Common ball bearings can support higher radial loads than axial
loads. <em>Thrust bearings</em> are specifically designed to carry axial
loads, such as in a turntable.</p>
<p>Electric motors are generally high-speed low-torque devices. Actuating a
mechanism almost always requires some form of <em>transmission</em> to
reduce speed and increase torque to match a load.</p>
<p>For our purposes, transmissions will be built from rollers, timing
pulleys and belts, winches and cable drives, and gears. These are
mechanisms with constant-ratio <em>transfer functions</em> in which an
input to output velocities have a fixed ratio.</p>
<p>In general, any mechanism with a transfer function between input and
output can act as a type of transmission. Structures with non-constant
ratios include levers, cams, and linkages.</p>
<p>Gear tooth design comes down to a straighforward idea: find compatible
shapes which interact to produce a constant velocity ratio from input to
output. The classic involute gear tooth shape essentially creates the
simple input-output behavior of two non-slipping rollers, but with the
increased load capacity of face contact instead of frictional contact.</p>
<p>In practice, gears have many problems: the teeth must slide across each
other, creating noise and friction; involute teeth induce forces which
press the gears apart; high-torque metal gears are often expensive
precision parts. However, low-cost gears can be laser-cut and careful
attention to shaft stiffness can manage tooth pressure forces.</p>
<p>Other common design problems we will face: attaching gears and pulleys to
shafts; mounting motors and actuators; attaching feedback sensors; using
bearings to reduce friction; translating rotational to linear motion;
building rigid structures; designing for assembly; creating 3D structures
from flat parts; creating snap-fit and locking features; designing using
standard parts and fasteners.</p>
<h3>Reference Links</h3>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Simple_machine">Wikipedia: Simple Machines</a></li>
<li><a href="http://en.wikipedia.org/wiki/Kinematic_pair">Wikipedia: Kinematic Pairs</a></li>
<li><a href="http://en.wikipedia.org/wiki/Involute_gear">Wikipedia: Involute Gear</a></li>
<li><a href="http://en.wikipedia.org/wiki/Bearing_%28mechanical%29">Wikipedia: Bearing</a></li>
<li><a href="http://books.google.com/books?id=vOhIAAAAMAAJ&dq=mechanical%20movements&pg=PR1#v=onepage&q&f=false">Google Books: 507 Mechanical Movements</a></li>
<li><a href="http://books.google.com/books?id=LlYSAAAAIAAJ&dq=mechanical%20movements&pg=PP1#v=onepage&q&f=false">Google
Books: The Engineer's Sketch-book of Mechanical Movements, Devices,
Appliances, Contrivances, and Details</a></li>
</ol>
<h3>Resource Links</h3>
<ol>
<li><a href="http://www.thingiverse.com/thing:16627">Parametric pulley - lots of tooth profiles</a></li>
<li><a href="http://hessmer.org/gears/InvoluteSpurGearBuilder.html">Involute Spur Gear Builder</a></li>
<li><a href="http://woodgears.ca/gear_cutting/template.html">Gear template generator</a></li>
<li><a href="http://www.thingiverse.com/thing:7881">Gear Profile Generator</a></li>
<li><a href="http://boxmaker.rahulbotics.com/">BoxMaker</a></li>
<li><a href="http://www.thingiverse.com/">thingiverse</a></li>
<li><a href="https://sketchfab.com/">sketchfab</a></li>
<li><a href="https://3dwarehouse.sketchup.com/">3D Warehouse</a></li>
<li><a href="http://www.3dcontentcentral.com/">3D Content Central</a></li>
</ol>
<hr/><!-- --------------------------------------------------------------- -->
<h3>Lab Exercises</h3>
<p>The lab exercises are intended to be performed by pairs of students or
small groups.</p>
<hr/><!-- --------------------------------------------------------------- -->
<h3>Graded Project:</h3>
<hr/><!-- --------------------------------------------------------------- -->
<h3>Challenge Yourself</h3>
<!-- --------------------------------------------------------------- -->
<h3>Examples</h3>
<p>Inspiration for project ideas can be found on
the <a href="http://physcomp.org/wow/">course website</a>.</p>
<h4>Sub-Folders</h4>
<ol>
<li><a href="i_mechanical-intelligence">i_mechanical-intelligence</a></li>
<li><a href="ii_mapping-arithmetic">ii_mapping-arithmetic</a></li>
<li><a href="iii_machine-learning">iii_machine-learning</a></li>
</ol>
</body>
</html>
|
cmuphyscomp/physcomp-examples
|
2_super-machines/a_smart-machines/index.html
|
HTML
|
bsd-3-clause
| 7,082 |
import os
import json
import logging
class CloudFoundryLoginError(Exception):
"""
A Cloud Foundry Login Error will be raised when the operation
is not permitted due to an invalid token.
"""
def __init__(self, message):
super(CloudFoundryLoginError, self).__init__(message)
logging.warning("Try 'cf login' to get a new token from Cloud Foundry (%s)." % (message))
class Config(object):
"""
Interface into a cached cloud foundry configuration file.
"""
def __init__(self, config_file='~/.cf/config.json', *args, **kwargs):
super(Config, self).__init__(*args, **kwargs)
logging.debug("Using CF config file: %s" % (config_file))
self.config_file = config_file
self.config = self._get_cloud_foundry_config()
def _get_cloud_foundry_config(self):
"""
Reads the local cf CLI cache stored in the users
home directory.
"""
config = os.path.expanduser(self.config_file)
if not os.path.exists(config):
raise CloudFoundryLoginError('You must run `cf login` to authenticate')
with open(config, "r") as data:
return json.load(data)
def get_access_token(self):
"""
Returns the access token from the cache, including the
"Bearer" identifier.
"""
return self.config['AccessToken']
def get_uaa_endpoint(self):
"""
Returns the UAA endpoint used for Predix Cloud Foundry
authentication.
"""
return self.config['UaaEndpoint']
def get_target(self):
"""
Returns the API target URI.
"""
return self.config['Target']
def _get_organization_info(self):
"""
Returns all cached information about the org.
"""
return self.config['OrganizationFields']
def get_organization_name(self):
"""
Returns the name of the organization currently targeted.
"""
if 'PREDIX_ORGANIZATION_NAME' in os.environ:
return os.environ['PREDIX_ORGANIZATION_NAME']
else:
return self._get_organization_info()['Name']
def get_organization_guid(self):
"""
Returns the GUID for the organization currently targeted.
"""
if 'PREDIX_ORGANIZATION_GUID' in os.environ:
return os.environ['PREDIX_ORGANIZATION_GUID']
else:
info = self._get_organization_info()
for key in ('Guid', 'GUID'):
if key in info.keys():
return info[key]
raise ValueError('Unable to determine cf organization guid')
def _get_space_info(self):
"""
Returns all cached information about the space.
"""
return self.config['SpaceFields']
def get_space_name(self):
"""
Returns the name of the space currently targeted.
"""
if 'PREDIX_SPACE_NAME' in os.environ:
return os.environ['PREDIX_SPACE_NAME']
else:
return self._get_space_info()['Name']
def get_space_guid(self):
"""
Returns the GUID for the space currently targeted.
Can be set by environment variable with PREDIX_SPACE_GUID.
Can be determined by ~/.cf/config.json.
"""
if 'PREDIX_SPACE_GUID' in os.environ:
return os.environ['PREDIX_SPACE_GUID']
else:
info = self._get_space_info()
for key in ('Guid', 'GUID'):
if key in info.keys():
return info[key]
raise ValueError('Unable to determine cf space guid')
|
j12y/predixpy
|
predix/admin/cf/config.py
|
Python
|
bsd-3-clause
| 3,655 |
namespace Coevery.Core.Settings.Metadata.Records {
public class ContentFieldDefinitionRecord {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
}
|
Coevery/Coevery-Framework
|
src/Coevery.Web/Core/Settings/Metadata/Records/ContentFieldDefinitionRecord.cs
|
C#
|
bsd-3-clause
| 200 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.