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
#pragma once #include <iostream> #include <vector> void sort_article_files(std::istream& article_titles_file, std::istream& article_dates_file, std::ostream& article_titles_output_file, std::ostream& article_dates_output_file); void sort_category_files(std::istream& category_titles_file, std::ostream& category_titles_output_file);
bencabrera/wikiMainPath
src/parsers/helpers/sortTitlesHelper.h
C
mit
335
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // Portions of this file are sourced from // chrome/browser/ui/views/frame/browser_desktop_window_tree_host_linux.cc, // Copyright (c) 2019 The Chromium Authors, // which is governed by a BSD-style license #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include <vector> #include "base/i18n/rtl.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/platform_window/platform_window.h" #include "ui/views/linux_ui/linux_ui.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_linux.h" #include "ui/views/window/non_client_view.h" namespace electron { ElectronDesktopWindowTreeHostLinux::ElectronDesktopWindowTreeHostLinux( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostLinux(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostLinux::~ElectronDesktopWindowTreeHostLinux() = default; bool ElectronDesktopWindowTreeHostLinux::SupportsClientFrameShadow() const { return platform_window()->CanSetDecorationInsets() && platform_window()->IsTranslucentWindowOpacitySupported(); } void ElectronDesktopWindowTreeHostLinux::OnWidgetInitDone() { views::DesktopWindowTreeHostLinux::OnWidgetInitDone(); UpdateFrameHints(); } void ElectronDesktopWindowTreeHostLinux::OnBoundsChanged( const BoundsChange& change) { views::DesktopWindowTreeHostLinux::OnBoundsChanged(change); UpdateFrameHints(); } void ElectronDesktopWindowTreeHostLinux::OnWindowStateChanged( ui::PlatformWindowState old_state, ui::PlatformWindowState new_state) { views::DesktopWindowTreeHostLinux::OnWindowStateChanged(old_state, new_state); UpdateFrameHints(); } void ElectronDesktopWindowTreeHostLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateFrameHints(); } void ElectronDesktopWindowTreeHostLinux::OnDeviceScaleFactorChanged() { UpdateFrameHints(); } void ElectronDesktopWindowTreeHostLinux::UpdateFrameHints() { if (SupportsClientFrameShadow() && native_window_view_->has_frame() && native_window_view_->has_client_frame()) { UpdateClientDecorationHints(static_cast<ClientFrameViewLinux*>( native_window_view_->widget()->non_client_view()->frame_view())); } SizeConstraintsChanged(); } void ElectronDesktopWindowTreeHostLinux::UpdateClientDecorationHints( ClientFrameViewLinux* view) { ui::PlatformWindow* window = platform_window(); bool showing_frame = !native_window_view_->IsFullscreen(); float scale = device_scale_factor(); bool should_set_opaque_region = window->IsTranslucentWindowOpacitySupported(); gfx::Insets insets; gfx::Insets input_insets; if (showing_frame) { insets = view->GetBorderDecorationInsets(); if (base::i18n::IsRTL()) { insets.Set(insets.top(), insets.right(), insets.bottom(), insets.left()); } input_insets = view->GetInputInsets(); } gfx::Insets scaled_insets = gfx::ScaleToCeiledInsets(insets, scale); window->SetDecorationInsets(&scaled_insets); gfx::Rect input_bounds(view->GetWidget()->GetWindowBoundsInScreen().size()); input_bounds.Inset(insets + input_insets); gfx::Rect scaled_bounds = gfx::ScaleToEnclosingRect(input_bounds, scale); window->SetInputRegion(&scaled_bounds); if (should_set_opaque_region) { // The opaque region is a list of rectangles that contain only fully // opaque pixels of the window. We need to convert the clipping // rounded-rect into this format. SkRRect rrect = view->GetRoundedWindowContentBounds(); gfx::RectF rectf(view->GetWindowContentBounds()); rectf.Scale(scale); // It is acceptable to omit some pixels that are opaque, but the region // must not include any translucent pixels. Therefore, we must // conservatively scale to the enclosed rectangle. gfx::Rect rect = gfx::ToEnclosedRect(rectf); // Create the initial region from the clipping rectangle without rounded // corners. SkRegion region(gfx::RectToSkIRect(rect)); // Now subtract out the small rectangles that cover the corners. struct { SkRRect::Corner corner; bool left; bool upper; } kCorners[] = { {SkRRect::kUpperLeft_Corner, true, true}, {SkRRect::kUpperRight_Corner, false, true}, {SkRRect::kLowerLeft_Corner, true, false}, {SkRRect::kLowerRight_Corner, false, false}, }; for (const auto& corner : kCorners) { auto radii = rrect.radii(corner.corner); auto rx = std::ceil(scale * radii.x()); auto ry = std::ceil(scale * radii.y()); auto corner_rect = SkIRect::MakeXYWH( corner.left ? rect.x() : rect.right() - rx, corner.upper ? rect.y() : rect.bottom() - ry, rx, ry); region.op(corner_rect, SkRegion::kDifference_Op); } // Convert the region to a list of rectangles. std::vector<gfx::Rect> opaque_region; for (SkRegion::Iterator i(region); !i.done(); i.next()) opaque_region.push_back(gfx::SkIRectToRect(i.rect())); window->SetOpaqueRegion(&opaque_region); } } } // namespace electron
electron/electron
shell/browser/ui/electron_desktop_window_tree_host_linux.cc
C++
mit
5,522
#pragma once #include <fstream> #include <iostream> #include <string> #include <vector> #include <string.h> #include "Light/Colour.hpp" namespace Graphics { class Image { private: // Colour* pixels; std::vector<Colour> pixels; unsigned char* int_to_chararr(unsigned int val); public: Image(int width, int height); Image(int width, int height, Colour bg); ~Image(); inline Colour& operator() (int x, int y); inline Colour operator() (int x, int y) const; const int width; const int height; bool write_to_file(const std::string &path); }; /* Image grid *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ inline Colour& Image::operator() (int x, int y) { return pixels[x+y*width]; } inline Colour Image::operator() (int x, int y) const { return pixels[x+y*width]; } }
brgmnn/uob-raytracer
src/Image.hpp
C++
mit
840
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Mon Sep 01 21:58:18 IST 2014 --> <title>DirectByteArrayOutputStream</title> <meta name="date" content="2014-09-01"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DirectByteArrayOutputStream"; } } catch(err) { } //--> var methods = {"i0":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DirectByteArrayOutputStream.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/security/crypt/io/CredentialReader.html" title="interface in org.security.crypt.io"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/security/crypt/io/HexFilterInputStream.html" title="class in org.security.crypt.io"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/security/crypt/io/DirectByteArrayOutputStream.html" target="_top">Frames</a></li> <li><a href="DirectByteArrayOutputStream.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.security.crypt.io</div> <h2 title="Class DirectByteArrayOutputStream" class="title">Class DirectByteArrayOutputStream</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.io.OutputStream</li> <li> <ul class="inheritance"> <li>java.io.ByteArrayOutputStream</li> <li> <ul class="inheritance"> <li>org.security.crypt.io.DirectByteArrayOutputStream</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Closeable, java.io.Flushable, java.lang.AutoCloseable</dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">DirectByteArrayOutputStream</span> extends java.io.ByteArrayOutputStream</pre> <div class="block">Extends <code>ByteArrayOutputStream</code> by allowing direct access to the internal byte buffer.</div> <dl> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>shivam</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/security/crypt/io/DirectByteArrayOutputStream.html#DirectByteArrayOutputStream--">DirectByteArrayOutputStream</a></span>()</code> <div class="block">Creates a new instance with a buffer of the default size.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/security/crypt/io/DirectByteArrayOutputStream.html#DirectByteArrayOutputStream-int-">DirectByteArrayOutputStream</a></span>(int&nbsp;capacity)</code> <div class="block">Creates a new instance with a buffer of the given initial capacity.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>byte[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/security/crypt/io/DirectByteArrayOutputStream.html#getBuffer--">getBuffer</a></span>()</code> <div class="block">Gets the internal byte buffer.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.io.ByteArrayOutputStream"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.io.ByteArrayOutputStream</h3> <code>close, reset, size, toByteArray, toString, toString, toString, write, write, writeTo</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.io.OutputStream"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.io.OutputStream</h3> <code>flush, write</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DirectByteArrayOutputStream--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DirectByteArrayOutputStream</h4> <pre>public&nbsp;DirectByteArrayOutputStream()</pre> <div class="block">Creates a new instance with a buffer of the default size.</div> </li> </ul> <a name="DirectByteArrayOutputStream-int-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DirectByteArrayOutputStream</h4> <pre>public&nbsp;DirectByteArrayOutputStream(int&nbsp;capacity)</pre> <div class="block">Creates a new instance with a buffer of the given initial capacity.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>capacity</code> - Initial capacity of internal buffer.</dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getBuffer--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getBuffer</h4> <pre>public&nbsp;byte[]&nbsp;getBuffer()</pre> <div class="block">Gets the internal byte buffer.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>Internal buffer that holds written bytes.</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DirectByteArrayOutputStream.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/security/crypt/io/CredentialReader.html" title="interface in org.security.crypt.io"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/security/crypt/io/HexFilterInputStream.html" title="class in org.security.crypt.io"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/security/crypt/io/DirectByteArrayOutputStream.html" target="_top">Frames</a></li> <li><a href="DirectByteArrayOutputStream.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
shivam091/Java-Security
crypt/doc/org/security/crypt/io/DirectByteArrayOutputStream.html
HTML
mit
11,576
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Projekt Zespołowy Coin address (e.g. Ger4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { #if QT_VERSION < 0x050000 formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); #else formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address)); #endif } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed!"), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->deleteLater(); updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::setAddress(const QString &address) { SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setVisible((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid Bitcoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
kryptokredyt/ProjektZespolowyCoin
src/qt/sendcoinsdialog.cpp
C++
mit
18,560
<section id="form" ng-show="data"> <div id="banner"> <div class="content"> BANNER </div> </div> <div class="ui stackable grid"> <div class="four wide column"> </div> <div class="eight wide column"> <div class="ui form basic segment"> <div class="field"> <h1> {{ data.title }}</h1> </div> <div class="field"> <label>Description</label> <div class="ui labeled input"> <input type="text" placeholder="Description" ng-model="data.description"> </div> </div> <div class="field"> <label>Name</label> <div class="ui labeled input"> <input type="text" placeholder="Name" ng-model="data.name"> </div> </div> <div class="field"> <label>Email</label> <div class="ui labeled input"> <input type="email" placeholder="Username" ng-model="data.email"> </div> </div> <div class="field"> <label>Age</label> <div class="ui labeled input"> <input type="number" placeholder="Username" ng-model="data.age"> </div> </div> <div class="field"> <label>Height</label> <div class="ui labeled input"> <input type="number" placeholder="Username" ng-model="data.height"> </div> </div> <div class="ui error message"> <div class="header">We noticed some issues</div> </div> <div class="ui purple fluid submit button" ng-click="submit()">Save</div> </div> </div> <div class="four wide column"></div> </div> <div class="ui page dimmer"> <div class="content"> <div class="center"> <i class="huge ui green emphasized checkmark icon"></i> <h2> Successfully updated! </h2> </div> </div> </div> </section>
ehzhang/reforms
client/partials/form.html
HTML
mit
2,136
object Main { def main(args: Array[String]) = for (arg <- args) println(arg) }
mkoltsov/AtomicScala
Advanced/OldApp.scala
Scala
mit
82
# # rm-macl/lib/rm-macl/xpan/vector/vector4.rb # by IceDragon require 'rm-macl/macl-core' require 'rm-macl/core_ext/module' require 'rm-macl/xpan/vector/vector' require 'rm-macl/xpan/type-stub' module MACL class Vector4 < Vector def initialize(x, y, z, w) super(4) self.x = x self.y = y self.z = z self.w = w end def x self[0] end def y self[1] end def z self[2] end def w self[3] end def x=(n) self[0] = n end def y=(n) self[1] = n end def z=(n) self[2] = n end def w=(n) self[3] = n end tcast_set(Numeric) { |n| new(n, n, n, n) } tcast_set(Array) { |a| new(a[0], a[1], a[2], a[3]) } tcast_set(self) { |s| new(s.x, s.y, s.z, s.w) } tcast_set(:default) { |s| s.to_vector4 } end end MACL.register('macl/xpan/vector/vector4', '2.0.0')
IceDragon200/rm-macl
lib/rm-macl/xpan/vector/vector4.rb
Ruby
mit
975
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace Application\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; use Zend\View\Model\JsonModel; use Application\Service\HubServiceInterface; use Application\Factory\Component\PaginatedTableFactory; use Application\Utils\Aggregate; use Application\Utils\DateAggregate; use Application\Utils\Order; use Application\Utils\DbConsts\DbViewVotes; use Application\Utils\DbConsts\DbViewFans; use Application\Utils\DbConsts\DbViewPagesAll; /** * Description of UserController * * @author Alexander */ class UserController extends AbstractActionController { /** * * @var Application\Service\ServiceHubInterface */ protected $services; protected function getFans($userId, $siteId, $byRatio, $limit = 10) { $fans = $this->services->getVoteService()->getUserBiggestFans($userId, $siteId, $byRatio, true); $fans->setCurrentPageNumber(1); $fans->setItemCountPerPage($limit); $result = []; $userPrototype = new \Application\Model\User($this->getServiceLocator()->get('UserActivityMapper'), $this->getServiceLocator()->get('MembershipMapper')); foreach ($fans as $fan) { $user = clone $userPrototype; $user->setId($fan[DbViewFans::USERID]); $user->setDisplayName($fan[DbViewFans::USERDISPLAYNAME]); $user->setDeleted($fan[DbViewFans::USERDELETED]); $result[] = [ 'user' => $user, 'positive' => $fan[DbViewFans::POSITIVE], 'negative' => $fan[DbViewFans::NEGATIVE] ]; } return $result; } protected function getFavoriteAuthors($userId, $siteId, $byRatio, $limit = 10) { $favs = $this->services->getVoteService()->getUserFavoriteAuthors($userId, $siteId, $byRatio, true); $favs->setCurrentPageNumber(1); $favs->setItemCountPerPage($limit); $result = []; $userPrototype = new \Application\Model\User($this->getServiceLocator()->get('UserActivityMapper'), $this->getServiceLocator()->get('MembershipMapper')); foreach ($favs as $fav) { $user = clone $userPrototype; $user->setId($fav[DbViewFans::AUTHORID]); $user->setDisplayName($fav[DbViewFans::AUTHORDISPLAYNAME]); $user->setDeleted($fav[DbViewFans::AUTHORDELETED]); $result[] = [ 'user' => $user, 'positive' => $fav[DbViewFans::POSITIVE], 'negative' => $fav[DbViewFans::NEGATIVE] ]; } return $result; } protected function getFavoriteTags($userId, $siteId, $byRatio, $limit = 10) { $tags = $this->services->getVoteService()->getUserFavoriteTags($userId, $siteId, $byRatio, true); $tags->setCurrentPageNumber(1); $tags->setItemCountPerPage($limit); $result = []; foreach ($tags as $tag) { $result[] = [ 'tag' => $tag['Tag'], 'positive' => $tag['Positive'], 'negative' => $tag['Negative'] ]; } return $result; } protected function getPagesTable($userId, $siteId, $deleted, $orderBy, $order, $page, $perPage) { $pages = $this->services->getPageService()->findPagesByUser($userId, $siteId, $deleted, [$orderBy => $order], true, $page, $perPage); $pages->setCurrentPageNumber($page); $pages->setItemCountPerPage($perPage); $table = PaginatedTableFactory::createPagesTable($pages); $table->getColumns()->setOrder($orderBy, $order === Order::ASCENDING); return $table; } protected function getTranslationsTable($userId, $siteId, $orderBy, $order, $page, $perPage) { $pages = $this->services->getPageService()->findTranslationsOfUser($userId, $siteId, [$orderBy => $order], true, $page, $perPage); $pages->setCurrentPageNumber($page); $pages->setItemCountPerPage($perPage); $table = PaginatedTableFactory::createPagesTable($pages); $table->getColumns()->setOrder($orderBy, $order === Order::ASCENDING); return $table; } protected function getVotesTable($userId, $siteId, $orderBy, $order, $page, $perPage) { $votes = $this->services->getVoteService()->findVotesOfUser($userId, $siteId, [$orderBy => $order], true, $page, $perPage); $votes->setCurrentPageNumber($page); $votes->setItemCountPerPage($perPage); $table = PaginatedTableFactory::createUserVotesTable($votes); $table->getColumns()->setOrder($orderBy, $order === Order::ASCENDING); return $table; } public function __construct(HubServiceInterface $services) { $this->services = $services; } public function userAction() { $siteId = $this->services->getUtilityService()->getSiteId(); $site = $this->services->getSiteService()->find($siteId); $userId = (int)$this->params()->fromRoute('userId'); try { $user = $this->services->getUserService()->find($userId); $pages = $this->getPagesTable($userId, $siteId, null, DbViewPagesAll::CREATIONDATE, ORDER::DESCENDING, 1, 10); $translations = $this->getTranslationsTable($userId, $siteId, DbViewPagesAll::CREATIONDATE, ORDER::DESCENDING, 1, 10); // if ($user->) } catch (\InvalidArgumentException $e) { return $this->notFoundAction(); } if (!$user) { return $this->notFoundAction(); } return new ViewModel([ 'user' => $user, 'site' => $site, 'pages' => $pages, 'translations' => $translations, 'deleted' => $this->services->getUserService()->countAuthorshipsOfUser($userId, $siteId, true), 'fans' => $this->getFans($userId, $siteId, true), 'tags' => $this->getFavoriteTags($userId, $siteId, true), 'authors' => $this->getFavoriteAuthors($userId, $siteId, true), 'allFavorites' => false, 'votes' => $this->getVotesTable($userId, $siteId, DbViewVotes::DATETIME, ORDER::DESCENDING, 1, 10) ]); } public function apiUserAction() { $userId = (int)$this->params()->fromQuery('id'); try { $user = $this->services->getUserService()->find($userId); } catch (\InvalidArgumentException $e) { return new JsonModel(['error' => 'User not found']); } return new JsonModel($user->toArray()); } public function ratingChartAction() { $result = ['success' => false]; $userId = (int)$this->params()->fromQuery('userId'); $siteId = (int)$this->params()->fromQuery('siteId'); $user = $this->services->getUserService()->find($userId); if ($user) { $votes = $this->services->getVoteService()->getChartDataForUser($userId, $siteId); $resVotes = []; foreach ($votes as $vote) { $resVotes[] = [$vote['Date']->format(\DateTime::ISO8601), (int)$vote['Votes']]; } $authorships = $this->services->getUserService()->findAuthorshipsOfUser($userId, $siteId, false); $milestones = []; foreach ($authorships as $auth) { $name = $auth->getPage()->getTitle(); if (mb_strlen($name) > 11) { $name = mb_substr($name, 0, 8).'...'; } $milestones[] = [ $auth->getPage()->getCreationDate()->format(\DateTime::ISO8601), [ 'name' => $name, 'text' => $auth->getPage()->getTitle() ] ]; } $result = [ 'success' => true, 'votes' => $resVotes, 'milestones' => $milestones, ]; } return new JsonModel($result); } public function pageListAction() { $userId = (int)$this->params()->fromQuery('userId'); $siteId = (int)$this->params()->fromQuery('siteId'); $page = (int)$this->params()->fromQuery('page', 1); $perPage = (int)$this->params()->fromQuery('perPage', 10); $orderBy = $this->params()->fromQuery('orderBy', DbViewPagesAll::CREATIONDATE); $order = $this->params()->fromQuery('ascending', false); if ($order) { $order = Order::ASCENDING; } else { $order = Order::DESCENDING; } $table = $this->getPagesTable($userId, $siteId, null, $orderBy, $order, $page, $perPage); $renderer = $this->getServiceLocator()->get('ViewHelperManager')->get('partial'); if ($renderer) { $result['success'] = true; $result['content'] = $renderer( 'partial/tables/default/table.phtml', [ 'table' => $table, 'data' => [] ] ); } return new JsonModel($result); } public function translationListAction() { $userId = (int)$this->params()->fromQuery('userId'); $siteId = (int)$this->params()->fromQuery('siteId'); $page = (int)$this->params()->fromQuery('page', 1); $perPage = (int)$this->params()->fromQuery('perPage', 10); $orderBy = $this->params()->fromQuery('orderBy', DbViewPagesAll::CREATIONDATE); $order = $this->params()->fromQuery('ascending', false); if ($order) { $order = Order::ASCENDING; } else { $order = Order::DESCENDING; } $table = $this->getTranslationsTable($userId, $siteId, $orderBy, $order, $page, $perPage); $renderer = $this->getServiceLocator()->get('ViewHelperManager')->get('partial'); if ($renderer) { $result['success'] = true; $result['content'] = $renderer( 'partial/tables/default/table.phtml', [ 'table' => $table, 'data' => [] ] ); } return new JsonModel($result); } public function voteListAction() { $userId = (int)$this->params()->fromQuery('userId'); $siteId = (int)$this->params()->fromQuery('siteId'); $page = (int)$this->params()->fromQuery('page', 1); $perPage = (int)$this->params()->fromQuery('perPage', 10); $orderBy = $this->params()->fromQuery('orderBy', DbViewVotes::DATETIME); $order = $this->params()->fromQuery('ascending', false); if ($order) { $order = Order::ASCENDING; } else { $order = Order::DESCENDING; } $table = $this->getVotesTable($userId, $siteId, $orderBy, $order, $page, $perPage); $renderer = $this->getServiceLocator()->get('ViewHelperManager')->get('partial'); if ($renderer) { $result['success'] = true; $result['content'] = $renderer( 'partial/tables/default/table.phtml', [ 'table' => $table, 'data' => [] ] ); } return new JsonModel($result); } public function favoritesAction() { $userId = (int)$this->params()->fromQuery('userId'); $siteId = (int)$this->params()->fromQuery('siteId'); $site = $this->services->getSiteService()->find($siteId); $orderByRatio = (bool)$this->params()->fromQuery('orderByRatio'); $all = (bool)$this->params()->fromQuery('all'); if ($all) { $limit = 100000; } else { $limit = 10; } $renderer = $this->getServiceLocator()->get('ViewHelperManager')->get('partial'); if ($renderer) { $result['success'] = true; $fans = $this->getFans($userId, $siteId, $orderByRatio, $limit); $favorites = $this->getFavoriteAuthors($userId, $siteId, $orderByRatio, $limit); $tags = $this->getFavoriteTags($userId, $siteId, $orderByRatio, $limit); $result['content'] = $renderer( 'application/user/partial/favorites.phtml', [ 'byRatio' => $orderByRatio, 'hasVotes' => count($favorites), 'hideVotes' => $site->getHideVotes(), 'isAuthor' => count($fans), 'authors' => $favorites, 'tags' => $tags, 'fans' => $fans, 'all' => $all ] ); } return new JsonModel($result); } public function searchAction() { $maxItems = 50; $result = ['success' => true]; $query = $this->params()->fromQuery('query', ''); $users = $this->services->getUserService()->findByName($query, null, true); $users->setItemCountPerPage($maxItems); $result['users'] = []; foreach ($users as $user) { $result['users'][] = [ 'id' => $user->getId(), 'label' => $user->getDisplayName()]; } return new JsonModel($result); } }
FiftyNine/ScpperDB
module/Application/src/Application/Controller/UserController.php
PHP
mit
13,801
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test" ```python def spin_words(sentence): words = sentence.split() for i, w in enumerate(words): if len(w) >= 5: words[i] = w[::-1] return ' '.join(words) ``` ```python def spin_words(sentence): # Your code goes here return " ".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(" ")]) ```
pzoladkiewicz/CodeWars
6-kyu/Stop gninnipS My sdroW!.md
Markdown
mit
854
from django.conf import settings from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('cmsplugin_cascade', '0027_version_1'), ] operations = [ migrations.AddField( model_name='cascadeclipboard', name='created_at', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now, verbose_name='Created at'), preserve_default=False, ), migrations.AddField( model_name='cascadeclipboard', name='created_by', field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='Created by'), preserve_default=False, ), migrations.AddField( model_name='cascadeclipboard', name='last_accessed_at', field=models.DateTimeField(default=None, editable=False, null=True, verbose_name='Last accessed at'), ), ]
jrief/djangocms-cascade
cmsplugin_cascade/migrations/0028_cascade_clipboard.py
Python
mit
1,135
package cli import ( "bytes" "errors" "flag" "fmt" "io/ioutil" "strings" "testing" ) func TestCommandFlagParsing(t *testing.T) { cases := []struct { testArgs []string skipFlagParsing bool useShortOptionHandling bool expectedErr error }{ // Test normal "not ignoring flags" flow {testArgs: []string{"test-cmd", "-break", "blah", "blah"}, skipFlagParsing: false, useShortOptionHandling: false, expectedErr: errors.New("flag provided but not defined: -break")}, {testArgs: []string{"test-cmd", "blah", "blah"}, skipFlagParsing: true, useShortOptionHandling: false, expectedErr: nil}, // Test SkipFlagParsing without any args that look like flags {testArgs: []string{"test-cmd", "blah", "-break"}, skipFlagParsing: true, useShortOptionHandling: false, expectedErr: nil}, // Test SkipFlagParsing with random flag arg {testArgs: []string{"test-cmd", "blah", "-help"}, skipFlagParsing: true, useShortOptionHandling: false, expectedErr: nil}, // Test SkipFlagParsing with "special" help flag arg {testArgs: []string{"test-cmd", "blah", "-h"}, skipFlagParsing: false, useShortOptionHandling: true, expectedErr: nil}, // Test UseShortOptionHandling } for _, c := range cases { app := &App{Writer: ioutil.Discard} set := flag.NewFlagSet("test", 0) _ = set.Parse(c.testArgs) context := NewContext(app, set, nil) command := Command{ Name: "test-cmd", Aliases: []string{"tc"}, Usage: "this is for testing", Description: "testing", Action: func(_ *Context) error { return nil }, SkipFlagParsing: c.skipFlagParsing, } err := command.Run(context) expect(t, err, c.expectedErr) expect(t, context.Args().Slice(), c.testArgs) } } func TestParseAndRunShortOpts(t *testing.T) { cases := []struct { testArgs args expectedErr error expectedArgs Args }{ {testArgs: args{"foo", "test", "-a"}, expectedErr: nil, expectedArgs: &args{}}, {testArgs: args{"foo", "test", "-c", "arg1", "arg2"}, expectedErr: nil, expectedArgs: &args{"arg1", "arg2"}}, {testArgs: args{"foo", "test", "-f"}, expectedErr: nil, expectedArgs: &args{}}, {testArgs: args{"foo", "test", "-ac", "--fgh"}, expectedErr: nil, expectedArgs: &args{}}, {testArgs: args{"foo", "test", "-af"}, expectedErr: nil, expectedArgs: &args{}}, {testArgs: args{"foo", "test", "-cf"}, expectedErr: nil, expectedArgs: &args{}}, {testArgs: args{"foo", "test", "-acf"}, expectedErr: nil, expectedArgs: &args{}}, {testArgs: args{"foo", "test", "--acf"}, expectedErr: errors.New("flag provided but not defined: -acf"), expectedArgs: nil}, {testArgs: args{"foo", "test", "-invalid"}, expectedErr: errors.New("flag provided but not defined: -invalid"), expectedArgs: nil}, {testArgs: args{"foo", "test", "-acf", "-invalid"}, expectedErr: errors.New("flag provided but not defined: -invalid"), expectedArgs: nil}, {testArgs: args{"foo", "test", "--invalid"}, expectedErr: errors.New("flag provided but not defined: -invalid"), expectedArgs: nil}, {testArgs: args{"foo", "test", "-acf", "--invalid"}, expectedErr: errors.New("flag provided but not defined: -invalid"), expectedArgs: nil}, {testArgs: args{"foo", "test", "-acf", "arg1", "-invalid"}, expectedErr: nil, expectedArgs: &args{"arg1", "-invalid"}}, {testArgs: args{"foo", "test", "-acf", "arg1", "--invalid"}, expectedErr: nil, expectedArgs: &args{"arg1", "--invalid"}}, {testArgs: args{"foo", "test", "-acfi", "not-arg", "arg1", "-invalid"}, expectedErr: nil, expectedArgs: &args{"arg1", "-invalid"}}, {testArgs: args{"foo", "test", "-i", "ivalue"}, expectedErr: nil, expectedArgs: &args{}}, {testArgs: args{"foo", "test", "-i", "ivalue", "arg1"}, expectedErr: nil, expectedArgs: &args{"arg1"}}, {testArgs: args{"foo", "test", "-i"}, expectedErr: errors.New("flag needs an argument: -i"), expectedArgs: nil}, } for _, c := range cases { var args Args cmd := &Command{ Name: "test", Usage: "this is for testing", Description: "testing", Action: func(c *Context) error { args = c.Args() return nil }, UseShortOptionHandling: true, Flags: []Flag{ &BoolFlag{Name: "abc", Aliases: []string{"a"}}, &BoolFlag{Name: "cde", Aliases: []string{"c"}}, &BoolFlag{Name: "fgh", Aliases: []string{"f"}}, &StringFlag{Name: "ijk", Aliases: []string{"i"}}, }, } app := newTestApp() app.Commands = []*Command{cmd} err := app.Run(c.testArgs) expect(t, err, c.expectedErr) expect(t, args, c.expectedArgs) } } func TestCommand_Run_DoesNotOverwriteErrorFromBefore(t *testing.T) { app := &App{ Commands: []*Command{ { Name: "bar", Before: func(c *Context) error { return fmt.Errorf("before error") }, After: func(c *Context) error { return fmt.Errorf("after error") }, }, }, Writer: ioutil.Discard, } err := app.Run([]string{"foo", "bar"}) if err == nil { t.Fatalf("expected to receive error from Run, got none") } if !strings.Contains(err.Error(), "before error") { t.Errorf("expected text of error from Before method, but got none in \"%v\"", err) } if !strings.Contains(err.Error(), "after error") { t.Errorf("expected text of error from After method, but got none in \"%v\"", err) } } func TestCommand_Run_BeforeSavesMetadata(t *testing.T) { var receivedMsgFromAction string var receivedMsgFromAfter string app := &App{ Commands: []*Command{ { Name: "bar", Before: func(c *Context) error { c.App.Metadata["msg"] = "hello world" return nil }, Action: func(c *Context) error { msg, ok := c.App.Metadata["msg"] if !ok { return errors.New("msg not found") } receivedMsgFromAction = msg.(string) return nil }, After: func(c *Context) error { msg, ok := c.App.Metadata["msg"] if !ok { return errors.New("msg not found") } receivedMsgFromAfter = msg.(string) return nil }, }, }, } err := app.Run([]string{"foo", "bar"}) if err != nil { t.Fatalf("expected no error from Run, got %s", err) } expectedMsg := "hello world" if receivedMsgFromAction != expectedMsg { t.Fatalf("expected msg from Action to match. Given: %q\nExpected: %q", receivedMsgFromAction, expectedMsg) } if receivedMsgFromAfter != expectedMsg { t.Fatalf("expected msg from After to match. Given: %q\nExpected: %q", receivedMsgFromAction, expectedMsg) } } func TestCommand_OnUsageError_hasCommandContext(t *testing.T) { app := &App{ Commands: []*Command{ { Name: "bar", Flags: []Flag{ &IntFlag{Name: "flag"}, }, OnUsageError: func(c *Context, err error, _ bool) error { return fmt.Errorf("intercepted in %s: %s", c.Command.Name, err.Error()) }, }, }, } err := app.Run([]string{"foo", "bar", "--flag=wrong"}) if err == nil { t.Fatalf("expected to receive error from Run, got none") } if !strings.HasPrefix(err.Error(), "intercepted in bar") { t.Errorf("Expect an intercepted error, but got \"%v\"", err) } } func TestCommand_OnUsageError_WithWrongFlagValue(t *testing.T) { app := &App{ Commands: []*Command{ { Name: "bar", Flags: []Flag{ &IntFlag{Name: "flag"}, }, OnUsageError: func(c *Context, err error, _ bool) error { if !strings.HasPrefix(err.Error(), "invalid value \"wrong\"") { t.Errorf("Expect an invalid value error, but got \"%v\"", err) } return errors.New("intercepted: " + err.Error()) }, }, }, } err := app.Run([]string{"foo", "bar", "--flag=wrong"}) if err == nil { t.Fatalf("expected to receive error from Run, got none") } if !strings.HasPrefix(err.Error(), "intercepted: invalid value") { t.Errorf("Expect an intercepted error, but got \"%v\"", err) } } func TestCommand_OnUsageError_WithSubcommand(t *testing.T) { app := &App{ Commands: []*Command{ { Name: "bar", Subcommands: []*Command{ { Name: "baz", }, }, Flags: []Flag{ &IntFlag{Name: "flag"}, }, OnUsageError: func(c *Context, err error, _ bool) error { if !strings.HasPrefix(err.Error(), "invalid value \"wrong\"") { t.Errorf("Expect an invalid value error, but got \"%v\"", err) } return errors.New("intercepted: " + err.Error()) }, }, }, } err := app.Run([]string{"foo", "bar", "--flag=wrong"}) if err == nil { t.Fatalf("expected to receive error from Run, got none") } if !strings.HasPrefix(err.Error(), "intercepted: invalid value") { t.Errorf("Expect an intercepted error, but got \"%v\"", err) } } func TestCommand_Run_SubcommandsCanUseErrWriter(t *testing.T) { app := &App{ ErrWriter: ioutil.Discard, Commands: []*Command{ { Name: "bar", Usage: "this is for testing", Subcommands: []*Command{ { Name: "baz", Usage: "this is for testing", Action: func(c *Context) error { if c.App.ErrWriter != ioutil.Discard { return fmt.Errorf("ErrWriter not passed") } return nil }, }, }, }, }, } err := app.Run([]string{"foo", "bar", "baz"}) if err != nil { t.Fatal(err) } } func TestCommandSkipFlagParsing(t *testing.T) { cases := []struct { testArgs args expectedArgs *args expectedErr error }{ {testArgs: args{"some-exec", "some-command", "some-arg", "--flag", "foo"}, expectedArgs: &args{"some-arg", "--flag", "foo"}, expectedErr: nil}, {testArgs: args{"some-exec", "some-command", "some-arg", "--flag=foo"}, expectedArgs: &args{"some-arg", "--flag=foo"}, expectedErr: nil}, } for _, c := range cases { var args Args app := &App{ Commands: []*Command{ { SkipFlagParsing: true, Name: "some-command", Flags: []Flag{ &StringFlag{Name: "flag"}, }, Action: func(c *Context) error { args = c.Args() return nil }, }, }, Writer: ioutil.Discard, } err := app.Run(c.testArgs) expect(t, err, c.expectedErr) expect(t, args, c.expectedArgs) } } func TestCommand_Run_CustomShellCompleteAcceptsMalformedFlags(t *testing.T) { cases := []struct { testArgs args expectedOut string }{ {testArgs: args{"--undefined"}, expectedOut: "found 0 args"}, {testArgs: args{"--number"}, expectedOut: "found 0 args"}, {testArgs: args{"--number", "fourty-two"}, expectedOut: "found 0 args"}, {testArgs: args{"--number", "42"}, expectedOut: "found 0 args"}, {testArgs: args{"--number", "42", "newArg"}, expectedOut: "found 1 args"}, } for _, c := range cases { var outputBuffer bytes.Buffer app := &App{ Writer: &outputBuffer, EnableBashCompletion: true, Commands: []*Command{ { Name: "bar", Usage: "this is for testing", Flags: []Flag{ &IntFlag{ Name: "number", Usage: "A number to parse", }, }, BashComplete: func(c *Context) { fmt.Fprintf(c.App.Writer, "found %d args", c.NArg()) }, }, }, } osArgs := args{"foo", "bar"} osArgs = append(osArgs, c.testArgs...) osArgs = append(osArgs, "--generate-bash-completion") err := app.Run(osArgs) stdout := outputBuffer.String() expect(t, err, nil) expect(t, stdout, c.expectedOut) } } func TestCommand_NoVersionFlagOnCommands(t *testing.T) { app := &App{ Version: "some version", Commands: []*Command{ { Name: "bar", Usage: "this is for testing", Subcommands: []*Command{{}}, // some subcommand HideHelp: true, Action: func(c *Context) error { if len(c.App.VisibleFlags()) != 0 { t.Fatal("unexpected flag on command") } return nil }, }, }, } err := app.Run([]string{"foo", "bar"}) expect(t, err, nil) } func TestCommand_CanAddVFlagOnCommands(t *testing.T) { app := &App{ Version: "some version", Writer: ioutil.Discard, Commands: []*Command{ { Name: "bar", Usage: "this is for testing", Subcommands: []*Command{{}}, // some subcommand Flags: []Flag{ &BoolFlag{ Name: "v", }, }, }, }, } err := app.Run([]string{"foo", "bar"}) expect(t, err, nil) }
urfave/cli
command_test.go
GO
mit
12,159
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Documentation</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <base href="../"> <link rel="icon" href="images/favicon.ico"/> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/base.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/template.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/css/all.min.css" integrity="sha256-ybRkN9dBjhcS2qrW1z+hfCxq+1aBdwyQM5wlQoQVt/0=" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/themes/prism-okaidia.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/plugins/line-numbers/prism-line-numbers.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/plugins/line-highlight/prism-line-highlight.css"> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> <script src="https://cdn.jsdelivr.net/npm/css-vars-ponyfill@2"></script> <script src="js/search.js"></script> <script defer src="js/searchIndex.js"></script> </head> <body id="top"> <header class="phpdocumentor-header phpdocumentor-section"> <h1 class="phpdocumentor-title"><a href="" class="phpdocumentor-title__link">Documentation</a></h1> <input class="phpdocumentor-header__menu-button" type="checkbox" id="menu-button" name="menu-button" /> <label class="phpdocumentor-header__menu-icon" for="menu-button"> <i class="fas fa-bars"></i> </label> <section data-search-form class="phpdocumentor-search"> <label> <span class="visually-hidden">Search for</span> <svg class="phpdocumentor-search__icon" width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="7.5" cy="7.5" r="6.5" stroke="currentColor" stroke-width="2"/> <line x1="12.4892" y1="12.2727" x2="19.1559" y2="18.9393" stroke="currentColor" stroke-width="3"/> </svg> <input type="search" class="phpdocumentor-field phpdocumentor-search__field" placeholder="Loading .." disabled /> </label> </section> <nav class="phpdocumentor-topnav"> <ul class="phpdocumentor-topnav__menu"> </ul> </nav> </header> <main class="phpdocumentor"> <div class="phpdocumentor-section"> <input class="phpdocumentor-sidebar__menu-button" type="checkbox" id="sidebar-button" name="sidebar-button" /> <label class="phpdocumentor-sidebar__menu-icon" for="sidebar-button"> Menu </label> <aside class="phpdocumentor-column -four phpdocumentor-sidebar"> <section class="phpdocumentor-sidebar__category"> <h2 class="phpdocumentor-sidebar__category-header">Namespaces</h2> <h4 class="phpdocumentor-sidebar__root-namespace"><a href="namespaces/lightncandy.html"><abbr title="\LightnCandy">LightnCandy</abbr></a></h4> <ul class="phpdocumentor-list"> </ul> </section> <section class="phpdocumentor-sidebar__category"> <h2 class="phpdocumentor-sidebar__category-header">Packages</h2> <h3 class="phpdocumentor-sidebar__root-package"><a href="packages/LightnCandy.html"><abbr title="\LightnCandy">LightnCandy</abbr></a></h3> </section> <section class="phpdocumentor-sidebar__category"> <h2 class="phpdocumentor-sidebar__category-header">Reports</h2> <h3 class="phpdocumentor-sidebar__root-package"><a href="reports/deprecated.html">Deprecated</a></h3> <h3 class="phpdocumentor-sidebar__root-package"><a href="reports/errors.html">Errors</a></h3> <h3 class="phpdocumentor-sidebar__root-package"><a href="reports/markers.html">Markers</a></h3> </section> <section class="phpdocumentor-sidebar__category"> <h2 class="phpdocumentor-sidebar__category-header">Indices</h2> <h3 class="phpdocumentor-sidebar__root-package"><a href="indices/files.html">Files</a></h3> </section> </aside> <div class="phpdocumentor-column -eight phpdocumentor-content"> <ul class="phpdocumentor-breadcrumbs"> </ul> <article class="phpdocumentor-element -file"> <h2 class="phpdocumentor-content__title">Partial.php</h2> <p class="phpdocumentor-summary">file to keep LightnCandy partial methods</p> <h5 class="phpdocumentor-tag-list__heading" id="tags"> Tags <a href="#tags" class="headerlink"><i class="fas fa-link"></i></a> </h5> <dl class="phpdocumentor-tag-list"> <dt class="phpdocumentor-tag-list__entry"> <span class="phpdocumentor-tag__name">author</span> </dt> <dd class="phpdocumentor-tag-list__definition"> <section class="phpdocumentor-description"><p>Zordius <a href="mailto:[email protected]">[email protected]</a></p> </section> </dd> </dl> <h3 id="interfaces_class_traits"> Interfaces, Classes and Traits <a href="#interfaces_class_traits" class="headerlink"><i class="fas fa-link"></i></a> </h3> <dl class="phpdocumentor-table-of-contents"> <dt class="phpdocumentor-table-of-contents__entry -class"><a href="classes/LightnCandy-Partial.html"><abbr title="\LightnCandy\Partial">Partial</abbr></a></dt> <dd>LightnCandy Partial handler</dd> </dl> </article> <section data-search-results class="phpdocumentor-search-results phpdocumentor-search-results--hidden"> <section class="phpdocumentor-search-results__dialog"> <header class="phpdocumentor-search-results__header"> <h2 class="phpdocumentor-search-results__title">Search results</h2> <button class="phpdocumentor-search-results__close"><i class="fas fa-times"></i></button> </header> <section class="phpdocumentor-search-results__body"> <ul class="phpdocumentor-search-results__entries"></ul> </section> </section> </section> </div> </div> <a href="files/src-partial.html#top" class="phpdocumentor-back-to-top"><i class="fas fa-chevron-circle-up"></i></a> </main> <script> cssVars({}); </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/prism.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/plugins/autoloader/prism-autoloader.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/plugins/line-numbers/prism-line-numbers.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/plugins/line-highlight/prism-line-highlight.min.js"></script> </body> </html>
zordius/lightncandy
docs/files/src-partial.html
HTML
mit
7,482
/* * (C) Copyright 2012 * Linaro * Linus Walleij <[email protected]> * Common ARM Integrator configuration settings * * SPDX-License-Identifier: GPL-2.0+ */ #define CONFIG_SYS_MEMTEST_START 0x100000 #define CONFIG_SYS_MEMTEST_END 0x10000000 #define CONFIG_SYS_TIMERBASE 0x13000100 /* Timer1 */ #define CONFIG_SYS_LOAD_ADDR 0x7fc0 /* default load address */ #define CONFIG_SYS_MALLOC_LEN (CONFIG_ENV_SIZE + 128*1024) /* Size of malloc() pool */ #define CONFIG_CMDLINE_TAG /* enable passing of ATAGs */ #define CONFIG_SETUP_MEMORY_TAGS #define CONFIG_MISC_INIT_R /* call misc_init_r during start up */ /* * There are various dependencies on the core module (CM) fitted * Users should refer to their CM user guide */ #include "armcoremodule.h" /* * Initialize and remap the core module, use SPD to detect memory size * If CONFIG_SKIP_LOWLEVEL_INIT is not defined & * the core module has a CM_INIT register * then the U-Boot initialisation code will * e.g. ARM Boot Monitor or pre-loader is repeated once * (to re-initialise any existing CM_INIT settings to safe values). * * This is usually not the desired behaviour since the platform * will either reboot into the ARM monitor (or pre-loader) * or continuously cycle thru it without U-Boot running, * depending upon the setting of Integrator/CP switch S2-4. * * However it may be needed if Integrator/CP switch S2-1 * is set OFF to boot direct into U-Boot. * In that case comment out the line below. */ #define CONFIG_CM_INIT #define CONFIG_CM_REMAP #define CONFIG_CM_SPD_DETECT /* * The ARM boot monitor initializes the board. * However, the default U-Boot code also performs the initialization. * If desired, this can be prevented by defining SKIP_LOWLEVEL_INIT * - see documentation supplied with board for details of how to choose the * image to run at reset/power up * e.g. whether the ARM Boot Monitor runs before U-Boot */ /* #define CONFIG_SKIP_LOWLEVEL_INIT */ /* * The ARM boot monitor does not relocate U-Boot. * However, the default U-Boot code performs the relocation check, * and may relocate the code if the memory map is changed. * If necessary this can be prevented by defining SKIP_RELOCATE_UBOOT */ /* #define SKIP_CONFIG_RELOCATE_UBOOT */ /* * Physical Memory Map */ #define CONFIG_NR_DRAM_BANKS 1 /* we have 1 bank of DRAM */ #define PHYS_SDRAM_1 0x00000000 /* SDRAM Bank #1 */ #define PHYS_SDRAM_1_SIZE 0x08000000 /* 128 MB */ #define CONFIG_SYS_SDRAM_BASE PHYS_SDRAM_1 #define CONFIG_SYS_INIT_RAM_SIZE PHYS_SDRAM_1_SIZE #define CONFIG_SYS_GBL_DATA_OFFSET (CONFIG_SYS_SDRAM_BASE + \ CONFIG_SYS_INIT_RAM_SIZE - \ GENERATED_GBL_DATA_SIZE) #define CONFIG_SYS_INIT_SP_ADDR CONFIG_SYS_GBL_DATA_OFFSET /* * FLASH and environment organization * Top varies according to amount fitted * Reserve top 4 blocks of flash * - ARM Boot Monitor * - Unused * - SIB block * - U-Boot environment */ #define CONFIG_SYS_FLASH_CFI 1 #define CONFIG_FLASH_CFI_DRIVER 1 #define CONFIG_SYS_FLASH_BASE 0x24000000 #define CONFIG_SYS_MAX_FLASH_BANKS 1 /* Timeout values in ticks */ #define CONFIG_SYS_FLASH_ERASE_TOUT (2 * CONFIG_SYS_HZ) /* Erase Timeout */ #define CONFIG_SYS_FLASH_WRITE_TOUT (2 * CONFIG_SYS_HZ) /* Write Timeout */ #define CONFIG_SYS_FLASH_PROTECTION /* The devices have real protection */ #define CONFIG_SYS_FLASH_EMPTY_INFO /* flinfo indicates empty blocks */
guileschool/BEAGLEBONE-tutorials
BBB-firmware/u-boot-v2018.05-rc2/include/configs/integrator-common.h
C
mit
3,414
<?php ?> <h3>Here is the result of the highlighter function for php</h3> <?php echo $highlighted; ?>
danwguy/OOF
application/views/Highlight/index.php
PHP
mit
100
<!doctype html> <html class="no-js"> <head> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui"> <title>GitHub Demo</title> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="styles/vendor.css"> <link rel="stylesheet" href="styles/main.css"> <script src="scripts/vendor/modernizr.js"></script> </head> <body> <header> <nav> <ul class="left"> <li><a href="#"><i class="mega-octicon octicon-mark-github"></i></a></li> <li><input class="search-github" type="text" placeholder="Search GitHub"></li> <li><a href="https://github.com/explore">Explore</a></li> <li><a href="https://gist.github.com">Gist</a></li> <li><a href="https://github.com/blog">Blog</a></li> <li><a href="https://help.github.com">Help</a></li> </ul> <div> <ul class="right"></ul> </div> </nav> </header> <div class="page-wrapper"> <aside> <div class="orgs"> <h3>Organizations</h3> <ul id="organizations"></ul> </div> </aside> <section class="main"> <nav class="tab"> <ul> <li><i class="octicon octicon-diff-added"></i>Contributions</li> <li class="active"><i class="octicon octicon-repo"></i>Repositories</li> <li><i class="octicon octicon-rss"></i>Public activity</li> </ul> <div class="tab-right"> <div class="slim-button"><i class="octicon octicon-pencil"></i>Edit profile</div> </div> </nav> <div class="filter-bar"> <form> <input class="search-repos" type="text" placeholder="Find a repository..."> <!-- <input type="submit std-button" value="Search"> --> </form> <div class="success-button"><i class="octicon octicon-repo"></i>New</div> <ul> <li><a href="#">Mirrors</a></li> <li><a href="#">Forks</a></li> <li><a href="#">Sources</a></li> <li><a href="#">Private</a></li> <li><a href="#">Public</a></li> <li class="active"><a href="#">All</a></li> </ul> </div> <ul class="repo-list"></ul> </section> </div> <footer> <nav> <ul class="left"> <li>&copy; 2015 GitHub, Inc.</li> <li><a href="#">Terms</a></li> <li><a href="#">Privacy</a></li> <li><a href="#">Security</a></li> <li><a href="#">Contact</a></li> </ul> <ul class="right"> <li><a href="#">About</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Shop</a></li> <li><a href="#">Training</a></li> <li><a href="#">API</a></li> <li><a href="#">Status</a></li> </ul> <div class="center"><a href="#"><i class="mega-octicon octicon-mark-github"></i></a></div> </nav> </footer> <script src="scripts/vendor.js"></script> <script src="scripts/main.js"></script> </body> </html>
bholben/GitHub
dist/index.html
HTML
mit
3,074
module.exports = function (config) { let travis = process.env.TRAVIS; function configureLocalBrowsers() { let isMac = /^darwin/.test(process.platform), isWindows = /^win/.test(process.platform), isLinux = !(isMac || isWindows); if (isMac) { return ['PhantomJS', 'Firefox', 'Chrome']; } else if (isLinux) { return ['PhantomJS', 'Firefox']; } else { return ['PhantomJS']; } } config.set({ frameworks: ['browserify', 'mocha', 'sinon-chai'], preprocessors: { 'test/**/*.js': [ 'browserify' ], 'src/**/*.js': [ 'browserify' ] }, coverageReporter: { dir: 'coverage/', reporters: [ {type: 'html'}, {type: 'text-summary'}, {type: 'lcov'} ] }, browserify: { transform: [ require('browserify-istanbul')({ instrumenter: require('isparta'), ignore: ['**/*.spec.js'] }), ['babelify', {'presets': ['es2015']}] ] }, files: [ 'node_modules/babel-polyfill/dist/polyfill.js', './test/setup/browser.js', 'test/**/*.spec.js', 'src/**/*.spec.js', {pattern: 'test/specs/**', included: false, served: true} ], proxies: { '/test/': '/base/test/', }, reporters:['mocha', 'coverage'], browsers: configureLocalBrowsers(), browserNoActivityTimeout: 60000 }); }
APIs-guru/OpenAPI-Lint
karma.conf.js
JavaScript
mit
1,589
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width; initial-scale=1.0"> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Typepicter</title> <link rel="stylesheet" type="text/css" href="stylesheets/style.css" /> <link rel="stylesheet" type="text/css" href="stylesheets/typepicter.css" /> <style> .tree { white-space: pre; color: #888; font-size: 0.6rem; overflow: hidden; margin-top: 2rem; } .flower { color: pink; } @media only screen and (min-width: 25em) { .tree { font-size: 0.8rem; } } @media only screen and (min-width: 36em) { .tree { font-size: 1.2rem; } } @media only screen and (min-width: 53em) { .tree { font-size: 1.5rem; } } .create { height: 15rem; padding: 3rem; width: 100%; } textarea { border: 1px solid #999999; width: 100%; margin: 5px 0; padding: 3px; height: 30rem; } </style> </head> <body class="bg-color"> <header class="header"> <h1 class="center">Typepicter</h1> <h3 class="center serif">A font that imitates the Uwasa Imperial Typepicter</h3> <div class="center bold yellow">By Morten Høfft - March 1, 2014</div> </header> <div class="content"> <p class="center"> <a href="http://mortenhofft.github.io/typepicter/">Read more</a> or download the font at <a href="https://github.com/MortenHofft/Typepicter">GitHub</a> </p> <div class="icon- tree"> r<span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>r<span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> r <span class="flower">t</span> <span class="flower">t</span> <span class="flower">t</span> r<span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> r<span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>E <span class="flower">t</span>r <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>r<span class="flower">t</span> r<span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span> <span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span><span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>w<span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span> <span class="flower">t</span>r <span class="flower">t</span><span class="flower">t</span> q<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>r<span class="flower">t</span>r y r r<span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> r<span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span> r<span class="flower">t</span>r<span class="flower">t</span> W<span class="flower">t</span><span class="flower">t</span> qr<span class="flower">t</span><span class="flower">t</span>rr<span class="flower">t</span> <span class="flower">t</span> <span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span>r <span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>r<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>qr <span class="flower">t</span><span class="flower">t</span><span class="flower">t</span><span class="flower">t</span> r qq<span class="flower">t</span><span class="flower">t</span><span class="flower">t</span><span class="flower">t</span>q<span class="flower">t</span> <span class="flower">t</span>W <span class="flower">t</span>W<span class="flower">t</span> y qqr<span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> <span class="flower">t</span>r<span class="flower">t</span> y qqq<span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span>E<span class="flower">t</span> y <span class="flower">t</span> w<span class="flower">t</span> E qq<span class="flower">t</span>r <span class="flower">t</span> e<span class="flower">t</span> <span class="flower">t</span><span class="flower">t</span> qqq<span class="flower">t</span>W<span class="flower">t</span> y <span class="flower">t</span><span class="flower">t</span> qqq <span class="flower">t</span><span class="flower">t</span> y qq y e y y qqq <span class="flower">t</span><span class="flower">t</span> y qqqq qqqqqq </div> <p class="divider">Try it using qwerty</p> <textarea class="icon- tree"> qwerty T tt tt ttt tt T trttr retttrtt ttWtttt t ttttt t tttt tRttttrt tt ttq ttt ttr ttt y tqtrtt ttt T qq Ett qq ttrt y y qq t qq y qq y qqqq </textarea> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-48466800-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
MortenHofft/Typepicter
index.html
HTML
mit
7,498
<!DOCTYPE html> <html> <head> <title>Hub.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <ul class="sections"> <li id="title"> <div class="annotation"> <h1>Hub.js</h1> </div> </li> <li id="section-1"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-1">&#182;</a> </div> <p>Imports</p> </div> </li> <li id="section-2"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-2">&#182;</a> </div> <p>Hub class.</p> </div> <div class="content"><div class='highlight'><pre><span class="hljs-keyword">class</span> Hub {</pre></div></div> </li> <li id="section-3"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-3">&#182;</a> </div> <p>life cycle constructor</p> </div> <div class="content"><div class='highlight'><pre> constructor(io, socket){ <span class="hljs-keyword">this</span>.io = io; <span class="hljs-keyword">this</span>.socket = socket; <span class="hljs-keyword">this</span>._parseRoute(); }</pre></div></div> </li> <li id="section-4"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-4">&#182;</a> </div> <p>default prototype namespace</p> </div> <div class="content"><div class='highlight'><pre> namespace(){ <span class="hljs-keyword">return</span> <span class="hljs-string">'/'</span>; }</pre></div></div> </li> <li id="section-5"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-5">&#182;</a> </div> <p>getter for routing object</p> </div> <div class="content"><div class='highlight'><pre> get routes(){ <span class="hljs-keyword">return</span> {}; }</pre></div></div> </li> <li id="section-6"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-6">&#182;</a> </div> <p>private parse routing</p> </div> <div class="content"><div class='highlight'><pre> _parseRoute(){ <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> route <span class="hljs-keyword">in</span> <span class="hljs-keyword">this</span>.routes){ <span class="hljs-keyword">this</span>.socket.on(route, <span class="hljs-keyword">this</span>.routes[route].bind(<span class="hljs-keyword">this</span>)); } }</pre></div></div> </li> <li id="section-7"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-7">&#182;</a> </div> <p>emit message to socket</p> </div> <div class="content"><div class='highlight'><pre> emit(key, obj) { <span class="hljs-keyword">this</span>.socket.emit(key, obj); }</pre></div></div> </li> <li id="section-8"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-8">&#182;</a> </div> <p>emit message to socket in room</p> </div> <div class="content"><div class='highlight'><pre> emitToRoom(room, key, obj) { <span class="hljs-keyword">this</span>.socket.to(room).emit(key, obj); }</pre></div></div> </li> <li id="section-9"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-9">&#182;</a> </div> <p>broadcast message to all socket in namespace</p> </div> <div class="content"><div class='highlight'><pre> broadcast(key, obj) { <span class="hljs-keyword">this</span>.io.of(<span class="hljs-keyword">this</span>.namespace()).emit(key, obj); }</pre></div></div> </li> <li id="section-10"> <div class="annotation"> <div class="pilwrap "> <a class="pilcrow" href="#section-10">&#182;</a> </div> <p>broadcast message to all socket connected</p> </div> <div class="content"><div class='highlight'><pre> broadcastToAll(key, obj) { <span class="hljs-keyword">this</span>.io.sockets.emit(key, obj); } } <span class="hljs-built_in">module</span>.exports = Hub;</pre></div></div> </li> </ul> </div> </body> </html>
microscopejs/microscope-ws-es6
docs/code/Hub.html
HTML
mit
5,834
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.5.4.20-4-44 description: > String.prototype.trim handles whitepace and lineterminators (\u000Dabc) includes: [runTestCase.js] ---*/ function testcase() { if ("\u000Dabc".trim() === "abc") { return true; } } runTestCase(testcase);
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/String/prototype/trim/15.5.4.20-4-44.js
JavaScript
mit
632
package common import "path/filepath" import "sync" type Setting struct { Port string Dir string } var instance *Setting var once sync.Once func (s *Setting) UpdateByArgs(args map[string]interface{}) { portArg := args["-p"] if portArg != nil { s.Port = portArg.(string) } dirArg := args["-d"] if dirArg != nil { s.Dir = dirArg.(string) } } func (s *Setting) PathFile(filename string) string { path, err := filepath.Abs(s.Dir) if err != nil { return "" } return path + "/" + filename + ".json" } func initSettings() { instance = &Setting { Port: "8080", Dir: "./", } } func Settings() *Setting { once.Do(initSettings) return instance }
cristianoliveira/apitogo
common/settings.go
GO
mit
680
from base import IfbyphoneApiBase class Survo(IfbyphoneApiBase): def delete_survey_results(self, **kwargs): """Delete all SurVo results for a single SurVo keyword arguments: survo_id -- unique ID for the survo before_date -- (optional) Restricts the delete operation to results prior to the specified date """ self.options.update(kwargs) self.options['action'] = 'survo.delete_survey_results' return self.call(self.options) def get_recording(self, **kwargs): """Retreive an audio recording made at an IVR level keyword arguments: format -- 'wav' 'mp3' survo_id -- unique ID of SurVo unique_id -- unique ID of caller on SurVo question -- question number for question where recording was taken sample_rate -- audio rate of streaming data """ self.option.update(kwargs) self.option['action'] = 'survo.get_recording' return self.call(self.options)
Opus1no2/Ifbyphone-API-Module
src/Ifbyphone/api/survo.py
Python
mit
1,093
<?php //Include FB config file && User class require_once 'fbConfig.php'; //page where fb config is donei.e. app id and secret id require_once 'User.php'; // page where your database configuration is done if(!$fbUser){ $fbUser = NULL; $loginURL = $facebook->getLoginUrl(array('redirect_uri'=>$redirectURL,'scope'=>$fbPermissions)); $output = '<a href="'.$loginURL.'"><img style="margin-left:4%; margin-top: 4%;" src="images/fblogin-btn.png"></a>'; }else{ //Get user profile data from facebook $fbUserProfile = $facebook->api('/me?fields=id,first_name,last_name,email,link,gender,locale,picture'); //Initialize User class $user = new User(); //Insert or update user data to the database $fbUserData = array( 'oauth_provider'=> 'facebook', 'oauth_uid' => $fbUserProfile['id'], 'first_name' => $fbUserProfile['first_name'], 'last_name' => $fbUserProfile['last_name'], 'email' => $fbUserProfile['email'], 'gender' => $fbUserProfile['gender'], 'locale' => $fbUserProfile['locale'], 'picture' => $fbUserProfile['picture']['data']['url'], 'link' => $fbUserProfile['link'] ); $userData = $user->checkUser($fbUserData); //Put user data into session $_SESSION['userData'] = $userData; //Render facebook profile data if(!empty($userData)){ $output = '<h1>Facebook Profile Details </h1>'; $output .= '<img src="'.$userData['picture'].'">'; $output .= '<br/>Facebook ID : ' . $userData['oauth_uid']; $output .= '<br/>Name : ' . $userData['first_name'].' '.$userData['last_name']; $output .= '<br/>Email : ' . $userData['email']; $output .= '<br/>Gender : ' . $userData['gender']; $output .= '<br/>Locale : ' . $userData['locale']; $output .= '<br/>Logged in with : Facebook'; $output .= '<br/><a href="'.$userData['link'].'" target="_blank">Click to Visit Facebook Page</a>'; $output .= '<br/>Logout from <a href="logout.php">Facebook</a>'; //header('location: http://cp4.chasingpapers.com/'); }else{ $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>'; } } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Login with Facebook using PHP by CodexWorld</title> <style type="text/css"> h1{font-family:Arial, Helvetica, sans-serif;color:#999999;} </style> </head> <body> <div><?php echo $output; ?></div> </body> </html>
AmirMustafa/Facebook-API-Login-PHP
index.php
PHP
mit
2,421
<HTML> <HEAD> <META NAME="generator" CONTENT="ISE EiffelStudio version 5.1.14"> <META NAME="project" CONTENT="Project Goanna <http://sourceforge.net/projects/goanna>"> <META NAME="library" CONTENT="log4e"> <META NAME="date" CONTENT="$Date$"> <META NAME="copyright" CONTENT="Copyright (c) 2001 Glenn Maughan and others"> <META NAME="revision" CONTENT="$Revision$"> <META NAME="description" CONTENT="Logging appender that writes to a file."> <META NAME="author" CONTENT="Glenn Maughan <[email protected]>"> <META NAME="license" CONTENT="Eiffel Forum Freeware License v1 (see forum.txt)."> <META NAME="keywords" CONTENT="Eiffel class"> <META NAME="keywords" CONTENT="Eiffel class"> <TITLE>L4E_FILE_APPENDER Contracts</TITLE> <LINK REL="stylesheet" HREF="../../default.css" TYPE="text/css"> <SCRIPT TYPE="text/javascript" SRC="../../goto.html"></SCRIPT> </HEAD> <BODY bgcolor="#FFcc99" text="#000000"> <pre><FORM ONSUBMIT="go_to('../../',this.c.value);return false;"> <TABLE CELLSPACING="5" CELLPADDING="4"><TR> <TD CLASS="link1"><A CLASS="link1" HREF="../../class_list.html">Classes</A></TD> <TD CLASS="link1"><A CLASS="link1" HREF="../../cluster_list.html">Clusters</A></TD> <TD CLASS="link1"><A CLASS="link1" HREF="../../cluster_hierarchy.html">Cluster hierarchy</A></TD> <TD CLASS="link2"><A CLASS="link2" HREF="l4e_file_appender_links.html">Relations</A></TD> <TD CLASS="nolink2">Contracts</TD> <TD CLASS="link2"><A CLASS="link2" HREF="l4e_file_appender_flatshort.html">Flat contracts</A></TD> <TD CLASS="link2">Go to: <INPUT NAME="c" VALUE="L4E_FILE_APPENDER"></TD> </TR></TABLE></FORM><SPAN CLASS="ekeyword">indexing</SPAN> <SPAN CLASS="eitag">description</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"Logging appender that writes to a file."</SPAN> <SPAN CLASS="eitag">project</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"Project Goanna &lt;</SPAN><A CLASS="estring" HREF="http://sourceforge.net/projects/goanna">http://sourceforge.net/projects/goanna</A><SPAN CLASS="estring">&gt;"</SPAN> <SPAN CLASS="eitag">library</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"log4e"</SPAN> <SPAN CLASS="eitag">date</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"$Date$"</SPAN> <SPAN CLASS="eitag">revision</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"$Revision$"</SPAN> <SPAN CLASS="eitag">author</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"Glenn Maughan &lt;</SPAN><A CLASS="estring" HREF="mailto:[email protected]">[email protected]</A><SPAN CLASS="estring">&gt;"</SPAN> <SPAN CLASS="eitag">copyright</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"Copyright (c) 2002 Glenn Maughan"</SPAN> <SPAN CLASS="eitag">license</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="estring">"Eiffel Forum License v1 (see forum.txt)."</SPAN> <SPAN CLASS="ekeyword">class</SPAN> <SPAN CLASS="ekeyword">interface</SPAN> <A CLASS="eclass" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html">L4E_FILE_APPENDER</A> <SPAN CLASS="ekeyword">create</SPAN> <A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_make">make</A> <SPAN CLASS="ekeyword">feature</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Initialisation</SPAN> <A NAME="f_make"><A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_make">make</A> <SPAN CLASS="esymbol">(</SPAN><SPAN CLASS="elocal">new_name</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="neclass">STRING</SPAN><SPAN CLASS="esymbol">;</SPAN> <SPAN CLASS="elocal">appending</SPAN><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="neclass">BOOLEAN</SPAN><SPAN CLASS="esymbol">)</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Create a new file appender on the file</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> with 'name'.</SPAN> <SPAN CLASS="ekeyword">ensure</SPAN> <SPAN CLASS="etag">l4e_stream_open</SPAN><SPAN CLASS="esymbol">:</SPAN> <A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_stream">stream</A><SPAN CLASS="edot">.</SPAN><SPAN CLASS="nefeature">is_open_write</SPAN> </A> <SPAN CLASS="ekeyword">feature</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Status Report</SPAN> <A NAME="f_append_mode"><A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_append_mode">append_mode</A><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="neclass">BOOLEAN</SPAN></A> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Append to file or create new file?</SPAN> <SPAN CLASS="ekeyword">feature</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Basic Operations</SPAN> <A NAME="f_close"><A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_close">close</A> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Release any resources for this appender.</SPAN> </A> <A NAME="f_do_append"><A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_do_append">do_append</A> <SPAN CLASS="esymbol">(</SPAN><SPAN CLASS="elocal">event</SPAN><SPAN CLASS="esymbol">:</SPAN> <A CLASS="eclass" HREF="../../l4e_log4e/l4e_event_short.html">L4E_EVENT</A><SPAN CLASS="esymbol">)</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Log event on this appender.</SPAN> </A> <SPAN CLASS="ekeyword">feature</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Stream</SPAN> <A NAME="f_stream"><A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_stream">stream</A><SPAN CLASS="esymbol">:</SPAN> <SPAN CLASS="neclass">KI_TEXT_OUTPUT_FILE</SPAN></A> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Stream to write log events to</SPAN> <SPAN CLASS="ekeyword">feature</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Removal</SPAN> <A NAME="f_dispose"><A CLASS="efeature" HREF="../../l4e_log4e/l4e_appenders/l4e_file_appender_short.html#f_dispose">dispose</A> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> Close this appender when garbage collected. Perform</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> minimal operations to release resources. Do not call</SPAN> <SPAN CLASS="ecomment">--</SPAN><SPAN CLASS="ecomment"> other object as they may have been garbage collected.</SPAN> </A> <SPAN CLASS="ekeyword">end</SPAN> -- <SPAN CLASS="ecomment">class </SPAN>L4E_FILE_APPENDER<FORM ONSUBMIT="go_to('../../',this.c.value);return false;"> <TABLE CELLSPACING="5" CELLPADDING="4"><TR> <TD CLASS="link1"><A CLASS="link1" HREF="../../class_list.html">Classes</A></TD> <TD CLASS="link1"><A CLASS="link1" HREF="../../cluster_list.html">Clusters</A></TD> <TD CLASS="link1"><A CLASS="link1" HREF="../../cluster_hierarchy.html">Cluster hierarchy</A></TD> <TD CLASS="link2"><A CLASS="link2" HREF="l4e_file_appender_links.html">Relations</A></TD> <TD CLASS="nolink2">Contracts</TD> <TD CLASS="link2"><A CLASS="link2" HREF="l4e_file_appender_flatshort.html">Flat contracts</A></TD> <TD CLASS="link2">Go to: <INPUT NAME="c" VALUE="L4E_FILE_APPENDER"></TD> </TR></TABLE></FORM></pre> <P> Goanna Log4E &#045;&#045; Copyright &copy; 2002 Glenn Maughan </BODY> </HTML>
Eiffel-World/log4e
doc/classes/l4e_log4e/l4e_appenders/l4e_file_appender_short.html
HTML
mit
7,300
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>continuations: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1 / continuations - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> continuations <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-11-16 15:55:17 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-11-16 15:55:17 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.7.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/continuations&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Continuations&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: exceptions&quot; &quot;keyword: monads&quot; &quot;keyword: continuations&quot; &quot;keyword: cps&quot; &quot;category: Computer Science/Semantics and Compilation/Semantics&quot; &quot;category: Miscellaneous/Extracted Programs/Combinatorics&quot; ] authors: [ &quot;Jean-François Monin&quot; ] bug-reports: &quot;https://github.com/coq-contribs/continuations/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/continuations.git&quot; synopsis: &quot;A toolkit to reason with programs raising exceptions&quot; description: &quot;&quot;&quot; We show a way of developing correct functionnal programs raising exceptions. This is made possible using a Continuation Passing Style translation, see the contribution &quot;exceptions&quot; from P. Casteran at Bordeaux. Things are made easier and more modular using some general definitions.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/continuations/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=048bd17ff2fd3e854c3c3384866430ad&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-continuations.8.6.0 coq.8.7.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1). The following dependencies couldn&#39;t be met: - coq-continuations -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-continuations.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.08.1-2.0.5/released/8.7.1/continuations/8.6.0.html
HTML
mit
7,227
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DesignPattern")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("nunit.tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Iliev88/QA-Automation
DesignPattern/Properties/AssemblyInfo.cs
C#
mit
1,257
package io.linuxserver.davos.schedule.workflow.filter; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import io.linuxserver.davos.transfer.ftp.FTPFile; public class ReferentialFileFilterTest { @Test public void shouldReturnAllFTPFilesIfLastScanIsEmpty() { List<FTPFile> newFiles = new ArrayList<>(); newFiles.add(new FTPFile("file1", 0, "", 0, false)); newFiles.add(new FTPFile("file2", 0, "", 0, false)); newFiles.add(new FTPFile("file3", 0, "", 0, false)); List<String> oldFiles = new ArrayList<>(); List<FTPFile> filteredFiles = new ReferentialFileFilter(oldFiles).filter(newFiles); assertThat(filteredFiles).hasSize(3); assertThat(filteredFiles.get(0).getName()).isEqualTo("file1"); assertThat(filteredFiles.get(1).getName()).isEqualTo("file2"); assertThat(filteredFiles.get(2).getName()).isEqualTo("file3"); } @Test public void shouldReturnFilteredFTPFilesIfLastScanIsMissingFiles() { List<FTPFile> newFiles = new ArrayList<>(); newFiles.add(new FTPFile("file1", 0, "", 0, false)); newFiles.add(new FTPFile("file2", 0, "", 0, false)); newFiles.add(new FTPFile("file3", 0, "", 0, false)); List<String> oldFiles = Arrays.asList("file1", "file3"); List<FTPFile> filteredFiles = new ReferentialFileFilter(oldFiles).filter(newFiles); assertThat(filteredFiles).hasSize(1); assertThat(filteredFiles.get(0).getName()).isEqualTo("file2"); } @Test public void shouldReturnEmptyListIfNewFilesAreEmpty() { List<FTPFile> newFiles = new ArrayList<>(); List<String> oldFiles = Arrays.asList("file1", "file3"); List<FTPFile> filteredFiles = new ReferentialFileFilter(oldFiles).filter(newFiles); assertThat(filteredFiles).isEmpty(); } }
linuxserver/davos
src/test/java/io/linuxserver/davos/schedule/workflow/filter/ReferentialFileFilterTest.java
Java
mit
2,054
""" Author: OMKAR PATHAK Created On: 31st July 2017 - Best = Average = O(n log(n)) - Worst = O(n ^ 2) """ import inspect def sort(_list): """ quick_sort algorithm :param _list: list of integers to sort :return: sorted list """ if len(_list) <= 1: return list(_list) pivot = _list[len(_list) // 2] left = [x for x in _list if x < pivot] middle = [x for x in _list if x == pivot] right = [x for x in _list if x > pivot] return sort(left) + middle + sort(right) # TODO: Are these necessary? def time_complexities(): """ Return information on functions time complexity :return: string """ return '''Best Case: O(nlogn), Average Case: O(nlogn), Worst Case: O(n ^ 2)''' def get_code(): """ easily retrieve the source code of the sort function :return: source code """ return inspect.getsource(sort)
OmkarPathak/pygorithm
pygorithm/sorting/quick_sort.py
Python
mit
904
<?php namespace Payment\SecurityBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class UserSearchType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name', 'text', array('label'=>utf8_encode('Usuario:'), 'required'=>false, 'max_length'=>64)); $builder->add('offset','hidden'); $builder->add('limit','hidden'); } public function getName() { return 'userSearch'; } }
efaby/proyect
src/Payment/SecurityBundle/Form/Type/UserSearchType.php
PHP
mit
507
//------------------------------------------------------------------------------ // Copyright (c) 2017 John D. Haughton // // 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. //------------------------------------------------------------------------------ #ifndef STB_MIDI_H #define STB_MIDI_H #include "STB/MidiDecoder.h" #include "STB/MidiFile.h" #endif
AnotherJohnH/Platform
include/STB/Midi.h
C
mit
1,379
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterUsersAddBioColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->text('bio'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('bio'); }); } }
rodineiti/laravel52-blog
database/migrations/2017_05_03_034104_alter_users_add_bio_column.php
PHP
mit
586
module CocoaPodsTrunk VERSION = '1.1.2'.freeze end
NutdanaiVankrua/iOSSwift
vendor/bundle/ruby/2.3.0/gems/cocoapods-trunk-1.1.2/lib/cocoapods_trunk.rb
Ruby
mit
53
using System; using Microsoft.AspNetCore.Mvc; namespace tekconf.web.Controllers { public class AccountController : Controller { public IActionResult AccessDenied() { return View(); } } }
tekconf/tekconf
tekconf.web/Controllers/AccountController.cs
C#
mit
240
function addToBasket(opt,ajaxNeeded) { if(ajaxNeeded) { $.ajax({ url: 'http://localhost/online_shop/laravel/public/addBasket', type: "get", data: opt, success: function (data) { alert("data=" + data); } }); } if($('#content ul.list-cart li[pid="'+opt.id+'"]').length) { var prev_count = $('#content ul.list-cart li[pid="'+opt.id+'"] .count span').text(); $('#content ul.list-cart li[pid="'+opt.id+'"] .count span').html((parseInt(prev_count) + parseInt(opt.num))); updateSum(); return; } html = ''; html += '<li pid="'+ opt.id +'">'; html += '<div class="wall">'; if (opt.img_url) { html += '<a href="' + site_url + '/pages/products/' + opt.id + '.php" class = "pro-img fr"><img src="'+ opt.img_url +'" alt="'+ name +'" width="80" height="80" /></a>'; } else { html += '<a href="' + site_url + '/pages/products/' + opt.id + '.php" class = "pro-img fr"><img src="'+ site_url +'assets/img/no_image.jpg" alt="" width="80" height="80" /></a>'; } html += '</div>'; html += '<div class="info">'; html += '<a class="de" onclick="removeFromBasket(this)">&times;</a>'; html += '<a class="name" href="' + site_url + '/pages/products/' + opt.id + '.php">' + opt.name + '</a>'; html += '<div class="count">تعداد :<span>' + opt.num + '</span></div>'; html += '<div class="price" amount="'+ opt.price +'"><span>' + num2fa(opt.price) + '&nbsp;</span>تومان</div>'; html += '</div>'; html += '</li>'; $('#content ul.list-cart').append(html); var num = $("#popModal_ex1 .shop_num").html(); if(num > 0) num++; else num = 1; $("#popModal_ex1 .shop_num").html(num); updateSum(); }; function removeFromBasket(target) { target = $(target); var pid = target.closest("li").attr("pid"); $.ajax({ url: 'http://localhost/online_shop/laravel/public/removeBasket', type: "get", data: {'id':pid}, success: function(data){ alert("data="+data); } }); target.closest("li").remove(); $("#popModal_ex1 .shop_num").html(parseInt($("#popModal_ex1 .shop_num").html()) - 1); updateSum(); } function updateSum() { var sum = 0; $("#content ul.list-cart li").each(function(index){ price = $(this).find(".price").attr("amount"); num = $(this).find(".count span").text(); sum += parseInt(parseInt(price) * parseInt(num)); }); $("#content .bottom .fine span.amount").html( num2fa(sum) ); } function getBasket() { var basket; $.ajax({ url: 'http://localhost/online_shop/laravel/public/getBasket', type: "get", dataType: 'json', success: function (data) { $.each(data, function(index, element) { addToBasket(element,false); }); } }); }
shayan-ys/online_shop
laravel/public/assets/js/basket2.js
JavaScript
mit
2,734
package net.bialon.dropwizard.metrics.influxdb; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.ScheduledReporter; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import io.dropwizard.metrics.BaseReporterFactory; import metrics_influxdb.InfluxdbReporter; import metrics_influxdb.api.protocols.InfluxdbProtocol; import metrics_influxdb.api.protocols.InfluxdbProtocols; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; /** * A factory for {@link InfluxDBReporterFactory} instances. */ @JsonTypeName("influxdb") public class InfluxDBReporterFactory extends BaseReporterFactory { private String prefix; @NotEmpty private String host = "localhost"; @Range(min = 1, max = 49151) private int port = 8086; private String database; private String username; private String password; private boolean skipIdle = false; @JsonProperty public String getPrefix() { return prefix; } @JsonProperty public void setPrefix(String prefix) { this.prefix = prefix; } @JsonProperty public String getHost() { return host; } @JsonProperty public void setHost(String host) { this.host = host; } @JsonProperty public int getPort() { return port; } @JsonProperty public void setPort(int port) { this.port = port; } @JsonProperty public String getDatabase() { return database; } @JsonProperty public void setDatabase(String database) { this.database = database; } @JsonProperty public String getUsername() { return username; } @JsonProperty public void setUsername(String username) { this.username = username; } @JsonProperty public String getPassword() { return password; } @JsonProperty public void setPassword(String password) { this.password = password; } @JsonProperty public boolean isSkipIdle() { return skipIdle; } @JsonProperty public void setSkipIdle(boolean skipIdle) { this.skipIdle = skipIdle; } public ScheduledReporter build(MetricRegistry registry) { InfluxdbProtocol protocol = InfluxdbProtocols.http(host, port, username, password, database); return InfluxdbReporter.forRegistry(registry) .protocol(protocol) .convertDurationsTo(getDurationUnit()) .convertRatesTo(getRateUnit()) .filter(getFilter()) .prefixedWith(getPrefix()) .skipIdleMetrics(isSkipIdle()) .build(); } }
mbialon/dropwizard-metrics-influxdb
src/main/java/net/bialon/dropwizard/metrics/influxdb/InfluxDBReporterFactory.java
Java
mit
2,774
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; namespace ImmaChatService { public class ChatBL { public DataSet user_login(string username, string password) { DataSet dset_login = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select username, password, first_name, last_name, gender, date_of_birth from users where username='" + username + "' and password='" + password + "'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_login = dbclass.Dbdset; } catch (Exception ex) { dset_login = null; } return dset_login; } public DataSet user_exists(string username) { DataSet dset_user_exists = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select 1 from users where username='" + username + "'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_user_exists = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_user_exists; } public string generate_serial(string serial_code) { string serial_value = " "; string sp_name = "generate_serials"; DBAccessClass dbclass = new DBAccessClass(); DataTable dtable = new DataTable(); try { dbclass.SerialCode = serial_code; dtable = dbclass.ExecuteStoredProc(sp_name).Tables["dbTable"]; serial_value = dtable.Rows[0]["value"].ToString(); } catch (Exception ex) { throw; } return serial_value; } public string insert_userInfo(Users userObj) { DBAccessClass dbclass = new DBAccessClass(); string SqlStatement = ""; try { DateTime dob = DateTime.Parse(userObj.date_of_birth); string user_id = generate_serial("USER"); SqlStatement += @" insert into users(user_id, username, password, first_name, last_name, gender, date_of_birth) "; SqlStatement += @" values('" + user_id + "','" + userObj.username + "','" + userObj.password + "','" + userObj.first_name + "','" + userObj.last_name + "','" + userObj.gender + "',CONVERT(datetime,'" + dob + "',102))"; dbclass.AddSqlStatements(SqlStatement); } catch (Exception ex) { throw new Exception("There was an error inserting", ex); } return dbclass.ExecuteSqlStatements(); } public DataSet get_friends(string username) { DataSet dset_friends = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select friend_id, username_1, username_2 from friends where (username_1 = '" + username + "' or username_2 = '" + username + "') and status = 'FRIENDS'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_friends = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_friends; } public DataSet load_userInfo(string username) { DataSet dset_userInfo= new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select username, first_name, last_name, gender, date_of_birth, status from users where username ='" + username + "'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_userInfo = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_userInfo; } public DataSet load_allUsers(string username) { DataSet dset_allUsers = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select * from users where username not like '" + username + "'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_allUsers = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_allUsers; } public DataSet load_messages(string username) { DataSet dset_messages = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select * from messages where user_from ='" + username + "' or user_to ='" + username + "'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_messages = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_messages; } public DataSet load_profileInfo(string username) { DataSet dset_profile = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select * from users where username ='" + username + "'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_profile = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_profile; } public string send_message(string user_from, string user_to, string message) { DBAccessClass dbclass = new DBAccessClass(); string SqlStatement = ""; try { SqlStatement += @"insert into [messages] (user_from, user_to, [message]) "; SqlStatement += @"values('" + user_from + "','" + user_to + "','" + message + "')"; dbclass.AddSqlStatements(SqlStatement); } catch (Exception ex) { throw new Exception("There was an error inserting", ex); } return dbclass.ExecuteSqlStatements(); } public string send_friendRequest(string username_1, string username_2) { DBAccessClass dbclass = new DBAccessClass(); string SqlStatement = ""; try { string friend_id = generate_serial("FRND"); SqlStatement += @"insert into friends(friend_id, username_1, username_2, status) "; SqlStatement += @"values('" + friend_id + "','" + username_1 + "','" + username_2 + "','PENDING')"; dbclass.AddSqlStatements(SqlStatement); } catch (Exception ex) { throw new Exception("There was an error inserting", ex); } return dbclass.ExecuteSqlStatements(); } public string accept_friendRequest(string username_1, string username_2) { DBAccessClass dbclass = new DBAccessClass(); string SqlStatement = ""; try { SqlStatement += @"update friends set status = 'FRIENDS' where (username_1 = '"+ username_1 + "' and username_2 = '" + username_2 + "') or (username_2 = '" + username_1 + "' and username_1 = '" + username_2 + "')"; dbclass.AddSqlStatements(SqlStatement); } catch (Exception ex) { throw new Exception("There was an error inserting", ex); } return dbclass.ExecuteSqlStatements(); } public string reject_friendRequest(string username_1, string username_2) { DBAccessClass dbclass = new DBAccessClass(); string SqlStatement = ""; try { SqlStatement += @"update friends set status = 'NULL' (where username_1 = '" + username_1 + "' and username_2 = '" + username_2 + "') or (where username_2 = '" + username_1 + "' and username_1 = '" + username_2 + "')"; dbclass.AddSqlStatements(SqlStatement); } catch (Exception ex) { throw new Exception("There was an error inserting", ex); } return dbclass.ExecuteSqlStatements(); } public DataSet friend_status(string username_1, string username_2) { DataSet dset_status = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select status from friends where (username_1 ='" + username_1 + "' and username_2 ='" + username_2 + "') or (username_1 ='" + username_2 + "' and username_2 ='" + username_1 + "')"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_status = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_status; } public string logout(string username) { DBAccessClass dbclass = new DBAccessClass(); string SqlStatement = ""; try { SqlStatement += @"update users set status = 'OFFLINE' where username = '" + username + "'"; dbclass.AddSqlStatements(SqlStatement); } catch (Exception ex) { throw new Exception("There was an error inserting", ex); } return dbclass.ExecuteSqlStatements(); } public string logged_in(string username) { DBAccessClass dbclass = new DBAccessClass(); string SqlStatement = ""; try { SqlStatement += @"update users set status = 'ONLINE' where username = '" + username + "'"; dbclass.AddSqlStatements(SqlStatement); } catch (Exception ex) { throw new Exception("There was an error inserting", ex); } return dbclass.ExecuteSqlStatements(); } public DataSet notify_request(string username) { DataSet dset_notify = new DataSet(); string SqlStatement = ""; try { SqlStatement = @" select username_1, username_2 from friends where (username_1 ='" + username + "' or username_2 ='" + username + "') and status = 'PENDING'"; DBAccessClass dbclass = new DBAccessClass(); dbclass.SearchSqlStatements(SqlStatement); dset_notify = dbclass.Dbdset; } catch (Exception ex) { throw; } return dset_notify; } } }
nyandikadon/Chat-Application
ImmaChatService/ImmaChatService/ChatBL.cs
C#
mit
11,595
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Majulak { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); app.UseDefaultFiles(); app.UseStaticFiles(); } } }
Flosus/Majulak
src/Majulak/Startup.cs
C#
mit
1,557
def create_foi_case_step(type: 'standard', delivery_method: :sent_by_email, uploaded_request_files: [], flag_for_disclosure: false) # Assume we are on a case listing page expect(cases_page).to have_new_case_button cases_page.new_case_button.click expect(cases_new_page).to be_displayed cases_new_page.create_link_for_correspondence('FOI').click expect(cases_new_foi_page).to be_displayed # cases_new_foi_page.fill_in_case_type(type) cases_new_foi_page.fill_in_case_details( type: type, delivery_method: delivery_method, uploaded_request_files: uploaded_request_files ) cases_new_foi_page.choose_flag_for_disclosure_specialists( flag_for_disclosure ? 'yes' : 'no' ) click_button 'Create case' # Return the case we created using the params of the current path kase_id = Rails.application.routes.recognize_path(current_path)[:case_id] Case::Base.find(kase_id) end def create_foi_case_auto_flagged_step(type: 'standard', delivery_method: :sent_by_email, uploaded_request_files: []) # Assume we are on a case listing page expect(cases_page).to have_new_case_button cases_page.new_case_button.click expect(cases_new_page).to be_displayed cases_new_page.create_link_for_correspondence('FOI').click expect(cases_new_foi_page).to be_displayed 2.times do cases_new_foi_page.fill_in_case_details( type: 'standard', delivery_method: delivery_method, uploaded_request_files: uploaded_request_files, ) expect(cases_new_foi_page).to have_content("Flag for disclosure specialists") cases_new_foi_page.fill_in_case_details( type: type, delivery_method: delivery_method, uploaded_request_files: uploaded_request_files, flag_for_disclosure_specialists: false ) expect(cases_new_foi_page).to_not have_content("Flag for disclosure specialists") end click_button 'Create case' # Return the case we created using the params of the current path kase_id = Rails.application.routes.recognize_path(current_path)[:case_id] Case::Base.find(kase_id) end def create_ico_case_step(original_case:, related_cases: [], uploaded_request_files: []) # Assume we are on a case listing page expect(cases_page).to have_new_case_button cases_page.new_case_button.click expect(cases_new_page).to be_displayed cases_new_page.create_link_for_correspondence('ICO').click expect(cases_new_ico_page).to be_displayed cases_new_ico_page.form.fill_in_case_details( uploaded_request_files: uploaded_request_files ) cases_new_ico_page.form.add_original_case(original_case) cases_new_ico_page.form.add_related_cases(related_cases) click_button 'Create case' expect(assignments_new_page).to be_displayed # Return the case we created using the params of the current path kase_id = Rails.application.routes.recognize_path(current_path)[:case_id] Case::Base.find(kase_id) end def create_sar_case_step(params={}) flag_for_disclosure = params.delete(:flag_for_disclosure) { false } # Assume we are on a case listing page expect(cases_page).to have_new_case_button cases_page.new_case_button.click expect(cases_new_page).to be_displayed cases_new_page.create_link_for_correspondence('SAR - Subject access request').click expect(cases_new_sar_page).to be_displayed cases_new_sar_page.fill_in_case_details(params) scroll_to cases_new_sar_page.choose_flag_for_disclosure_specialists cases_new_sar_page.choose_flag_for_disclosure_specialists( flag_for_disclosure ? 'yes' : 'no' ) click_button 'Create case' # Return the case we created using the params of the current path kase_id = Rails.application.routes.recognize_path(current_path)[:case_id] expect(assignments_new_page).to be_displayed(case_id: kase_id) Case::Base.find(kase_id) end def create_offender_sar_case_step(params = {}) # flag_for_disclosure = params.delete(:flag_for_disclosure) { false } # Assume we are on a case listing page expect(cases_page).to have_new_case_button cases_page.new_case_button.click expect(cases_new_page).to be_displayed cases_new_page.create_link_for_correspondence('OFFENDER').click expect(cases_new_offender_sar_subject_details_page).to be_displayed cases_new_offender_sar_subject_details_page.fill_in_case_details(params) click_on "Continue" expect(cases_new_offender_sar_requester_details_page).to be_displayed cases_new_offender_sar_requester_details_page.fill_in_case_details(params) click_on "Continue" expect(cases_new_offender_sar_requested_info_page).to be_displayed cases_new_offender_sar_requested_info_page.fill_in_case_details(params) click_on "Continue" expect(cases_new_offender_sar_date_received_page).to be_displayed cases_new_offender_sar_date_received_page.fill_in_case_details(params) click_on "Continue" expect(cases_show_page).to be_displayed expect(cases_show_page).to have_content "Case created successfully" expect(cases_show_page.page_heading).to have_content "Sabrina Adams" click_on "Cases" expect(open_cases_page).to be_displayed expect(cases_page).to have_content "Branston Registry" expect(open_cases_page).to have_content "Sabrina Adams" end def create_overturned_ico_case_step(params={}) # rubocop:disable Metrics/MethodLength ico_case = params.delete(:ico_case) flagged = params.delete(:flag_for_disclosure) case_type = params[:case_type].downcase cases_show_page.load(id: ico_case.id) expect(cases_show_page).to be_displayed(id: ico_case.id) # Replace the following-line with a click on the "New overturned case" # button when available cases_show_page.actions.create_overturned.click if case_type.upcase == 'SAR' new_overturned_ico_page = cases_new_sar_overturned_ico_page else new_overturned_ico_page = cases_new_foi_overturned_ico_page end expect(new_overturned_ico_page).to be_displayed(id: ico_case.id) expect(new_overturned_ico_page).to have_form expect(new_overturned_ico_page).to have_text(ico_case.number) form = new_overturned_ico_page.form final_deadline = 10.business_days.from_now form.final_deadline.day.set(final_deadline.day) form.final_deadline.month.set(final_deadline.month) form.final_deadline.year.set(final_deadline.year) expect(form.has_checked_field?('By email', visible: false)).to eq true expect(form.has_field?( "Name of the ICO information officer who's handling this case", with: ico_case.ico_officer_name, type: :text )).to eq true if form.has_flag_for_disclosure_specialists? form.choose_flag_for_disclosure_specialists(flagged ? 'yes' : 'no', case_type: case_type.downcase) end click_button 'Create case' # Return the case we created using the params of the current path kase_id = Rails.application.routes.recognize_path(current_path)[:case_id] Case::Base.find(kase_id) end
ministryofjustice/correspondence_tool_staff
spec/support/features/steps/cases/create_steps.rb
Ruby
mit
7,054
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07. SumNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07. SumNumbers")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3bf658da-9ed4-475b-ba61-005829f2dc18")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
kalinalazarova1/TelerikAcademy
Programming/1. CSharpPartOne/CS1_04.Console Input and Output/07. SumNumbers/Properties/AssemblyInfo.cs
C#
mit
1,404
<?php /* * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Types; /** * Type that maps a PHP array to a clob SQL type. * * @since 2.0 */ class ArrayType extends Type { public function getSQLDeclaration(array $fieldDeclaration, \Doctrine\DBAL\Platforms\AbstractPlatform $platform) { return $platform->getClobTypeDeclarationSQL($fieldDeclaration); } public function convertToDatabaseValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform) { return serialize($value); } public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform) { if ($value === null) { return null; } $value = (is_resource($value)) ? stream_get_contents($value) : $value; $val = unserialize($value); if ($val === false && $value != 'b:0;') { throw ConversionException::conversionFailed($value, $this->getName()); } return $val; } public function getName() { return Type::TARRAY; } }
flyingfeet/FlyingFeet
vendor/doctrine-dbal/lib/Doctrine/DBAL/Types/ArrayType.php
PHP
mit
1,885
// This file is part of the AliceVision project. // Copyright (c) 2016 AliceVision contributors. // Copyright (c) 2012 openMVG contributors. // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at https://mozilla.org/MPL/2.0/. #include "ImageDescriber_AKAZE_OCV.hpp" #include "aliceVision/image/all.hpp" #include <opencv2/opencv.hpp> #include <opencv2/core/eigen.hpp> namespace aliceVision { namespace feature { bool ImageDescriber_AKAZE_OCV::describe(const image::Image<unsigned char>& image, std::unique_ptr<Regions>& regions, const image::Image<unsigned char>* mask) { cv::Mat img; cv::eigen2cv(image.GetMat(), img); std::vector< cv::KeyPoint > vec_keypoints; cv::Mat m_desc; cv::Ptr<cv::Feature2D> extractor = cv::AKAZE::create(cv::AKAZE::DESCRIPTOR_KAZE); extractor->detectAndCompute(img, cv::Mat(), vec_keypoints, m_desc); if (vec_keypoints.empty()) { return false; } allocate(regions); // Build alias to cached data AKAZE_Float_Regions* regionsCasted = dynamic_cast<AKAZE_Float_Regions*>(regions.get()); // Reserve some memory for faster keypoint saving regionsCasted->Features().reserve(vec_keypoints.size()); regionsCasted->Descriptors().reserve(vec_keypoints.size()); typedef Descriptor<float, 64> DescriptorT; DescriptorT descriptor; int cpt = 0; for(const auto& i_keypoint : vec_keypoints) { SIOPointFeature feat(i_keypoint.pt.x, i_keypoint.pt.y, i_keypoint.size, i_keypoint.angle); regionsCasted->Features().push_back(feat); memcpy(descriptor.getData(), m_desc.ptr<typename DescriptorT::bin_type>(cpt), DescriptorT::static_size*sizeof(DescriptorT::bin_type)); regionsCasted->Descriptors().push_back(descriptor); ++cpt; } return true; } } //namespace feature } //namespace aliceVision
poparteu/openMVG
src/aliceVision/feature/openCV/ImageDescriber_AKAZE_OCV.cpp
C++
mit
2,007
export const ic_hourglass_top_outline = {"viewBox":"0 0 24 24","children":[{"name":"g","attribs":{},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[]}]}]},{"name":"g","attribs":{},"children":[{"name":"path","attribs":{"d":"M6,2l0.01,6L10,12l-3.99,4.01L6,22h12v-6l-4-4l4-3.99V2H6z M16,16.5V20H8v-3.5l4-4L16,16.5z"},"children":[{"name":"path","attribs":{"d":"M6,2l0.01,6L10,12l-3.99,4.01L6,22h12v-6l-4-4l4-3.99V2H6z M16,16.5V20H8v-3.5l4-4L16,16.5z"},"children":[]}]}]}]};
wmira/react-icons-kit
src/md/ic_hourglass_top_outline.js
JavaScript
mit
593
# DINOKIKI Available at http://dinokiki.com ## What is Dinokiki? Dinokiki is an interactive website with one purpose: have fun!!! Turn your audio on and click on the Dinosaur and get ready! Everytime you click over him a jQuery function randomly calls one of the kikis. ## Build Setup ``` bash # install dependencies npm install # serve with hot reload at localhost:8080 npm run dev # build for production with minification npm run build # build for production and view the bundle analyzer report npm run build --report ``` For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
giuliacardieri/dinokiki
README.md
Markdown
mit
703
FROM ubuntu:16.04 MAINTAINER [email protected] ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && \ apt-get -y install python-pip && \ pip install awscli && \ apt-get autoremove && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* ADD s3-backup-tools.sh /opt/s3-backup-tools.sh ENTRYPOINT ["/opt/s3-backup-tools.sh"]
anduintransaction/Dockerfiles
s3backup/Dockerfile
Dockerfile
mit
366
from __future__ import unicode_literals NAME = "dermitch/redis" # Booleans AT_MITCH_HOME = True # Scalar values PORT = 6379 # Underscore var for validation and/or transformation # Can be a list, dict or any callable _DATABASE = ( "mysql", "postgres", ) DATABASE = "mysql" # If you use a dict as transform, the renderer will # use the value of the mapping instead of the key _FOO = { 'a': 'foo', 'b': 'bar' } FOO = "b" # FOO will be 'bar' later # If you use a callable, it's result will be used def _HOST_IP(value): import socket return socket.gethostbyname(value) # Default argument for _HOST_IP() HOST_IP = "google.de"
DerMitch/dodo
testconfig.py
Python
mit
640
{% extends 'layouts/main.html' %} {% block title %}Home{% endblock %} {% block content %} <!-- upper main stats --> <div id="main-stats"> <div class="row stats-row"> <div class="col-md-3 col-sm-3 stat"> <div class="data"> <span class="number">70,300</span> stars </div> <span class="date">in database</span> </div> <div class="col-md-3 col-sm-3 stat"> <div class="data"> <span class="number">0</span> stars </div> <span class="date">analysed</span> </div> <div class="col-md-3 col-sm-3 stat"> <div class="data"> <span class="number">5</span> collaborators </div> <span class="date">active this week</span> </div> <div class="col-md-3 col-sm-3 stat last"> <div class="data"> <span class="number">322</span> visits </div> <span class="date">last 30 days</span> </div> </div> </div> <!-- end upper main stats --> <div id="pad-wrapper"> <!-- statistics chart built with jQuery Flot --> <div class="row chart"> <div class="col-md-12"> <h4 class="clearfix pull-left"> Statistics </h4> <div class="btn-group pull-right"> <button class="glow left">DAY</button> <button class="glow middle active">MONTH</button> <button class="glow right">YEAR</button> </div> </div> <div class="col-md-12"> <div id="statsChart"></div> </div> </div> <!-- end statistics chart --> <!-- UI Elements section --> <div class="row section ui-elements"> <div class="col-md-12"> <h4>UI Elements</h4> </div> <div class="col-md-5 knobs"> <div class="knob-wrapper"> <input type="text" value="50" class="knob" data-thickness=".3" data-inputColor="#333" data-fgColor="#30a1ec" data-bgColor="#d4ecfd" data-width="150"> <div class="info"> <div class="param"> <span class="line blue"></span> Active users </div> </div> </div> <div class="knob-wrapper"> <input type="text" value="75" class="knob second" data-thickness=".3" data-inputColor="#333" data-fgColor="#3d88ba" data-bgColor="#d4ecfd" data-width="150"> <div class="info"> <div class="param"> <span class="line blue"></span> % disk space usage </div> </div> </div> </div> <div class="col-md-6 showcase"> <div class="ui-sliders"> <div class="slider slider-sample1 vertical-handler"></div> <div class="slider slider-sample2"></div> <div class="slider slider-sample3"></div> </div> <div class="ui-group"> <a class="btn-flat inverse">Large Button</a> <a class="btn-flat gray">Large Button</a> <a class="btn-flat default">Large Button</a> <a class="btn-flat primary">Large Button</a> </div> <div class="ui-group"> <a class="btn-flat icon"> <i class="tool"></i> Icon button </a> <a class="btn-glow small inverse"> <i class="shuffle"></i> </a> <a class="btn-glow small primary"> <i class="setting"></i> </a> <a class="btn-glow small default"> <i class="attach"></i> </a> <div class="ui-select"> <select> <option selected>Dropdown</option> <option>Custom selects</option> <option>Pure css styles</option> </select> </div> <div class="btn-group"> <button class="glow left">LEFT</button> <button class="glow right">RIGHT</button> </div> </div> </div> </div> <!-- end UI elements section --> <!-- table sample --> <!-- the script for the toggle all checkboxes from header is located in js/theme.js --> <div class="table-products section"> <div class="row head"> <div class="col-md-12"> <h4>Products <small>Table sample</small></h4> </div> </div> <div class="row filter-block"> <div class="col-md-8 col-md-offset-5"> <div class="ui-select"> <select> <option>Filter users</option> <option>Signed last 30 days</option> <option>Active users</option> </select> </div> <input type="text" class="search"> <a class="btn-flat new-product">+ Add product</a> </div> </div> <div class="row"> <table class="table table-hover"> <thead> <tr> <th class="col-md-3"> <input type="checkbox"> Product </th> <th class="col-md-3"> <span class="line"></span>Description </th> <th class="col-md-3"> <span class="line"></span>Status </th> </tr> </thead> <tbody> <!-- row --> <tr class="first"> <td> <input type="checkbox"> <div class="img"> <img src="img/table-img.png" alt="pic" /> </div> <a href="#">There are many variations </a> </td> <td class="description"> if you are going to use a passage of Lorem Ipsum. </td> <td> <span class="label label-success">Active</span> <ul class="actions"> <li><i class="table-edit"></i></li> <li><i class="table-settings"></i></li> <li class="last"><i class="table-delete"></i></li> </ul> </td> </tr> <!-- row --> <tr> <td> <input type="checkbox"> <div class="img"> <img src="img/table-img.png" alt="pic" /> </div> <a href="#">Internet tend</a> </td> <td class="description"> There are many variations of passages. </td> <td> <ul class="actions"> <li><i class="table-edit"></i></li> <li><i class="table-settings"></i></li> <li class="last"><i class="table-delete"></i></li> </ul> </td> </tr> <!-- row --> <tr> <td> <input type="checkbox"> <div class="img"> <img src="img/table-img.png" alt="pic" /> </div> <a href="#">Many desktop publishing </a> </td> <td class="description"> if you are going to use a passage of Lorem Ipsum. </td> <td> <ul class="actions"> <li><i class="table-edit"></i></li> <li><i class="table-settings"></i></li> <li class="last"><i class="table-delete"></i></li> </ul> </td> </tr> <!-- row --> <tr> <td> <input type="checkbox"> <div class="img"> <img src="img/table-img.png" alt="pic" /> </div> <a href="#">Generate Lorem </a> </td> <td class="description"> There are many variations of passages. </td> <td> <span class="label label-info">Standby</span> <ul class="actions"> <li><i class="table-edit"></i></li> <li><i class="table-settings"></i></li> <li class="last"><i class="table-delete"></i></li> </ul> </td> </tr> <!-- row --> <tr> <td> <input type="checkbox"> <div class="img"> <img src="img/table-img.png" alt="pic" /> </div> <a href="#">Internet tend</a> </td> <td class="description"> There are many variations of passages. </td> <td> <ul class="actions"> <li><i class="table-edit"></i></li> <li><i class="table-settings"></i></li> <li class="last"><i class="table-delete"></i></li> </ul> </td> </tr> </tbody> </table> </div> <ul class="pagination"> <li><a href="#">&laquo;</a></li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">&raquo;</a></li> </ul> </div> <!-- end table sample --> </div> {% endblock %}
andycasey/original-oracle
flask-app/templates/pages/placeholder.home.html
HTML
mit
11,379
root = "/home/deploy/htc/current" worker_processes 4 working_directory "/home/deploy/htc/current" # available in 0.94.0+ listen "/tmp/unicorn.htc.sock", :backlog => 64 listen 8080, :tcp_nopush => true timeout 30 pid "/home/deploy/htc/current/tmp/pids/unicorn.pid" stderr_path "/home/deploy/htc/current/log/unicorn.stderr.log" stdout_path "/home/deploy/htc/current/log/unicorn.stdout.log"
rubyonrails3/unicorn_deployer
config/unicorn.rb
Ruby
mit
389
def userdata_openvpn() return <<-EOM #!/bin/bash export DEBIAN_FRONTEND=noninteractive; export PUBLIC_IP=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address) export PRIVATE_IP=$(curl -s http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address) #Install OpenVPN apt-get update apt-get install -y openvpn apt-get install -y easy-rsa #Generate Server Certificates cp -r /usr/share/easy-rsa /etc/openvpn/easy-rsa cd /etc/openvpn/easy-rsa mkdir keys source ./vars ./clean-all ./pkitool --batch --initca ./pkitool --batch --server server ./build-dh openssl dhparam -out /etc/openvpn/dh1024.pem 2048 cp /etc/openvpn/easy-rsa/keys/ca.crt /etc/openvpn cp /etc/openvpn/easy-rsa/keys/ca.key /etc/openvpn cp /etc/openvpn/easy-rsa/keys/server.crt /etc/openvpn cp /etc/openvpn/easy-rsa/keys/server.key /etc/openvpn cd /etc/openvpn/easy-rsa source ./vars ./pkitool --batch user1 #add user/group openvpn adduser --system --no-create-home --disabled-login openvpn addgroup --system --no-create-home --disabled-login openvpn #copy configuration files / unpack them cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/ gunzip /etc/openvpn/server.conf.gz cd /etc/openvpn #Configure aspects of the VPN server echo "user openvpn" >> server.conf echo "group openvpn" >> server.conf echo 'push "redirect-gateway def1"' >> server.conf echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j SNAT --to $PUBLIC_IP service openvpn restart EOM end
CloudCowboyCo/do-openvpn
userdata_openvpn.rb
Ruby
mit
1,529
import { Component, OnInit, ViewChild } from '@angular/core'; import { Registry } from '../../entities/registry'; import { RegistryService } from '../../services/registry.service'; import { DialogComponent } from '../dialog/dialog.component'; @Component({ selector: 'app-registry', templateUrl: './registry.component.html', styleUrls: ['./registry.component.css'] }) export class RegistryComponent implements OnInit { registries: Registry[]; registry: Registry; @ViewChild(DialogComponent) private dialog: DialogComponent; constructor(private registryService: RegistryService) { this.registries = []; this.registry = new Registry(); } onFetchRegistries() { this.registryService.getRegistries().then(registries => { console.log(registries); this.registries = registries; }); } ngOnInit() { this.onFetchRegistries(); } onAdd() { this.registryService.addRegistry(this.registry).then(registry => { this.registry = new Registry(); console.log('Registry:', registry); this.onFetchRegistries(); this.dialog.close(); }); } }
euskadi31/docker-manager
ui/src/app/components/registry/registry.component.ts
TypeScript
mit
1,220
<?php namespace Phile\Plugin\Siezi\PhileTotalCache; use Phile\Core\ServiceLocator; class PageCache { protected $cache; protected $cacheId; public function __construct($cacheId) { if (ServiceLocator::hasService('Phile_Cache')) { $this->cache = ServiceLocator::getService('Phile_Cache'); } $this->cacheId = 'siezi-phileTotalCache.' . md5($cacheId); } public function get() { if (!$this->cache || !$this->cache->has($this->cacheId)) { return; } return $this->cache->get($this->cacheId); } public function set($body, array $options = []) { if (!$this->cache) { return; } $page = ['body' => $body] + $options; $this->cache->set($this->cacheId, $page); } }
Schlaefer/phileTotalCache
Classes/PageCache.php
PHP
mit
697
.PHONY: gdal vagrant gdal: sudo apt-get install --ignore-missing -y subversion python-numpy python-dev postgis postgresql-server-dev-9.1 postgresql-9.1-postgis libpq-dev libpng12-dev libjpeg-dev libgif-dev liblzma-dev libgeos-dev libcurl4-gnutls-dev libproj-dev libxml2-dev libexpat-dev libxerces-c-dev libxerces-c3.1 libnetcdf-dev netcdf-bin libpoppler-dev libspatialite-dev gpsbabel swig libhdf4-alt-dev libhdf5-serial-dev libpodofo-dev poppler-utils libfreexl-dev unixodbc-dev libwebp-dev openjdk-7-jdk libepsilon-dev liblcms2-2 libpcre3-dev libjasper-dev libarmadillo-dev make g++ autoconf cmake bison flex libkml0 libkml-dev vim && \ sudo ldconfig && \ curl -L http://download.osgeo.org/gdal/1.10.1/gdal-1.10.1.tar.gz -s -o - | tar xz -C . -f - && \ cd gdal-* && \ sudo mkdir -p /home/travis/build/gdal && \ sudo ./configure --prefix=/home/travis/build/gdal \ --with-pcraster=no \ --with-jasper=no \ --with-grib=no \ --with-vfk=no \ --with-hide-internal-symbols \ --with-xerces && \ sudo make install && \ cd /home/travis/build/gdal && \ sudo cp /usr/lib/libxerces* ./lib && \ sudo cp /usr/lib/libicu* ./lib && \ tar zcf /vagrant/gdal-1.10.1-precise64.tar.gz . vagrant: vagrant init precise64 && \ vagrant up && \ vagrant ssh
hsr-ba-fs15-dat/opendatahub
.travis/gdal/Makefile
Makefile
mit
1,259
namespace EngineOverflow.Data.Common.Models { using System; public interface IAuditInfo { DateTime CreatedOn { get; set; } bool PreserveCreatedOn { get; set; } DateTime? ModifiedOn { get; set; } } }
delyan-nikolov-1992/EngineOverflow
Source/Data/EngineOverflow.Data.Common/Models/IAuditInfo.cs
C#
mit
245
import fetch from 'node-fetch'; import fs from 'fs'; import { PATHS } from '../utils/constants'; import path from 'path'; var name = process.argv.slice(3)[0], type = process.argv.slice(2)[0], camelCasedType = `${type[0].toUpperCase()}${type.slice(1)}`, camelCasedName = `${name[0].toUpperCase()}${name.slice(1)}`, url = `https://raw.githubusercontent.com/DCKT/express-boilerplate/master/app/${type}s/Index${camelCasedType}.js`; var filePath = PATHS[type]; fs.stat(`${filePath}/${camelCasedName}${camelCasedType}.js`, exist => { exist == null ? fileExist() : createFile() }); function createFile () { fetch(url) .then(res => { return res.text(); }) .then(body => { var file = body.replace(/Home|Index/g, camelCasedName).replace('path: /', `path: /${name.toLowerCase()}`); fs.writeFile(`${filePath}/${camelCasedName}${camelCasedType}.js`, file, (err, data) => { if (err) { console.error(err); return; } else { console.log("File created !") } }); }) .catch(function(ex) { console.log('Something went wrong fetching file', ex) }); } function fileExist () { console.log("\n###### WAIT ######"); console.log(`You already have a route file named : ${camelCasedName}Route.js`); }
DCKT/ShortLink
tasks/new.js
JavaScript
mit
1,332
from argparse import ArgumentParser import os import sys from coverage import Coverage import django from django.conf import settings from termcolor import colored TESTS_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) TESTS_THRESHOLD = 100 def main(): parser = ArgumentParser(description='Run the dj-stripe Test Suite.') parser.add_argument( "--no-coverage", action="store_true", help="Disable checking for 100% code coverage (Not advised)." ) parser.add_argument("tests", nargs='*', default=['.']) args = parser.parse_args() run_test_suite(args) def run_test_suite(args): enable_coverage = not args.no_coverage tests = args.tests if enable_coverage: cov = Coverage(config_file=True) cov.erase() cov.start() settings.configure( DEBUG=True, USE_TZ=True, TIME_ZONE="UTC", SITE_ID=1, DATABASES={ "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "djstripe", "USER": "", "PASSWORD": "", "HOST": "", "PORT": "", }, }, TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', ], }, }, ], ROOT_URLCONF="tests.test_urls", INSTALLED_APPS=[ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "jsonfield", "djstripe", "tests", "tests.apps.testapp" ], MIDDLEWARE=( "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware" ), STRIPE_PUBLIC_KEY=os.environ.get("STRIPE_PUBLIC_KEY", ""), STRIPE_SECRET_KEY=os.environ.get("STRIPE_SECRET_KEY", ""), DJSTRIPE_PLANS={ "test0": { "stripe_plan_id": "test_id_0", "name": "Test Plan 0", "description": "A test plan", "price": 1000, # $10.00 "currency": "usd", "interval": "month" }, "test": { "stripe_plan_id": "test_id", "name": "Test Plan 1", "description": "Another test plan", "price": 2500, # $25.00 "currency": "usd", "interval": "month" }, "test2": { "stripe_plan_id": "test_id_2", "name": "Test Plan 2", "description": "Yet Another test plan", "price": 5000, # $50.00 "currency": "usd", "interval": "month" }, "test_deletion": { "stripe_plan_id": "test_id_3", "name": "Test Plan 3", "description": "Test plan for deletion.", "price": 5000, # $50.00 "currency": "usd", "interval": "month" }, "test_trial": { "stripe_plan_id": "test_id_4", "name": "Test Plan 4", "description": "Test plan for trails.", "price": 7000, # $70.00 "currency": "usd", "interval": "month", "trial_period_days": 7 }, "unidentified_test_plan": { "name": "Unidentified Test Plan", "description": "A test plan with no ID.", "price": 2500, # $25.00 "currency": "usd", "interval": "month" } }, DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=( "(admin)", "test_url_name", "testapp_namespaced:test_url_namespaced", "fn:/test_fnmatch*" ), DJSTRIPE_USE_NATIVE_JSONFIELD=os.environ.get("USE_NATIVE_JSONFIELD", "") == "1", ) # Avoid AppRegistryNotReady exception # http://stackoverflow.com/questions/24793351/django-appregistrynotready if hasattr(django, "setup"): django.setup() # Announce the test suite sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"])) sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"])) sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"])) # Announce test run sys.stdout.write(colored(text="Step 1: Running unit tests.\n\n", color="yellow", attrs=["bold"])) # Hack to reset the global argv before nose has a chance to grab it # http://stackoverflow.com/a/1718407/1834570 args = sys.argv[1:] sys.argv = sys.argv[0:1] from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner(verbosity=1, keepdb=True, failfast=True) failures = test_runner.run_tests(tests) if failures: sys.exit(failures) if enable_coverage: # Announce coverage run sys.stdout.write(colored(text="\nStep 2: Generating coverage results.\n\n", color="yellow", attrs=["bold"])) cov.stop() percentage = round(cov.report(show_missing=True), 2) cov.html_report(directory='cover') cov.save() if percentage < TESTS_THRESHOLD: sys.stderr.write(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " + "WAS {old}%, IS NOW {new}%.\n\n".format(old=TESTS_THRESHOLD, new=percentage), color="red", attrs=["bold"])) sys.exit(1) else: # Announce disabled coverage run sys.stdout.write(colored(text="\nStep 2: Generating coverage results [SKIPPED].", color="yellow", attrs=["bold"])) # Announce success if enable_coverage: sys.stdout.write(colored(text="\nTests completed successfully with no errors. Congrats!\n", color="green", attrs=["bold"])) else: sys.stdout.write(colored(text="\nTests completed successfully, but some step(s) were skipped!\n", color="green", attrs=["bold"])) sys.stdout.write(colored(text="Don't push without running the skipped step(s).\n", color="red", attrs=["bold"])) if __name__ == "__main__": main()
tkwon/dj-stripe
runtests.py
Python
mit
6,893
# react-native-cloudinary ## Getting started `$ npm install react-native-cloudinary --save` ### Mostly automatic installation `$ react-native link react-native-cloudinary` ### Manual installation #### iOS 1. In XCode, in the project navigator, right click `Libraries` ➜ `Add Files to [your project's name]` 2. Go to `node_modules` ➜ `react-native-cloudinary` and add `RNCloudinary.xcodeproj` 3. In XCode, in the project navigator, select your project. Add `libRNCloudinary.a` to your project's `Build Phases` ➜ `Link Binary With Libraries` 4. Import Cloudinary SDK Open Terminal and navigate to `ios` directory. If your project is not initialized as a git repository, run the command: ```bash $ git init ``` To add cloudinary as a git submodule, run the command: ```bash $ git submodule add https://github.com/cloudinary/cloudinary_ios.git ``` - Drag `Cloudinary.xcodeproj` into the Project Navigator of your application's Xcode project. It should appear under your application's blue project icon. - Select `Cloudinary.xcodeproj` and make sure the deployment target matches that of your application target. - Select your application project. Under 'TARGETS' select your application, open the 'General' tab, click on the `+` button under the 'Embedded Binaries' and Select 'Cloudinary.framework'. 5. Import Cloudinary SDK Open Terminal and navigate to `ios` directory. ```bash $ git init ``` - Add Alamofire as a git by running the following command: ```bash $ git submodule add https://github.com/Alamofire/Alamofire.git ``` - Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. - Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. - In the tab bar at the top of that window, open the "General" panel. - Click on the `+` button under the "Embedded Binaries" section. - You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - Select the top `Alamofire.framework` for iOS and the bottom one for OS X. > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. - And that's it! > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. #### Android 1. Open up `android/app/src/main/java/[...]/MainActivity.java` - Add `import com.reactlibrary.RNCloudinaryPackage;` to the imports at the top of the file - Add `new RNCloudinaryPackage()` to the list returned by the `getPackages()` method 2. Append the following lines to `android/settings.gradle`: ``` include ':react-native-cloudinary' project(':react-native-cloudinary').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-cloudinary/android') ``` 3. Insert the following lines inside the dependencies block in `android/app/build.gradle`: ``` compile project(':react-native-cloudinary') ``` ## Usage ```javascript import RNCloudinary from 'react-native-cloudinary'; 1. Config RNCloudinary.config(CLOUD_NAME, API_KEY, API_SECRET, PRESET_NAME); 2. Upload image Use the Uri file path for uploading the image to the Cloudinary cloud service. RNCloudinary.uploadImage(filePath).then(data => { ... }) .catch(err => { ... }); // TODO: What to do with the module? ```
javierrunning/react-native-cloudinary
README.md
Markdown
mit
4,346
// RUN: %check %s struct A { int n; int vals[]; } x[] = { // ucc allows this 1, { 7 }, // CHECK: /warning: initialisation of flexible array/ 2, { 5, 6 }, // CHECK: /warning: initialisation of flexible array/ };
8l/ucc-c-compiler
test2/flexarr/struct_ar_init.c
C
mit
219
class CreateBands < ActiveRecord::Migration def change create_table :bands do |t| t.string :name t.string :last_fm_id t.string :wikipedia_id t.string :homepage_url t.text :bio t.boolean :is_editors_choice t.text :editors_choice_note t.timestamps end end end
sleighter/dcdecibel
db/migrate/20120102231637_create_bands.rb
Ruby
mit
319
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { HttpModule } from '@angular/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import PageNotFoundRouteComponent from './components/page-not-found.component'; import ProductListComponent from './components/product-list.component'; import HomepageComponent from './components/homepage.component'; import UserInfoComponent from './components/user-info.component'; import ShoppingCartComponent from './components/shopping-cart.component'; import ProductDetailsComponent from './components/product-details.component'; import AddProductComponent from './components/add-product.component'; import SearchBarComponent from './components/search-bar.component'; import ProductService from './services/product.service'; import ShoppingCartService from './services/shopping-cart.service'; import UserService from './services/user.service'; @NgModule({ imports: [ BrowserModule, AppRoutingModule, HttpModule, FormsModule ], declarations: [ AppComponent, HomepageComponent, PageNotFoundRouteComponent, ProductListComponent, ProductDetailsComponent, AddProductComponent, UserInfoComponent, SearchBarComponent, ShoppingCartComponent ], providers: [ ProductService, ShoppingCartService, UserService ], bootstrap: [ AppComponent ] }) export class AppModule { }
mskorsur/NWT-WebshopApplication
src/NWT_Webshop_Application/App_Client/src/app/app.module.ts
TypeScript
mit
1,531
--- layout: automation title: Automation of Electric Motor, Power Tool, and Related Repairers subtitle: Will robots and artificial intelligence take the job of Electric Motor, Power Tool, and Related Repairers? Get the facts. soc: code: 49-2092 title: Electric Motor, Power Tool, and Related Repairers definition: 'Repair, maintain, or install electric motors, wiring, or switches.' employment: current: us: 17300 projected: us: 18600 change: us: 0.07 wage: hourly: us: 21.5 annual: us: 44720 probability: oxford: 0.76 rank: oxford: 417 tags: - ---
simonmesmith/simonmesmith.github.io
_automation/electric-motor-power-tool-and-related-repairers.md
Markdown
mit
592
#container { width: 96%; margin: auto; }
chintown/simple-data-binding
styles/base.css
CSS
mit
45
html{ overflow-x:hidden; padding-bottom:142px; } .pacman{ margin:50px 10px; background: #fff; } .pacman-top{ margin-top: 105px; transform-origin: bottom left; margin-bottom: -5px; height:50px; width:100px; border-radius:50px 50px 10px 10px; animation: spin1 0.5s infinite linear; } .pacman-bottom{ top: 205px; transform-origin: top left; z-index:-1; height:50px; width:100px; border-radius:20px 20px 50px 50px; animation: spin2 0.5s infinite linear; } .feed { margin-top: -215px; margin-left:25px; width: 75px; height: 35px; border-radius: 25%; -moz-animation: eat 2s linear 0s infinite; -webkit-animation: eat 2s linear 0s infinite; animation: eat 1s linear 0s infinite; } /* Animation*/ @keyframes spin1 { 70%{transform: rotate(10deg);} 50%{transform: rotate(-20deg);} } @keyframes spin2 { 70%{transform: rotate(-10deg);} 50%{transform: rotate(20deg);} } @-moz-keyframes spin1 { 0% {transform: rotate(0deg);} 50%{transform: rotate(-35deg);} } @-moz-keyframes spin2 { 0% {transform: rotate(0deg);} 50%{transform: rotate(35deg);} } @-webkit-keyframes spin1 { 0% {transform: rotate(0deg);} 50%{transform: rotate(-35deg);} } @-webkit-keyframes spin2 { 0% {transform: rotate(0deg);} 50%{transform: rotate(35deg);} } .food { position: absolute; -moz-animation: feed linear infinite; -webkit-animation: feed linear infinite; -o-animation: feed linear infinite; animation: feed linear infinite; } @-moz-keyframes feed { from { -moz-transform: translateX(300px); } to { -moz-transform: translateX(150px); } } @-webkit-keyframes feed { from { -webkit-transform: translateX(300px); } to { -webkit-transform: translateX(150px); } } @-o-keyframes feed { from { -o-transform: translateX(300px); } to { -o-transform: translateX(150px); } } @keyframes feed { from { transform: translateX(300px); } to { transform: translateX(150px); } } .sml { z-index: -1; padding: 5px; top: 305px; left: -55px; -moz-animation-duration: 6s; -webkit-animation-duration: 6s; -o-animation-duration: 6s; animation-duration: 3s; animation-delay: 1s; } .lrg { z-index: -1; padding: 5px; top: 305px; left: -55px; -moz-animation-duration: 6s; -webkit-animation-duration: 6s; -o-animation-duration: 6s; animation-duration: 3s; animation-delay: 2s; } .med { z-index: -1; padding: 5px; top: 305px; left: -55px; -moz-animation-duration: 6s; -webkit-animation-duration: 6s; -o-animation-duration: 4s; animation-duration: 3s; animation-delay: 3s; }
Eatr/eatr
public/styles/splash.css
CSS
mit
2,633
#define SETTINGS_KEY 0 #define NUM_MENU_SECTIONS 3 #define NUM_FIRST_MENU_ITEMS 4 #define NUM_SECOND_MENU_ITEMS 1 #define NUM_THIRD_MENU_ITEMS 2 Window *main_window, *timer_window; TextLayer *minute_5_t, *minute_21_t, *hour_4_t; GBitmap *play, *pause, *restart, *resistance, *enlightened; BitmapLayer *team_layer; GFont *coda, *coda_small; ActionBarLayer *ab; InverterLayer *theme, *menu_theme; char timer1_buffer[] = "00:00."; char timer2_buffer[] = "00:00."; char timer3_buffer[] = "00:00:00."; typedef struct persist { bool theme; bool team; }__attribute__((__packed__)) persist; persist settings = { .theme = 0, .team = 0, }; typedef struct mytimer_struct { int16_t min; int16_t sec; int16_t hour; } timer; static timer min5_td = { .min = 5, .sec = 0, .hour = 0, }; static timer min21_td = { .min = 21, .sec = 0, .hour = 0, }; static timer hour4_td = { .min = 0, .sec = 0, .hour = 4, }; int timerFired, value; int animationSpeed = 500; bool timer1_running, timer2_running, timer3_running; static SimpleMenuLayer *main_menu; static SimpleMenuSection menu_sections[NUM_MENU_SECTIONS]; static SimpleMenuItem first_menu_items[NUM_FIRST_MENU_ITEMS]; static SimpleMenuItem second_menu_items[NUM_SECOND_MENU_ITEMS]; static SimpleMenuItem third_menu_items[NUM_THIRD_MENU_ITEMS];
edwinfinch/ingresstimer
src/elements.h
C
mit
1,311
package de.szilch.leuchtfeuer.model.api; import de.szilch.leuchtfeuer.util.ResourceUtils; /** * Created by szilch on 09.09.16. * * NavLight Colors */ public enum NavLightColor { BLUE("#0101DF", "color.blue"), YELLOW("#FFFF00", "color.yellow"), GREEN("#7BC618", "color.green"), ORANGE("#FFBF00", "color.orange"), RED("#FF0000", "color.red"), VIOLET("#BF00FF", "color.violet"), WHITE("#FFFFC6", "color.white"); private String hexValue; /** * used for the frontend in order to be multilingual */ private String resourceKey; NavLightColor(String hexValue, String resourceKey) { this.hexValue = hexValue; this.resourceKey = resourceKey; } public String getHexValue() { return this.hexValue; } @Override public String toString() { return ResourceUtils.getInstance().getString(resourceKey); } }
szilch/navlight-sim
src/main/java/de/szilch/leuchtfeuer/model/api/NavLightColor.java
Java
mit
909
# PLUGIN Makefile PLUGIN_NAME = test_retorno OBJ = test_retorno OBJ_FULL = $(addsuffix .$(OBJ_SUFFIX), $(OBJ)) include ../main.mak
reality3d/rgba
plugins/test_retorno/Makefile
Makefile
mit
145
import React, {Component} from 'react'; import {StyleSheet,Image,Text} from 'react-native'; import NavBar, { NavGroup, NavButton, NavButtonText, NavTitle } from 'react-native-nav' import Theme from '../utils/Theme' export default class ArticleNav extends Component { render() { let theme = new Theme(this.props.zhihu.theme); let styles = StyleSheet.create({ statusBar: { backgroundColor: theme.colors.statusBar }, navBar: { backgroundColor: theme.colors.titleBar, height: 50, paddingLeft: 0 }, buttonText: { marginLeft:15, color: '#rgba(255, 255, 255, 1)' }, number:{ alignSelf:'center',fontSize:15,color:'white' }, navButton:{ marginTop: 20, flex: 1 }, icon:{ width:30, height:30 } }); let {extra} = this.props.zhihu.article; if (extra.comments>1000) extra.comments = (extra.comments/1000).toFixed(1)+'k'; if (extra.popularity>1000) extra.popularity = (extra.popularity/1000).toFixed(1)+'k'; return ( <NavBar style={styles}> <NavButton style={styles.navButton} onPress={()=>{this.props.onNavigate({type:'pop'})}}> <NavButtonText style={styles.buttonText}> <Image style={styles.icon} source={require('../img/ic_back_white.png')} resizeMode={'contain'}/> </NavButtonText> </NavButton> <NavGroup> <NavButton style={styles.navButton}> <NavButtonText style={styles.buttonText}> <Image style={styles.icon} source={require('../img/ic_share_white.png')} resizeMode={'contain'}/> </NavButtonText> </NavButton> <NavButton style={styles.navButton}> <NavButtonText style={styles.buttonText}> <Image style={styles.icon} source={require('../img/ic_collect_white.png')} resizeMode={'contain'}/> </NavButtonText> </NavButton> <NavButton style={styles.navButton}> <NavButtonText style={styles.buttonText}> <Image style={styles.icon} source={require('../img/ic_comment_white.png')} resizeMode={'contain'}/> </NavButtonText> </NavButton> <Text style={styles.number}>{extra.comments}</Text> <NavButton style={styles.navButton}> <NavButtonText style={styles.buttonText}> <Image style={styles.icon} source={require('../img/ic_praise_white.png')} resizeMode={'contain'}/> </NavButtonText> </NavButton> <Text style={styles.number}>{extra.popularity}</Text> </NavGroup> </NavBar> ); } }
ZevenFang/react-native-redux-zhihudaily
src/components/ArticleNav.ios.js
JavaScript
mit
2,689
using System; using System.Collections.Generic; using AESharp.UnaryOperators; using AESharp.Values; namespace AESharp.SystemFunctions { public class CosFunc : SysFunc, IInvertable { public CosFunc() : this(null) { } public CosFunc(Scope scope) : base("cos", scope) { ValidArguments = new List<ArgumentType>() { ArgumentType.Real }; } public override Expression Call(List args) { if (!IsArgumentsValid(args)) return new ArgumentError(this); var res = args[0].Evaluate(); var deg = GetBool("deg"); if (res is Real) { double value = res as Real; if (value == (90 * (deg ? 1.0 : (double)Constant.DegToRad.V))) return Constant.Zero; return new Irrational(Math.Cos((double)(deg ? Constant.DegToRad.V : 1) * value)).Evaluate(); } return new Error(this, "Could not take Cos of: " + args[0]); } public override Expression Reduce(List args, Scope scope) { var reduced = args.Reduce() as List; if (reduced[0] is Call && (reduced[0] as Call).Child.Value is AcosFunc) return (reduced[0] as Call).Arguments[0]; return this; } //cos[x] -> acos[other] public Expression InvertOn(Expression other) { var arg = new List(); arg.Items.Add(other); return MakeFunction(arg, CurScope, "acos"); } } }
prozum/ae-sharp
AESharp/SystemFunctions/CosFunc.cs
C#
mit
1,649
class Memory attr_accessor :brain, :skills, :credentials end
thirtysixthspan/billygoat
lib/billygoat/memory.rb
Ruby
mit
65
#ifndef SESSION_HPP #define SESSION_HPP #include <deque> #include <memory> #include <boost/asio.hpp> #include "message.hpp" using tcp = boost::asio::ip::tcp; class tcp_session_manager; // class manages single connection and provides methods for handling // reading and writing messages in boost::asio io_service.run() loop class session : public std::enable_shared_from_this<session> { public: session(boost::asio::io_service& io_service, tcp_session_manager& tcp_session_manager); ~session(); tcp::socket& socket(); void start(); void stop(); void name(std::string str); std::string name(); void send_message(message msg); std::string socket_info(); void print_socket_alert(const std::string& str); private: void read_header(); void read_body(); void write(); void handle_read_header(const boost::system::error_code& error); void handle_read_body(const boost::system::error_code& error); void handle_write(const boost::system::error_code& error); tcp::socket socket_; tcp_session_manager& session_manager; bool sending; std::string name_; message_queue send_msgs; message read_msg; }; #endif // SESSION_HPP
wrutra/instant_messenger
include/session.hpp
C++
mit
1,371
'use strict'; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addPackagesToProject([ { name: 'ember-cli-sass', target: '5.3.1' } ]).then(function() { return this.addBowerPackagesToProject([ { name: 'paint', target: '0.9.5' }, { name: 'modernizr', target: '2.8.3' }, { name: 'spinjs', target: '2.0.2' }, { name: 'tooltipster', target: '3.3.0' }, { name: 'trackpad-scroll-emulator', target: '1.0.8' } ]).then(function() { return this.insertIntoFile('.jshintrc', ' "Spinner",', { after: '"predef": [\n' } ); }.bind(this)); }.bind(this)); } }
alphasights/ember-cli-paint
blueprints/ember-cli-paint/index.js
JavaScript
mit
680
--Run with admin user privileges (possibly postges) -- Database: kanbandb -- DROP DATABASE kanbandb; CREATE DATABASE kanbandb WITH OWNER = postgres ENCODING = 'UTF8' LC_COLLATE = 'Russian_Russia.1251' LC_CTYPE = 'Russian_Russia.1251' TABLESPACE = pg_default CONNECTION LIMIT = -1; GRANT ALL ON DATABASE kanbandb TO postgres; GRANT ALL ON DATABASE kanbandb TO "kanbanJavaServerUser"; GRANT TEMPORARY, CONNECT ON DATABASE kanbandb TO PUBLIC; CREATE DATABASE kanbandb WITH OWNER = postgres ENCODING = 'UTF8' TABLESPACE = pg_default CONNECTION LIMIT = -1; GRANT ALL ON DATABASE kanbandb TO postgres; GRANT ALL ON DATABASE kanbandb TO "kanbanJavaServerUser"; GRANT TEMPORARY, CONNECT ON DATABASE kanbandb TO PUBLIC;
savushkin/KANBAN-2990
kanban-all/kanban-data/db/postgres/dbCreationScript.sql
SQL
mit
722
<!DOCTYPE html> <html ng-app='app'> <head> <title>Import features example</title> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <meta name="mobile-web-app-capable" content="yes"> <link rel="stylesheet" href="../node_modules/openlayers/css/ol.css" type="text/css"> <style> #map { width: 600px; height: 400px; } </style> </head> <body ng-controller="MainController as ctrl"> <div id="map" ngeo-map="ctrl.map"></div> <input id="export" type="file" ngeo-filereader="ctrl.fileContent" ngeo-filereader-supported="ctrl.fileReaderSupported" /> <p ng-hide="::ctrl.fileReaderSupported">Your browser doesn't support the <code>FileReader</code> API! IE 9?</p> <p id="desc">This example shows how to use the <code><a href="../apidoc/ngeo.filereaderDirective.html" title="Read our documentation">ngeo-filereader</a></code> directive to import features from a KML file read from the user's file system.</p> <p>You can download and use the <a href="http://openlayers.org/en/master/examples/data/kml/2012-02-10.kml">2012-02-10.kml file</a> from the OpenLayers examples for testing.</p> <script src="../node_modules/angular/angular.js"></script> <script src="../node_modules/angular-gettext/dist/angular-gettext.js"></script> <script src="/@?main=importfeatures.js"></script> <script src="default.js"></script> <script src="../utils/watchwatchers.js"></script> </body> </html>
pgiraud/ngeo
examples/importfeatures.html
HTML
mit
1,539
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112-google-v7) on Thu Feb 08 16:33:19 PST 2018 --> <title>org.robolectric.android.controller Class Hierarchy</title> <meta name="date" content="2018-02-08"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.robolectric.android.controller Class Hierarchy"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/robolectric/android/package-tree.html">Prev</a></li> <li><a href="../../../../org/robolectric/android/fakes/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/robolectric/android/controller/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.robolectric.android.controller</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">org.robolectric.android.controller.<a href="../../../../org/robolectric/android/controller/ComponentController.html" title="class in org.robolectric.android.controller"><span class="typeNameLink">ComponentController</span></a>&lt;C,T&gt; <ul> <li type="circle">org.robolectric.android.controller.<a href="../../../../org/robolectric/android/controller/ActivityController.html" title="class in org.robolectric.android.controller"><span class="typeNameLink">ActivityController</span></a>&lt;T&gt;</li> <li type="circle">org.robolectric.android.controller.<a href="../../../../org/robolectric/android/controller/BackupAgentController.html" title="class in org.robolectric.android.controller"><span class="typeNameLink">BackupAgentController</span></a>&lt;T&gt;</li> <li type="circle">org.robolectric.android.controller.<a href="../../../../org/robolectric/android/controller/FragmentController.html" title="class in org.robolectric.android.controller"><span class="typeNameLink">FragmentController</span></a>&lt;F&gt;</li> <li type="circle">org.robolectric.android.controller.<a href="../../../../org/robolectric/android/controller/IntentServiceController.html" title="class in org.robolectric.android.controller"><span class="typeNameLink">IntentServiceController</span></a>&lt;T&gt;</li> <li type="circle">org.robolectric.android.controller.<a href="../../../../org/robolectric/android/controller/ServiceController.html" title="class in org.robolectric.android.controller"><span class="typeNameLink">ServiceController</span></a>&lt;T&gt;</li> </ul> </li> <li type="circle">org.robolectric.android.controller.<a href="../../../../org/robolectric/android/controller/ContentProviderController.html" title="class in org.robolectric.android.controller"><span class="typeNameLink">ContentProviderController</span></a>&lt;T&gt;</li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><script type="text/javascript" src="../../../../highlight.pack.js"></script> <script type="text/javascript"><!-- hljs.initHighlightingOnLoad(); //--></script></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/robolectric/android/package-tree.html">Prev</a></li> <li><a href="../../../../org/robolectric/android/fakes/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/robolectric/android/controller/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
robolectric/robolectric.github.io
javadoc/3.7/org/robolectric/android/controller/package-tree.html
HTML
mit
6,489
__author__ = 'mirko'
fcracker79/multiprocess_rolling_logger
test/__init__.py
Python
mit
21
Grafana and dogbot logging: # Running grafana sudo service grafana-server start go to http://127.0.0.1:3000 in browser default admin user is 'admin' scripted dashbaord: http://127.0.0.1:3000/dashboard/script/jointstates.js # Install http://docs.grafana.org/installation/debian/ -follow apt install summary of where stuff ends up: Installs binary to /usr/sbin/grafana-server Installs Init.d script to /etc/init.d/grafana-server Creates default file (environment vars) to /etc/default/grafana-server Installs configuration file to /etc/grafana/grafana.ini Installs systemd service (if systemd is available) name grafana-server.service The default configuration sets the log file at /var/log/grafana/grafana.log The default configuration specifies an sqlite3 db at /var/lib/grafana/grafana.db Installs HTML/JS/CSS and other Grafana files at /usr/share/grafana # Setting up postgresql psql -U reactai CREATE DATABASE dogbot; then back at a command prompt, this should work: psql -U reactai dogbot <./config/postgres.sql when using psql: \c dogbot; SET search_path TO dogbot1, sim1, public; # logging to postgres from the simulation, in two windows roslaunch dogbot gazebo.launch roslaunch dogbot logger.launch logging_config:=sim_logging.yaml
craftit/BMC2-Firmware
Utilities/DataRecorder/postgres_and_grafana.md
Markdown
mit
1,316
//***************************************************************************** // // can.c - Driver for the CAN module. // // Copyright (c) 2006-2010 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 6075 of the Stellaris Peripheral Driver Library. // //***************************************************************************** //***************************************************************************** // //! \addtogroup can_api //! @{ // //***************************************************************************** #include "hw_can.h" #include "hw_ints.h" #include "hw_nvic.h" #include "hw_memmap.h" #include "hw_types.h" #include "can.h" #include "debug.h" #include "interrupt.h" //***************************************************************************** // // This is the maximum number that can be stored as an 11bit Message // identifier. // //***************************************************************************** #define CAN_MAX_11BIT_MSG_ID (0x7ff) //***************************************************************************** // // This is used as the loop delay for accessing the CAN controller registers. // //***************************************************************************** #define CAN_RW_DELAY (5) // // The maximum CAN bit timing divisor is 13. // #define CAN_MAX_BIT_DIVISOR (13) // // The minimum CAN bit timing divisor is 5. // #define CAN_MIN_BIT_DIVISOR (5) // // The maximum CAN pre-divisor is 1024. // #define CAN_MAX_PRE_DIVISOR (1024) // // The minimum CAN pre-divisor is 1. // #define CAN_MIN_PRE_DIVISOR (1) //***************************************************************************** // // This table is used by the CANBitRateSet() API as the register defaults for // the bit timing values. // //***************************************************************************** static const unsigned short g_usCANBitValues[] = { 0x1100, // TSEG2 2, TSEG1 2, SJW 1, Divide 5 0x1200, // TSEG2 2, TSEG1 3, SJW 1, Divide 6 0x2240, // TSEG2 3, TSEG1 3, SJW 2, Divide 7 0x2340, // TSEG2 3, TSEG1 4, SJW 2, Divide 8 0x3340, // TSEG2 4, TSEG1 4, SJW 2, Divide 9 0x3440, // TSEG2 4, TSEG1 5, SJW 2, Divide 10 0x3540, // TSEG2 4, TSEG1 6, SJW 2, Divide 11 0x3640, // TSEG2 4, TSEG1 7, SJW 2, Divide 12 0x3740 // TSEG2 4, TSEG1 8, SJW 2, Divide 13 }; //***************************************************************************** // //! \internal //! Checks a CAN base address. //! //! \param ulBase is the base address of the CAN controller. //! //! This function determines if a CAN controller base address is valid. //! //! \return Returns \b true if the base address is valid and \b false //! otherwise. // //***************************************************************************** #ifdef DEBUG static tBoolean CANBaseValid(unsigned long ulBase) { return((ulBase == CAN0_BASE) || (ulBase == CAN1_BASE) || (ulBase == CAN2_BASE)); } #endif //***************************************************************************** // //! \internal //! //! Returns the CAN controller interrupt number. //! //! \param ulBase is the base address of the selected CAN controller //! //! Given a CAN controller base address, returns the corresponding interrupt //! number. //! //! This function replaces the original CANGetIntNumber() API and performs the //! same actions. A macro is provided in <tt>can.h</tt> to map the original //! API to this API. //! //! \return Returns a CAN interrupt number, or -1 if \e ulPort is invalid. // //***************************************************************************** static long CANIntNumberGet(unsigned long ulBase) { long lIntNumber; // // Return the interrupt number for the given CAN controller. // switch(ulBase) { // // Return the interrupt number for CAN 0 // case CAN0_BASE: { lIntNumber = INT_CAN0; break; } // // Return the interrupt number for CAN 1 // case CAN1_BASE: { lIntNumber = INT_CAN1; break; } // // Return the interrupt number for CAN 2 // case CAN2_BASE: { lIntNumber = INT_CAN2; break; } // // Return -1 to indicate a bad address was passed in. // default: { lIntNumber = -1; } } return(lIntNumber); } //***************************************************************************** // //! \internal //! //! Reads a CAN controller register. //! //! \param ulRegAddress is the full address of the CAN register to be read. //! //! This function performs the necessary synchronization to read from a CAN //! controller register. //! //! This function replaces the original CANReadReg() API and performs the same //! actions. A macro is provided in <tt>can.h</tt> to map the original API to //! this API. //! //! \note This function provides the delay required to access CAN registers. //! This delay is required when accessing CAN registers directly. //! //! \return Returns the value read from the register. // //***************************************************************************** static unsigned long CANRegRead(unsigned long ulRegAddress) { volatile int iDelay; unsigned long ulRetVal; unsigned long ulIntNumber; unsigned long ulReenableInts; // // Get the CAN interrupt number from the register base address. // ulIntNumber = CANIntNumberGet(ulRegAddress & 0xfffff000); // // Make sure that the CAN base address was valid. // ASSERT(ulIntNumber != (unsigned long)-1); // // Remember current state so that CAN interrupts are only re-enabled if // they were already enabled. // ulReenableInts = HWREG(NVIC_EN1) & (1 << (ulIntNumber - 48)); // // If the CAN interrupt was enabled then disable it. // if(ulReenableInts) { IntDisable(ulIntNumber); } // // Trigger the initial read to the CAN controller. The value returned at // this point is not valid. // HWREG(ulRegAddress); // // This delay is necessary for the CAN have the correct data on the bus. // for(iDelay = 0; iDelay < CAN_RW_DELAY; iDelay++) { } // // Do the final read that has the valid value of the register. // ulRetVal = HWREG(ulRegAddress); // // Enable CAN interrupts if they were enabled before this call. // if(ulReenableInts) { IntEnable(ulIntNumber); } return(ulRetVal); } //***************************************************************************** // //! \internal //! //! Writes a CAN controller register. //! //! \param ulRegAddress is the full address of the CAN register to be written. //! \param ulRegValue is the value to write into the register specified by //! \e ulRegAddress. //! //! This function takes care of the synchronization necessary to write to a //! CAN controller register. //! //! This function replaces the original CANWriteReg() API and performs the same //! actions. A macro is provided in <tt>can.h</tt> to map the original API to //! this API. //! //! \note The delays in this function are required when accessing CAN registers //! directly. //! //! \return None. // //***************************************************************************** static void CANRegWrite(unsigned long ulRegAddress, unsigned long ulRegValue) { volatile int iDelay; // // Trigger the initial write to the CAN controller. The value will not make // it out to the CAN controller for CAN_RW_DELAY cycles. // HWREG(ulRegAddress) = ulRegValue; // // Delay to allow the CAN controller to receive the new data. // for(iDelay = 0; iDelay < CAN_RW_DELAY; iDelay++) { } } //***************************************************************************** // //! \internal //! //! Copies data from a buffer to the CAN Data registers. //! //! \param pucData is a pointer to the data to be written out to the CAN //! controller's data registers. //! \param pulRegister is an unsigned long pointer to the first register of the //! CAN controller's data registers. For example, in order to use the IF1 //! register set on CAN controller 0, the value would be: \b CAN0_BASE \b + //! \b CAN_O_IF1DA1. //! \param iSize is the number of bytes to copy into the CAN controller. //! //! This function takes the steps necessary to copy data from a contiguous //! buffer in memory into the non-contiguous data registers used by the CAN //! controller. This function is rarely used outside of the CANMessageSet() //! function. //! //! This function replaces the original CANWriteDataReg() API and performs the //! same actions. A macro is provided in <tt>can.h</tt> to map the original //! API to this API. //! //! \return None. // //***************************************************************************** static void CANDataRegWrite(unsigned char *pucData, unsigned long *pulRegister, int iSize) { int iIdx; unsigned long ulValue; // // Loop always copies 1 or 2 bytes per iteration. // for(iIdx = 0; iIdx < iSize; ) { // // Write out the data 16 bits at a time since this is how the registers // are aligned in memory. // ulValue = pucData[iIdx++]; // // Only write the second byte if needed otherwise it will be zero. // if(iIdx < iSize) { ulValue |= (pucData[iIdx++] << 8); } CANRegWrite((unsigned long)(pulRegister++), ulValue); } } //***************************************************************************** // //! \internal //! //! Copies data from a buffer to the CAN Data registers. //! //! \param pucData is a pointer to the location to store the data read from the //! CAN controller's data registers. //! \param pulRegister is an unsigned long pointer to the first register of the //! CAN controller's data registers. For example, in order to use the IF1 //! register set on CAN controller 1, the value would be: \b CAN0_BASE \b + //! \b CAN_O_IF1DA1. //! \param iSize is the number of bytes to copy from the CAN controller. //! //! This function takes the steps necessary to copy data to a contiguous buffer //! in memory from the non-contiguous data registers used by the CAN //! controller. This function is rarely used outside of the CANMessageGet() //! function. //! //! This function replaces the original CANReadDataReg() API and performs the //! same actions. A macro is provided in <tt>can.h</tt> to map the original //! API to this API. //! //! \return None. // //***************************************************************************** static void CANDataRegRead(unsigned char *pucData, unsigned long *pulRegister, int iSize) { int iIdx; unsigned long ulValue; // // Loop always copies 1 or 2 bytes per iteration. // for(iIdx = 0; iIdx < iSize; ) { // // Read out the data 16 bits at a time since this is how the registers // are aligned in memory. // ulValue = CANRegRead((unsigned long)(pulRegister++)); // // Store the first byte. // pucData[iIdx++] = (unsigned char)ulValue; // // Only read the second byte if needed. // if(iIdx < iSize) { pucData[iIdx++] = (unsigned char)(ulValue >> 8); } } } //***************************************************************************** // //! Initializes the CAN controller after reset. //! //! \param ulBase is the base address of the CAN controller. //! //! After reset, the CAN controller is left in the disabled state. However, //! the memory used for message objects contains undefined values and must be //! cleared prior to enabling the CAN controller the first time. This prevents //! unwanted transmission or reception of data before the message objects are //! configured. This function must be called before enabling the controller //! the first time. //! //! \return None. // //***************************************************************************** void CANInit(unsigned long ulBase) { int iMsg; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // Place CAN controller in init state, regardless of previous state. This // will put controller in idle, and allow the message object RAM to be // programmed. // CANRegWrite(ulBase + CAN_O_CTL, CAN_CTL_INIT); // // Wait for busy bit to clear // while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY) { } // // Clear the message value bit in the arbitration register. This indicates // the message is not valid and is a "safe" condition to leave the message // object. The same arb reg is used to program all the message objects. // CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_ARB | CAN_IF1CMSK_CONTROL); CANRegWrite(ulBase + CAN_O_IF1ARB2, 0); CANRegWrite(ulBase + CAN_O_IF1MCTL, 0); // // Loop through to program all 32 message objects // for(iMsg = 1; iMsg <= 32; iMsg++) { // // Wait for busy bit to clear // while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY) { } // // Initiate programming the message object // CANRegWrite(ulBase + CAN_O_IF1CRQ, iMsg); } // // Make sure that the interrupt and new data flags are updated for the // message objects. // CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_NEWDAT | CAN_IF1CMSK_CLRINTPND); // // Loop through to program all 32 message objects // for(iMsg = 1; iMsg <= 32; iMsg++) { // // Wait for busy bit to clear. // while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY) { } // // Initiate programming the message object // CANRegWrite(ulBase + CAN_O_IF1CRQ, iMsg); } // // Acknowledge any pending status interrupts. // CANRegRead(ulBase + CAN_O_STS); } //***************************************************************************** // //! Enables the CAN controller. //! //! \param ulBase is the base address of the CAN controller to enable. //! //! Enables the CAN controller for message processing. Once enabled, the //! controller will automatically transmit any pending frames, and process any //! received frames. The controller can be stopped by calling CANDisable(). //! Prior to calling CANEnable(), CANInit() should have been called to //! initialize the controller and the CAN bus clock should be configured by //! calling CANBitTimingSet(). //! //! \return None. // //***************************************************************************** void CANEnable(unsigned long ulBase) { // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // Clear the init bit in the control register. // CANRegWrite(ulBase + CAN_O_CTL, CANRegRead(ulBase + CAN_O_CTL) & ~CAN_CTL_INIT); } //***************************************************************************** // //! Disables the CAN controller. //! //! \param ulBase is the base address of the CAN controller to disable. //! //! Disables the CAN controller for message processing. When disabled, the //! controller will no longer automatically process data on the CAN bus. The //! controller can be restarted by calling CANEnable(). The state of the CAN //! controller and the message objects in the controller are left as they were //! before this call was made. //! //! \return None. // //***************************************************************************** void CANDisable(unsigned long ulBase) { // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // Set the init bit in the control register. // CANRegWrite(ulBase + CAN_O_CTL, CANRegRead(ulBase + CAN_O_CTL) | CAN_CTL_INIT); } //***************************************************************************** // //! Reads the current settings for the CAN controller bit timing. //! //! \param ulBase is the base address of the CAN controller. //! \param pClkParms is a pointer to a structure to hold the timing parameters. //! //! This function reads the current configuration of the CAN controller bit //! clock timing, and stores the resulting information in the structure //! supplied by the caller. Refer to CANBitTimingSet() for the meaning of the //! values that are returned in the structure pointed to by \e pClkParms. //! //! This function replaces the original CANGetBitTiming() API and performs the //! same actions. A macro is provided in <tt>can.h</tt> to map the original //! API to this API. //! //! \return None. // //***************************************************************************** /* void CANBitTimingGet(unsigned long ulBase, tCANBitClkParms *pClkParms) { unsigned int uBitReg; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT(pClkParms != 0); // // Read out all the bit timing values from the CAN controller registers. // uBitReg = CANRegRead(ulBase + CAN_O_BIT); // // Set the phase 2 segment. // pClkParms->uPhase2Seg = ((uBitReg & CAN_BIT_TSEG2_M) >> 12) + 1; // // Set the phase 1 segment. // pClkParms->uSyncPropPhase1Seg = ((uBitReg & CAN_BIT_TSEG1_M) >> 8) + 1; // // Set the synchronous jump width. // pClkParms->uSJW = ((uBitReg & CAN_BIT_SJW_M) >> 6) + 1; // // Set the pre-divider for the CAN bus bit clock. // pClkParms->uQuantumPrescaler = ((uBitReg & CAN_BIT_BRP_M) | ((CANRegRead(ulBase + CAN_O_BRPE) & CAN_BRPE_BRPE_M) << 6)) + 1; } */ //***************************************************************************** // //! This function is used to set the CAN bit timing values to a nominal setting //! based on a desired bit rate. //! //! \param ulBase is the base address of the CAN controller. //! \param ulSourceClock is the system clock for the device in Hz. //! \param ulBitRate is the desired bit rate. //! //! This function will set the CAN bit timing for the bit rate passed in the //! \e ulBitRate parameter based on the \e ulSourceClock parameter. Since the //! CAN clock is based off of the system clock the calling function should pass //! in the source clock rate either by retrieving it from SysCtlClockGet() or //! using a specific value in Hz. The CAN bit clock is calculated to be an //! average timing value that should work for most systems. If tighter timing //! requirements are needed, then the CANBitTimingSet() function is available //! for full customization of all of the CAN bit timing values. Since not all //! bit rates can be matched exactly, the bit rate is set to the value closest //! to the desired bit rate without being higher than the \e ulBitRate value. //! //! \note On some devices the source clock is fixed at 8MHz so the //! \e ulSourceClock should be set to 8000000. //! //! \return This function returns the bit rate that the CAN controller was //! configured to use or it returns 0 to indicate that the bit rate was not //! changed because the requested bit rate was not valid. //! //***************************************************************************** unsigned long CANBitRateSet(unsigned long ulBase, unsigned long ulSourceClock, unsigned long ulBitRate) { unsigned long ulDesiredRatio; unsigned long ulCANBits; unsigned long ulPreDivide; unsigned long ulRegValue; unsigned short usCANCTL; ASSERT(ulBitRate != 0); // // Calculate the desired clock rate. // ulDesiredRatio = ulSourceClock / ulBitRate; // // If the ratio of CAN bit rate to processor clock is too small or too // large then return 0 indicating that no bit rate was set. // ASSERT(ulDesiredRatio <= (CAN_MAX_PRE_DIVISOR * CAN_MAX_BIT_DIVISOR)); ASSERT(ulDesiredRatio >= (CAN_MIN_PRE_DIVISOR * CAN_MIN_BIT_DIVISOR)); // // Make sure that the Desired Ratio is not too large. This enforces the // requirement that the bit rate is larger than requested. // if((ulSourceClock / ulDesiredRatio) > ulBitRate) { ulDesiredRatio += 1; } // // Check all possible values to find a matching value. // while(ulDesiredRatio <= CAN_MAX_PRE_DIVISOR * CAN_MAX_BIT_DIVISOR) { // // Loop through all possible CAN bit divisors. // for(ulCANBits = CAN_MAX_BIT_DIVISOR; ulCANBits >= CAN_MIN_BIT_DIVISOR; ulCANBits--) { // // For a given CAN bit divisor save the pre divisor. // ulPreDivide = ulDesiredRatio / ulCANBits; // // If the calculated divisors match the desired clock ratio then // return these bit rate and set the CAN bit timing. // if((ulPreDivide * ulCANBits) == ulDesiredRatio) { // // Start building the bit timing value by adding the bit timing // in time quanta. // ulRegValue = g_usCANBitValues[ulCANBits - CAN_MIN_BIT_DIVISOR]; // // To set the bit timing register, the controller must be placed // in init mode (if not already), and also configuration change // bit enabled. The state of the register should be saved // so it can be restored. // usCANCTL = CANRegRead(ulBase + CAN_O_CTL); CANRegWrite(ulBase + CAN_O_CTL, usCANCTL | CAN_CTL_INIT | CAN_CTL_CCE); // // Now add in the pre-scalar on the bit rate. // ulRegValue |= ((ulPreDivide - 1)& CAN_BIT_BRP_M); // // Set the clock bits in the and the lower bits of the // pre-scalar. // CANRegWrite(ulBase + CAN_O_BIT, ulRegValue); // // Set the divider upper bits in the extension register. // CANRegWrite(ulBase + CAN_O_BRPE, ((ulPreDivide - 1) >> 6) & CAN_BRPE_BRPE_M); // // Restore the saved CAN Control register. // CANRegWrite(ulBase + CAN_O_CTL, usCANCTL); // // Return the computed bit rate. // return(ulSourceClock / ( ulPreDivide * ulCANBits)); } } // // Move the divisor up one and look again. Only in rare cases are // more than 2 loops required to find the value. // ulDesiredRatio++; } return(0); } //***************************************************************************** // //! Configures the CAN controller bit timing. //! //! \param ulBase is the base address of the CAN controller. //! \param pClkParms points to the structure with the clock parameters. //! //! Configures the various timing parameters for the CAN bus bit timing: //! Propagation segment, Phase Buffer 1 segment, Phase Buffer 2 segment, and //! the Synchronization Jump Width. The values for Propagation and Phase //! Buffer 1 segments are derived from the combination //! \e pClkParms->uSyncPropPhase1Seg parameter. Phase Buffer 2 is determined //! from the \e pClkParms->uPhase2Seg parameter. These two parameters, along //! with \e pClkParms->uSJW are based in units of bit time quanta. The actual //! quantum time is determined by the \e pClkParms->uQuantumPrescaler value, //! which specifies the divisor for the CAN module clock. //! //! The total bit time, in quanta, will be the sum of the two Seg parameters, //! as follows: //! //! bit_time_q = uSyncPropPhase1Seg + uPhase2Seg + 1 //! //! Note that the Sync_Seg is always one quantum in duration, and will be added //! to derive the correct duration of Prop_Seg and Phase1_Seg. //! //! The equation to determine the actual bit rate is as follows: //! //! CAN Clock / //! ((\e uSyncPropPhase1Seg + \e uPhase2Seg + 1) * (\e uQuantumPrescaler)) //! //! This means that with \e uSyncPropPhase1Seg = 4, \e uPhase2Seg = 1, //! \e uQuantumPrescaler = 2 and an 8 MHz CAN clock, that the bit rate will be //! (8 MHz) / ((5 + 2 + 1) * 2) or 500 Kbit/sec. //! //! This function replaces the original CANSetBitTiming() API and performs the //! same actions. A macro is provided in <tt>can.h</tt> to map the original //! API to this API. //! //! \return None. // //***************************************************************************** /* void CANBitTimingSet(unsigned long ulBase, tCANBitClkParms *pClkParms) { unsigned int uBitReg; unsigned int uSavedInit; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT(pClkParms != 0); // // The phase 1 segment must be in the range from 2 to 16. // ASSERT((pClkParms->uSyncPropPhase1Seg >= 2) && (pClkParms->uSyncPropPhase1Seg <= 16)); // // The phase 2 segment must be in the range from 1 to 8. // ASSERT((pClkParms->uPhase2Seg >= 1) && (pClkParms->uPhase2Seg <= 8)); // // The synchronous jump windows must be in the range from 1 to 4. // ASSERT((pClkParms->uSJW >= 1) && (pClkParms->uSJW <= 4)); // // The CAN clock pre-divider must be in the range from 1 to 1024. // ASSERT((pClkParms->uQuantumPrescaler <= 1024) && (pClkParms->uQuantumPrescaler >= 1)); // // To set the bit timing register, the controller must be placed in init // mode (if not already), and also configuration change bit enabled. State // of the init bit should be saved so it can be restored at the end. // uSavedInit = CANRegRead(ulBase + CAN_O_CTL); CANRegWrite(ulBase + CAN_O_CTL, uSavedInit | CAN_CTL_INIT | CAN_CTL_CCE); // // Set the bit fields of the bit timing register according to the parms. // uBitReg = ((pClkParms->uPhase2Seg - 1) << 12) & CAN_BIT_TSEG2_M; uBitReg |= ((pClkParms->uSyncPropPhase1Seg - 1) << 8) & CAN_BIT_TSEG1_M; uBitReg |= ((pClkParms->uSJW - 1) << 6) & CAN_BIT_SJW_M; uBitReg |= (pClkParms->uQuantumPrescaler - 1) & CAN_BIT_BRP_M; CANRegWrite(ulBase + CAN_O_BIT, uBitReg); // // Set the divider upper bits in the extension register. // CANRegWrite(ulBase + CAN_O_BRPE, ((pClkParms->uQuantumPrescaler - 1) >> 6) & CAN_BRPE_BRPE_M); // // Clear the config change bit, and restore the init bit. // uSavedInit &= ~CAN_CTL_CCE; // // If Init was not set before, then clear it. // if(uSavedInit & CAN_CTL_INIT) { uSavedInit &= ~CAN_CTL_INIT; } CANRegWrite(ulBase + CAN_O_CTL, uSavedInit); } */ //***************************************************************************** // //! Registers an interrupt handler for the CAN controller. //! //! \param ulBase is the base address of the CAN controller. //! \param pfnHandler is a pointer to the function to be called when the //! enabled CAN interrupts occur. //! //! This function registers the interrupt handler in the interrupt vector //! table, and enables CAN interrupts on the interrupt controller; specific CAN //! interrupt sources must be enabled using CANIntEnable(). The interrupt //! handler being registered must clear the source of the interrupt using //! CANIntClear(). //! //! If the application is using a static interrupt vector table stored in //! flash, then it is not necessary to register the interrupt handler this way. //! Instead, IntEnable() should be used to enable CAN interrupts on the //! interrupt controller. //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void CANIntRegister(unsigned long ulBase, void (*pfnHandler)(void)) { unsigned long ulIntNumber; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // Get the actual interrupt number for this CAN controller. // ulIntNumber = CANIntNumberGet(ulBase); // // Register the interrupt handler. // IntRegister(ulIntNumber, pfnHandler); // // Enable the Ethernet interrupt. // IntEnable(ulIntNumber); } //***************************************************************************** // //! Unregisters an interrupt handler for the CAN controller. //! //! \param ulBase is the base address of the controller. //! //! This function unregisters the previously registered interrupt handler and //! disables the interrupt on the interrupt controller. //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void CANIntUnregister(unsigned long ulBase) { unsigned long ulIntNumber; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // Get the actual interrupt number for this CAN controller. // ulIntNumber = CANIntNumberGet(ulBase); // // Register the interrupt handler. // IntUnregister(ulIntNumber); // // Disable the CAN interrupt. // IntDisable(ulIntNumber); } //***************************************************************************** // //! Enables individual CAN controller interrupt sources. //! //! \param ulBase is the base address of the CAN controller. //! \param ulIntFlags is the bit mask of the interrupt sources to be enabled. //! //! Enables specific interrupt sources of the CAN controller. Only enabled //! sources will cause a processor interrupt. //! //! The \e ulIntFlags parameter is the logical OR of any of the following: //! //! - \b CAN_INT_ERROR - a controller error condition has occurred //! - \b CAN_INT_STATUS - a message transfer has completed, or a bus error has //! been detected //! - \b CAN_INT_MASTER - allow CAN controller to generate interrupts //! //! In order to generate any interrupts, \b CAN_INT_MASTER must be enabled. //! Further, for any particular transaction from a message object to generate //! an interrupt, that message object must have interrupts enabled (see //! CANMessageSet()). \b CAN_INT_ERROR will generate an interrupt if the //! controller enters the ``bus off'' condition, or if the error counters reach //! a limit. \b CAN_INT_STATUS will generate an interrupt under quite a few //! status conditions and may provide more interrupts than the application //! needs to handle. When an interrupt occurs, use CANIntStatus() to determine //! the cause. //! //! \return None. // //***************************************************************************** void CANIntEnable(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT((ulIntFlags & ~(CAN_CTL_EIE | CAN_CTL_SIE | CAN_CTL_IE)) == 0); // // Enable the specified interrupts. // CANRegWrite(ulBase + CAN_O_CTL, CANRegRead(ulBase + CAN_O_CTL) | ulIntFlags); } //***************************************************************************** // //! Disables individual CAN controller interrupt sources. //! //! \param ulBase is the base address of the CAN controller. //! \param ulIntFlags is the bit mask of the interrupt sources to be disabled. //! //! Disables the specified CAN controller interrupt sources. Only enabled //! interrupt sources can cause a processor interrupt. //! //! The \e ulIntFlags parameter has the same definition as in the //! CANIntEnable() function. //! //! \return None. // //***************************************************************************** void CANIntDisable(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT((ulIntFlags & ~(CAN_CTL_EIE | CAN_CTL_SIE | CAN_CTL_IE)) == 0); // // Disable the specified interrupts. // CANRegWrite(ulBase + CAN_O_CTL, CANRegRead(ulBase + CAN_O_CTL) & ~(ulIntFlags)); } //***************************************************************************** // //! Returns the current CAN controller interrupt status. //! //! \param ulBase is the base address of the CAN controller. //! \param eIntStsReg indicates which interrupt status register to read //! //! Returns the value of one of two interrupt status registers. The interrupt //! status register read is determined by the \e eIntStsReg parameter, which //! can have one of the following values: //! //! - \b CAN_INT_STS_CAUSE - indicates the cause of the interrupt //! - \b CAN_INT_STS_OBJECT - indicates pending interrupts of all message //! objects //! //! \b CAN_INT_STS_CAUSE returns the value of the controller interrupt register //! and indicates the cause of the interrupt. It will be a value of //! \b CAN_INT_INTID_STATUS if the cause is a status interrupt. In this case, //! the status register should be read with the CANStatusGet() function. //! Calling this function to read the status will also clear the status //! interrupt. If the value of the interrupt register is in the range 1-32, //! then this indicates the number of the highest priority message object that //! has an interrupt pending. The message object interrupt can be cleared by //! using the CANIntClear() function, or by reading the message using //! CANMessageGet() in the case of a received message. The interrupt handler //! can read the interrupt status again to make sure all pending interrupts are //! cleared before returning from the interrupt. //! //! \b CAN_INT_STS_OBJECT returns a bit mask indicating which message objects //! have pending interrupts. This can be used to discover all of the pending //! interrupts at once, as opposed to repeatedly reading the interrupt register //! by using \b CAN_INT_STS_CAUSE. //! //! \return Returns the value of one of the interrupt status registers. // //***************************************************************************** unsigned long CANIntStatus(unsigned long ulBase, tCANIntStsReg eIntStsReg) { unsigned long ulStatus; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // See which status the caller is looking for. // switch(eIntStsReg) { // // The caller wants the global interrupt status for the CAN controller // specified by ulBase. // case CAN_INT_STS_CAUSE: { ulStatus = CANRegRead(ulBase + CAN_O_INT); break; } // // The caller wants the current message status interrupt for all // messages. // case CAN_INT_STS_OBJECT: { // // Read and combine both 16 bit values into one 32bit status. // ulStatus = (CANRegRead(ulBase + CAN_O_MSG1INT) & CAN_MSG1INT_INTPND_M); ulStatus |= (CANRegRead(ulBase + CAN_O_MSG2INT) << 16); break; } // // Request was for unknown status so just return 0. // default: { ulStatus = 0; break; } } // // Return the interrupt status value // return(ulStatus); } //***************************************************************************** // //! Clears a CAN interrupt source. //! //! \param ulBase is the base address of the CAN controller. //! \param ulIntClr is a value indicating which interrupt source to clear. //! //! This function can be used to clear a specific interrupt source. The //! \e ulIntClr parameter should be one of the following values: //! //! - \b CAN_INT_INTID_STATUS - Clears a status interrupt. //! - 1-32 - Clears the specified message object interrupt //! //! It is not necessary to use this function to clear an interrupt. This //! should only be used if the application wants to clear an interrupt source //! without taking the normal interrupt action. //! //! Normally, the status interrupt is cleared by reading the controller status //! using CANStatusGet(). A specific message object interrupt is normally //! cleared by reading the message object using CANMessageGet(). //! //! \note Since there is a write buffer in the Cortex-M3 processor, it may take //! several clock cycles before the interrupt source is actually cleared. //! Therefore, it is recommended that the interrupt source be cleared early in //! the interrupt handler (as opposed to the very last action) to avoid //! returning from the interrupt handler before the interrupt source is //! actually cleared. Failure to do so may result in the interrupt handler //! being immediately reentered (since NVIC still sees the interrupt source //! asserted). //! //! \return None. // //***************************************************************************** void CANIntClear(unsigned long ulBase, unsigned long ulIntClr) { // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT((ulIntClr == CAN_INT_INTID_STATUS) || ((ulIntClr>=1) && (ulIntClr <=32))); if(ulIntClr == CAN_INT_INTID_STATUS) { // // Simply read and discard the status to clear the interrupt. // CANRegRead(ulBase + CAN_O_STS); } else { // // Wait to be sure that this interface is not busy. // while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY) { } // // Only change the interrupt pending state by setting only the // CAN_IF1CMSK_CLRINTPND bit. // CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_CLRINTPND); // // Send the clear pending interrupt command to the CAN controller. // CANRegWrite(ulBase + CAN_O_IF1CRQ, ulIntClr & CAN_IF1CRQ_MNUM_M); // // Wait to be sure that this interface is not busy. // while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY) { } } } //***************************************************************************** // //! Sets the CAN controller automatic retransmission behavior. //! //! \param ulBase is the base address of the CAN controller. //! \param bAutoRetry enables automatic retransmission. //! //! Enables or disables automatic retransmission of messages with detected //! errors. If \e bAutoRetry is \b true, then automatic retransmission is //! enabled, otherwise it is disabled. //! //! \return None. // //***************************************************************************** void CANRetrySet(unsigned long ulBase, tBoolean bAutoRetry) { unsigned long ulCtlReg; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ulCtlReg = CANRegRead(ulBase + CAN_O_CTL); // // Conditionally set the DAR bit to enable/disable auto-retry. // if(bAutoRetry) { // // Clearing the DAR bit tells the controller to not disable the // auto-retry of messages which were not transmitted or received // correctly. // ulCtlReg &= ~CAN_CTL_DAR; } else { // // Setting the DAR bit tells the controller to disable the auto-retry // of messages which were not transmitted or received correctly. // ulCtlReg |= CAN_CTL_DAR; } CANRegWrite(ulBase + CAN_O_CTL, ulCtlReg); } //***************************************************************************** // //! Returns the current setting for automatic retransmission. //! //! \param ulBase is the base address of the CAN controller. //! //! Reads the current setting for the automatic retransmission in the CAN //! controller and returns it to the caller. //! //! \return Returns \b true if automatic retransmission is enabled, \b false //! otherwise. // //***************************************************************************** tBoolean CANRetryGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // Read the disable automatic retry setting from the CAN controller. // if(CANRegRead(ulBase + CAN_O_CTL) & CAN_CTL_DAR) { // // Automatic data retransmission is not enabled. // return(false); } // // Automatic data retransmission is enabled. // return(true); } //***************************************************************************** // //! Reads one of the controller status registers. //! //! \param ulBase is the base address of the CAN controller. //! \param eStatusReg is the status register to read. //! //! Reads a status register of the CAN controller and returns it to the caller. //! The different status registers are: //! //! - \b CAN_STS_CONTROL - the main controller status //! - \b CAN_STS_TXREQUEST - bit mask of objects pending transmission //! - \b CAN_STS_NEWDAT - bit mask of objects with new data //! - \b CAN_STS_MSGVAL - bit mask of objects with valid configuration //! //! When reading the main controller status register, a pending status //! interrupt will be cleared. This should be used in the interrupt handler //! for the CAN controller if the cause is a status interrupt. The controller //! status register fields are as follows: //! //! - \b CAN_STATUS_BUS_OFF - controller is in bus-off condition //! - \b CAN_STATUS_EWARN - an error counter has reached a limit of at least 96 //! - \b CAN_STATUS_EPASS - CAN controller is in the error passive state //! - \b CAN_STATUS_RXOK - a message was received successfully (independent of //! any message filtering). //! - \b CAN_STATUS_TXOK - a message was successfully transmitted //! - \b CAN_STATUS_LEC_MSK - mask of last error code bits (3 bits) //! - \b CAN_STATUS_LEC_NONE - no error //! - \b CAN_STATUS_LEC_STUFF - stuffing error detected //! - \b CAN_STATUS_LEC_FORM - a format error occurred in the fixed format part //! of a message //! - \b CAN_STATUS_LEC_ACK - a transmitted message was not acknowledged //! - \b CAN_STATUS_LEC_BIT1 - dominant level detected when trying to send in //! recessive mode //! - \b CAN_STATUS_LEC_BIT0 - recessive level detected when trying to send in //! dominant mode //! - \b CAN_STATUS_LEC_CRC - CRC error in received message //! //! The remaining status registers are 32-bit bit maps to the message objects. //! They can be used to quickly obtain information about the status of all the //! message objects without needing to query each one. They contain the //! following information: //! //! - \b CAN_STS_TXREQUEST - if a message object's TxRequest bit is set, that //! means that a transmission is pending on that object. The application can //! use this to determine which objects are still waiting to send a message. //! - \b CAN_STS_NEWDAT - if a message object's NewDat bit is set, that means //! that a new message has been received in that object, and has not yet been //! picked up by the host application //! - \b CAN_STS_MSGVAL - if a message object's MsgVal bit is set, that means //! it has a valid configuration programmed. The host application can use this //! to determine which message objects are empty/unused. //! //! \return Returns the value of the status register. // //***************************************************************************** unsigned long CANStatusGet(unsigned long ulBase, tCANStsReg eStatusReg) { unsigned long ulStatus; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); switch(eStatusReg) { // // Just return the global CAN status register since that is what was // requested. // case CAN_STS_CONTROL: { ulStatus = CANRegRead(ulBase + CAN_O_STS); CANRegWrite(ulBase + CAN_O_STS, ~(CAN_STS_RXOK | CAN_STS_TXOK | CAN_STS_LEC_M)); break; } // // Combine the Transmit status bits into one 32bit value. // case CAN_STS_TXREQUEST: { ulStatus = CANRegRead(ulBase + CAN_O_TXRQ1); ulStatus |= CANRegRead(ulBase + CAN_O_TXRQ2) << 16; break; } // // Combine the New Data status bits into one 32bit value. // case CAN_STS_NEWDAT: { ulStatus = CANRegRead(ulBase + CAN_O_NWDA1); ulStatus |= CANRegRead(ulBase + CAN_O_NWDA2) << 16; break; } // // Combine the Message valid status bits into one 32bit value. // case CAN_STS_MSGVAL: { ulStatus = CANRegRead(ulBase + CAN_O_MSG1VAL); ulStatus |= CANRegRead(ulBase + CAN_O_MSG2VAL) << 16; break; } // // Unknown CAN status requested so return 0. // default: { ulStatus = 0; break; } } return(ulStatus); } //***************************************************************************** // //! Reads the CAN controller error counter register. //! //! \param ulBase is the base address of the CAN controller. //! \param pulRxCount is a pointer to storage for the receive error counter. //! \param pulTxCount is a pointer to storage for the transmit error counter. //! //! Reads the error counter register and returns the transmit and receive error //! counts to the caller along with a flag indicating if the controller receive //! counter has reached the error passive limit. The values of the receive and //! transmit error counters are returned through the pointers provided as //! parameters. //! //! After this call, \e *pulRxCount will hold the current receive error count //! and \e *pulTxCount will hold the current transmit error count. //! //! \return Returns \b true if the receive error count has reached the error //! passive limit, and \b false if the error count is below the error passive //! limit. // //***************************************************************************** tBoolean CANErrCntrGet(unsigned long ulBase, unsigned long *pulRxCount, unsigned long *pulTxCount) { unsigned long ulCANError; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); // // Read the current count of transmit/receive errors. // ulCANError = CANRegRead(ulBase + CAN_O_ERR); // // Extract the error numbers from the register value. // *pulRxCount = (ulCANError & CAN_ERR_REC_M) >> CAN_ERR_REC_S; *pulTxCount = (ulCANError & CAN_ERR_TEC_M) >> CAN_ERR_TEC_S; if(ulCANError & CAN_ERR_RP) { return(true); } return(false); } //***************************************************************************** // //! Configures a message object in the CAN controller. //! //! \param ulBase is the base address of the CAN controller. //! \param ulObjID is the object number to configure (1-32). //! \param pMsgObject is a pointer to a structure containing message object //! settings. //! \param eMsgType indicates the type of message for this object. //! //! This function is used to configure any one of the 32 message objects in the //! CAN controller. A message object can be configured as any type of CAN //! message object as well as several options for automatic transmission and //! reception. This call also allows the message object to be configured to //! generate interrupts on completion of message receipt or transmission. The //! message object can also be configured with a filter/mask so that actions //! are only taken when a message that meets certain parameters is seen on the //! CAN bus. //! //! The \e eMsgType parameter must be one of the following values: //! //! - \b MSG_OBJ_TYPE_TX - CAN transmit message object. //! - \b MSG_OBJ_TYPE_TX_REMOTE - CAN transmit remote request message object. //! - \b MSG_OBJ_TYPE_RX - CAN receive message object. //! - \b MSG_OBJ_TYPE_RX_REMOTE - CAN receive remote request message object. //! - \b MSG_OBJ_TYPE_RXTX_REMOTE - CAN remote frame receive remote, then //! transmit message object. //! //! The message object pointed to by \e pMsgObject must be populated by the //! caller, as follows: //! //! - \e ulMsgID - contains the message ID, either 11 or 29 bits. //! - \e ulMsgIDMask - mask of bits from \e ulMsgID that must match if //! identifier filtering is enabled. //! - \e ulFlags //! - Set \b MSG_OBJ_TX_INT_ENABLE flag to enable interrupt on transmission. //! - Set \b MSG_OBJ_RX_INT_ENABLE flag to enable interrupt on receipt. //! - Set \b MSG_OBJ_USE_ID_FILTER flag to enable filtering based on the //! identifier mask specified by \e ulMsgIDMask. //! - \e ulMsgLen - the number of bytes in the message data. This should be //! non-zero even for a remote frame; it should match the expected bytes of the //! data responding data frame. //! - \e pucMsgData - points to a buffer containing up to 8 bytes of data for a //! data frame. //! //! \b Example: To send a data frame or remote frame(in response to a remote //! request), take the following steps: //! //! -# Set \e eMsgType to \b MSG_OBJ_TYPE_TX. //! -# Set \e pMsgObject->ulMsgID to the message ID. //! -# Set \e pMsgObject->ulFlags. Make sure to set \b MSG_OBJ_TX_INT_ENABLE to //! allow an interrupt to be generated when the message is sent. //! -# Set \e pMsgObject->ulMsgLen to the number of bytes in the data frame. //! -# Set \e pMsgObject->pucMsgData to point to an array containing the bytes //! to send in the message. //! -# Call this function with \e ulObjID set to one of the 32 object buffers. //! //! \b Example: To receive a specific data frame, take the following steps: //! //! -# Set \e eMsgObjType to \b MSG_OBJ_TYPE_RX. //! -# Set \e pMsgObject->ulMsgID to the full message ID, or a partial mask to //! use partial ID matching. //! -# Set \e pMsgObject->ulMsgIDMask bits that should be used for masking //! during comparison. //! -# Set \e pMsgObject->ulFlags as follows: //! - Set \b MSG_OBJ_RX_INT_ENABLE flag to be interrupted when the data frame //! is received. //! - Set \b MSG_OBJ_USE_ID_FILTER flag to enable identifier based filtering. //! -# Set \e pMsgObject->ulMsgLen to the number of bytes in the expected data //! frame. //! -# The buffer pointed to by \e pMsgObject->pucMsgData is not used by this //! call as no data is present at the time of the call. //! -# Call this function with \e ulObjID set to one of the 32 object buffers. //! //! If you specify a message object buffer that already contains a message //! definition, it will be overwritten. //! //! \return None. // //***************************************************************************** void CANMessageSet(unsigned long ulBase, unsigned long ulObjID, tCANMsgObject *pMsgObject, tMsgObjType eMsgType) { unsigned short usCmdMaskReg; unsigned short usMaskReg0, usMaskReg1; unsigned short usArbReg0, usArbReg1; unsigned short usMsgCtrl; tBoolean bTransferData; tBoolean bUseExtendedID; bTransferData = 0; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT((ulObjID <= 32) && (ulObjID != 0)); ASSERT((eMsgType == MSG_OBJ_TYPE_TX) || (eMsgType == MSG_OBJ_TYPE_TX_REMOTE) || (eMsgType == MSG_OBJ_TYPE_RX) || (eMsgType == MSG_OBJ_TYPE_RX_REMOTE) || (eMsgType == MSG_OBJ_TYPE_TX_REMOTE) || (eMsgType == MSG_OBJ_TYPE_RXTX_REMOTE)); // // Wait for busy bit to clear // while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY) { } // // See if we need to use an extended identifier or not. // if((pMsgObject->ulMsgID > CAN_MAX_11BIT_MSG_ID) || (pMsgObject->ulFlags & MSG_OBJ_EXTENDED_ID)) { bUseExtendedID = 1; } else { bUseExtendedID = 0; } // // This is always a write to the Message object as this call is setting a // message object. This call will also always set all size bits so it sets // both data bits. The call will use the CONTROL register to set control // bits so this bit needs to be set as well. // usCmdMaskReg = (CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_DATAA | CAN_IF1CMSK_DATAB | CAN_IF1CMSK_CONTROL); // // Initialize the values to a known state before filling them in based on // the type of message object that is being configured. // usArbReg0 = 0; usArbReg1 = 0; usMsgCtrl = 0; usMaskReg0 = 0; usMaskReg1 = 0; switch(eMsgType) { // // Transmit message object. // case MSG_OBJ_TYPE_TX: { // // Set the TXRQST bit and the reset the rest of the register. // usMsgCtrl |= CAN_IF1MCTL_TXRQST; usArbReg1 = CAN_IF1ARB2_DIR; bTransferData = 1; break; } // // Transmit remote request message object // case MSG_OBJ_TYPE_TX_REMOTE: { // // Set the TXRQST bit and the reset the rest of the register. // usMsgCtrl |= CAN_IF1MCTL_TXRQST; usArbReg1 = 0; break; } // // Receive message object. // case MSG_OBJ_TYPE_RX: { // // This clears the DIR bit along with everything else. The TXRQST // bit was cleared by defaulting usMsgCtrl to 0. // usArbReg1 = 0; break; } // // Receive remote request message object. // case MSG_OBJ_TYPE_RX_REMOTE: { // // The DIR bit is set to one for remote receivers. The TXRQST bit // was cleared by defaulting usMsgCtrl to 0. // usArbReg1 = CAN_IF1ARB2_DIR; // // Set this object so that it only indicates that a remote frame // was received and allow for software to handle it by sending back // a data frame. // usMsgCtrl = CAN_IF1MCTL_UMASK; // // Use the full Identifier by default. // usMaskReg0 = 0xffff; usMaskReg1 = 0x1fff; // // Make sure to send the mask to the message object. // usCmdMaskReg |= CAN_IF1CMSK_MASK; break; } // // Remote frame receive remote, with auto-transmit message object. // case MSG_OBJ_TYPE_RXTX_REMOTE: { // // Oddly the DIR bit is set to one for remote receivers. // usArbReg1 = CAN_IF1ARB2_DIR; // // Set this object to auto answer if a matching identifier is seen. // usMsgCtrl = CAN_IF1MCTL_RMTEN | CAN_IF1MCTL_UMASK; // // The data to be returned needs to be filled in. // bTransferData = 1; break; } // // This case should never happen due to the ASSERT statement at the // beginning of this function. // default: { return; } } // // Configure the Mask Registers. // if(pMsgObject->ulFlags & MSG_OBJ_USE_ID_FILTER) { if(bUseExtendedID) { // // Set the 29 bits of Identifier mask that were requested. // usMaskReg0 = pMsgObject->ulMsgIDMask & CAN_IF1MSK1_IDMSK_M; usMaskReg1 = ((pMsgObject->ulMsgIDMask >> 16) & CAN_IF1MSK2_IDMSK_M); } else { // // Lower 16 bit are unused so set them to zero. // usMaskReg0 = 0; // // Put the 11 bit Mask Identifier into the upper bits of the field // in the register. // usMaskReg1 = ((pMsgObject->ulMsgIDMask << 2) & CAN_IF1MSK2_IDMSK_M); } } // // If the caller wants to filter on the extended ID bit then set it. // if((pMsgObject->ulFlags & MSG_OBJ_USE_EXT_FILTER) == MSG_OBJ_USE_EXT_FILTER) { usMaskReg1 |= CAN_IF1MSK2_MXTD; } // // The caller wants to filter on the message direction field. // if((pMsgObject->ulFlags & MSG_OBJ_USE_DIR_FILTER) == MSG_OBJ_USE_DIR_FILTER) { usMaskReg1 |= CAN_IF1MSK2_MDIR; } if(pMsgObject->ulFlags & (MSG_OBJ_USE_ID_FILTER | MSG_OBJ_USE_DIR_FILTER | MSG_OBJ_USE_EXT_FILTER)) { // // Set the UMASK bit to enable using the mask register. // usMsgCtrl |= CAN_IF1MCTL_UMASK; // // Set the MASK bit so that this gets transferred to the Message Object. // usCmdMaskReg |= CAN_IF1CMSK_MASK; } // // Set the Arb bit so that this gets transferred to the Message object. // usCmdMaskReg |= CAN_IF1CMSK_ARB; // // Configure the Arbitration registers. // if(bUseExtendedID) { // // Set the 29 bit version of the Identifier for this message object. // usArbReg0 |= pMsgObject->ulMsgID & CAN_IF1ARB1_ID_M; usArbReg1 |= (pMsgObject->ulMsgID >> 16) & CAN_IF1ARB2_ID_M; // // Mark the message as valid and set the extended ID bit. // usArbReg1 |= CAN_IF1ARB2_MSGVAL | CAN_IF1ARB2_XTD; } else { // // Set the 11 bit version of the Identifier for this message object. // The lower 18 bits are set to zero. // usArbReg1 |= (pMsgObject->ulMsgID << 2) & CAN_IF1ARB2_ID_M; // // Mark the message as valid. // usArbReg1 |= CAN_IF1ARB2_MSGVAL; } // // Set the data length since this is set for all transfers. This is also a // single transfer and not a FIFO transfer so set EOB bit. // usMsgCtrl |= (pMsgObject->ulMsgLen & CAN_IF1MCTL_DLC_M); // // Mark this as the last entry if this is not the last entry in a FIFO. // if((pMsgObject->ulFlags & MSG_OBJ_FIFO) == 0) { usMsgCtrl |= CAN_IF1MCTL_EOB; } // // Enable transmit interrupts if they should be enabled. // if(pMsgObject->ulFlags & MSG_OBJ_TX_INT_ENABLE) { usMsgCtrl |= CAN_IF1MCTL_TXIE; } // // Enable receive interrupts if they should be enabled. // if(pMsgObject->ulFlags & MSG_OBJ_RX_INT_ENABLE) { usMsgCtrl |= CAN_IF1MCTL_RXIE; } // // Write the data out to the CAN Data registers if needed. // if(bTransferData) { CANDataRegWrite(pMsgObject->pucMsgData, (unsigned long *)(ulBase + CAN_O_IF1DA1), pMsgObject->ulMsgLen); } // // Write out the registers to program the message object. // CANRegWrite(ulBase + CAN_O_IF1CMSK, usCmdMaskReg); CANRegWrite(ulBase + CAN_O_IF1MSK1, usMaskReg0); CANRegWrite(ulBase + CAN_O_IF1MSK2, usMaskReg1); CANRegWrite(ulBase + CAN_O_IF1ARB1, usArbReg0); CANRegWrite(ulBase + CAN_O_IF1ARB2, usArbReg1); CANRegWrite(ulBase + CAN_O_IF1MCTL, usMsgCtrl); // // Transfer the message object to the message object specifiec by ulObjID. // CANRegWrite(ulBase + CAN_O_IF1CRQ, ulObjID & CAN_IF1CRQ_MNUM_M); return; } //***************************************************************************** // //! Reads a CAN message from one of the message object buffers. //! //! \param ulBase is the base address of the CAN controller. //! \param ulObjID is the object number to read (1-32). //! \param pMsgObject points to a structure containing message object fields. //! \param bClrPendingInt indicates whether an associated interrupt should be //! cleared. //! //! This function is used to read the contents of one of the 32 message objects //! in the CAN controller, and return it to the caller. The data returned is //! stored in the fields of the caller-supplied structure pointed to by //! \e pMsgObject. The data consists of all of the parts of a CAN message, //! plus some control and status information. //! //! Normally this is used to read a message object that has received and stored //! a CAN message with a certain identifier. However, this could also be used //! to read the contents of a message object in order to load the fields of the //! structure in case only part of the structure needs to be changed from a //! previous setting. //! //! When using CANMessageGet, all of the same fields of the structure are //! populated in the same way as when the CANMessageSet() function is used, //! with the following exceptions: //! //! \e pMsgObject->ulFlags: //! //! - \b MSG_OBJ_NEW_DATA indicates if this is new data since the last time it //! was read //! - \b MSG_OBJ_DATA_LOST indicates that at least one message was received on //! this message object, and not read by the host before being overwritten. //! //! \return None. // //***************************************************************************** void CANMessageGet(unsigned long ulBase, unsigned long ulObjID, tCANMsgObject *pMsgObject, tBoolean bClrPendingInt) { unsigned short usCmdMaskReg; unsigned short usMaskReg0, usMaskReg1; unsigned short usArbReg0, usArbReg1; unsigned short usMsgCtrl; // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT((ulObjID <= 32) && (ulObjID != 0)); // // This is always a read to the Message object as this call is setting a // message object. // usCmdMaskReg = (CAN_IF1CMSK_DATAA | CAN_IF1CMSK_DATAB | CAN_IF1CMSK_CONTROL | CAN_IF1CMSK_MASK | CAN_IF1CMSK_ARB); // // Clear a pending interrupt and new data in a message object. // if(bClrPendingInt) { usCmdMaskReg |= CAN_IF1CMSK_CLRINTPND; } // // Set up the request for data from the message object. // CANRegWrite(ulBase + CAN_O_IF2CMSK, usCmdMaskReg); // // Transfer the message object to the message object specified by ulObjID. // CANRegWrite(ulBase + CAN_O_IF2CRQ, ulObjID & CAN_IF1CRQ_MNUM_M); // // Wait for busy bit to clear // while(CANRegRead(ulBase + CAN_O_IF2CRQ) & CAN_IF1CRQ_BUSY) { } // // Read out the IF Registers. // usMaskReg0 = CANRegRead(ulBase + CAN_O_IF2MSK1); usMaskReg1 = CANRegRead(ulBase + CAN_O_IF2MSK2); usArbReg0 = CANRegRead(ulBase + CAN_O_IF2ARB1); usArbReg1 = CANRegRead(ulBase + CAN_O_IF2ARB2); usMsgCtrl = CANRegRead(ulBase + CAN_O_IF2MCTL); pMsgObject->ulFlags = MSG_OBJ_NO_FLAGS; // // Determine if this is a remote frame by checking the TXRQST and DIR bits. // if((!(usMsgCtrl & CAN_IF1MCTL_TXRQST) && (usArbReg1 & CAN_IF1ARB2_DIR)) || ((usMsgCtrl & CAN_IF1MCTL_TXRQST) && (!(usArbReg1 & CAN_IF1ARB2_DIR)))) { pMsgObject->ulFlags |= MSG_OBJ_REMOTE_FRAME; } // // Get the identifier out of the register, the format depends on size of // the mask. // if(usArbReg1 & CAN_IF1ARB2_XTD) { // // Set the 29 bit version of the Identifier for this message object. // pMsgObject->ulMsgID = ((usArbReg1 & CAN_IF1ARB2_ID_M) << 16) | usArbReg0; pMsgObject->ulFlags |= MSG_OBJ_EXTENDED_ID; } else { // // The Identifier is an 11 bit value. // pMsgObject->ulMsgID = (usArbReg1 & CAN_IF1ARB2_ID_M) >> 2; } // // Indicate that we lost some data. // if(usMsgCtrl & CAN_IF1MCTL_MSGLST) { pMsgObject->ulFlags |= MSG_OBJ_DATA_LOST; } // // Set the flag to indicate if ID masking was used. // if(usMsgCtrl & CAN_IF1MCTL_UMASK) { if(usArbReg1 & CAN_IF1ARB2_XTD) { // // The Identifier Mask is assumed to also be a 29 bit value. // pMsgObject->ulMsgIDMask = ((usMaskReg1 & CAN_IF1MSK2_IDMSK_M) << 16) | usMaskReg0; // // If this is a fully specified Mask and a remote frame then don't // set the MSG_OBJ_USE_ID_FILTER because the ID was not really // filtered. // if((pMsgObject->ulMsgIDMask != 0x1fffffff) || ((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0)) { pMsgObject->ulFlags |= MSG_OBJ_USE_ID_FILTER; } } else { // // The Identifier Mask is assumed to also be an 11 bit value. // pMsgObject->ulMsgIDMask = ((usMaskReg1 & CAN_IF1MSK2_IDMSK_M) >> 2); // // If this is a fully specified Mask and a remote frame then don't // set the MSG_OBJ_USE_ID_FILTER because the ID was not really // filtered. // if((pMsgObject->ulMsgIDMask != 0x7ff) || ((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0)) { pMsgObject->ulFlags |= MSG_OBJ_USE_ID_FILTER; } } // // Indicate if the extended bit was used in filtering. // if(usMaskReg1 & CAN_IF1MSK2_MXTD) { pMsgObject->ulFlags |= MSG_OBJ_USE_EXT_FILTER; } // // Indicate if direction filtering was enabled. // if(usMaskReg1 & CAN_IF1MSK2_MDIR) { pMsgObject->ulFlags |= MSG_OBJ_USE_DIR_FILTER; } } // // Set the interrupt flags. // if(usMsgCtrl & CAN_IF1MCTL_TXIE) { pMsgObject->ulFlags |= MSG_OBJ_TX_INT_ENABLE; } if(usMsgCtrl & CAN_IF1MCTL_RXIE) { pMsgObject->ulFlags |= MSG_OBJ_RX_INT_ENABLE; } // // See if there is new data available. // if(usMsgCtrl & CAN_IF1MCTL_NEWDAT) { // // Get the amount of data needed to be read. // pMsgObject->ulMsgLen = (usMsgCtrl & CAN_IF1MCTL_DLC_M); // // Don't read any data for a remote frame, there is nothing valid in // that buffer anyway. // if((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0) { // // Read out the data from the CAN registers. // CANDataRegRead(pMsgObject->pucMsgData, (unsigned long *)(ulBase + CAN_O_IF2DA1), pMsgObject->ulMsgLen); } // // Now clear out the new data flag. // CANRegWrite(ulBase + CAN_O_IF2CMSK, CAN_IF1CMSK_NEWDAT); // // Transfer the message object to the message object specified by // ulObjID. // CANRegWrite(ulBase + CAN_O_IF2CRQ, ulObjID & CAN_IF1CRQ_MNUM_M); // // Wait for busy bit to clear // while(CANRegRead(ulBase + CAN_O_IF2CRQ) & CAN_IF1CRQ_BUSY) { } // // Indicate that there is new data in this message. // pMsgObject->ulFlags |= MSG_OBJ_NEW_DATA; } else { // // Along with the MSG_OBJ_NEW_DATA not being set the amount of data // needs to be set to zero if none was available. // pMsgObject->ulMsgLen = 0; } } //***************************************************************************** // //! Clears a message object so that it is no longer used. //! //! \param ulBase is the base address of the CAN controller. //! \param ulObjID is the message object number to disable (1-32). //! //! This function frees the specified message object from use. Once a message //! object has been ``cleared,'' it will no longer automatically send or //! receive messages, or generate interrupts. //! //! \return None. // //***************************************************************************** void CANMessageClear(unsigned long ulBase, unsigned long ulObjID) { // // Check the arguments. // ASSERT(CANBaseValid(ulBase)); ASSERT((ulObjID >= 1) && (ulObjID <= 32)); // // Wait for busy bit to clear // while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY) { } // // Clear the message value bit in the arbitration register. This indicates // the message is not valid. // CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_ARB); CANRegWrite(ulBase + CAN_O_IF1ARB1, 0); CANRegWrite(ulBase + CAN_O_IF1ARB2, 0); // // Initiate programming the message object // CANRegWrite(ulBase + CAN_O_IF1CRQ, ulObjID & CAN_IF1CRQ_MNUM_M); } //***************************************************************************** // // Close the Doxygen group. //! @} // //*****************************************************************************
baw959/RTOS
can.c
C
mit
70,534
import java.util.Scanner; /** * Created by rnossal on 22/05/17. */ public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String[] nomeCompleto = scan.nextLine().trim().replace(" +", " ").split(" "); if (nomeCompleto.length == 1 || nomeCompleto.length == 0) { System.out.println("Sobrenome não informado"); } else { System.out.println(nomeCompleto[nomeCompleto.length -1]); } } }
rnossal/faculdade
Linguagem de Programação Orientada a Objetos I/aula9/Sobrenome/src/Main.java
Java
mit
467
# API Reference (v3.x) - [`.privateKeyVerify(Buffer privateKey)`](#privatekeyverifybuffer-privatekey---boolean) - [`.privateKeyExport(Buffer privateKey [, Boolean compressed = true])`](#privatekeyexportbuffer-privatekey--boolean-compressed--true---buffer) - [`.privateKeyImport(Buffer privateKey)`](#privatekeyimportbuffer-privatekey---buffer) - [`.privateKeyTweakAdd(Buffer privateKey, Buffer tweak)`](#privatekeytweakaddbuffer-privatekey-buffer-tweak---buffer) - [`.privateKeyTweakMul(Buffer privateKey, Buffer tweak)`](#privatekeytweakmulbuffer-privatekey-buffer-tweak---buffer) - [`.publicKeyCreate(Buffer privateKey [, Boolean compressed = true])`](#publickeycreatebuffer-privatekey--boolean-compressed--true---buffer) - [`.publicKeyConvert(Buffer publicKey [, Boolean compressed = true])`](#publickeyconvertbuffer-publickey--boolean-compressed--true---buffer) - [`.publicKeyVerify(Buffer publicKey)`](#publickeyverifybuffer-publickey---boolean) - [`.publicKeyTweakAdd(Buffer publicKey, Buffer tweak [, Boolean compressed = true])`](#publickeytweakaddbuffer-publickey-buffer-tweak--boolean-compressed--true---buffer) - [`.publicKeyTweakMul(Buffer publicKey, Buffer tweak [, Boolean compressed = true])`](#publickeytweakmulbuffer-publickey-buffer-tweak--boolean-compressed--true---buffer) - [`.publicKeyCombine(Array<Buffer> publicKeys [, Boolean compressed = true])`](#publickeycombinearraybuffer-publickeys--boolean-compressed--true---buffer) - [`.signatureNormalize(Buffer signature)`](#signaturenormalizebuffer-signature---buffer) - [`.signatureExport(Buffer signature)`](#signatureexportbuffer-signature---buffer) - [`.signatureImport(Buffer signature)`](#signatureimportbuffer-signature---buffer) - [`.signatureImportLax(Buffer signature)`](#signatureimportlaxbuffer-signature---buffer) - [`.sign(Buffer message, Buffer privateKey [, Object options])`](#signbuffer-message-buffer-privatekey--object-options---signature-buffer-recovery-number) - [Option: `Function noncefn`](#option-function-noncefn) - [Option: `Buffer data`](#option-buffer-data) - [`.verify(Buffer message, Buffer signature, Buffer publicKey)`](#verifybuffer-message-buffer-signature-buffer-publickey---boolean) - [`.recover(Buffer message, Buffer signature, Number recovery [, Boolean compressed = true])`](#recoverbuffer-message-buffer-signature-number-recovery--boolean-compressed--true---buffer) - [`.ecdh(Buffer publicKey, Buffer privateKey)`](#ecdhbuffer-publickey-buffer-privatekey---buffer) - [`.ecdhUnsafe(Buffer publicKey, Buffer privateKey [, Boolean compressed = true])`](#ecdhunsafebuffer-publickey-buffer-privatekey--boolean-compressed--true---buffer) #####`.privateKeyVerify(Buffer privateKey)` -> `Boolean` Verify an ECDSA *privateKey*. <hr> #####`.privateKeyExport(Buffer privateKey [, Boolean compressed = true])` -> `Buffer` Export a *privateKey* in DER format. <hr> #####`.privateKeyImport(Buffer privateKey)` -> `Buffer` Import a *privateKey* in DER format. <hr> #####`.privateKeyTweakAdd(Buffer privateKey, Buffer tweak)` -> `Buffer` Tweak a *privateKey* by adding *tweak* to it. <hr> #####`.privateKeyTweakMul(Buffer privateKey, Buffer tweak)` -> `Buffer` Tweak a *privateKey* by multiplying it by a *tweak*. <hr> #####`.publicKeyCreate(Buffer privateKey [, Boolean compressed = true])` -> `Buffer` Compute the public key for a *privateKey*. <hr> #####`.publicKeyConvert(Buffer publicKey [, Boolean compressed = true])` -> `Buffer` Convert a *publicKey* to *compressed* or *uncompressed* form. <hr> #####`.publicKeyVerify(Buffer publicKey)` -> `Boolean` Verify an ECDSA *publicKey*. <hr> #####`.publicKeyTweakAdd(Buffer publicKey, Buffer tweak [, Boolean compressed = true])` -> `Buffer` Tweak a *publicKey* by adding *tweak* times the generator to it. <hr> #####`.publicKeyTweakMul(Buffer publicKey, Buffer tweak [, Boolean compressed = true])` -> `Buffer` Tweak a *publicKey* by multiplying it by a *tweak* value. <hr> #####`.publicKeyCombine(Array<Buffer> publicKeys [, Boolean compressed = true])` -> `Buffer` Add a given *publicKeys* together. <hr> #####`.signatureNormalize(Buffer signature)` -> `Buffer` Convert a *signature* to a normalized lower-S form. <hr> #####`.signatureExport(Buffer signature)` -> `Buffer` Serialize an ECDSA *signature* in DER format. <hr> #####`.signatureImport(Buffer signature)` -> `Buffer` Parse a DER ECDSA *signature* (follow by [BIP66](https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki)). <hr> #####`.signatureImportLax(Buffer signature)` -> `Buffer` Same as [signatureImport](#signatureimportbuffer-signature---buffer) but not follow by [BIP66](https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki). <hr> #####`.sign(Buffer message, Buffer privateKey [, Object options])` -> `{signature: Buffer, recovery: number}` Create an ECDSA signature. Always return low-S signature. ######Option: `Function noncefn` Nonce generator. By default it is [rfc6979](https://tools.ietf.org/html/rfc6979). Function signature: `noncefn(Buffer message, Buffer privateKey, ?Buffer algo, ?Buffer data, Number attempt)` -> `Buffer` ######Option: `Buffer data` Additional data for [noncefn](#option-function-noncefn) (RFC 6979 3.6) (32 bytes). By default is `null`. <hr> #####`.verify(Buffer message, Buffer signature, Buffer publicKey)` -> `Boolean` Verify an ECDSA signature. Note: **return false for high signatures!** <hr> #####`.recover(Buffer message, Buffer signature, Number recovery [, Boolean compressed = true])` -> `Buffer` Recover an ECDSA public key from a signature. <hr> #####`.ecdh(Buffer publicKey, Buffer privateKey)` -> `Buffer` Compute an EC Diffie-Hellman secret and applied sha256 to compressed public key. <hr> #####`.ecdhUnsafe(Buffer publicKey, Buffer privateKey [, Boolean compressed = true])` -> `Buffer` Compute an EC Diffie-Hellman secret and return public key as result.
LordGoodman/light-wallet
node_modules/secp256k1/API.md
Markdown
mit
5,913
/* * The MIT License * * Copyright 2016 gburdell. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package laol.ast; import apfe.runtime.Acceptor; import apfe.runtime.Marker; import apfe.runtime.Repetition; import apfe.runtime.Sequence; import apfe.runtime.Util; import java.util.LinkedList; import java.util.List; /** * * @author gburdell */ public class BasedNumber extends Item { public BasedNumber(final laol.parser.apfe.BasedNumber decl) { super(decl); Sequence seq = asSequence(); Repetition rep = asRepetition(seq, 0); if (0 < rep.sizeofAccepted()) { m_size = Integer.parseInt(rep.toString().replace("_", "")); } else { m_size = -1; } seq = asPrioritizedChoice(seq.itemAt(3)).getAccepted(); m_base = Character.toUpperCase(seq.itemAt(0).toString().charAt(0)); m_val = seq.itemAt(1).toString(); } public boolean hasSize() { return m_size >= 0; } public int getSize() { return m_size; } public char getBase() { return m_base; } public String getVal() { return m_val; } private final int m_size; private final char m_base; private final String m_val; }
gburdell/laol
src/laol/ast/BasedNumber.java
Java
mit
2,299
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ /* This is a compiled file, you should be editing the file in the templates directory */ .pace { -webkit-pointer-events: none; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; user-select: none; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; -o-box-sizing: border-box; box-sizing: border-box; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; z-index: 2000; position: fixed; margin: auto; top: 12px; left: 0; right: 0; bottom: 0; width: 200px; height: 50px; overflow: hidden; } .pace .pace-progress { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; -o-box-sizing: border-box; box-sizing: border-box; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); display: block; position: absolute; right: 100%; margin-right: -7px; width: 93%; top: 7px; height: 14px; font-size: 12px; background: #ffffff; color: #ffffff; line-height: 60px; font-weight: bold; font-family: Helvetica, Arial, "Lucida Grande", sans-serif; -webkit-box-shadow: 120px 0 #fff, 240px 0 #fff; -ms-box-shadow: 120px 0 #fff, 240px 0 #fff; box-shadow: 120px 0 #fff, 240px 0 #fff; } .pace .pace-progress:after { content: attr(data-progress-text); display: inline-block; position: fixed; width: 45px; text-align: right; right: 0; padding-right: 16px; top: 4px; } .pace .pace-progress[data-progress-text="0%"]:after { right: -200px } .pace .pace-progress[data-progress-text="1%"]:after { right: -198.14px } .pace .pace-progress[data-progress-text="2%"]:after { right: -196.28px } .pace .pace-progress[data-progress-text="3%"]:after { right: -194.42px } .pace .pace-progress[data-progress-text="4%"]:after { right: -192.56px } .pace .pace-progress[data-progress-text="5%"]:after { right: -190.7px } .pace .pace-progress[data-progress-text="6%"]:after { right: -188.84px } .pace .pace-progress[data-progress-text="7%"]:after { right: -186.98px } .pace .pace-progress[data-progress-text="8%"]:after { right: -185.12px } .pace .pace-progress[data-progress-text="9%"]:after { right: -183.26px } .pace .pace-progress[data-progress-text="10%"]:after { right: -181.4px } .pace .pace-progress[data-progress-text="11%"]:after { right: -179.54px } .pace .pace-progress[data-progress-text="12%"]:after { right: -177.68px } .pace .pace-progress[data-progress-text="13%"]:after { right: -175.82px } .pace .pace-progress[data-progress-text="14%"]:after { right: -173.96px } .pace .pace-progress[data-progress-text="15%"]:after { right: -172.1px } .pace .pace-progress[data-progress-text="16%"]:after { right: -170.24px } .pace .pace-progress[data-progress-text="17%"]:after { right: -168.38px } .pace .pace-progress[data-progress-text="18%"]:after { right: -166.52px } .pace .pace-progress[data-progress-text="19%"]:after { right: -164.66px } .pace .pace-progress[data-progress-text="20%"]:after { right: -162.8px } .pace .pace-progress[data-progress-text="21%"]:after { right: -160.94px } .pace .pace-progress[data-progress-text="22%"]:after { right: -159.08px } .pace .pace-progress[data-progress-text="23%"]:after { right: -157.22px } .pace .pace-progress[data-progress-text="24%"]:after { right: -155.36px } .pace .pace-progress[data-progress-text="25%"]:after { right: -153.5px } .pace .pace-progress[data-progress-text="26%"]:after { right: -151.64px } .pace .pace-progress[data-progress-text="27%"]:after { right: -149.78px } .pace .pace-progress[data-progress-text="28%"]:after { right: -147.92px } .pace .pace-progress[data-progress-text="29%"]:after { right: -146.06px } .pace .pace-progress[data-progress-text="30%"]:after { right: -144.2px } .pace .pace-progress[data-progress-text="31%"]:after { right: -142.34px } .pace .pace-progress[data-progress-text="32%"]:after { right: -140.48px } .pace .pace-progress[data-progress-text="33%"]:after { right: -138.62px } .pace .pace-progress[data-progress-text="34%"]:after { right: -136.76px } .pace .pace-progress[data-progress-text="35%"]:after { right: -134.9px } .pace .pace-progress[data-progress-text="36%"]:after { right: -133.04px } .pace .pace-progress[data-progress-text="37%"]:after { right: -131.18px } .pace .pace-progress[data-progress-text="38%"]:after { right: -129.32px } .pace .pace-progress[data-progress-text="39%"]:after { right: -127.46px } .pace .pace-progress[data-progress-text="40%"]:after { right: -125.6px } .pace .pace-progress[data-progress-text="41%"]:after { right: -123.74px } .pace .pace-progress[data-progress-text="42%"]:after { right: -121.88px } .pace .pace-progress[data-progress-text="43%"]:after { right: -120.02px } .pace .pace-progress[data-progress-text="44%"]:after { right: -118.16px } .pace .pace-progress[data-progress-text="45%"]:after { right: -116.3px } .pace .pace-progress[data-progress-text="46%"]:after { right: -114.44px } .pace .pace-progress[data-progress-text="47%"]:after { right: -112.58px } .pace .pace-progress[data-progress-text="48%"]:after { right: -110.72px } .pace .pace-progress[data-progress-text="49%"]:after { right: -108.86px } .pace .pace-progress[data-progress-text="50%"]:after { right: -107px } .pace .pace-progress[data-progress-text="51%"]:after { right: -105.14px } .pace .pace-progress[data-progress-text="52%"]:after { right: -103.28px } .pace .pace-progress[data-progress-text="53%"]:after { right: -101.42px } .pace .pace-progress[data-progress-text="54%"]:after { right: -99.56px } .pace .pace-progress[data-progress-text="55%"]:after { right: -97.7px } .pace .pace-progress[data-progress-text="56%"]:after { right: -95.84px } .pace .pace-progress[data-progress-text="57%"]:after { right: -93.98px } .pace .pace-progress[data-progress-text="58%"]:after { right: -92.12px } .pace .pace-progress[data-progress-text="59%"]:after { right: -90.26px } .pace .pace-progress[data-progress-text="60%"]:after { right: -88.4px } .pace .pace-progress[data-progress-text="61%"]:after { right: -86.53999999999999px } .pace .pace-progress[data-progress-text="62%"]:after { right: -84.68px } .pace .pace-progress[data-progress-text="63%"]:after { right: -82.82px } .pace .pace-progress[data-progress-text="64%"]:after { right: -80.96000000000001px } .pace .pace-progress[data-progress-text="65%"]:after { right: -79.1px } .pace .pace-progress[data-progress-text="66%"]:after { right: -77.24px } .pace .pace-progress[data-progress-text="67%"]:after { right: -75.38px } .pace .pace-progress[data-progress-text="68%"]:after { right: -73.52px } .pace .pace-progress[data-progress-text="69%"]:after { right: -71.66px } .pace .pace-progress[data-progress-text="70%"]:after { right: -69.8px } .pace .pace-progress[data-progress-text="71%"]:after { right: -67.94px } .pace .pace-progress[data-progress-text="72%"]:after { right: -66.08px } .pace .pace-progress[data-progress-text="73%"]:after { right: -64.22px } .pace .pace-progress[data-progress-text="74%"]:after { right: -62.36px } .pace .pace-progress[data-progress-text="75%"]:after { right: -60.5px } .pace .pace-progress[data-progress-text="76%"]:after { right: -58.64px } .pace .pace-progress[data-progress-text="77%"]:after { right: -56.78px } .pace .pace-progress[data-progress-text="78%"]:after { right: -54.92px } .pace .pace-progress[data-progress-text="79%"]:after { right: -53.06px } .pace .pace-progress[data-progress-text="80%"]:after { right: -51.2px } .pace .pace-progress[data-progress-text="81%"]:after { right: -49.34px } .pace .pace-progress[data-progress-text="82%"]:after { right: -47.480000000000004px } .pace .pace-progress[data-progress-text="83%"]:after { right: -45.62px } .pace .pace-progress[data-progress-text="84%"]:after { right: -43.76px } .pace .pace-progress[data-progress-text="85%"]:after { right: -41.9px } .pace .pace-progress[data-progress-text="86%"]:after { right: -40.04px } .pace .pace-progress[data-progress-text="87%"]:after { right: -38.18px } .pace .pace-progress[data-progress-text="88%"]:after { right: -36.32px } .pace .pace-progress[data-progress-text="89%"]:after { right: -34.46px } .pace .pace-progress[data-progress-text="90%"]:after { right: -32.6px } .pace .pace-progress[data-progress-text="91%"]:after { right: -30.740000000000002px } .pace .pace-progress[data-progress-text="92%"]:after { right: -28.880000000000003px } .pace .pace-progress[data-progress-text="93%"]:after { right: -27.02px } .pace .pace-progress[data-progress-text="94%"]:after { right: -25.16px } .pace .pace-progress[data-progress-text="95%"]:after { right: -23.3px } .pace .pace-progress[data-progress-text="96%"]:after { right: -21.439999999999998px } .pace .pace-progress[data-progress-text="97%"]:after { right: -19.58px } .pace .pace-progress[data-progress-text="98%"]:after { right: -17.72px } .pace .pace-progress[data-progress-text="99%"]:after { right: -15.86px } .pace .pace-progress[data-progress-text="100%"]:after { right: -14px } .pace .pace-activity { position: absolute; width: 100%; height: 28px; z-index: 2001; box-shadow: inset 0 0 0 2px #ffffff, inset 0 0 0 7px #FFF; border-radius: 10px; } .pace.pace-inactive { display: none; }
N00bface/Real-Dolmen-Stage-Opdrachten
stageopdracht/src/main/resources/static/vendors/gentelella/vendors/PACE/themes/white/pace-theme-loading-bar.css
CSS
mit
9,724
import createReducer from './createReducer' import * as R from 'ramda' export const SET_IS_OPEN_FILE_MENU_OPEN = 'SET_IS_OPEN_FILE_MENU_OPEN' export let setIsOpenFileMenuOpen = (value) => ({ type: SET_IS_OPEN_FILE_MENU_OPEN, value }) export const SET_IS_OPEN_OF_ADD_DIALOG = 'SET_IS_OPEN_OF_ADD_DIALOG' export let setIsOpenOfAddDialog = (value) => ({ type: SET_IS_OPEN_OF_ADD_DIALOG, value }) export const SET_CONTENT_OF_ADD_DIALOG = 'SET_CONTENT_OF_ADD_DIALOG' export let setContentOfAddDialog = (content) => ({ type: SET_CONTENT_OF_ADD_DIALOG, content }) export const SET_FILE_NAME_OF_ADD_DIALOG = 'SET_FILE_NAME_OF_ADD_DIALOG' export let setFileNameOfAddDialog = (fileName) => ({ type: SET_FILE_NAME_OF_ADD_DIALOG, fileName }) export const RESET_ADD_DIALOG = 'RESET_ADD_DIALOG' export let resetAddDialog = () => ({ type: RESET_ADD_DIALOG }) export let selectIsOpenFileMenuOpen = R.path(['fileManagement', 'isOpenFileMenuOpen']) export let selectIsOpenAddFileDialog = R.path(['fileManagement', 'addFile', 'isOpen']) export let selectFileNameOfAddDialog = R.path(['fileManagement', 'addFile', 'fileName']) export let selectContentOfAddDialog = R.path(['fileManagement', 'addFile', 'content']) let initialState = { isOpenFileMenuOpen: false, addFile: { isOpen: false, fileName: '', content: '' } } let reducerFunctions = { [SET_IS_OPEN_FILE_MENU_OPEN]: (state, action) => ({ ...state, isOpenFileMenuOpen: action.value }), [SET_IS_OPEN_OF_ADD_DIALOG]: (state, action) => R.assocPath(['addFile', 'isOpen'], action.value, state), [SET_CONTENT_OF_ADD_DIALOG]: (state, {content}) => R.assocPath(['addFile', 'content'], content, state), [SET_FILE_NAME_OF_ADD_DIALOG]: (state, {fileName}) => R.assocPath(['addFile', 'fileName'], fileName, state), [RESET_ADD_DIALOG]: (state) => ({ ...state, addFile: { ...state.addFile, fileName: '', content: '' } }) } let fileManagement = createReducer(initialState, reducerFunctions) export default fileManagement
hoschi/yode
packages/demo/src/store/fileManagement.js
JavaScript
mit
2,128
package skidbladnir trait Handle{ val interfaces:List[String] = null override def toString():String = { val sh = this.asInstanceOf[Shadow] if(sh.isInstanceOf[BaseShadow]){ "base '" + sh.name + "'"} else{ if(sh.name != null){ "static '" + sh.name + "'"} else{ "dynamic " + sh.proto.getClass().getName() + "@" +System.identityHashCode(sh)}} } }
AlexCAB/CompoDev
skidbladnir/Handle.scala
Scala
mit
397
<?php namespace Geazi\Interbits\App\Models; use Illuminate\Database\Eloquent\Model; class Functions extends Model { protected $fillable = [ 'name' ]; }
geazioliveira/interbits
src/app/Models/Functions.php
PHP
mit
171
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.digitaltwins.models; import com.azure.resourcemanager.digitaltwins.fluent.models.GroupIdInformationInner; /** An immutable client-side representation of GroupIdInformation. */ public interface GroupIdInformation { /** * Gets the properties property: The group information properties. * * @return the properties value. */ GroupIdInformationProperties properties(); /** * Gets the id property: The resource identifier. * * @return the id value. */ String id(); /** * Gets the name property: The resource name. * * @return the name value. */ String name(); /** * Gets the type property: The resource type. * * @return the type value. */ String type(); /** * Gets the inner com.azure.resourcemanager.digitaltwins.fluent.models.GroupIdInformationInner object. * * @return the inner object. */ GroupIdInformationInner innerModel(); }
Azure/azure-sdk-for-java
sdk/digitaltwins/azure-resourcemanager-digitaltwins/src/main/java/com/azure/resourcemanager/digitaltwins/models/GroupIdInformation.java
Java
mit
1,165
<?php require_once PUMPCMS_APP_PATH . '/module/user/plugin/google/oauth_google_model.php'; class OAuth_google { private function get_callback_url() { return PC_Config::url() . '/user/oauth/callback?type=google'; } public function get_tag() { $querys = array( 'client_id' => PC_Config::get('google_client_id'), 'redirect_uri' => $this->get_callback_url(), 'scope' => 'https://www.googleapis.com/auth/userinfo.email', 'response_type' => 'code', ); $url = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($querys); $code = sprintf("location.href = '%s';", $url); $tag = sprintf('<button class="btn btn-default" onclick="%s">google認証</button>', $code); return $tag; } public function callback() { $code = $_GET['code']; if (empty($code)) { throw new Exception('Code not found.'); } $baseURL = 'https://accounts.google.com/o/oauth2/token'; $params = array( 'code' => $code, 'client_id' => PC_Config::get('google_client_id'), 'client_secret' => PC_Config::get('google_client_secret'), 'redirect_uri' => $this->get_callback_url(), 'grant_type' => 'authorization_code' ); $headers = array( 'Content-Type: application/x-www-form-urlencoded', ); $options = array('http' => array( 'method' => 'POST', 'content' => http_build_query($params), 'header' => implode("\r\n", $headers), )); $response = json_decode(file_get_contents($baseURL, false, stream_context_create($options))); $response = (array)$response; $user_info = $this->get_google_user_info($response['access_token']); $user_info = (array)$user_info; $user_info['google_id'] = $user_info['id']; $param = array_merge($response, $user_info); $_SESSION['google_param'] = http_build_query($param); parse_str($_SESSION['google_param'], $param); if(empty($response) || isset($response->error)){ throw new Exception('Invalid response'); } } private function get_google_user_info($asscess_token) { if (empty($asscess_token)) { throw new Exception('Invalid access token'); } $user_info = json_decode(file_get_contents('https://www.googleapis.com/oauth2/v1/userinfo?'. 'access_token=' . $asscess_token) ); if (empty($user_info)) { throw new Exception('Invalid response oauth2/v1/userinfo'); } return $user_info; } public function register($user_id) { if (empty($_SESSION['google_param'])) { throw new Exception('Invalid access: oauth twitter token'); } parse_str($_SESSION['google_param'], $param); $oauth_google_model = new OAuth_google_Model(); $oauth_google_model->register($user_id, $param['google_id'], $param['access_token'], $param['name'], $param['given_name'], $param['family_name'], $param['link'], $param['picture'], $param['gender'] ); } public function get_user() { parse_str($_SESSION['google_param'], $param); $google_id = @$param['id']; if (empty($google_id) || !is_numeric($google_id)) { throw new Exception('google_id is invalid'); } $oauth_google_model = new OAuth_google_Model(); return $oauth_google_model->get_user($google_id); } public function get_name() { parse_str($_SESSION['google_param'], $param); return $param['name']; } public function get_email() { parse_str($_SESSION['google_param'], $param); return $param['email']; } public function get_icon_url($sns_user) { parse_str($_SESSION['google_param'], $param); return $param['picture']; } public function login($google_user) { $oauth_google_model = new OAuth_google_Model(); $oauth_google_model->login($google_user['user_id']); } public function finish() { unset($_SESSION['google_param']); } }
tokitam/pumpkincms
app/module/user/plugin/google/oauth_google.php
PHP
mit
4,901
class FollowersForUsers attr_accessor :screen_names, :oauth_token, :oauth_token_secret, :consumer_key, :consumer_secret, :client def initialize(opts={}) opts = Hashie::Mash[opts] @screen_names = opts[:screen_names] || [] @oauth_token = opts[:oauth_token] @oauth_token_secret = opts[:oauth_token_secret] @consumer_key = opts[:consumer_key] @consumer_secret = opts[:consumer_secret] @screen_names = [@screen_names].flatten Twitter.configure do |config| config.consumer_key = @consumer_key config.consumer_secret = @consumer_secret config.oauth_token = @oauth_token config.oauth_token_secret = @oauth_token_secret end @client = Twitter::Client.new end def grab_followers results = {} @screen_names.each do |screen_name| puts "Current progress: #{@screen_names.index(screen_name)}/#{@screen_names.length} started" user = user_data_for(screen_name) follower_ids = follower_ids_for(screen_name) user_data = user_data_for(follower_ids) results[user.first.attrs] = user_data puts "Current progress: ##{@screen_names.index(screen_name)}/#{@screen_names.length} complete" end puts "Done!" return results end def follower_ids_for(screen_name) return direction_ids_for screen_name, "follower" end def friend_ids_for(screen_name) return direction_ids_for screen_name, "friend" end def direction_ids_for(screen_name, direction) cursor = -1 ids = [] while cursor != 0 puts cursor begin data = Hashie::Mash[@client.send(direction+"_ids", screen_name, :cursor => cursor).attrs] rescue Twitter::Error::BadGateway puts "Got Twitter::Error::BadGateway error - usually this is just a missed connect from Twitter." sleep(10) retry rescue Twitter::Error::TooManyRequests puts "Got Twitter::Error::TooManyRequests error - we are rate limited and will sleep for 15 minutes. See you in a bit." sleep(15*60) retry end ids = ids|data.ids cursor = data["next_cursor"] end return ids end def user_data_for(screen_names) screen_names = [screen_names].flatten user_data = [] screen_names.each_slice(100) do |screen_name_set| begin user_data = [user_data|@client.users(screen_name_set)].flatten rescue Twitter::Error::BadGateway puts "Got Twitter::Error::BadGateway error - usually this is just a missed connect from Twitter." sleep(10) retry rescue Twitter::Error::TooManyRequests puts "Got Twitter::Error::TooManyRequests error - we are rate limited and will sleep for 15 minutes. See you in a bit." sleep(15*60) retry end end user_data end end
DGaffney/oii_twitter_goodies
lib/oii_twitter_goodies/lib/followers_for_users.rb
Ruby
mit
2,806
package rabbitmq.test; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; public class EmitLogDirect { private static final String EXCHANGE_NAME = "direct_logs"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct"); String severity = getSeverity(argv); String message = getMessage(argv); channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes()); System.out.println(" [x] Sent '" + severity + "':'" + message + "'"); channel.close(); connection.close(); } private static String getSeverity(String[] strings){ if (strings.length < 1) return "info"; return strings[0]; } private static String getMessage(String[] strings){ if (strings.length < 2) return "Hello World!"; return joinStrings(strings, " ", 1); } private static String joinStrings(String[] strings, String delimiter, int startIndex) { int length = strings.length; if (length == 0 ) return ""; if (length < startIndex ) return ""; StringBuilder words = new StringBuilder(strings[startIndex]); for (int i = startIndex + 1; i < length; i++) { words.append(delimiter).append(strings[i]); } return words.toString(); } }
qifanyang/tool
tool/src/test/java/rabbitmq/test/EmitLogDirect.java
Java
mit
1,540
class UserMailer < ActionMailer::Base def self.set_home_from_request(request) default_url_options[:host] = "#{request.host_with_port}" end def welcome_email(new_user) setup_email(new_user) @subject << "Welcome to RecipeTrees.com" @body[:user] = new_user end def notify_admins_signup(admins, new_user) set_email_header @subject << 'New User Registration' @recipients = admins.inject([]){|result, admin| result << admin.email} @body[:user] = new_user end def contact_us(contact, admins, ip) set_email_header #override @from = contact[:email] unless contact[:email].blank? @recipients = admins.inject([]){|result, admin| result << admin.email} @subject << 'Contact Us' @contact = contact @ip = ip end def tried_your_recipe(current_user, recipe, other) setup_email(recipe.user) @subject << "#{current_user.name} has tried your #{recipe.name} recipe" @body[:recipe] = recipe @body[:other] = other @body[:current_user] = current_user @body[:recipe_owner] = recipe.user end protected def setup_email(user) set_email_header @recipients = "#{user.email}" @body[:user] = user end def set_email_header @from = "[email protected]" @subject = "[RecipeTrees.com] - " @sent_on = Time.now @content_type = "text/html" end end
nazar/recipetrees
app/models/user_mailer.rb
Ruby
mit
1,399
#motion detection import numpy as np import cv2 #import matplotlib.pyplot as plt from collections import deque import imutils import argparse import sys cap = cv2.VideoCapture(0) fgbg = cv2.createBackgroundSubtractorMOG2 () while True: ret, frame = cap.read() fgmask = fgbg.apply(frame) kar = cv2.bitwise_and(frame,frame,mask = fgmask) cv2.imshow('original', frame) cv2.imshow('fg', kar) k = cv2.waitKey(30) & 0xff if k == 27: break cap.release() cv2.destroyAllWindows()
yahyanik/phd_research
motion.py
Python
mit
511
--- layout: post title: "JAVA中的锁(三)-读写锁" desc: "JAVA中的锁(三)-读写锁" keywords: "JAVA中的锁(三)-读写锁,java,kinglyjn,张庆力" date: 2017-07-28 categories: [Java] tags: [Java] icon: fa-coffee --- ### 读写锁 读写锁在同一时刻可以允许多个读线程访问,但是在写线程访问时,所有的度线程和写线程均被阻塞。读写锁维护了一对锁,一个读锁和一个写锁,通过分离读锁和写锁,使得并发性相比其他锁有了很大提升。 除了保证写操作对读操作的可见性以及并发性的提升以外,读写锁能够简化读写交互场景的编程方式。在没有写锁支持的时候,如果需要完成预想的读写工作,就要使用到java的等待通知机制,就是当写操作开始时,所有晚于写操作的读操作均会进入等待线程,只有写操作完成并进行通知以后,所有等待的读操作才能继续执行(写操作之间依靠synchronized关键字进行同步),这样做的目的是使读操作能读取到正确的数据,不会出现脏读。改用读写锁实现上述功能,只需要在读操作时获取读锁,在写操作时获取写锁即可。当写锁被获取到时,后续的(非当前写线程的)读写操作都会被阻塞,写锁释放之后,所有操作继续执行,编程方式相对于使用等待通知的实现机制而言变得更加简单明了。 一般情况下,读写锁的性能会比排它锁好,因为大多数场景下读是多于写的,在读多于写的情况下,读写锁能够提供必排它所更好的并发性和吞吐量。java并发包提供的排它锁的实现是ReentrantReadWriteLock,它提供的特性如下: * 公平性选择:支持非公平(默认)和公平的锁获取方式,吞吐量还是非公平由于公平; * 重进入:该锁支持重进入,以读写线程为例,度线程在获取了读锁之后,能够再次获取读锁;而写线程在获取了写锁之后能够再次获取写锁,同时也可以获取读锁; * 锁降级:遵循获取写锁、获取读锁再释放写锁的次序,写锁能够降级称为读锁; <br> ReadWriteLock仅定义了 readLock() 和 writeLock()方法,而其实现 ReentrantReadWriteLock,除了接口方法外,还提供了一些便于外界监控其内部工作状态的方法: ```java //返回当前读锁被获取的次数。该次数不等于获取读锁的线程数。 //例如仅一个线程,它连续获取(重进入)了n次读锁,那么占据读锁的线程数是1,但该方法返回n int getReadLockCount() //返回当前线程获取读锁的次数。该方法在java6中加入到ReentrantReadWriteLock中, //使用ThreadLocal保存当前线程获取的次数,这也使得java6变得更加复杂 int getReadHoldCount() //返回当前写锁被获取的次数 int getWriteHoldCount() //判断写锁是否被获取 int isWriteLocked() ``` 接下来通过一个缓存示例来说明读写锁的使用方式: ```java import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Cache { static Map<String, Object> map = new HashMap<>(); static ReentrantReadWriteLock rw1 = new ReentrantReadWriteLock(); static Lock r = rw1.readLock(); static Lock w = rw1.writeLock(); //获取一个key对应的value public static final Object get(String key) { r.lock(); try { return map.get(key); } finally { r.unlock(); } } //设置key对应的value,并返回就的value public static final Object put(String key, Object value) { w.lock(); try { return map.put(key, value); } finally { w.unlock(); } } //清空所有的内容 public static final void clear() { w.lock(); try { map.clear(); } finally { w.unlock(); } } } ``` 在上述示例中,Cache组合一个非线程安全的HashMap作为缓存的实现,同时使用读写锁的读锁和写锁来保证Cache是线程安全的。在读操作get(key)方法中,需要获取读锁,这使得并发访问该方法时不会被阻塞,写操作put(key, value)方法和clear()方法,在更新map时必须提前获取写锁,当获取写锁后,其他线程对于读锁和写锁的获取均被阻塞,而只有写锁释放以后,其他的读写操作才能继续。Cache使用读写锁来提升读操作的并发性,也保证每次写操作对所有读操作的可见性,同时简化了编程方式。 <br> ### 读写锁的实现分析 主要内容包括:读写状态的设计、写锁的获取与释放、读锁的获取与释放、锁降级。 读写锁同样依赖自定义的同步器来实现同步功能,而读写状态就是其同步状态。回想ReentrantLock中自定义同步器的实现,同步状态就表示锁被一个线程重复获取的次数,而读写锁的自定义同步器需要在同步状态(一个整型变量)上维护多个读线程和一个写线程的状态,使得该状态的设计成为读写所实现的关键。 如果在一个整型变量上维护多种状态,就一定要“按位切割使用”这个变量,读写锁,将变量切分成了两部分:高16位表示读,低16位表示写,划分方式如下所示: ```shell 0000000000000010 0000000000000011 ---------------- ---------------- 高16位 读状态=2 低16位 写状态=3 ``` 当前同步状态表示一个线程已经获取了写锁,且重进入了两次同时也连续获取了2次读锁。读写锁通过位运算迅速确定其读状态和写状态。假设当前的同步状态值为S,那么写状态就等于 S&0x0000ffff(高16位全部抹去),读状态就等于 S>>>16(无符号补0右移16位)。当写状态增加1时,读写状态等于 S+1,当读状态增加1时,读写状态等于 S+(1<<16),也就是 S+0x00010000。 根据读写状态的划分得出一个推论: ```default 当S不等于0时而写状态(S&0x0000ffff)等于0时,则读状态(S>>>16)大于0,即读锁已被获取。 ``` <br> **写锁的获取与释放** 写锁是一个支持可重入的排他锁,如果当前线程获取了写锁,则增加写状态。如果当前线程在获取写锁时,读锁已经被获取(读状态不为0)或者该线程不是已经获取写锁的线程,则当前线程进入等待状态,获取写锁的代码如下: ```java protected final boolean tryAcquire(int acquires) { /* * Walkthrough: * 1. If read count nonzero or write count nonzero * and owner is a different thread, fail. * 2. If count would saturate, fail. (This can only * happen if count is already nonzero.) * 3. Otherwise, this thread is eligible for lock if * it is either a reentrant acquire or * queue policy allows it. If so, update state * and set owner. */ Thread current = Thread.currentThread(); int c = getState(); int w = exclusiveCount(c); if (c != 0) { // (Note: if c != 0 and w == 0 then shared count != 0) if (w == 0 || current != getExclusiveOwnerThread()) return false; if (w + exclusiveCount(acquires) > MAX_COUNT) throw new Error("Maximum lock count exceeded"); // Reentrant acquire setState(c + acquires); return true; } if (writerShouldBlock() || !compareAndSetState(c, c + acquires)) return false; setExclusiveOwnerThread(current); return true; } ``` 该方法除了重入条件(当前线程未获取了写锁的线程),增加了一个读锁是否存在的判断。如果存在读锁,则写锁不能被获取,原因在于读写所要确保写锁的操作对读锁可见,如果允许读锁在已经被获取的情况下对写锁的获取,那么正在运行的其他线程就无法感知到当前写线程的操作,因此只有等待其他读线程都释放了读锁,写锁才能被当前线程获取,而写锁一旦被获取,则其他读写线程的后续访问均被阻塞。 写锁的释放与ReentrantLock的释放过程基本类似,每次释放均减少写状态,当写状态为0的时候表示写锁已经被释放,从而等待的读写线程能够继续访问读写锁,同时前一次写线程的修改对后续的读写线程可见。 <br> **读锁的获取与释放** 读锁是一个支持可重入的共享锁,它能够被多个线同时获取,在没有其他线程访问(或者写状态为0)时,读锁总会被成功的获取,而所做的只是(线程安全地)增加读状态。如果当前线程已经获取了读锁,则增加读状态。如果当前线程在获取读锁时,写锁已经被其他线程获取,则进入等待状态。读状态时所有线程获取读锁次数的总和,而每个线程各自获取读状态的次数只能选择保存在ThreadLocal中,由线程自身来维护,这使得获取读锁的实现变得更加复杂。因此这里讲获取读锁的代码做了删减,仅保留必要部分: ```java protected final int tryAcquireShared(int unused) { for(;;) { int c = getState(); int nextc = c + (1<<16); if (nextc < c) { throw new Error("Maximum lock count exceeded"); } if (exclusiveCount(c)!=0 && owner!=Thread.currentThread()) { return -1; } if (compareAndSetState(c, nextc)) { return 1; } } } ``` 读锁的每次释放(线程安全的,可能有多个读线程同时释放锁)均减少读状态,减少的值是(1<<16)。 <br> ### 锁降级 锁降级就是写锁降级称为读锁,如果当前线程拥有写锁,然后将其释放,最后再获取读锁,这种分段完成的过程不能称之为锁降级。锁降级是指 把持住(当前拥有的)写锁,在获取到读锁,随后释放(先前拥有的)写锁的过程。 接下来看一个锁降级的示例。因为数据不常变化,所以多个线程可以并发地进行数据的处理,当数据变更后,如果当前线程感知到数据的变化,则进行数据的准备工作,同时其他处理线程被阻塞,直到当前线程完成数据的准备工作。 ```java public void processData() { readLock.lock(); if (!update) { //必须先释放读锁 readLock.unlock(); //锁降级从写锁获取到开始 writeLock.lock(); try { if (!update) { //准备数据的流程(略) // TODO update = true; } readLock.lock(); } finally { writeLock.unlock(); } } try { //使用数据的流程(略) // TODO } finally { readLock.unlock(); } } ``` 上述示例中,数据发生变更后,update变量(volatile boolean类型)被设置为false,此时所有访问processData方法的线程都能够感知到变化,但是只有一个线程能获取到写锁,,其他线程会被阻塞在读锁和写锁的lock方法上。当前线程获取写锁完成数据准备工作后,再获取读锁,随后释放写锁,完成锁降级。 锁降级中读锁的获取是否是必要的呢?答案是必要的,主要是为了保证数据的可见性,如果当前线程不获取读锁而是直接释放写锁,假设此刻另一个线程(记为T)获取了写锁并修改了数据,那么当前线程是无法根治线程T的数据更新的。如果当前线程获取读锁,即遵循锁降级的步骤,那么线程T将会被阻塞,直到当前线程使用数据并释放读锁之后,线程T才能获取写锁,进行数据的更新操作。 ReentrantReadWriteLock不支持锁升级(把持读锁,获取写锁,最后释放读锁的过程)。目的也是为了保证数据的可见性,如果读锁已被多个线程获取,其中任意一个线程成功获取了写锁并更新了数据,则其更新对其他获取到读锁的线程是不可见的。
kinglyjn/kinglyjn.github.io
_posts/2017-07-28-java-concurrent-08.md
Markdown
mit
11,963
const component = { template: ` <implicit style="width: 50%; float: left;"></implicit> <inject style="width: 50%; float: left;"></inject> ` }; export default component; export const name = 'myApp';
jsperts/workshop_unterlagen
angularjs/examples/05-DI/app/main.component.js
JavaScript
mit
211
#pragma once #include "Enums.h" namespace VEngine { namespace Renderer { class DescriptorSetInterface; class DescriptorSetLayoutInterface { public: virtual void addField(VEngineDescriptorSetFieldType fieldType, VEngineDescriptorSetFieldStage fieldAccesibility) = 0; virtual DescriptorSetInterface* generateDescriptorSet() = 0; }; } }
achlubek/venginenative
VEngine/Interface/Renderer/DescriptorSetLayoutInterface.h
C
mit
413
lan-friends-day ===============
songecko/lan-friends-day
README.md
Markdown
mit
32
Ext.define('KitchenSink.view.Viewport', { extend: 'Ext.container.Viewport', requires:[ 'Ext.tab.Panel', 'Ext.layout.container.Border' ], layout: 'border', items: [{ region: 'north', xtype: 'appHeader' }, { region: 'west', xtype: 'navigation', width: 250, minWidth: 100, height: 200, split: true, stateful: true, stateId: 'mainnav.west', collapsible: true }, { region: 'center', xtype: 'contentPanel' }, { xtype: 'codePreview', region: 'east', id: 'east-region', itemId: 'codePreview', stateful: true, stateId: 'mainnav.east', split: true, collapsible: true, width: 350, minWidth: 100 }] });
lucas-solutions/work-server
ext/examples/kitchensink/app/view/Viewport.js
JavaScript
mit
828
export function routerConfig ($stateProvider, $urlRouterProvider) { 'ngInject'; $stateProvider .state('dashboard', { url: '/', templateUrl: 'app/dashboard/dashboard.html', controller: 'DashboardController', //controllerAs: 'dashboard' }) .state('hud', { url: '/hud', templateUrl: 'app/hud/hud.html', controller: 'HudController', //controllerAs: 'hud' }) .state('hud.crosshairs', { url: '/crosshairs', templateUrl: 'app/hud/crosshairs/crosshairs.html', controller: 'HudCrosshairsController', //controllerAs: 'crosshairs' }) .state('hud.colors', { url: '/colors', templateUrl: 'app/hud/colors/colors.html', controller: 'HudColorsController', }) .state('hud.styles', { url: '/styles', templateUrl: 'app/hud/styles/styles.html', controller: 'HudStylesController', }) .state('hud.background', { url: '/background', templateUrl: 'app/hud/background/background.html', controller: 'HudBackgroundController', onEnter: function($rootScope) { $rootScope.customBackground = true; }, onExit: function($rootScope) { $rootScope.customBackground = false; }, }) .state('news', { url: '/news', templateUrl: 'app/news/news.html', controller: 'HudNewsController', onEnter: function($rootScope) { $rootScope.hideHud = true; }, onExit: function($rootScope) { $rootScope.hideHud = false; }, }) .state('settings', { url: '/settings', templateUrl: 'app/settings/settings.html', controller: 'SettingsController', //controllerAs: 'settings' }); $urlRouterProvider.otherwise('/'); }
ainstaller/aInstaller
app/app/index.route.js
JavaScript
mit
1,774
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=11"/> <meta name="generator" content="Doxygen 1.9.2"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>O2: o2l_msg Struct Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="o2.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">O2<span id="projectnumber">&#160;2.0</span> </div> <div id="projectbrief">A communication protocol for interactive music and media applications.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.9.2 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */ var searchBox = new SearchBox("searchBox", "search",'Search','.html'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */ </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-attribs">Public Attributes</a> &#124; <a href="structo2l__msg-members.html">List of all members</a> </div> <div class="headertitle"><div class="title">o2l_msg Struct Reference</div></div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a id="pub-attribs" name="pub-attribs"></a> Public Attributes</h2></td></tr> <tr class="memitem:a42f59e8b4fd76f22560735ed49f2ebf6"><td class="memItemLeft" align="right" valign="top"><a id="a42f59e8b4fd76f22560735ed49f2ebf6" name="a42f59e8b4fd76f22560735ed49f2ebf6"></a> int32_t&#160;</td><td class="memItemRight" valign="bottom"><b>length</b></td></tr> <tr class="separator:a42f59e8b4fd76f22560735ed49f2ebf6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a6199a1516629d3a1b605ac9dedd7de1c"><td class="memItemLeft" align="right" valign="top"><a id="a6199a1516629d3a1b605ac9dedd7de1c" name="a6199a1516629d3a1b605ac9dedd7de1c"></a> int32_t&#160;</td><td class="memItemRight" valign="bottom"><b>misc</b></td></tr> <tr class="separator:a6199a1516629d3a1b605ac9dedd7de1c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac42a0dbfb2b778e88dcc2b43dc52da9f"><td class="memItemLeft" align="right" valign="top"><a id="ac42a0dbfb2b778e88dcc2b43dc52da9f" name="ac42a0dbfb2b778e88dcc2b43dc52da9f"></a> double&#160;</td><td class="memItemRight" valign="bottom"><b>timestamp</b></td></tr> <tr class="separator:ac42a0dbfb2b778e88dcc2b43dc52da9f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a190393dc4b1cd22719151a1ae14851f1"><td class="memItemLeft" align="right" valign="top"><a id="a190393dc4b1cd22719151a1ae14851f1" name="a190393dc4b1cd22719151a1ae14851f1"></a> char&#160;</td><td class="memItemRight" valign="bottom"><b>address</b> [4]</td></tr> <tr class="separator:a190393dc4b1cd22719151a1ae14851f1"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this struct was generated from the following file:<ul> <li>/Users/rbd/o2/src/<a class="el" href="o2lite_8h_source.html">o2lite.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by&#160;<a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.2 </small></address> </body> </html>
rbdannenberg/o2
docs/html/structo2l__msg.html
HTML
mit
5,083
using Client.Core.Contracts; using System; namespace Client.Decorators { public class EngineDecorator : IEngine { private readonly IEngine engine; private readonly IWriter writer; public EngineDecorator(IEngine engine, IWriter writer) { this.engine = engine ?? throw new ArgumentNullException("Engine can't be null!"); this.writer = writer ?? throw new ArgumentNullException("Writer can't be null!"); } public void Start() { string entryMenu = $@" █████╗ ██╗ ██╗████████╗ ██████╗ ██████╗ ███████╗███╗ ██╗████████╗ ██╔══██╗██║ ██║╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║╚══██╔══╝ ███████║██║ ██║ ██║ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║ ██║ ██╔══██║██║ ██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║╚██╗██║ ██║ ██║ ██║╚██████╔╝ ██║ ╚██████╔╝██║ ██║███████╗██║ ╚████║ ██║ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ Rent-a-Car management service Commands Menu: CREATING createcar [make] [model] [type] [price] [available] [officeId] - creates new car createoffice [city] [address] - creates new office createuser [firstName] [familyName] [pin] [drivingLicenseNumber] [phoneNumber] [status] - creates new user LISTING listcars [city] [car type] - returns available cars of selected type listcities - returns cities where offices are located listoffices [city] - returns offices in a sellected city listusers - returns all users ORDERING choosecar [carId] - adds the selected car to the order chooseuser [pin] - adds the selected user to the order setdetails [destinationOffice] [departureDate (dd/mm/yyyy)] [duration] - sets order details checkorder - views order's details createorder - finalizes the order DELETE deletecar [carId] - deletes car by Id OTHER loadcars - loads cars from XML file loadoffices - loads offices from JSON file movecartooffice [carId] [officeId] - moves car from one office to other exit - terminates the system Enter command: "; this.writer.Write(entryMenu); this.engine.Start(); this.writer.Write($"Exiting service" + Environment.NewLine); } } }
JSTeam6/AutoRent
Client/Decorators/EngineDecorator.cs
C#
mit
2,903
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment, WITNESS_COMMITMENT_HEADER from test_framework.key import CECKey, CPubKey import time import random from binascii import hexlify # The versionbit bit used to signal activation of SegWit VB_WITNESS_BIT = 1 VB_PERIOD = 144 VB_ACTIVATION_THRESHOLD = 108 VB_TOP_BITS = 0x20000000 MAX_SIGOP_COST = 80000 ''' SegWit p2p test. ''' # Calculate the virtual size of a witness block: # (base + witness/4) def get_virtual_size(witness_block): base_size = len(witness_block.serialize()) total_size = len(witness_block.serialize(with_witness=True)) # the "+3" is so we round up vsize = int((3*base_size + total_size + 3)/4) return vsize # Note: we can reduce code by using SingleNodeConnCB (in master, not 0.12) class TestNode(NodeConnCB): def __init__(self): NodeConnCB.__init__(self) self.connection = None self.ping_counter = 1 self.last_pong = msg_pong(0) self.sleep_time = 0.05 self.getdataset = set() self.last_reject = None def add_connection(self, conn): self.connection = conn # Wrapper for the NodeConn's send_message function def send_message(self, message): self.connection.send_message(message) def on_inv(self, conn, message): self.last_inv = message def on_block(self, conn, message): self.last_block = message.block self.last_block.calc_sha256() def on_getdata(self, conn, message): for inv in message.inv: self.getdataset.add(inv.hash) self.last_getdata = message def on_getheaders(self, conn, message): self.last_getheaders = message def on_pong(self, conn, message): self.last_pong = message def on_reject(self, conn, message): self.last_reject = message #print (message) # Syncing helpers def sync(self, test_function, timeout=60): while timeout > 0: with mininode_lock: if test_function(): return time.sleep(self.sleep_time) timeout -= self.sleep_time raise AssertionError("Sync failed to complete") def sync_with_ping(self, timeout=60): self.send_message(msg_ping(nonce=self.ping_counter)) test_function = lambda: self.last_pong.nonce == self.ping_counter self.sync(test_function, timeout) self.ping_counter += 1 return def wait_for_block(self, blockhash, timeout=60): test_function = lambda: self.last_block != None and self.last_block.sha256 == blockhash self.sync(test_function, timeout) return def wait_for_getdata(self, timeout=60): test_function = lambda: self.last_getdata != None self.sync(test_function, timeout) def wait_for_getheaders(self, timeout=60): test_function = lambda: self.last_getheaders != None self.sync(test_function, timeout) def wait_for_inv(self, expected_inv, timeout=60): test_function = lambda: self.last_inv != expected_inv self.sync(test_function, timeout) def announce_tx_and_wait_for_getdata(self, tx, timeout=60): with mininode_lock: self.last_getdata = None self.send_message(msg_inv(inv=[CInv(1, tx.sha256)])) self.wait_for_getdata(timeout) return def announce_block_and_wait_for_getdata(self, block, use_header, timeout=60): with mininode_lock: self.last_getdata = None self.last_getheaders = None msg = msg_headers() msg.headers = [ CBlockHeader(block) ] if use_header: self.send_message(msg) else: self.send_message(msg_inv(inv=[CInv(2, block.sha256)])) self.wait_for_getheaders() self.send_message(msg) self.wait_for_getdata() return def announce_block(self, block, use_header): with mininode_lock: self.last_getdata = None if use_header: msg = msg_headers() msg.headers = [ CBlockHeader(block) ] self.send_message(msg) else: self.send_message(msg_inv(inv=[CInv(2, block.sha256)])) def request_block(self, blockhash, inv_type, timeout=60): with mininode_lock: self.last_block = None self.send_message(msg_getdata(inv=[CInv(inv_type, blockhash)])) self.wait_for_block(blockhash, timeout) return self.last_block def test_transaction_acceptance(self, tx, with_witness, accepted, reason=None): tx_message = msg_tx(tx) if with_witness: tx_message = msg_witness_tx(tx) self.send_message(tx_message) self.sync_with_ping() assert_equal(tx.hash in self.connection.rpc.getrawmempool(), accepted) if (reason != None and not accepted): # Check the rejection reason as well. with mininode_lock: assert_equal(self.last_reject.reason, reason) # Test whether a witness block had the correct effect on the tip def test_witness_block(self, block, accepted, with_witness=True): if with_witness: self.send_message(msg_witness_block(block)) else: self.send_message(msg_block(block)) self.sync_with_ping() assert_equal(self.connection.rpc.getbestblockhash() == block.hash, accepted) # Used to keep track of anyone-can-spend outputs that we can use in the tests class UTXO(object): def __init__(self, sha256, n, nValue): self.sha256 = sha256 self.n = n self.nValue = nValue # Helper for getting the script associated with a P2PKH def GetP2PKHScript(pubkeyhash): return CScript([CScriptOp(OP_DUP), CScriptOp(OP_HASH160), pubkeyhash, CScriptOp(OP_EQUALVERIFY), CScriptOp(OP_CHECKSIG)]) # Add signature for a P2PK witness program. def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key): tx_hash = SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, value) signature = key.sign(tx_hash) + chr(hashtype).encode('latin-1') txTo.wit.vtxinwit[inIdx].scriptWitness.stack = [signature, script] txTo.rehash() class SegWitTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 3 def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros=1", "-whitelist=127.0.0.1"])) # Start a node for testing IsStandard rules. self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros=1", "-whitelist=127.0.0.1", "-acceptnonstdtxn=0"])) connect_nodes(self.nodes[0], 1) # Disable segwit's bip9 parameter to simulate upgrading after activation. self.nodes.append(start_node(2, self.options.tmpdir, ["-debug", "-whitelist=127.0.0.1", "-bip9params=segwit:0:0"])) connect_nodes(self.nodes[0], 2) ''' Helpers ''' # Build a block on top of node0's tip. def build_next_block(self, nVersion=VB_TOP_BITS): tip = self.nodes[0].getbestblockhash() height = self.nodes[0].getblockcount() + 1 block_time = self.nodes[0].getblockheader(tip)["mediantime"] + 1 block = create_block(int(tip, 16), create_coinbase(height), block_time) block.nVersion = nVersion block.rehash() return block # Adds list of transactions to block, adds witness commitment, then solves. def update_witness_block_with_transactions(self, block, tx_list, nonce=0): block.vtx.extend(tx_list) add_witness_commitment(block, nonce) block.solve() return ''' Individual tests ''' def test_witness_services(self): print("\tVerifying NODE_WITNESS service bit") assert((self.test_node.connection.nServices & NODE_WITNESS) != 0) # See if sending a regular transaction works, and create a utxo # to use in later tests. def test_non_witness_transaction(self): # Mine a block with an anyone-can-spend coinbase, # let it mature, then try to spend it. print("\tTesting non-witness transaction") block = self.build_next_block(nVersion=1) block.solve() self.test_node.send_message(msg_block(block)) self.test_node.sync_with_ping() # make sure the block was processed txid = block.vtx[0].sha256 self.nodes[0].generate(99) # let the block mature # Create a transaction that spends the coinbase tx = CTransaction() tx.vin.append(CTxIn(COutPoint(txid, 0), b"")) tx.vout.append(CTxOut(49*100000000, CScript([OP_TRUE]))) tx.calc_sha256() # Check that serializing it with or without witness is the same # This is a sanity check of our testing framework. assert_equal(msg_tx(tx).serialize(), msg_witness_tx(tx).serialize()) self.test_node.send_message(msg_witness_tx(tx)) self.test_node.sync_with_ping() # make sure the tx was processed assert(tx.hash in self.nodes[0].getrawmempool()) # Save this transaction for later self.utxo.append(UTXO(tx.sha256, 0, 49*100000000)) self.nodes[0].generate(1) # Verify that blocks with witnesses are rejected before activation. def test_unnecessary_witness_before_segwit_activation(self): print("\tTesting behavior of unnecessary witnesses") # For now, rely on earlier tests to have created at least one utxo for # us to use assert(len(self.utxo) > 0) assert(get_bip9_status(self.nodes[0], 'segwit')['status'] != 'active') tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)])] # Verify the hash with witness differs from the txid # (otherwise our testing framework must be broken!) tx.rehash() assert(tx.sha256 != tx.calc_sha256(with_witness=True)) # Construct a segwit-signaling block that includes the transaction. block = self.build_next_block(nVersion=(VB_TOP_BITS|(1 << VB_WITNESS_BIT))) self.update_witness_block_with_transactions(block, [tx]) # Sending witness data before activation is not allowed (anti-spam # rule). self.test_node.test_witness_block(block, accepted=False) # TODO: fix synchronization so we can test reject reason # Right now, bitcoind delays sending reject messages for blocks # until the future, making synchronization here difficult. #assert_equal(self.test_node.last_reject.reason, "unexpected-witness") # But it should not be permanently marked bad... # Resend without witness information. self.test_node.send_message(msg_block(block)) self.test_node.sync_with_ping() assert_equal(self.nodes[0].getbestblockhash(), block.hash) sync_blocks(self.nodes) # Create a p2sh output -- this is so we can pass the standardness # rules (an anyone-can-spend OP_TRUE would be rejected, if not wrapped # in P2SH). p2sh_program = CScript([OP_TRUE]) p2sh_pubkey = hash160(p2sh_program) scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]) # Now check that unnecessary witnesses can't be used to blind a node # to a transaction, eg by violating standardness checks. tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-100000, scriptPubKey)) tx2.rehash() self.test_node.test_transaction_acceptance(tx2, False, True) self.nodes[0].generate(1) sync_blocks(self.nodes) # We'll add an unnecessary witness to this transaction that would cause # it to be non-standard, to test that violating policy with a witness before # segwit activation doesn't blind a node to a transaction. Transactions # rejected for having a witness before segwit activation shouldn't be added # to the rejection cache. tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), CScript([p2sh_program]))) tx3.vout.append(CTxOut(tx2.vout[0].nValue-100000, scriptPubKey)) tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit[0].scriptWitness.stack = [b'a'*400000] tx3.rehash() # Note that this should be rejected for the premature witness reason, # rather than a policy check, since segwit hasn't activated yet. self.std_node.test_transaction_acceptance(tx3, True, False, b'no-witness-yet') # If we send without witness, it should be accepted. self.std_node.test_transaction_acceptance(tx3, False, True) # Now create a new anyone-can-spend utxo for the next test. tx4 = CTransaction() tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), CScript([p2sh_program]))) tx4.vout.append(CTxOut(tx3.vout[0].nValue-100000, CScript([OP_TRUE]))) tx4.rehash() self.test_node.test_transaction_acceptance(tx3, False, True) self.test_node.test_transaction_acceptance(tx4, False, True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Update our utxo list; we spent the first entry. self.utxo.pop(0) self.utxo.append(UTXO(tx4.sha256, 0, tx4.vout[0].nValue)) # Mine enough blocks for segwit's vb state to be 'started'. def advance_to_segwit_started(self): height = self.nodes[0].getblockcount() # Will need to rewrite the tests here if we are past the first period assert(height < VB_PERIOD - 1) # Genesis block is 'defined'. assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'defined') # Advance to end of period, status should now be 'started' self.nodes[0].generate(VB_PERIOD-height-1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') # Mine enough blocks to lock in segwit, but don't activate. # TODO: we could verify that lockin only happens at the right threshold of # signalling blocks, rather than just at the right period boundary. def advance_to_segwit_lockin(self): height = self.nodes[0].getblockcount() assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') # Advance to end of period, and verify lock-in happens at the end self.nodes[0].generate(VB_PERIOD-1) height = self.nodes[0].getblockcount() assert((height % VB_PERIOD) == VB_PERIOD - 2) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') self.nodes[0].generate(1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') # Mine enough blocks to activate segwit. # TODO: we could verify that activation only happens at the right threshold # of signalling blocks, rather than just at the right period boundary. def advance_to_segwit_active(self): assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') height = self.nodes[0].getblockcount() self.nodes[0].generate(VB_PERIOD - (height%VB_PERIOD) - 2) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') self.nodes[0].generate(1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'active') # This test can only be run after segwit has activated def test_witness_commitments(self): print("\tTesting witness commitments") # First try a correct witness commitment. block = self.build_next_block() add_witness_commitment(block) block.solve() # Test the test -- witness serialization should be different assert(msg_witness_block(block).serialize() != msg_block(block).serialize()) # This empty block should be valid. self.test_node.test_witness_block(block, accepted=True) # Try to tweak the nonce block_2 = self.build_next_block() add_witness_commitment(block_2, nonce=28) block_2.solve() # The commitment should have changed! assert(block_2.vtx[0].vout[-1] != block.vtx[0].vout[-1]) # This should also be valid. self.test_node.test_witness_block(block_2, accepted=True) # Now test commitments with actual transactions assert (len(self.utxo) > 0) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) # Let's construct a witness program witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() # tx2 will spend tx1, and send back to a regular anyone-can-spend address tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program)) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program] tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx, tx2], nonce=1) # Add an extra OP_RETURN output that matches the witness commitment template, # even though it has extra data after the incorrect commitment. # This block should fail. block_3.vtx[0].vout.append(CTxOut(0, CScript([OP_RETURN, WITNESS_COMMITMENT_HEADER + ser_uint256(2), 10]))) block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() block_3.rehash() block_3.solve() self.test_node.test_witness_block(block_3, accepted=False) # Add a different commitment with different nonce, but in the # right location, and with some funds burned(!). # This should succeed (nValue shouldn't affect finding the # witness commitment). add_witness_commitment(block_3, nonce=0) block_3.vtx[0].vout[0].nValue -= 1 block_3.vtx[0].vout[-1].nValue += 1 block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() block_3.rehash() assert(len(block_3.vtx[0].vout) == 4) # 3 OP_returns block_3.solve() self.test_node.test_witness_block(block_3, accepted=True) # Finally test that a block with no witness transactions can # omit the commitment. block_4 = self.build_next_block() tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program)) tx3.rehash() block_4.vtx.append(tx3) block_4.hashMerkleRoot = block_4.calc_merkle_root() block_4.solve() self.test_node.test_witness_block(block_4, with_witness=False, accepted=True) # Update available utxo's for use in later test. self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) def test_block_malleability(self): print("\tTesting witness block malleability") # Make sure that a block that has too big a virtual size # because of a too-large coinbase witness is not permanently # marked bad. block = self.build_next_block() add_witness_commitment(block) block.solve() block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.append(b'a'*5000000) assert(get_virtual_size(block) > MAX_BLOCK_BASE_SIZE) # We can't send over the p2p network, because this is too big to relay # TODO: repeat this test with a block that can be relayed self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() != block.hash) block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.pop() assert(get_virtual_size(block) < MAX_BLOCK_BASE_SIZE) self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() == block.hash) # Now make sure that malleating the witness nonce doesn't # result in a block permanently marked bad. block = self.build_next_block() add_witness_commitment(block) block.solve() # Change the nonce -- should not cause the block to be permanently # failed block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(1) ] self.test_node.test_witness_block(block, accepted=False) # Changing the witness nonce doesn't change the block hash block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(0) ] self.test_node.test_witness_block(block, accepted=True) def test_witness_block_size(self): print("\tTesting witness block size limit") # TODO: Test that non-witness carrying blocks can't exceed 1MB # Skipping this test for now; this is covered in p2p-fullblocktest.py # Test that witness-bearing blocks are limited at ceil(base + wit/4) <= 1MB. block = self.build_next_block() assert(len(self.utxo) > 0) # Create a P2WSH transaction. # The witness program will be a bunch of OP_2DROP's, followed by OP_TRUE. # This should give us plenty of room to tweak the spending tx's # virtual size. NUM_DROPS = 200 # 201 max ops per script! NUM_OUTPUTS = 50 witness_program = CScript([OP_2DROP]*NUM_DROPS + [OP_TRUE]) witness_hash = uint256_from_str(sha256(witness_program)) scriptPubKey = CScript([OP_0, ser_uint256(witness_hash)]) prevout = COutPoint(self.utxo[0].sha256, self.utxo[0].n) value = self.utxo[0].nValue parent_tx = CTransaction() parent_tx.vin.append(CTxIn(prevout, b"")) child_value = int(value/NUM_OUTPUTS) for i in range(NUM_OUTPUTS): parent_tx.vout.append(CTxOut(child_value, scriptPubKey)) parent_tx.vout[0].nValue -= 50000 assert(parent_tx.vout[0].nValue > 0) parent_tx.rehash() child_tx = CTransaction() for i in range(NUM_OUTPUTS): child_tx.vin.append(CTxIn(COutPoint(parent_tx.sha256, i), b"")) child_tx.vout = [CTxOut(value - 100000, CScript([OP_TRUE]))] for i in range(NUM_OUTPUTS): child_tx.wit.vtxinwit.append(CTxInWitness()) child_tx.wit.vtxinwit[-1].scriptWitness.stack = [b'a'*195]*(2*NUM_DROPS) + [witness_program] child_tx.rehash() self.update_witness_block_with_transactions(block, [parent_tx, child_tx]) vsize = get_virtual_size(block) additional_bytes = (MAX_BLOCK_BASE_SIZE - vsize)*4 i = 0 while additional_bytes > 0: # Add some more bytes to each input until we hit MAX_BLOCK_BASE_SIZE+1 extra_bytes = min(additional_bytes+1, 55) block.vtx[-1].wit.vtxinwit[int(i/(2*NUM_DROPS))].scriptWitness.stack[i%(2*NUM_DROPS)] = b'a'*(195+extra_bytes) additional_bytes -= extra_bytes i += 1 block.vtx[0].vout.pop() # Remove old commitment add_witness_commitment(block) block.solve() vsize = get_virtual_size(block) assert_equal(vsize, MAX_BLOCK_BASE_SIZE + 1) # Make sure that our test case would exceed the old max-network-message # limit assert(len(block.serialize(True)) > 2*1024*1024) self.test_node.test_witness_block(block, accepted=False) # Now resize the second transaction to make the block fit. cur_length = len(block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0]) block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(cur_length-1) block.vtx[0].vout.pop() add_witness_commitment(block) block.solve() assert(get_virtual_size(block) == MAX_BLOCK_BASE_SIZE) self.test_node.test_witness_block(block, accepted=True) # Update available utxo's self.utxo.pop(0) self.utxo.append(UTXO(block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue)) # submitblock will try to add the nonce automatically, so that mining # software doesn't need to worry about doing so itself. def test_submit_block(self): block = self.build_next_block() # Try using a custom nonce and then don't supply it. # This shouldn't possibly work. add_witness_commitment(block, nonce=1) block.vtx[0].wit = CTxWitness() # drop the nonce block.solve() self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() != block.hash) # Now redo commitment with the standard nonce, but let bitcoind fill it in. add_witness_commitment(block, nonce=0) block.vtx[0].wit = CTxWitness() block.solve() self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert_equal(self.nodes[0].getbestblockhash(), block.hash) # This time, add a tx with non-empty witness, but don't supply # the commitment. block_2 = self.build_next_block() add_witness_commitment(block_2) block_2.solve() # Drop commitment and nonce -- submitblock should not fill in. block_2.vtx[0].vout.pop() block_2.vtx[0].wit = CTxWitness() self.nodes[0].submitblock(bytes_to_hex_str(block_2.serialize(True))) # Tip should not advance! assert(self.nodes[0].getbestblockhash() != block_2.hash) # Consensus tests of extra witness data in a transaction. def test_extra_witness_data(self): print("\tTesting extra witness data in tx") assert(len(self.utxo) > 0) block = self.build_next_block() witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # First try extra witness data on a tx that doesn't require a witness tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-200000, scriptPubKey)) tx.vout.append(CTxOut(1000, CScript([OP_TRUE]))) # non-witness output tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([])] tx.rehash() self.update_witness_block_with_transactions(block, [tx]) # Extra witness data should not be allowed. self.test_node.test_witness_block(block, accepted=False) # Try extra signature data. Ok if we're not spending a witness output. block.vtx[1].wit.vtxinwit = [] block.vtx[1].vin[0].scriptSig = CScript([OP_0]) block.vtx[1].rehash() add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Now try extra witness/signature data on an input that DOES require a # witness tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) # witness output tx2.vin.append(CTxIn(COutPoint(tx.sha256, 1), b"")) # non-witness tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) tx2.wit.vtxinwit.extend([CTxInWitness(), CTxInWitness()]) tx2.wit.vtxinwit[0].scriptWitness.stack = [ CScript([CScriptNum(1)]), CScript([CScriptNum(1)]), witness_program ] tx2.wit.vtxinwit[1].scriptWitness.stack = [ CScript([OP_TRUE]) ] block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) # This has extra witness data, so it should fail. self.test_node.test_witness_block(block, accepted=False) # Now get rid of the extra witness, but add extra scriptSig data tx2.vin[0].scriptSig = CScript([OP_TRUE]) tx2.vin[1].scriptSig = CScript([OP_TRUE]) tx2.wit.vtxinwit[0].scriptWitness.stack.pop(0) tx2.wit.vtxinwit[1].scriptWitness.stack = [] tx2.rehash() add_witness_commitment(block) block.solve() # This has extra signature data for a witness input, so it should fail. self.test_node.test_witness_block(block, accepted=False) # Now get rid of the extra scriptsig on the witness input, and verify # success (even with extra scriptsig data in the non-witness input) tx2.vin[0].scriptSig = b"" tx2.rehash() add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Update utxo for later tests self.utxo.pop(0) self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_max_witness_push_length(self): ''' Should only allow up to 520 byte pushes in witness stack ''' print("\tTesting maximum witness push size") MAX_SCRIPT_ELEMENT_SIZE = 520 assert(len(self.utxo)) block = self.build_next_block() witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-100000, scriptPubKey)) tx.rehash() tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-100000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) # First try a 521-byte stack element tx2.wit.vtxinwit[0].scriptWitness.stack = [ b'a'*(MAX_SCRIPT_ELEMENT_SIZE+1), witness_program ] tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Now reduce the length of the stack element tx2.wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(MAX_SCRIPT_ELEMENT_SIZE) add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Update the utxo for later tests self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_max_witness_program_length(self): # Can create witness outputs that are long, but can't be greater than # 10k bytes to successfully spend print("\tTesting maximum witness program length") assert(len(self.utxo)) MAX_PROGRAM_LENGTH = 10000 # This program is 19 max pushes (9937 bytes), then 64 more opcode-bytes. long_witness_program = CScript([b'a'*520]*19 + [OP_DROP]*63 + [OP_TRUE]) assert(len(long_witness_program) == MAX_PROGRAM_LENGTH+1) long_witness_hash = sha256(long_witness_program) long_scriptPubKey = CScript([OP_0, long_witness_hash]) block = self.build_next_block() tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-100000, long_scriptPubKey)) tx.rehash() tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-100000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*44 + [long_witness_program] tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Try again with one less byte in the witness program witness_program = CScript([b'a'*520]*19 + [OP_DROP]*62 + [OP_TRUE]) assert(len(witness_program) == MAX_PROGRAM_LENGTH) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx.vout[0] = CTxOut(tx.vout[0].nValue, scriptPubKey) tx.rehash() tx2.vin[0].prevout.hash = tx.sha256 tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*43 + [witness_program] tx2.rehash() block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_witness_input_length(self): ''' Ensure that vin length must match vtxinwit length ''' print("\tTesting witness input length") assert(len(self.utxo)) witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # Create a transaction that splits our utxo into many outputs tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) nValue = self.utxo[0].nValue for i in range(10): tx.vout.append(CTxOut(int(nValue/10), scriptPubKey)) tx.vout[0].nValue -= 1000 assert(tx.vout[0].nValue >= 0) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) # Try various ways to spend tx that should all break. # This "broken" transaction serializer will not normalize # the length of vtxinwit. class BrokenCTransaction(CTransaction): def serialize_with_witness(self): flags = 0 if not self.wit.is_null(): flags |= 1 r = b"" r += struct.pack("<i", self.nVersion) if flags: dummy = [] r += ser_vector(dummy) r += struct.pack("<B", flags) r += ser_vector(self.vin) r += ser_vector(self.vout) if flags & 1: r += self.wit.serialize() r += struct.pack("<I", self.nLockTime) return r tx2 = BrokenCTransaction() for i in range(10): tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) tx2.vout.append(CTxOut(nValue-3000, CScript([OP_TRUE]))) # First try using a too long vtxinwit for i in range(11): tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[i].scriptWitness.stack = [b'a', witness_program] block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Now try using a too short vtxinwit tx2.wit.vtxinwit.pop() tx2.wit.vtxinwit.pop() block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Now make one of the intermediate witnesses be incorrect tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [b'a', witness_program] tx2.wit.vtxinwit[5].scriptWitness.stack = [ witness_program ] block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Fix the broken witness and the block should be accepted. tx2.wit.vtxinwit[5].scriptWitness.stack = [b'a', witness_program] block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_witness_tx_relay_before_segwit_activation(self): print("\tTesting relay of witness transactions") # Generate a transaction that doesn't require a witness, but send it # with a witness. Should be rejected for premature-witness, but should # not be added to recently rejected list. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-100000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ] tx.rehash() tx_hash = tx.sha256 tx_value = tx.vout[0].nValue # Verify that if a peer doesn't set nServices to include NODE_WITNESS, # the getdata is just for the non-witness portion. self.old_node.announce_tx_and_wait_for_getdata(tx) assert(self.old_node.last_getdata.inv[0].type == 1) # Since we haven't delivered the tx yet, inv'ing the same tx from # a witness transaction ought not result in a getdata. try: self.test_node.announce_tx_and_wait_for_getdata(tx, timeout=2) print("Error: duplicate tx getdata!") assert(False) except AssertionError as e: pass # Delivering this transaction with witness should fail (no matter who # its from) assert_equal(len(self.nodes[0].getrawmempool()), 0) assert_equal(len(self.nodes[1].getrawmempool()), 0) self.old_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) # But eliminating the witness should fix it self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) # Cleanup: mine the first transaction and update utxo self.nodes[0].generate(1) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.utxo.pop(0) self.utxo.append(UTXO(tx_hash, 0, tx_value)) # After segwit activates, verify that mempool: # - rejects transactions with unnecessary/extra witnesses # - accepts transactions with valid witnesses # and that witness transactions are relayed to non-upgraded peers. def test_tx_relay_after_segwit_activation(self): print("\tTesting relay of witness transactions") # Generate a transaction that doesn't require a witness, but send it # with a witness. Should be rejected because we can't use a witness # when spending a non-witness output. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-100000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ] tx.rehash() tx_hash = tx.sha256 # Verify that unnecessary witnesses are rejected. self.test_node.announce_tx_and_wait_for_getdata(tx) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) # Verify that removing the witness succeeds. self.test_node.announce_tx_and_wait_for_getdata(tx) self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) # Now try to add extra witness data to a valid witness tx. witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx_hash, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-100000, scriptPubKey)) tx2.rehash() tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.wit.vtxinwit.append(CTxInWitness()) # Add too-large for IsStandard witness and check that it does not enter reject filter p2sh_program = CScript([OP_TRUE]) p2sh_pubkey = hash160(p2sh_program) witness_program2 = CScript([b'a'*400000]) tx3.vout.append(CTxOut(tx2.vout[0].nValue-100000, CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]))) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program2] tx3.rehash() # Node will not be blinded to the transaction self.std_node.announce_tx_and_wait_for_getdata(tx3) self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size') self.std_node.announce_tx_and_wait_for_getdata(tx3) self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size') # Remove witness stuffing, instead add extra witness push on stack tx3.vout[0] = CTxOut(tx2.vout[0].nValue-100000, CScript([OP_TRUE])) tx3.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)]), witness_program ] tx3.rehash() self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True) self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False) # Get rid of the extra witness, and verify acceptance. tx3.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] # Also check that old_node gets a tx announcement, even though this is # a witness transaction. self.old_node.wait_for_inv(CInv(1, tx2.sha256)) # wait until tx2 was inv'ed self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) self.old_node.wait_for_inv(CInv(1, tx3.sha256)) # Test that getrawtransaction returns correct witness information # hash, size, vsize raw_tx = self.nodes[0].getrawtransaction(tx3.hash, 1) assert_equal(int(raw_tx["hash"], 16), tx3.calc_sha256(True)) assert_equal(raw_tx["size"], len(tx3.serialize_with_witness())) vsize = (len(tx3.serialize_with_witness()) + 3*len(tx3.serialize_without_witness()) + 3) / 4 assert_equal(raw_tx["vsize"], vsize) assert_equal(len(raw_tx["vin"][0]["txinwitness"]), 1) assert_equal(raw_tx["vin"][0]["txinwitness"][0], hexlify(witness_program).decode('ascii')) assert(vsize != raw_tx["size"]) # Cleanup: mine the transactions and update utxo for next test self.nodes[0].generate(1) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) # Test that block requests to NODE_WITNESS peer are with MSG_WITNESS_FLAG # This is true regardless of segwit activation. # Also test that we don't ask for blocks from unupgraded peers def test_block_relay(self, segwit_activated): print("\tTesting block relay") blocktype = 2|MSG_WITNESS_FLAG # test_node has set NODE_WITNESS, so all getdata requests should be for # witness blocks. # Test announcing a block via inv results in a getdata, and that # announcing a version 4 or random VB block with a header results in a getdata block1 = self.build_next_block() block1.solve() self.test_node.announce_block_and_wait_for_getdata(block1, use_header=False) assert(self.test_node.last_getdata.inv[0].type == blocktype) self.test_node.test_witness_block(block1, True) # Viz: Blocks with nVersion < VB_TOP_BITS are rejected # block2 = self.build_next_block(nVersion=4) # block2.solve() # self.test_node.announce_block_and_wait_for_getdata(block2, use_header=True) # assert(self.test_node.last_getdata.inv[0].type == blocktype) # self.test_node.test_witness_block(block2, True) block3 = self.build_next_block(nVersion=(VB_TOP_BITS | (1<<15))) block3.solve() self.test_node.announce_block_and_wait_for_getdata(block3, use_header=True) assert(self.test_node.last_getdata.inv[0].type == blocktype) self.test_node.test_witness_block(block3, True) # Check that we can getdata for witness blocks or regular blocks, # and the right thing happens. if segwit_activated == False: # Before activation, we should be able to request old blocks with # or without witness, and they should be the same. chain_height = self.nodes[0].getblockcount() # Pick 10 random blocks on main chain, and verify that getdata's # for MSG_BLOCK, MSG_WITNESS_BLOCK, and rpc getblock() are equal. all_heights = list(range(chain_height+1)) random.shuffle(all_heights) all_heights = all_heights[0:10] for height in all_heights: block_hash = self.nodes[0].getblockhash(height) rpc_block = self.nodes[0].getblock(block_hash, False) block_hash = int(block_hash, 16) block = self.test_node.request_block(block_hash, 2) wit_block = self.test_node.request_block(block_hash, 2|MSG_WITNESS_FLAG) assert_equal(block.serialize(True), wit_block.serialize(True)) assert_equal(block.serialize(), hex_str_to_bytes(rpc_block)) else: # After activation, witness blocks and non-witness blocks should # be different. Verify rpc getblock() returns witness blocks, while # getdata respects the requested type. block = self.build_next_block() self.update_witness_block_with_transactions(block, []) # This gives us a witness commitment. assert(len(block.vtx[0].wit.vtxinwit) == 1) assert(len(block.vtx[0].wit.vtxinwit[0].scriptWitness.stack) == 1) self.test_node.test_witness_block(block, accepted=True) # Now try to retrieve it... rpc_block = self.nodes[0].getblock(block.hash, False) non_wit_block = self.test_node.request_block(block.sha256, 2) wit_block = self.test_node.request_block(block.sha256, 2|MSG_WITNESS_FLAG) assert_equal(wit_block.serialize(True), hex_str_to_bytes(rpc_block)) assert_equal(wit_block.serialize(False), non_wit_block.serialize()) assert_equal(wit_block.serialize(True), block.serialize(True)) # Test size, vsize, weight rpc_details = self.nodes[0].getblock(block.hash, True) assert_equal(rpc_details["size"], len(block.serialize(True))) assert_equal(rpc_details["strippedsize"], len(block.serialize(False))) weight = 3*len(block.serialize(False)) + len(block.serialize(True)) assert_equal(rpc_details["weight"], weight) # Upgraded node should not ask for blocks from unupgraded # Viz: Blocks with nVersion < VB_TOP_BITS are rejected block4 = self.build_next_block(nVersion=(VB_TOP_BITS | (1<<15))) block4.solve() self.old_node.getdataset = set() # Blocks can be requested via direct-fetch (immediately upon processing the announcement) # or via parallel download (with an indeterminate delay from processing the announcement) # so to test that a block is NOT requested, we could guess a time period to sleep for, # and then check. We can avoid the sleep() by taking advantage of transaction getdata's # being processed after block getdata's, and announce a transaction as well, # and then check to see if that particular getdata has been received. self.old_node.announce_block(block4, use_header=False) self.old_node.announce_tx_and_wait_for_getdata(block4.vtx[0]) assert(block4.sha256 not in self.old_node.getdataset) # V0 segwit outputs should be standard after activation, but not before. def test_standardness_v0(self, segwit_activated): print("\tTesting standardness of v0 outputs (%s activation)" % ("after" if segwit_activated else "before")) assert(len(self.utxo)) witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) p2sh_pubkey = hash160(witness_program) p2sh_scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]) # First prepare a p2sh output (so that spending it will pass standardness) p2sh_tx = CTransaction() p2sh_tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] p2sh_tx.vout = [CTxOut(self.utxo[0].nValue-100000, p2sh_scriptPubKey)] p2sh_tx.rehash() # Mine it on test_node to create the confirmed output. self.test_node.test_transaction_acceptance(p2sh_tx, with_witness=True, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Now test standardness of v0 P2WSH outputs. # Start by creating a transaction with two outputs. tx = CTransaction() tx.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx.vout = [CTxOut(p2sh_tx.vout[0].nValue-1000000, scriptPubKey)] tx.vout.append(CTxOut(800000, scriptPubKey)) # Might burn this later tx.rehash() self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=segwit_activated) # Now create something that looks like a P2PKH output. This won't be spendable. scriptPubKey = CScript([OP_0, hash160(witness_hash)]) tx2 = CTransaction() if segwit_activated: # if tx was accepted, then we spend the second output. tx2.vin = [CTxIn(COutPoint(tx.sha256, 1), b"")] tx2.vout = [CTxOut(700000, scriptPubKey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program] else: # if tx wasn't accepted, we just re-spend the p2sh output we started with. tx2.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx2.vout = [CTxOut(p2sh_tx.vout[0].nValue-100000, scriptPubKey)] tx2.rehash() self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=segwit_activated) # Now update self.utxo for later tests. tx3 = CTransaction() if segwit_activated: # tx and tx2 were both accepted. Don't bother trying to reclaim the # P2PKH output; just send tx's first output back to an anyone-can-spend. sync_mempools([self.nodes[0], self.nodes[1]]) tx3.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] tx3.vout = [CTxOut(tx.vout[0].nValue-100000, CScript([OP_TRUE]))] tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program] tx3.rehash() self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) else: # tx and tx2 didn't go anywhere; just clean up the p2sh_tx output. tx3.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx3.vout = [CTxOut(p2sh_tx.vout[0].nValue-100000, witness_program)] tx3.rehash() self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) assert_equal(len(self.nodes[1].getrawmempool()), 0) # Verify that future segwit upgraded transactions are non-standard, # but valid in blocks. Can run this before and after segwit activation. def test_segwit_versions(self): print("\tTesting standardness/consensus for segwit versions (0-16)") assert(len(self.utxo)) NUM_TESTS = 17 # will test OP_0, OP1, ..., OP_16 if (len(self.utxo) < NUM_TESTS): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) split_value = (self.utxo[0].nValue - 400000) // NUM_TESTS for i in range(NUM_TESTS): tx.vout.append(CTxOut(split_value, CScript([OP_TRUE]))) tx.rehash() block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop(0) for i in range(NUM_TESTS): self.utxo.append(UTXO(tx.sha256, i, split_value)) sync_blocks(self.nodes) temp_utxo = [] tx = CTransaction() count = 0 witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) assert_equal(len(self.nodes[1].getrawmempool()), 0) for version in list(range(OP_1, OP_16+1)) + [OP_0]: count += 1 # First try to spend to a future version segwit scriptPubKey. scriptPubKey = CScript([CScriptOp(version), witness_hash]) tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] tx.vout = [CTxOut(self.utxo[0].nValue-100000, scriptPubKey)] tx.rehash() self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True) self.utxo.pop(0) temp_utxo.append(UTXO(tx.sha256, 0, tx.vout[0].nValue)) self.nodes[0].generate(1) # Mine all the transactions sync_blocks(self.nodes) assert(len(self.nodes[0].getrawmempool()) == 0) # Finally, verify that version 0 -> version 1 transactions # are non-standard scriptPubKey = CScript([CScriptOp(OP_1), witness_hash]) tx2 = CTransaction() tx2.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] tx2.vout = [CTxOut(tx.vout[0].nValue-100000, scriptPubKey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] tx2.rehash() # Gets accepted to test_node, because standardness of outputs isn't # checked with fRequireStandard self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True) self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=False) temp_utxo.pop() # last entry in temp_utxo was the output we just spent temp_utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) # Spend everything in temp_utxo back to an OP_TRUE output. tx3 = CTransaction() total_value = 0 for i in temp_utxo: tx3.vin.append(CTxIn(COutPoint(i.sha256, i.n), b"")) tx3.wit.vtxinwit.append(CTxInWitness()) total_value += i.nValue tx3.wit.vtxinwit[-1].scriptWitness.stack = [witness_program] tx3.vout.append(CTxOut(total_value - 100000, CScript([OP_TRUE]))) tx3.rehash() # Spending a higher version witness output is not allowed by policy, # even with fRequireStandard=false. self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False) self.test_node.sync_with_ping() with mininode_lock: assert(b"reserved for soft-fork upgrades" in self.test_node.last_reject.reason) # Building a block with the transaction must be valid, however. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2, tx3]) self.test_node.test_witness_block(block, accepted=True) sync_blocks(self.nodes) # Add utxo to our list self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) def test_premature_coinbase_witness_spend(self): print("\tTesting premature coinbase witness spend") block = self.build_next_block() # Change the output of the block to be a witness output. witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) block.vtx[0].vout[0].scriptPubKey = scriptPubKey # This next line will rehash the coinbase and update the merkle # root, and solve. self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) spend_tx = CTransaction() spend_tx.vin = [CTxIn(COutPoint(block.vtx[0].sha256, 0), b"")] spend_tx.vout = [CTxOut(block.vtx[0].vout[0].nValue, witness_program)] spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] spend_tx.rehash() # Now test a premature spend. self.nodes[0].generate(98) sync_blocks(self.nodes) block2 = self.build_next_block() self.update_witness_block_with_transactions(block2, [spend_tx]) self.test_node.test_witness_block(block2, accepted=False) # Advancing one more block should allow the spend. self.nodes[0].generate(1) block2 = self.build_next_block() self.update_witness_block_with_transactions(block2, [spend_tx]) self.test_node.test_witness_block(block2, accepted=True) sync_blocks(self.nodes) def test_signature_version_1(self): print("\tTesting segwit signature hash version 1") key = CECKey() key.set_secretbytes(b"9") pubkey = CPubKey(key.get_pubkey()) witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # First create a witness output for use in the tests. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-100000, scriptPubKey)) tx.rehash() self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True) # Mine this transaction in preparation for following tests. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) sync_blocks(self.nodes) self.utxo.pop(0) # Test each hashtype prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) for sigflag in [ 0, SIGHASH_ANYONECANPAY ]: for hashtype in [SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE]: hashtype |= sigflag block = self.build_next_block() tx = CTransaction() tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b"")) tx.vout.append(CTxOut(prev_utxo.nValue - 100000, scriptPubKey)) tx.wit.vtxinwit.append(CTxInWitness()) # Too-large input value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue+1, key) self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=False) # Too-small input value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue-1, key) block.vtx.pop() # remove last tx self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=False) # Now try correct value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue, key) block.vtx.pop() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) # Test combinations of signature hashes. # Split the utxo into a lot of outputs. # Randomly choose up to 10 to spend, sign with different hashtypes, and # output to a random number of outputs. Repeat NUM_TESTS times. # Ensure that we've tested a situation where we use SIGHASH_SINGLE with # an input index > number of outputs. NUM_TESTS = 500 temp_utxos = [] tx = CTransaction() tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b"")) split_value = prev_utxo.nValue // NUM_TESTS for i in range(NUM_TESTS): tx.vout.append(CTxOut(split_value, scriptPubKey)) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, prev_utxo.nValue, key) for i in range(NUM_TESTS): temp_utxos.append(UTXO(tx.sha256, i, split_value)) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) block = self.build_next_block() used_sighash_single_out_of_bounds = False for i in range(NUM_TESTS): # Ping regularly to keep the connection alive if (not i % 100): self.test_node.sync_with_ping() # Choose random number of inputs to use. num_inputs = random.randint(1, 10) # Create a slight bias for producing more utxos num_outputs = random.randint(1, 11) random.shuffle(temp_utxos) assert(len(temp_utxos) > num_inputs) tx = CTransaction() total_value = 0 for i in range(num_inputs): tx.vin.append(CTxIn(COutPoint(temp_utxos[i].sha256, temp_utxos[i].n), b"")) tx.wit.vtxinwit.append(CTxInWitness()) total_value += temp_utxos[i].nValue split_value = total_value // num_outputs for i in range(num_outputs): tx.vout.append(CTxOut(split_value, scriptPubKey)) for i in range(num_inputs): # Now try to sign each input, using a random hashtype. anyonecanpay = 0 if random.randint(0, 1): anyonecanpay = SIGHASH_ANYONECANPAY hashtype = random.randint(1, 3) | anyonecanpay sign_P2PK_witness_input(witness_program, tx, i, hashtype, temp_utxos[i].nValue, key) if (hashtype == SIGHASH_SINGLE and i >= num_outputs): used_sighash_single_out_of_bounds = True tx.rehash() for i in range(num_outputs): temp_utxos.append(UTXO(tx.sha256, i, split_value)) temp_utxos = temp_utxos[num_inputs:] block.vtx.append(tx) # Test the block periodically, if we're close to maxblocksize if (get_virtual_size(block) > MAX_BLOCK_BASE_SIZE - 1000): self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) block = self.build_next_block() if (not used_sighash_single_out_of_bounds): print("WARNING: this test run didn't attempt SIGHASH_SINGLE with out-of-bounds index value") # Test the transactions we've added to the block if (len(block.vtx) > 1): self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) # Now test witness version 0 P2PKH transactions pubkeyhash = hash160(pubkey) scriptPKH = CScript([OP_0, pubkeyhash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(temp_utxos[0].sha256, temp_utxos[0].n), b"")) tx.vout.append(CTxOut(temp_utxos[0].nValue, scriptPKH)) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, temp_utxos[0].nValue, key) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) script = GetP2PKHScript(pubkeyhash) sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL # Check that we can't have a scriptSig tx2.vin[0].scriptSig = CScript([signature, pubkey]) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Move the signature to the witness. block.vtx.pop() tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [signature, pubkey] tx2.vin[0].scriptSig = b"" tx2.rehash() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) temp_utxos.pop(0) # Update self.utxos for later tests. Just spend everything in # temp_utxos to a corresponding entry in self.utxos tx = CTransaction() index = 0 for i in temp_utxos: # Just spend to our usual anyone-can-spend output # Use SIGHASH_SINGLE|SIGHASH_ANYONECANPAY so we can build up # the signatures as we go. tx.vin.append(CTxIn(COutPoint(i.sha256, i.n), b"")) tx.vout.append(CTxOut(i.nValue, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, index, SIGHASH_SINGLE|SIGHASH_ANYONECANPAY, i.nValue, key) index += 1 block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) for i in range(len(tx.vout)): self.utxo.append(UTXO(tx.sha256, i, tx.vout[i].nValue)) # Test P2SH wrapped witness programs. def test_p2sh_witness(self, segwit_activated): print("\tTesting P2SH witness transactions") assert(len(self.utxo)) # Prepare the p2sh-wrapped witness output witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) p2wsh_pubkey = CScript([OP_0, witness_hash]) p2sh_witness_hash = hash160(p2wsh_pubkey) scriptPubKey = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL]) scriptSig = CScript([p2wsh_pubkey]) # a push of the redeem script # Fund the P2SH output tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-100000, scriptPubKey)) tx.rehash() # Verify mempool acceptance and block validity self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True, with_witness=segwit_activated) sync_blocks(self.nodes) # Now test attempts to spend the output. spend_tx = CTransaction() spend_tx.vin.append(CTxIn(COutPoint(tx.sha256, 0), scriptSig)) spend_tx.vout.append(CTxOut(tx.vout[0].nValue-100000, CScript([OP_TRUE]))) spend_tx.rehash() # This transaction should not be accepted into the mempool pre- or # post-segwit. Mempool acceptance will use SCRIPT_VERIFY_WITNESS which # will require a witness to spend a witness program regardless of # segwit activation. Note that older bitcoind's that are not # segwit-aware would also reject this for failing CLEANSTACK. self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False) # Try to put the witness script in the scriptSig, should also fail. spend_tx.vin[0].scriptSig = CScript([p2wsh_pubkey, b'a']) spend_tx.rehash() self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False) # Now put the witness script in the witness, should succeed after # segwit activates. spend_tx.vin[0].scriptSig = scriptSig spend_tx.rehash() spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a', witness_program ] # Verify mempool acceptance self.test_node.test_transaction_acceptance(spend_tx, with_witness=True, accepted=segwit_activated) block = self.build_next_block() self.update_witness_block_with_transactions(block, [spend_tx]) # If we're before activation, then sending this without witnesses # should be valid. If we're after activation, then sending this with # witnesses should be valid. if segwit_activated: self.test_node.test_witness_block(block, accepted=True) else: self.test_node.test_witness_block(block, accepted=True, with_witness=False) # Update self.utxo self.utxo.pop(0) self.utxo.append(UTXO(spend_tx.sha256, 0, spend_tx.vout[0].nValue)) # Test the behavior of starting up a segwit-aware node after the softfork # has activated. As segwit requires different block data than pre-segwit # nodes would have stored, this requires special handling. # To enable this test, pass --oldbinary=<path-to-pre-segwit-bitcoind> to # the test. def test_upgrade_after_activation(self, node, node_id): print("\tTesting software upgrade after softfork activation") assert(node_id != 0) # node0 is assumed to be a segwit-active bitcoind # Make sure the nodes are all up sync_blocks(self.nodes) # Restart with the new binary stop_node(node, node_id) self.nodes[node_id] = start_node(node_id, self.options.tmpdir, ["-debug"]) connect_nodes(self.nodes[0], node_id) sync_blocks(self.nodes) # Make sure that this peer thinks segwit has activated. assert(get_bip9_status(node, 'segwit')['status'] == "active") # Make sure this peers blocks match those of node0. height = node.getblockcount() while height >= 0: block_hash = node.getblockhash(height) assert_equal(block_hash, self.nodes[0].getblockhash(height)) assert_equal(self.nodes[0].getblock(block_hash), node.getblock(block_hash)) height -= 1 def test_witness_sigops(self): '''Ensure sigop counting is correct inside witnesses.''' print("\tTesting sigops limit") assert(len(self.utxo)) # Keep this under MAX_OPS_PER_SCRIPT (201) witness_program = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKMULTISIG]*5 + [OP_CHECKSIG]*193 + [OP_ENDIF]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) sigops_per_script = 20*5 + 193*1 # We'll produce 2 extra outputs, one with a program that would take us # over max sig ops, and one with a program that would exactly reach max # sig ops outputs = (MAX_SIGOP_COST // sigops_per_script) + 2 extra_sigops_available = MAX_SIGOP_COST % sigops_per_script # We chose the number of checkmultisigs/checksigs to make this work: assert(extra_sigops_available < 100) # steer clear of MAX_OPS_PER_SCRIPT # This script, when spent with the first # N(=MAX_SIGOP_COST//sigops_per_script) outputs of our transaction, # would push us just over the block sigop limit. witness_program_toomany = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available + 1) + [OP_ENDIF]) witness_hash_toomany = sha256(witness_program_toomany) scriptPubKey_toomany = CScript([OP_0, witness_hash_toomany]) # If we spend this script instead, we would exactly reach our sigop # limit (for witness sigops). witness_program_justright = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available) + [OP_ENDIF]) witness_hash_justright = sha256(witness_program_justright) scriptPubKey_justright = CScript([OP_0, witness_hash_justright]) # First split our available utxo into a bunch of outputs split_value = self.utxo[0].nValue // outputs tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) for i in range(outputs): tx.vout.append(CTxOut(split_value, scriptPubKey)) tx.vout[-2].scriptPubKey = scriptPubKey_toomany tx.vout[-1].scriptPubKey = scriptPubKey_justright tx.rehash() block_1 = self.build_next_block() self.update_witness_block_with_transactions(block_1, [tx]) self.test_node.test_witness_block(block_1, accepted=True) tx2 = CTransaction() # If we try to spend the first n-1 outputs from tx, that should be # too many sigops. total_value = 0 for i in range(outputs-1): tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program ] total_value += tx.vout[i].nValue tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_toomany ] tx2.vout.append(CTxOut(total_value, CScript([OP_TRUE]))) tx2.rehash() block_2 = self.build_next_block() self.update_witness_block_with_transactions(block_2, [tx2]) self.test_node.test_witness_block(block_2, accepted=False) # Try dropping the last input in tx2, and add an output that has # too many sigops (contributing to legacy sigop count). checksig_count = (extra_sigops_available // 4) + 1 scriptPubKey_checksigs = CScript([OP_CHECKSIG]*checksig_count) tx2.vout.append(CTxOut(0, scriptPubKey_checksigs)) tx2.vin.pop() tx2.wit.vtxinwit.pop() tx2.vout[0].nValue -= tx.vout[-2].nValue tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx2]) self.test_node.test_witness_block(block_3, accepted=False) # If we drop the last checksig in this output, the tx should succeed. block_4 = self.build_next_block() tx2.vout[-1].scriptPubKey = CScript([OP_CHECKSIG]*(checksig_count-1)) tx2.rehash() self.update_witness_block_with_transactions(block_4, [tx2]) self.test_node.test_witness_block(block_4, accepted=True) # Reset the tip back down for the next test sync_blocks(self.nodes) for x in self.nodes: x.invalidateblock(block_4.hash) # Try replacing the last input of tx2 to be spending the last # output of tx block_5 = self.build_next_block() tx2.vout.pop() tx2.vin.append(CTxIn(COutPoint(tx.sha256, outputs-1), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_justright ] tx2.rehash() self.update_witness_block_with_transactions(block_5, [tx2]) self.test_node.test_witness_block(block_5, accepted=True) # TODO: test p2sh sigop counting def test_getblocktemplate_before_lockin(self): print("\tTesting getblocktemplate setting of segwit versionbit (before lockin)") # Node0 is segwit aware, node2 is not. for node in [self.nodes[0], self.nodes[2]]: gbt_results = node.getblocktemplate() block_version = gbt_results['version'] # If we're not indicating segwit support, we will still be # signalling for segwit activation. assert_equal((block_version & (1 << VB_WITNESS_BIT) != 0), node == self.nodes[0]) # If we don't specify the segwit rule, then we won't get a default # commitment. assert('default_witness_commitment' not in gbt_results) # Workaround: # Can either change the tip, or change the mempool and wait 5 seconds # to trigger a recomputation of getblocktemplate. txid = int(self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1), 16) # Using mocktime lets us avoid sleep() sync_mempools(self.nodes) self.nodes[0].setmocktime(int(time.time())+10) self.nodes[2].setmocktime(int(time.time())+10) for node in [self.nodes[0], self.nodes[2]]: gbt_results = node.getblocktemplate({"rules" : ["segwit"]}) block_version = gbt_results['version'] if node == self.nodes[2]: # If this is a non-segwit node, we should still not get a witness # commitment, nor a version bit signalling segwit. assert_equal(block_version & (1 << VB_WITNESS_BIT), 0) assert('default_witness_commitment' not in gbt_results) else: # For segwit-aware nodes, check the version bit and the witness # commitment are correct. assert(block_version & (1 << VB_WITNESS_BIT) != 0) assert('default_witness_commitment' in gbt_results) witness_commitment = gbt_results['default_witness_commitment'] # TODO: this duplicates some code from blocktools.py, would be nice # to refactor. # Check that default_witness_commitment is present. block = CBlock() witness_root = block.get_merkle_root([ser_uint256(0), ser_uint256(txid)]) check_commitment = uint256_from_str(hash256(ser_uint256(witness_root)+ser_uint256(0))) from test_framework.blocktools import WITNESS_COMMITMENT_HEADER output_data = WITNESS_COMMITMENT_HEADER + ser_uint256(check_commitment) script = CScript([OP_RETURN, output_data]) assert_equal(witness_commitment, bytes_to_hex_str(script)) # undo mocktime self.nodes[0].setmocktime(0) self.nodes[2].setmocktime(0) # Uncompressed pubkeys are no longer supported in default relay policy, # but (for now) are still valid in blocks. def test_uncompressed_pubkey(self): print("\tTesting uncompressed pubkeys") # Segwit transactions using uncompressed pubkeys are not accepted # under default policy, but should still pass consensus. key = CECKey() key.set_secretbytes(b"9") key.set_compressed(False) pubkey = CPubKey(key.get_pubkey()) assert_equal(len(pubkey), 65) # This should be an uncompressed pubkey assert(len(self.utxo) > 0) utxo = self.utxo.pop(0) # Test 1: P2WPKH # First create a P2WPKH output that uses an uncompressed pubkey pubkeyhash = hash160(pubkey) scriptPKH = CScript([OP_0, pubkeyhash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(utxo.sha256, utxo.n), b"")) tx.vout.append(CTxOut(utxo.nValue-100000, scriptPKH)) tx.rehash() # Confirm it in a block. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) # Now try to spend it. Send it to a P2WSH output, which we'll # use in the next test. witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)]) witness_hash = sha256(witness_program) scriptWSH = CScript([OP_0, witness_hash]) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-100000, scriptWSH)) script = GetP2PKHScript(pubkeyhash) sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [ signature, pubkey ] tx2.rehash() # Should fail policy test. self.test_node.test_transaction_acceptance(tx2, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') # But passes consensus. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) # Test 2: P2WSH # Try to spend the P2WSH output created in last test. # Send it to a P2SH(P2WSH) output, which we'll use in the next test. p2sh_witness_hash = hash160(scriptWSH) scriptP2SH = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL]) scriptSig = CScript([scriptWSH]) tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.vout.append(CTxOut(tx2.vout[0].nValue-100000, scriptP2SH)) tx3.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx3, 0, SIGHASH_ALL, tx2.vout[0].nValue, key) # Should fail policy test. self.test_node.test_transaction_acceptance(tx3, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') # But passes consensus. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx3]) self.test_node.test_witness_block(block, accepted=True) # Test 3: P2SH(P2WSH) # Try to spend the P2SH output created in the last test. # Send it to a P2PKH output, which we'll use in the next test. scriptPubKey = GetP2PKHScript(pubkeyhash) tx4 = CTransaction() tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), scriptSig)) tx4.vout.append(CTxOut(tx3.vout[0].nValue-100000, scriptPubKey)) tx4.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx4, 0, SIGHASH_ALL, tx3.vout[0].nValue, key) # Should fail policy test. self.test_node.test_transaction_acceptance(tx4, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx4]) self.test_node.test_witness_block(block, accepted=True) # Test 4: Uncompressed pubkeys should still be valid in non-segwit # transactions. tx5 = CTransaction() tx5.vin.append(CTxIn(COutPoint(tx4.sha256, 0), b"")) tx5.vout.append(CTxOut(tx4.vout[0].nValue-100000, CScript([OP_TRUE]))) (sig_hash, err) = SignatureHash(scriptPubKey, tx5, 0, SIGHASH_ALL) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL tx5.vin[0].scriptSig = CScript([signature, pubkey]) tx5.rehash() # Should pass policy and consensus. self.test_node.test_transaction_acceptance(tx5, True, True) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx5]) self.test_node.test_witness_block(block, accepted=True) self.utxo.append(UTXO(tx5.sha256, 0, tx5.vout[0].nValue)) def test_non_standard_witness(self): print("\tTesting detection of non-standard P2WSH witness") pad = chr(1).encode('latin-1') # Create scripts for tests scripts = [] scripts.append(CScript([OP_DROP] * 100)) scripts.append(CScript([OP_DROP] * 99)) scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 60)) scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 61)) p2wsh_scripts = [] assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) # For each script, generate a pair of P2WSH and P2SH-P2WSH output. outputvalue = (self.utxo[0].nValue - 100000) // (len(scripts) * 2) for i in scripts: p2wsh = CScript([OP_0, sha256(i)]) p2sh = hash160(p2wsh) p2wsh_scripts.append(p2wsh) tx.vout.append(CTxOut(outputvalue, p2wsh)) tx.vout.append(CTxOut(outputvalue, CScript([OP_HASH160, p2sh, OP_EQUAL]))) tx.rehash() txid = tx.sha256 self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Creating transactions for tests p2wsh_txs = [] p2sh_txs = [] for i in range(len(scripts)): p2wsh_tx = CTransaction() p2wsh_tx.vin.append(CTxIn(COutPoint(txid,i*2))) p2wsh_tx.vout.append(CTxOut(outputvalue - 500000, CScript([OP_0, hash160(hex_str_to_bytes(""))]))) p2wsh_tx.wit.vtxinwit.append(CTxInWitness()) p2wsh_tx.rehash() p2wsh_txs.append(p2wsh_tx) p2sh_tx = CTransaction() p2sh_tx.vin.append(CTxIn(COutPoint(txid,i*2+1), CScript([p2wsh_scripts[i]]))) p2sh_tx.vout.append(CTxOut(outputvalue - 500000, CScript([OP_0, hash160(hex_str_to_bytes(""))]))) p2sh_tx.wit.vtxinwit.append(CTxInWitness()) p2sh_tx.rehash() p2sh_txs.append(p2sh_tx) # Testing native P2WSH # Witness stack size, excluding witnessScript, over 100 is non-standard p2wsh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]] self.std_node.test_transaction_acceptance(p2wsh_txs[0], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[0], True, True) # Stack element size over 80 bytes is non-standard p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[1], True, True) # Standard nodes should accept if element size is not over 80 bytes p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, True) # witnessScript size at 3600 bytes is standard p2wsh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]] self.test_node.test_transaction_acceptance(p2wsh_txs[2], True, True) self.std_node.test_transaction_acceptance(p2wsh_txs[2], True, True) # witnessScript size at 3601 bytes is non-standard p2wsh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]] self.std_node.test_transaction_acceptance(p2wsh_txs[3], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[3], True, True) # Repeating the same tests with P2SH-P2WSH p2sh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]] self.std_node.test_transaction_acceptance(p2sh_txs[0], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[0], True, True) p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2sh_txs[1], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[1], True, True) p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2sh_txs[1], True, True) p2sh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]] self.test_node.test_transaction_acceptance(p2sh_txs[2], True, True) self.std_node.test_transaction_acceptance(p2sh_txs[2], True, True) p2sh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]] self.std_node.test_transaction_acceptance(p2sh_txs[3], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[3], True, True) self.nodes[0].generate(1) # Mine and clean up the mempool of non-standard node # Valid but non-standard transactions in a block should be accepted by standard node sync_blocks(self.nodes) assert_equal(len(self.nodes[0].getrawmempool()), 0) assert_equal(len(self.nodes[1].getrawmempool()), 0) self.utxo.pop(0) def test_reject_blocks(self): print ("\tTesting rejection of block.nVersion < BIP9_TOP_BITS blocks") block = self.build_next_block(nVersion=4) block.solve() resp = self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert_equal(resp, 'bad-version(0x00000004)') def run_test(self): # Setup the p2p connections and start up the network thread. self.test_node = TestNode() # sets NODE_WITNESS|NODE_NETWORK self.old_node = TestNode() # only NODE_NETWORK self.std_node = TestNode() # for testing node1 (fRequireStandard=true) self.p2p_connections = [self.test_node, self.old_node] self.connections = [] self.connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node, services=NODE_NETWORK|NODE_WITNESS)) self.connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.old_node, services=NODE_NETWORK)) self.connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], self.std_node, services=NODE_NETWORK|NODE_WITNESS)) self.test_node.add_connection(self.connections[0]) self.old_node.add_connection(self.connections[1]) self.std_node.add_connection(self.connections[2]) NetworkThread().start() # Start up network handling in another thread # Keep a place to store utxo's that can be used in later tests self.utxo = [] # Test logic begins here self.test_node.wait_for_verack() print("\nStarting tests before segwit lock in:") self.test_witness_services() # Verifies NODE_WITNESS self.test_non_witness_transaction() # non-witness tx's are accepted self.test_unnecessary_witness_before_segwit_activation() self.test_block_relay(segwit_activated=False) # Advance to segwit being 'started' self.advance_to_segwit_started() sync_blocks(self.nodes) self.test_getblocktemplate_before_lockin() sync_blocks(self.nodes) # At lockin, nothing should change. print("\nTesting behavior post lockin, pre-activation") self.advance_to_segwit_lockin() # Retest unnecessary witnesses self.test_unnecessary_witness_before_segwit_activation() self.test_witness_tx_relay_before_segwit_activation() self.test_block_relay(segwit_activated=False) self.test_p2sh_witness(segwit_activated=False) self.test_standardness_v0(segwit_activated=False) sync_blocks(self.nodes) # Now activate segwit print("\nTesting behavior after segwit activation") self.advance_to_segwit_active() sync_blocks(self.nodes) # Test P2SH witness handling again self.test_reject_blocks() self.test_p2sh_witness(segwit_activated=True) self.test_witness_commitments() self.test_block_malleability() self.test_witness_block_size() self.test_submit_block() self.test_extra_witness_data() self.test_max_witness_push_length() self.test_max_witness_program_length() self.test_witness_input_length() self.test_block_relay(segwit_activated=True) self.test_tx_relay_after_segwit_activation() self.test_standardness_v0(segwit_activated=True) self.test_segwit_versions() self.test_premature_coinbase_witness_spend() self.test_uncompressed_pubkey() self.test_signature_version_1() self.test_non_standard_witness() sync_blocks(self.nodes) self.test_upgrade_after_activation(self.nodes[2], 2) self.test_witness_sigops() if __name__ == '__main__': SegWitTest().main()
viz-dev/viz
qa/rpc-tests/p2p-segwit.py
Python
mit
93,414
import * as React from 'react'; import { shallow, ShallowWrapper } from 'enzyme'; import { Input, InputProps, InputState } from '../../src'; describe('Input component tests', () => { it('Input exists', () => { let input = shallow(<Input />); expect(input).toBeDefined(); }); it('Input value equals props value', () => { let testValue: string = "Hello world!"; let input: ShallowWrapper<InputProps, InputState> = shallow<InputProps, InputState>( <Input value={testValue} /> ); let inputProps: InputProps = input.props(); let inputPropsValue: string = inputProps.value; let inputState: InputState = input.state(); let inputStateValue: string = inputState.value; expect(inputPropsValue).toEqual(testValue); expect(inputStateValue).toEqual(testValue); }); it('Input state changes when user types something in the input', () => { let testValue: string = "Hello world!"; let input = shallow<InputProps, InputState>( <Input value={testValue} /> ); let inputEl = input.find('input'); testValue = 'New value'; inputEl.simulate('change', { target: { value: testValue } }); let inputState: InputState = input.state(); let inputStateValue: string = inputState.value; expect(inputStateValue).toEqual(testValue); }); });
sinelshchikovigor/react-ui-kit
tests/input/input.spec.tsx
TypeScript
mit
1,473
<?php namespace Doctrine\ODM\CouchDB\Mapping; use Doctrine\Common\Persistence\Mapping\ClassMetadata AS IClassMetadata, ReflectionClass, ReflectionProperty; /** * Metadata class * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.com * @since 1.0 * @author Benjamin Eberlei <[email protected]> * @author Lukas Kahwe Smith <[email protected]> */ class ClassMetadata extends ClassMetadataInfo implements IClassMetadata { /** * The ReflectionClass instance of the mapped class. * * @var ReflectionClass */ public $reflClass; /** * The ReflectionProperty instances of the mapped class. * * @var array */ public $reflFields = array(); /** * The prototype from which new instances of the mapped class are created. * * @var object */ private $prototype; /** * Initializes a new ClassMetadata instance that will hold the object-document mapping * metadata of the class with the given name. * * @param string $documentName The name of the document class the new instance is used for. */ public function __construct($documentName) { parent::__construct($documentName); $this->reflClass = new \ReflectionClass($documentName); $this->name = $this->reflClass->getName(); $this->namespace = $this->reflClass->getNamespaceName(); } /** * Used to derive a class metadata of the current instance for a mapped child class. * * @param string $childName * @return ClassMetadata */ public function deriveChildMetadata($childName) { if (!is_subclass_of($childName, $this->name)) { throw new \InvalidArgumentException("Only child class names of '".$this->name."' are valid values."); } $cm = clone $this; /* @var $cm ClassMetadata */ $cm->reflClass = new \ReflectionClass($childName); $cm->name = $cm->reflClass->getName(); $cm->namespace = $cm->reflClass->getNamespaceName(); if ($this->isMappedSuperclass) { $cm->rootDocumentName = $cm->name; } $cm->isMappedSuperclass = false; $cm->isEmbeddedDocument = false; foreach ($cm->fieldMappings AS $fieldName => $fieldMapping) { if (!isset($fieldMapping['declared'])) { $cm->fieldMappings[$fieldName]['declared'] = $this->name; } } foreach ($cm->associationsMappings AS $assocName => $assocMapping) { if (!isset($assocMapping['declared'])) { $cm->associationsMappings[$assocName]['declared'] = $this->name; } } if ($cm->attachmentField && !$cm->attachmentDeclaredClass) { $cm->attachmentDeclaredClass = $this->name; } return $cm; } protected function validateAndCompleteFieldMapping($mapping) { $mapping = parent::validateAndCompleteFieldMapping($mapping); $reflProp = $this->reflClass->getProperty($mapping['fieldName']); $reflProp->setAccessible(true); $this->reflFields[$mapping['fieldName']] = $reflProp; return $mapping; } public function mapAttachments($fieldName) { parent::mapAttachments($fieldName); $this->reflFields[$fieldName] = $this->reflClass->getProperty($fieldName); $this->reflFields[$fieldName]->setAccessible(true); } /** * Determines which fields get serialized. * * It is only serialized what is necessary for best unserialization performance. * That means any metadata properties that are not set or empty or simply have * their default value are NOT serialized. * * Parts that are also NOT serialized because they can not be properly unserialized: * - reflClass (ReflectionClass) * - reflFields (ReflectionProperty array) * * @return array The names of all the fields that should be serialized. */ public function __sleep() { // This metadata is always serialized/cached. $serialized = array( 'name', 'associationsMappings', 'fieldMappings', 'jsonNames', 'idGenerator', 'identifier', 'rootDocumentName', ); if ($this->inInheritanceHierachy) { $serialized[] = 'inInheritanceHierachy'; } if ($this->parentClasses) { $serialized[] = 'parentClasses'; } if ($this->isVersioned) { $serialized[] = 'isVersioned'; $serialized[] = 'versionField'; } if ($this->customRepositoryClassName) { $serialized[] = 'customRepositoryClassName'; } if ($this->hasAttachments) { $serialized[] = 'hasAttachments'; $serialized[] = 'attachmentField'; if ($this->attachmentDeclaredClass) { $serialized[] = 'attachmentDeclaredClass'; } } if ($this->isReadOnly) { $serialized[] = 'isReadOnly'; } if ($this->isMappedSuperclass) { $serialized[] = 'isMappedSuperclass'; } if ($this->indexed) { $serialized[] = 'indexed'; } if ($this->indexes) { $serialized[] = 'indexes'; } if ($this->lifecycleCallbacks) { $serialized[] = 'lifecycleCallbacks'; } return $serialized; } /** * Restores some state that can not be serialized/unserialized. * * @return void */ public function __wakeup() { // Restore ReflectionClass and properties $this->reflClass = new \ReflectionClass($this->name); $this->namespace = $this->reflClass->getNamespaceName(); foreach ($this->fieldMappings as $field => $mapping) { if (isset($mapping['declared'])) { $reflField = new \ReflectionProperty($mapping['declared'], $field); } else { $reflField = $this->reflClass->getProperty($field); } $reflField->setAccessible(true); $this->reflFields[$field] = $reflField; } foreach ($this->associationsMappings as $field => $mapping) { if (isset($mapping['declared'])) { $reflField = new \ReflectionProperty($mapping['declared'], $field); } else { $reflField = $this->reflClass->getProperty($field); } $reflField->setAccessible(true); $this->reflFields[$field] = $reflField; } if ($this->hasAttachments) { if ($this->attachmentDeclaredClass) { $reflField = new \ReflectionProperty($this->attachmentDeclaredClass, $this->attachmentField); } else { $reflField = $this->reflClass->getProperty($this->attachmentField); } $reflField->setAccessible(true); $this->reflFields[$this->attachmentField] = $reflField; } } /** * Creates a new instance of the mapped class, without invoking the constructor. * * @return object */ public function newInstance() { if ($this->prototype === null) { $this->prototype = unserialize( sprintf( 'O:%d:"%s":0:{}', strlen($this->name), $this->name ) ); } return clone $this->prototype; } /** * Gets the ReflectionClass instance of the mapped class. * * @return ReflectionClass */ public function getReflectionClass() { if ( ! $this->reflClass) { $this->reflClass = new ReflectionClass($this->name); } return $this->reflClass; } /** * Gets the ReflectionPropertys of the mapped class. * * @return array An array of ReflectionProperty instances. */ public function getReflectionProperties() { return $this->reflFields; } /** * Gets a ReflectionProperty for a specific field of the mapped class. * * @param string $name * @return ReflectionProperty */ public function getReflectionProperty($name) { return $this->reflFields[$name]; } /** * Sets the document identifier of a document. * * @param object $document * @param mixed $id */ public function setIdentifierValue($document, $id) { $this->reflFields[$this->identifier]->setValue($document, $id); } /** * Gets the document identifier. * * @param object $document * @return string $id */ public function getIdentifierValue($document) { return (string) $this->reflFields[$this->identifier]->getValue($document); } /** * Get identifier values of this document. * * Since CouchDB only allows exactly one identifier field this is a proxy * to {@see getIdentifierValue()} and returns an array with the identifier * field as a key. * * @param object $document * @return array */ public function getIdentifierValues($document) { return array($this->identifier => $this->getIdentifierValue($document)); } /** * Sets the specified field to the specified value on the given document. * * @param object $document * @param string $field * @param mixed $value */ public function setFieldValue($document, $field, $value) { $this->reflFields[$field]->setValue($document, $value); } /** * Gets the specified field's value off the given document. * * @param object $document * @param string $field */ public function getFieldValue($document, $field) { return $this->reflFields[$field]->getValue($document); } }
simplethings/couchdb-odm
lib/Doctrine/ODM/CouchDB/Mapping/ClassMetadata.php
PHP
mit
10,069
<!doctype html> <html class="default no-js"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>resolveSrv | picturepark-sdk-v1-widgets API</title> <meta name="description" content="Documentation for picturepark-sdk-v1-widgets API"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../assets/css/main.css"> </head> <body> <header> <div class="tsd-page-toolbar"> <div class="container"> <div class="table-wrap"> <div class="table-cell" id="tsd-search" data-index="../assets/js/search.json" data-base=".."> <div class="field"> <label for="tsd-search-field" class="tsd-widget search no-caption">Search</label> <input id="tsd-search-field" type="text" /> </div> <ul class="results"> <li class="state loading">Preparing search index...</li> <li class="state failure">The search index is not available</li> </ul> <a href="../index.html" class="title">picturepark-sdk-v1-widgets API</a> </div> <div class="table-cell" id="tsd-widgets"> <div id="tsd-filter"> <a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a> <div class="tsd-filter-group"> <div class="tsd-select" id="tsd-filter-visibility"> <span class="tsd-select-label">All</span> <ul class="tsd-select-list"> <li data-value="public">Public</li> <li data-value="protected">Public/Protected</li> <li data-value="private" class="selected">All</li> </ul> </div> <input type="checkbox" id="tsd-filter-inherited" checked /> <label class="tsd-widget" for="tsd-filter-inherited">Inherited</label> <input type="checkbox" id="tsd-filter-externals" checked /> <label class="tsd-widget" for="tsd-filter-externals">Externals</label> <input type="checkbox" id="tsd-filter-only-exported" /> <label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label> </div> </div> <a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a> </div> </div> </div> </div> <div class="tsd-page-title"> <div class="container"> <ul class="tsd-breadcrumb"> <li> <a href="../globals.html">Globals</a> </li> <li> <a href="_dns_.html">&quot;dns&quot;</a> </li> <li> <a href="_dns_.resolvesrv.html">resolveSrv</a> </li> </ul> <h1>Namespace resolveSrv</h1> </div> </div> </header> <div class="container container-main"> <div class="row"> <div class="col-8 col-content"> <section class="tsd-panel"> <h3 class="tsd-before-signature">Callable</h3> <ul class="tsd-signatures tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <li class="tsd-signature tsd-kind-icon">resolve<wbr>Srv<span class="tsd-signature-symbol">(</span>hostname<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">string</span>, callback<span class="tsd-signature-symbol">: </span><span class="tsd-signature-symbol">(</span>err<span class="tsd-signature-symbol">: </span><a href="../interfaces/nodejs.errnoexception.html" class="tsd-signature-type">ErrnoException</a><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">null</span>, addresses<span class="tsd-signature-symbol">: </span><a href="../interfaces/_dns_.srvrecord.html" class="tsd-signature-type">SrvRecord</a><span class="tsd-signature-symbol">[]</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol"> =&gt; </span><span class="tsd-signature-type">void</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">void</span></li> </ul> <ul class="tsd-descriptions"> <li class="tsd-description"> <aside class="tsd-sources"> <ul> <li>Defined in node_modules/@types/node/dns.d.ts:234</li> </ul> </aside> <h4 class="tsd-parameters-title">Parameters</h4> <ul class="tsd-parameters"> <li> <h5>hostname: <span class="tsd-signature-type">string</span></h5> </li> <li> <h5>callback: <span class="tsd-signature-symbol">(</span>err<span class="tsd-signature-symbol">: </span><a href="../interfaces/nodejs.errnoexception.html" class="tsd-signature-type">ErrnoException</a><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">null</span>, addresses<span class="tsd-signature-symbol">: </span><a href="../interfaces/_dns_.srvrecord.html" class="tsd-signature-type">SrvRecord</a><span class="tsd-signature-symbol">[]</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol"> =&gt; </span><span class="tsd-signature-type">void</span></h5> <ul class="tsd-parameters"> <li class="tsd-parameter-signature"> <ul class="tsd-signatures tsd-kind-type-literal"> <li class="tsd-signature tsd-kind-icon"><span class="tsd-signature-symbol">(</span>err<span class="tsd-signature-symbol">: </span><a href="../interfaces/nodejs.errnoexception.html" class="tsd-signature-type">ErrnoException</a><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">null</span>, addresses<span class="tsd-signature-symbol">: </span><a href="../interfaces/_dns_.srvrecord.html" class="tsd-signature-type">SrvRecord</a><span class="tsd-signature-symbol">[]</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">void</span></li> </ul> <ul class="tsd-descriptions"> <li class="tsd-description"> <h4 class="tsd-parameters-title">Parameters</h4> <ul class="tsd-parameters"> <li> <h5>err: <a href="../interfaces/nodejs.errnoexception.html" class="tsd-signature-type">ErrnoException</a><span class="tsd-signature-symbol"> | </span><span class="tsd-signature-type">null</span></h5> </li> <li> <h5>addresses: <a href="../interfaces/_dns_.srvrecord.html" class="tsd-signature-type">SrvRecord</a><span class="tsd-signature-symbol">[]</span></h5> </li> </ul> <h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">void</span></h4> </li> </ul> </li> </ul> </li> </ul> <h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">void</span></h4> </li> </ul> </section> <section class="tsd-panel-group tsd-index-group"> <h2>Index</h2> <section class="tsd-panel tsd-index-panel"> <div class="tsd-index-content"> <section class="tsd-index-section tsd-is-external"> <h3>Functions</h3> <ul class="tsd-index-list"> <li class="tsd-kind-function tsd-parent-kind-namespace tsd-is-external"><a href="_dns_.resolvesrv.html#__promisify__" class="tsd-kind-icon">__promisify__</a></li> </ul> </section> </div> </section> </section> <section class="tsd-panel-group tsd-member-group tsd-is-external"> <h2>Functions</h2> <section class="tsd-panel tsd-member tsd-kind-function tsd-parent-kind-namespace tsd-is-external"> <a name="__promisify__" class="tsd-anchor"></a> <h3>__promisify__</h3> <ul class="tsd-signatures tsd-kind-function tsd-parent-kind-namespace tsd-is-external"> <li class="tsd-signature tsd-kind-icon">__promisify__<span class="tsd-signature-symbol">(</span>hostname<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">string</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="../interfaces/promise.html" class="tsd-signature-type">Promise</a><span class="tsd-signature-symbol">&lt;</span><a href="../interfaces/_dns_.srvrecord.html" class="tsd-signature-type">SrvRecord</a><span class="tsd-signature-symbol">[]</span><span class="tsd-signature-symbol">&gt;</span></li> </ul> <ul class="tsd-descriptions"> <li class="tsd-description"> <aside class="tsd-sources"> <ul> <li>Defined in node_modules/@types/node/dns.d.ts:236</li> </ul> </aside> <h4 class="tsd-parameters-title">Parameters</h4> <ul class="tsd-parameters"> <li> <h5>hostname: <span class="tsd-signature-type">string</span></h5> </li> </ul> <h4 class="tsd-returns-title">Returns <a href="../interfaces/promise.html" class="tsd-signature-type">Promise</a><span class="tsd-signature-symbol">&lt;</span><a href="../interfaces/_dns_.srvrecord.html" class="tsd-signature-type">SrvRecord</a><span class="tsd-signature-symbol">[]</span><span class="tsd-signature-symbol">&gt;</span></h4> </li> </ul> </section> </section> </div> <div class="col-4 col-menu menu-sticky-wrap menu-highlight"> <nav class="tsd-navigation primary"> <ul> <li class="globals "> <a href="../globals.html"><em>Globals</em></a> </li> <li class="current tsd-kind-module tsd-is-external"> <a href="_dns_.html">&quot;dns&quot;</a> <ul> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.lookup.html">lookup</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.lookupservice.html">lookup<wbr>Service</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.promises.html">promises</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolve.html">resolve</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolve4.html">resolve4</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolve6.html">resolve6</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolveany.html">resolve<wbr>Any</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolvecname.html">resolve<wbr>Cname</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolvemx.html">resolve<wbr>Mx</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolvenaptr.html">resolve<wbr>Naptr</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolvens.html">resolve<wbr>Ns</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolveptr.html">resolve<wbr>Ptr</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolvesoa.html">resolve<wbr>Soa</a> </li> <li class="current tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolvesrv.html">resolve<wbr>Srv</a> </li> <li class=" tsd-kind-namespace tsd-parent-kind-module tsd-is-external"> <a href="_dns_.resolvetxt.html">resolve<wbr>Txt</a> </li> </ul> </li> </ul> </nav> <nav class="tsd-navigation secondary menu-sticky"> <ul class="before-current"> <li class=" tsd-kind-function tsd-parent-kind-namespace tsd-is-external"> <a href="_dns_.resolvesrv.html#__promisify__" class="tsd-kind-icon">__promisify__</a> </li> </ul> </nav> </div> </div> </div> <footer class="with-border-bottom"> <div class="container"> <h2>Legend</h2> <div class="tsd-legend-group"> <ul class="tsd-legend"> <li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li> </ul> </div> </div> </footer> <div class="container tsd-generator"> <p>Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p> </div> <div class="overlay"></div> <script src="../assets/js/main.js"></script> </body> </html>
Picturepark/Picturepark.SDK.TypeScript
docs/picturepark-sdk-v1-widgets/api/modules/_dns_.resolvesrv.html
HTML
mit
12,294