text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
package flex.messaging.log;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class LogTest extends TestCase
{
public LogTest(String name)
{
super(name);
}
private TestingTarget testTarget;
public static Test suite()
{
// Make sure the logger is reset before starting the tests.
Log.clear();
// Explicitly specify the order of the tests.
TestSuite suite = new TestSuite();
suite.addTest(new LogTest("testInitialLogState"));
suite.addTest(new LogTest("testLogStateAfterAddingTarget"));
suite.addTest(new LogTest("testLogStateAfterAddRemoveTarget"));
suite.addTest(new LogTest("testAddTargetGetLogger"));
suite.addTest(new LogTest("testAddTargetGetLoggerThenRemoveFilter"));
suite.addTest(new LogTest("testGetLoggerAddTarget"));
suite.addTest(new LogTest("testLogAddFilterNull"));
suite.addTest(new LogTest("testLogSetFilterNull"));
return suite;
}
protected void setUp() throws Exception
{
Log.createLog();
// Init a ConsoleLogTarget for testing purposes.
testTarget = new TestingTarget(); // Defaults to a log level of none with no filters.
super.setUp();
}
protected void tearDown() throws Exception
{
Log.flush();
super.tearDown();
}
public void testInitialLogState()
{
Assert.assertEquals(Log.getTargetLevel(), LogEvent.NONE);
Assert.assertTrue(Log.getTargets().size() == 0);
}
public void testLogStateAfterAddingTarget()
{
Assert.assertEquals(testTarget.getLevel(), LogEvent.ERROR);
testTarget.setLevel(LogEvent.FATAL);
Assert.assertEquals(testTarget.getLevel(), LogEvent.FATAL);
Assert.assertTrue(testTarget.getFilters().size() == 1);
Log.addTarget(testTarget);
Assert.assertEquals(Log.getTargetLevel(), LogEvent.FATAL);
Assert.assertTrue(Log.getTargets().size() == 1);
}
public void testLogStateAfterAddRemoveTarget()
{
testTarget.setLevel(LogEvent.FATAL);
Log.addTarget(testTarget);
Log.removeTarget(testTarget);
Assert.assertEquals(Log.getTargetLevel(), LogEvent.NONE);
Assert.assertTrue(Log.getTargets().size() == 0);
}
public void testAddTargetGetLogger()
{
testTarget.setLevel(LogEvent.ALL);
testTarget.addFilter("*");
Assert.assertTrue(testTarget.getFilters().size() == 1);
Log.addTarget(testTarget);
Log.getLogger("foo");
Assert.assertTrue(testTarget.loggerCount == 1);
Log.getLogger("bar");
Assert.assertTrue(testTarget.loggerCount == 2);
Log.removeTarget(testTarget);
Assert.assertTrue(testTarget.loggerCount == 0);
testTarget.removeFilter("*");
Assert.assertTrue(testTarget.getFilters().size() == 0);
}
public void testAddTargetGetLoggerThenRemoveFilter()
{
testTarget.setLevel(LogEvent.ALL);
testTarget.addFilter("foo.*");
Assert.assertTrue(testTarget.getFilters().size() == 1);
Log.addTarget(testTarget);
Log.getLogger("foo.bar");
Assert.assertTrue(testTarget.loggerCount == 1);
testTarget.removeFilter("foo.*");
Assert.assertTrue(testTarget.loggerCount == 0);
}
public void testGetLoggerAddTarget()
{
// First, remove the default "*" filter.
testTarget.removeFilter("*");
Log.getLogger("foo");
Log.getLogger("bar");
Log.getLogger("baz"); // Shouldn't be added to the target later.
testTarget.setLevel(LogEvent.ALL);
Log.addTarget(testTarget);
Assert.assertTrue(testTarget.loggerCount == 0);
// Now add filters.
List<String> filters = new ArrayList<String>();
filters.add("foo");
filters.add("bar");
testTarget.setFilters(filters);
Assert.assertTrue(testTarget.loggerCount == 2);
}
public void testLogAddFilterNull()
{
// First, remove the default "*" filter.
testTarget.removeFilter("*");
Log.getLogger("foo");
testTarget.setLevel(LogEvent.ALL);
Log.addTarget(testTarget);
Assert.assertTrue(testTarget.loggerCount == 0);
// Now null filters.
List filters = new ArrayList();
testTarget.addFilter(null);
testTarget.setFilters(filters);
Assert.assertTrue(testTarget.loggerCount == 1);
}
public void testLogSetFilterNull()
{
// First, remove the default "*" filter.
testTarget.removeFilter("*");
Log.getLogger("foo");
testTarget.setLevel(LogEvent.ALL);
Log.addTarget(testTarget);
Assert.assertTrue(testTarget.loggerCount == 0);
// Now null filters.
List filters = new ArrayList();
testTarget.setFilters(filters);
Assert.assertTrue(testTarget.loggerCount == 1);
}
}
| {'content_hash': '960265a5b31d1d8efcd01fb4d8d78851', 'timestamp': '', 'source': 'github', 'line_count': 163, 'max_line_length': 93, 'avg_line_length': 32.65644171779141, 'alnum_prop': 0.6131880518504602, 'repo_name': 'azureplus/flex-blazeds', 'id': '215644003abfc3cf06ecbf226233662d4a7709c5', 'size': '6124', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'modules/testsuite/src/test/java/flex/messaging/log/LogTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ActionScript', 'bytes': '485387'}, {'name': 'Batchfile', 'bytes': '13682'}, {'name': 'CSS', 'bytes': '29281'}, {'name': 'HTML', 'bytes': '257992'}, {'name': 'Java', 'bytes': '4351360'}, {'name': 'JavaScript', 'bytes': '787627'}, {'name': 'Shell', 'bytes': '17775'}, {'name': 'XSLT', 'bytes': '104096'}]} |
<?php
namespace Magento\Translation\Model\ResourceModel;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\App\Config;
use Magento\Translation\App\Config\Type\Translation;
class Translate extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb implements
\Magento\Framework\Translate\ResourceInterface
{
/**
* @var \Magento\Framework\App\ScopeResolverInterface
*/
protected $scopeResolver;
/**
* @var null|string
*/
protected $scope;
/**
* @var Config
*/
private $appConfig;
/**
* @var DeploymentConfig
*/
private $deployedConfig;
/**
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
* @param \Magento\Framework\App\ScopeResolverInterface $scopeResolver
* @param string $connectionName
* @param null|string $scope
*/
public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Magento\Framework\App\ScopeResolverInterface $scopeResolver,
$connectionName = null,
$scope = null
) {
$this->scopeResolver = $scopeResolver;
$this->scope = $scope;
parent::__construct($context, $connectionName);
}
/**
* Define main table
*
* @return void
*/
protected function _construct()
{
$this->_init('translation', 'key_id');
}
/**
* Retrieve translation array for store / locale code
*
* @param int $storeId
* @param string $locale
* @return array
*/
public function getTranslationArray($storeId = null, $locale = null)
{
if ($storeId === null) {
$storeId = $this->getStoreId();
}
$locale = (string) $locale;
$data = $this->getAppConfig()->get(
Translation::CONFIG_TYPE,
$locale . '/' . $this->getStoreCode($storeId),
[]
);
$connection = $this->getConnection();
if ($connection) {
$select = $connection->select()
->from($this->getMainTable(), ['string', 'translate'])
->where('store_id IN (0 , :store_id)')
->where('locale = :locale')
->order('store_id');
$bind = [':locale' => $locale, ':store_id' => $storeId];
$dbData = $connection->fetchPairs($select, $bind);
$data = array_replace($data, $dbData);
}
return $data;
}
/**
* Retrieve translations array by strings
*
* @param array $strings
* @param int|null $storeId
* @return array
*/
public function getTranslationArrayByStrings(array $strings, $storeId = null)
{
if ($storeId === null) {
$storeId = $this->getStoreId();
}
$connection = $this->getConnection();
if (!$connection) {
return [];
}
if (empty($strings)) {
return [];
}
$bind = [':store_id' => $storeId];
$select = $connection->select()
->from($this->getMainTable(), ['string', 'translate'])
->where('string IN (?)', $strings)
->where('store_id = :store_id');
return $connection->fetchPairs($select, $bind);
}
/**
* Retrieve table checksum
*
* @return int
*/
public function getMainChecksum()
{
return $this->getChecksum($this->getMainTable());
}
/**
* Get connection
*
* @return \Magento\Framework\DB\Adapter\AdapterInterface|false
*/
public function getConnection()
{
if (!$this->getDeployedConfig()->isDbAvailable()) {
return false;
}
return parent::getConnection();
}
/**
* Retrieve current store identifier
*
* @return int
*/
protected function getStoreId()
{
return $this->scopeResolver->getScope($this->scope)->getId();
}
/**
* Retrieve store code by store id
*
* @param int $storeId
* @return string
*/
private function getStoreCode($storeId)
{
return $this->scopeResolver->getScope($storeId)->getCode();
}
/**
* @deprecated
* @return DeploymentConfig
*/
private function getDeployedConfig()
{
if ($this->deployedConfig === null) {
$this->deployedConfig = ObjectManager::getInstance()->get(DeploymentConfig::class);
}
return $this->deployedConfig;
}
/**
* @deprecated
* @return Config
*/
private function getAppConfig()
{
if ($this->appConfig === null) {
$this->appConfig = ObjectManager::getInstance()->get(Config::class);
}
return $this->appConfig;
}
}
| {'content_hash': 'af98884b803d416de54f3d429c6d692e', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 95, 'avg_line_length': 25.282722513089006, 'alnum_prop': 0.5520811762269621, 'repo_name': 'j-froehlich/magento2_wk', 'id': '072605d3ea76dd7ef496d2b6043ae229db6f67b2', 'size': '4937', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'vendor/magento/module-translation/Model/ResourceModel/Translate.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '13636'}, {'name': 'CSS', 'bytes': '2076720'}, {'name': 'HTML', 'bytes': '6151072'}, {'name': 'JavaScript', 'bytes': '2488727'}, {'name': 'PHP', 'bytes': '12466046'}, {'name': 'Shell', 'bytes': '6088'}, {'name': 'XSLT', 'bytes': '19979'}]} |
package filodb.core.reprojector
import com.typesafe.config.ConfigFactory
import org.velvia.filo.{RowReader, TupleRowReader}
import scala.concurrent.Future
import filodb.core._
import filodb.core.metadata.{Column, Dataset}
import filodb.core.columnstore.SegmentSpec
import org.scalatest.{FunSpec, Matchers, BeforeAndAfter}
class SchedulerSpec extends FunSpec with Matchers with BeforeAndAfter {
import SegmentSpec._
import MemTable._
val keyRange = KeyRange("dataset", Dataset.DefaultPartitionKey, 0L, 10000L)
var mTable: MemTable = _
var reprojections: Seq[(Types.TableName, Int)] = Nil
val flushPolicy = new NumRowsFlushPolicy(100L)
var scheduler: Scheduler = _
before {
mTable = new MapDBMemTable(ConfigFactory.load("application_test.conf"))
reprojections = Nil
scheduler = new Scheduler(mTable, testReprojector, flushPolicy, maxTasks = 2)
}
after {
mTable.close()
}
val schemaWithPartCol = schema ++ Seq(
Column("league", "dataset", 0, Column.ColumnType.StringColumn)
)
val namesWithPartCol = (0 until 50).flatMap { partNum =>
names.map { t => (t._1, t._2, t._3, Some(partNum.toString)) }
}
private def ingestRows(datasetName: String, numRows: Int) {
val myDataset = dataset.copy(partitionColumn = "league", name = datasetName)
mTable.setupIngestion(myDataset, schemaWithPartCol, 0) should equal (SetupDone)
val resp = mTable.ingestRows(datasetName, 0, namesWithPartCol.take(numRows).map(TupleRowReader))
resp should equal (Ingested)
}
import RowReader._
val testReprojector = new Reprojector {
def reproject[K: TypedFieldExtractor](memTable: MemTable, setup: IngestionSetup, version: Int):
Future[Seq[String]] = {
reprojections = reprojections :+ (setup.dataset.name -> version)
Future.successful(Seq("Success"))
}
}
it("should do nothing if memtable is empty") {
scheduler.runOnce()
scheduler.tasks should have size (0)
reprojections should equal (Nil)
}
it("should do nothing if datasets not reached limit yet") {
ingestRows("A", 50)
ingestRows("B", 49)
scheduler.runOnce()
scheduler.tasks should have size (0)
reprojections should equal (Nil)
}
it("should pick largest dataset for flushing, and keep flush going") {
ingestRows("A", 51)
ingestRows("B", 49)
// Should schedule flush of "A"
scheduler.runOnce()
scheduler.tasks should have size (1)
reprojections should equal (Seq(("A", 0)))
mTable.flushingDatasets should equal (Seq((("A", 0), 51)))
// Add some new rows to A active
mTable.ingestRows("A", 0, namesWithPartCol.take(10).map(TupleRowReader))
// Should continue flush of "A", but recommend "B" since limit not reached
// Also tests that "A" is not re-recommended since it is already flushing (if it did try,
// then would not be able to recommend flushing B)
reprojections = Nil
scheduler.runOnce()
scheduler.tasks should have size (2)
reprojections should equal (Seq(("A", 0), ("B", 0)))
mTable.flushingDatasets.toSet should equal (Set((("A", 0), 51), (("B", 0), 49)))
mTable.allNumRows(Active, true) should equal (Seq((("A", 0), 10)))
}
it("should limit flushes if reached max task limit") {
ingestRows("A", 30)
ingestRows("B", 40)
ingestRows("C", 50)
// Should schedule flush of "C"
scheduler.runOnce()
scheduler.tasks should have size (1)
reprojections should equal (Seq(("C", 0)))
// Should reschedule "C", then flush "B"
reprojections = Nil
scheduler.runOnce()
scheduler.tasks should have size (2)
reprojections should equal (Seq(("C", 0), ("B", 0)))
// Now, should reschedule "C" and "B", then reach limit and not flush anymore.
reprojections = Nil
scheduler.runOnce()
scheduler.tasks should have size (2)
reprojections should equal (Seq(("C", 0), ("B", 0)))
mTable.flushingDatasets.toSet should equal (Set((("B", 0), 40), (("C", 0), 50)))
}
it("flush() should initiate flush even if datasets not reached limit yet") {
ingestRows("A", 50)
ingestRows("B", 49)
scheduler.flush("B", 0) should equal (Scheduler.Flushed)
scheduler.tasks should have size (1)
reprojections should equal (Seq(("B", 0)))
}
}
| {'content_hash': '097759d2acd80804faf4b4e6468129d7', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 100, 'avg_line_length': 33.62992125984252, 'alnum_prop': 0.6801685787871693, 'repo_name': 'YanjieGao/FiloDB', 'id': '1584511761750b7d86c52a5a866b9d17f5ecfb8e', 'size': '4271', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/src/test/scala/filodb.core/reprojector/SchedulerSpec.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Scala', 'bytes': '223100'}, {'name': 'Shell', 'bytes': '852'}]} |
package com.coolweather.android.db;
import org.litepal.crud.DataSupport;
/**
* Created by szz on 2017/8/5.
*/
public class City extends DataSupport {
private int id;
private String cityName;
private int cityCode;
private int provinceId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
| {'content_hash': '2850a2ccb20fe545b28e919a443f1adc', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 47, 'avg_line_length': 16.76, 'alnum_prop': 0.6097852028639618, 'repo_name': 'SZzzZs/coolweather', 'id': '02f4582ba55df51edde51fa17ae4490587d2ff7f', 'size': '838', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/coolweather/android/db/City.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '33153'}]} |
<div class="commune_descr limited">
<p>
Chaumeil est
un village
situé dans le département de Corrèze en Limousin. On dénombrait 158 habitants en 2008.</p>
<p>La commune compte quelques aménagements, elle propose entre autres un centre d'équitation.</p>
<p>Si vous envisagez de venir habiter à Chaumeil, vous pourrez aisément trouver une maison à acheter. </p>
<p>Le parc de logements, à Chaumeil, était réparti en 2011 en neuf appartements et 193 maisons soit
un marché plutôt équilibré.</p>
<p>À proximité de Chaumeil sont positionnées géographiquement les communes de
<a href="{{VLROOT}}/immobilier/saint-geniez-o-merle_19205/">Saint-Geniez-ô-Merle</a> à 1 km, 104 habitants,
<a href="{{VLROOT}}/immobilier/hautefage_19091/">Hautefage</a> localisée à 4 km, 305 habitants,
<a href="{{VLROOT}}/immobilier/servieres-le-chateau_19258/">Servières-le-Château</a> située à 6 km, 678 habitants,
<a href="{{VLROOT}}/immobilier/saint-martial-entraygues_19221/">Saint-Martial-Entraygues</a> localisée à 7 km, 85 habitants,
<a href="{{VLROOT}}/immobilier/saint-privat_19237/">Saint-Privat</a> à 7 km, 1 105 habitants,
<a href="{{VLROOT}}/immobilier/cros-de-montvert_15057/">Cros-de-Montvert</a> localisée à 7 km, 221 habitants,
entre autres. De plus, Chaumeil est située à seulement 26 km de <a href="{{VLROOT}}/immobilier/mauriac_15120/">Mauriac</a>.</p>
</div>
| {'content_hash': 'e4860490268cf8296c6b1d7d486dd5c9', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 133, 'avg_line_length': 78.44444444444444, 'alnum_prop': 0.7436260623229461, 'repo_name': 'donaldinou/frontend', 'id': 'db2829c184f37876f8af2f267af299e01d2a9f52', 'size': '1447', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Viteloge/CoreBundle/Resources/descriptions/19051.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3073'}, {'name': 'CSS', 'bytes': '111338'}, {'name': 'HTML', 'bytes': '58634405'}, {'name': 'JavaScript', 'bytes': '88564'}, {'name': 'PHP', 'bytes': '841919'}]} |
package io.atomix.core.tree;
/**
* An exception to be thrown when a node cannot be removed normally because
* it does not exist or because it is not a leaf node.
*/
public class IllegalDocumentModificationException extends DocumentException {
public IllegalDocumentModificationException() {
}
public IllegalDocumentModificationException(String message) {
super(message);
}
public IllegalDocumentModificationException(String message,
Throwable cause) {
super(message, cause);
}
public IllegalDocumentModificationException(Throwable cause) {
super(cause);
}
}
| {'content_hash': 'adc02d9885855fba8ec2d27a0fc238d9', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 77, 'avg_line_length': 25.64, 'alnum_prop': 0.7082683307332294, 'repo_name': 'atomix/atomix', 'id': 'b3bb2ed85c8db67db3d0b738d4b6f8e9595560cd', 'size': '1258', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/io/atomix/core/tree/IllegalDocumentModificationException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '6083318'}, {'name': 'Shell', 'bytes': '2233'}]} |
namespace {
// The height of the arrow, and the width will be about twice the height.
const int kArrowSize = 8;
// Number of pixels to the middle of the arrow from the close edge of the
// window.
const int kArrowX = 18;
// Number of pixels between the tip of the arrow and the region we're
// pointing to.
const int kArrowToContentPadding = -4;
// We draw flat diagonal corners, each corner is an NxN square.
const int kCornerSize = 3;
// The amount of padding (in pixels) from the top of |toplevel_window_| to the
// top of |window_| when fixed positioning is used.
const int kFixedPositionPaddingEnd = 10;
const int kFixedPositionPaddingTop = 5;
const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xff, 0xff, 0xff);
const GdkColor kFrameColor = GDK_COLOR_RGB(0x63, 0x63, 0x63);
// Helper functions that encapsulate arrow locations.
bool HasArrow(BubbleGtk::FrameStyle frame_style) {
return frame_style != BubbleGtk::FLOAT_BELOW_RECT &&
frame_style != BubbleGtk::CENTER_OVER_RECT &&
frame_style != BubbleGtk::FIXED_TOP_LEFT &&
frame_style != BubbleGtk::FIXED_TOP_RIGHT;
}
bool IsArrowLeft(BubbleGtk::FrameStyle frame_style) {
return frame_style == BubbleGtk::ANCHOR_TOP_LEFT ||
frame_style == BubbleGtk::ANCHOR_BOTTOM_LEFT;
}
bool IsArrowMiddle(BubbleGtk::FrameStyle frame_style) {
return frame_style == BubbleGtk::ANCHOR_TOP_MIDDLE ||
frame_style == BubbleGtk::ANCHOR_BOTTOM_MIDDLE;
}
bool IsArrowRight(BubbleGtk::FrameStyle frame_style) {
return frame_style == BubbleGtk::ANCHOR_TOP_RIGHT ||
frame_style == BubbleGtk::ANCHOR_BOTTOM_RIGHT;
}
bool IsArrowTop(BubbleGtk::FrameStyle frame_style) {
return frame_style == BubbleGtk::ANCHOR_TOP_LEFT ||
frame_style == BubbleGtk::ANCHOR_TOP_MIDDLE ||
frame_style == BubbleGtk::ANCHOR_TOP_RIGHT;
}
bool IsArrowBottom(BubbleGtk::FrameStyle frame_style) {
return frame_style == BubbleGtk::ANCHOR_BOTTOM_LEFT ||
frame_style == BubbleGtk::ANCHOR_BOTTOM_MIDDLE ||
frame_style == BubbleGtk::ANCHOR_BOTTOM_RIGHT;
}
bool IsFixed(BubbleGtk::FrameStyle frame_style) {
return frame_style == BubbleGtk::FIXED_TOP_LEFT ||
frame_style == BubbleGtk::FIXED_TOP_RIGHT;
}
BubbleGtk::FrameStyle AdjustFrameStyleForLocale(
BubbleGtk::FrameStyle frame_style) {
// Only RTL requires more work.
if (!base::i18n::IsRTL())
return frame_style;
switch (frame_style) {
// These don't flip.
case BubbleGtk::ANCHOR_TOP_MIDDLE:
case BubbleGtk::ANCHOR_BOTTOM_MIDDLE:
case BubbleGtk::FLOAT_BELOW_RECT:
case BubbleGtk::CENTER_OVER_RECT:
return frame_style;
// These do flip.
case BubbleGtk::ANCHOR_TOP_LEFT:
return BubbleGtk::ANCHOR_TOP_RIGHT;
case BubbleGtk::ANCHOR_TOP_RIGHT:
return BubbleGtk::ANCHOR_TOP_LEFT;
case BubbleGtk::ANCHOR_BOTTOM_LEFT:
return BubbleGtk::ANCHOR_BOTTOM_RIGHT;
case BubbleGtk::ANCHOR_BOTTOM_RIGHT:
return BubbleGtk::ANCHOR_BOTTOM_LEFT;
case BubbleGtk::FIXED_TOP_LEFT:
return BubbleGtk::FIXED_TOP_RIGHT;
case BubbleGtk::FIXED_TOP_RIGHT:
return BubbleGtk::FIXED_TOP_LEFT;
}
NOTREACHED();
return BubbleGtk::ANCHOR_TOP_LEFT;
}
} // namespace
// static
BubbleGtk* BubbleGtk::Show(GtkWidget* anchor_widget,
const gfx::Rect* rect,
GtkWidget* content,
FrameStyle frame_style,
int attribute_flags,
GtkThemeService* provider,
BubbleDelegateGtk* delegate) {
BubbleGtk* bubble = new BubbleGtk(provider,
AdjustFrameStyleForLocale(frame_style),
attribute_flags);
bubble->Init(anchor_widget, rect, content, attribute_flags);
bubble->set_delegate(delegate);
return bubble;
}
BubbleGtk::BubbleGtk(GtkThemeService* provider,
FrameStyle frame_style,
int attribute_flags)
: delegate_(NULL),
window_(NULL),
theme_service_(provider),
accel_group_(gtk_accel_group_new()),
toplevel_window_(NULL),
anchor_widget_(NULL),
mask_region_(NULL),
requested_frame_style_(frame_style),
actual_frame_style_(ANCHOR_TOP_LEFT),
match_system_theme_(attribute_flags & MATCH_SYSTEM_THEME),
grab_input_(attribute_flags & GRAB_INPUT),
closed_by_escape_(false) {
}
BubbleGtk::~BubbleGtk() {
// Notify the delegate that we're about to close. This gives the chance
// to save state / etc from the hosted widget before it's destroyed.
if (delegate_)
delegate_->BubbleClosing(this, closed_by_escape_);
g_object_unref(accel_group_);
if (mask_region_)
gdk_region_destroy(mask_region_);
}
void BubbleGtk::Init(GtkWidget* anchor_widget,
const gfx::Rect* rect,
GtkWidget* content,
int attribute_flags) {
// If there is a current grab widget (menu, other bubble, etc.), hide it.
GtkWidget* current_grab_widget = gtk_grab_get_current();
if (current_grab_widget)
gtk_widget_hide(current_grab_widget);
DCHECK(!window_);
anchor_widget_ = anchor_widget;
toplevel_window_ = gtk_widget_get_toplevel(anchor_widget_);
DCHECK(gtk_widget_is_toplevel(toplevel_window_));
rect_ = rect ? *rect : gtk_util::WidgetBounds(anchor_widget);
// Using a TOPLEVEL window may cause placement issues with certain WMs but it
// is necessary to be able to focus the window.
window_ = gtk_window_new(attribute_flags & POPUP_WINDOW ?
GTK_WINDOW_POPUP : GTK_WINDOW_TOPLEVEL);
gtk_widget_set_app_paintable(window_, TRUE);
// Resizing is handled by the program, not user.
gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
if (!(attribute_flags & NO_ACCELERATORS)) {
// Attach all of the accelerators to the bubble.
for (BubbleAcceleratorsGtk::const_iterator
i(BubbleAcceleratorsGtk::begin());
i != BubbleAcceleratorsGtk::end();
++i) {
gtk_accel_group_connect(accel_group_,
i->keyval,
i->modifier_type,
GtkAccelFlags(0),
g_cclosure_new(G_CALLBACK(&OnGtkAcceleratorThunk),
this,
NULL));
}
gtk_window_add_accel_group(GTK_WINDOW(window_), accel_group_);
}
// |requested_frame_style_| is used instead of |actual_frame_style_| here
// because |actual_frame_style_| is only correct after calling
// |UpdateFrameStyle()|. Unfortunately, |UpdateFrameStyle()| requires knowing
// the size of |window_| (which happens later on).
int arrow_padding = HasArrow(requested_frame_style_) ? kArrowSize : 0;
GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
gtk_alignment_set_padding(GTK_ALIGNMENT(alignment), arrow_padding, 0, 0, 0);
gtk_container_add(GTK_CONTAINER(alignment), content);
gtk_container_add(GTK_CONTAINER(window_), alignment);
// GtkWidget only exposes the bitmap mask interface. Use GDK to more
// efficently mask a GdkRegion. Make sure the window is realized during
// OnSizeAllocate, so the mask can be applied to the GdkWindow.
gtk_widget_realize(window_);
UpdateFrameStyle(true); // Force move and reshape.
StackWindow();
gtk_widget_add_events(window_, GDK_BUTTON_PRESS_MASK);
// Connect during the bubbling phase so the border is always on top.
signals_.ConnectAfter(window_, "expose-event",
G_CALLBACK(OnExposeThunk), this);
signals_.Connect(window_, "size-allocate", G_CALLBACK(OnSizeAllocateThunk),
this);
signals_.Connect(window_, "button-press-event",
G_CALLBACK(OnButtonPressThunk), this);
signals_.Connect(window_, "destroy", G_CALLBACK(OnDestroyThunk), this);
signals_.Connect(window_, "hide", G_CALLBACK(OnHideThunk), this);
if (grab_input_) {
signals_.Connect(window_, "grab-broken-event",
G_CALLBACK(OnGrabBrokenThunk), this);
}
// If the toplevel window is being used as the anchor, then the signals below
// are enough to keep us positioned correctly.
if (anchor_widget_ != toplevel_window_) {
signals_.Connect(anchor_widget_, "size-allocate",
G_CALLBACK(OnAnchorAllocateThunk), this);
signals_.Connect(anchor_widget_, "destroy",
G_CALLBACK(OnAnchorDestroyThunk), this);
}
signals_.Connect(toplevel_window_, "configure-event",
G_CALLBACK(OnToplevelConfigureThunk), this);
signals_.Connect(toplevel_window_, "unmap-event",
G_CALLBACK(OnToplevelUnmapThunk), this);
signals_.Connect(window_, "destroy",
G_CALLBACK(OnToplevelDestroyThunk), this);
gtk_widget_show_all(window_);
if (grab_input_)
gtk_grab_add(window_);
GrabPointerAndKeyboard();
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
content::Source<ThemeService>(theme_service_));
theme_service_->InitThemesFor(this);
}
// NOTE: This seems a bit overcomplicated, but it requires a bunch of careful
// fudging to get the pixels rasterized exactly where we want them, the arrow to
// have a 1 pixel point, etc.
// TODO(deanm): Windows draws with Skia and uses some PNG images for the
// corners. This is a lot more work, but they get anti-aliasing.
// static
std::vector<GdkPoint> BubbleGtk::MakeFramePolygonPoints(
FrameStyle frame_style,
int width,
int height,
FrameType type) {
using gtk_util::MakeBidiGdkPoint;
std::vector<GdkPoint> points;
int top_arrow_size = IsArrowTop(frame_style) ? kArrowSize : 0;
int bottom_arrow_size = IsArrowBottom(frame_style) ? kArrowSize : 0;
bool on_left = IsArrowLeft(frame_style);
// If we're stroking the frame, we need to offset some of our points by 1
// pixel. We do this when we draw horizontal lines that are on the bottom or
// when we draw vertical lines that are closer to the end (where "end" is the
// right side for ANCHOR_TOP_LEFT).
int y_off = type == FRAME_MASK ? 0 : -1;
// We use this one for arrows located on the left.
int x_off_l = on_left ? y_off : 0;
// We use this one for RTL.
int x_off_r = !on_left ? -y_off : 0;
// Top left corner.
points.push_back(MakeBidiGdkPoint(
x_off_r, top_arrow_size + kCornerSize - 1, width, on_left));
points.push_back(MakeBidiGdkPoint(
kCornerSize + x_off_r - 1, top_arrow_size, width, on_left));
// The top arrow.
if (top_arrow_size) {
int arrow_x = frame_style == ANCHOR_TOP_MIDDLE ? width / 2 : kArrowX;
points.push_back(MakeBidiGdkPoint(
arrow_x - top_arrow_size + x_off_r, top_arrow_size, width, on_left));
points.push_back(MakeBidiGdkPoint(
arrow_x + x_off_r, 0, width, on_left));
points.push_back(MakeBidiGdkPoint(
arrow_x + 1 + x_off_l, 0, width, on_left));
points.push_back(MakeBidiGdkPoint(
arrow_x + top_arrow_size + 1 + x_off_l, top_arrow_size,
width, on_left));
}
// Top right corner.
points.push_back(MakeBidiGdkPoint(
width - kCornerSize + 1 + x_off_l, top_arrow_size, width, on_left));
points.push_back(MakeBidiGdkPoint(
width + x_off_l, top_arrow_size + kCornerSize - 1, width, on_left));
// Bottom right corner.
points.push_back(MakeBidiGdkPoint(
width + x_off_l, height - bottom_arrow_size - kCornerSize,
width, on_left));
points.push_back(MakeBidiGdkPoint(
width - kCornerSize + x_off_r, height - bottom_arrow_size + y_off,
width, on_left));
// The bottom arrow.
if (bottom_arrow_size) {
int arrow_x = frame_style == ANCHOR_BOTTOM_MIDDLE ?
width / 2 : kArrowX;
points.push_back(MakeBidiGdkPoint(
arrow_x + bottom_arrow_size + 1 + x_off_l,
height - bottom_arrow_size + y_off,
width,
on_left));
points.push_back(MakeBidiGdkPoint(
arrow_x + 1 + x_off_l, height + y_off, width, on_left));
points.push_back(MakeBidiGdkPoint(
arrow_x + x_off_r, height + y_off, width, on_left));
points.push_back(MakeBidiGdkPoint(
arrow_x - bottom_arrow_size + x_off_r,
height - bottom_arrow_size + y_off,
width,
on_left));
}
// Bottom left corner.
points.push_back(MakeBidiGdkPoint(
kCornerSize + x_off_l, height -bottom_arrow_size + y_off,
width, on_left));
points.push_back(MakeBidiGdkPoint(
x_off_r, height - bottom_arrow_size - kCornerSize, width, on_left));
return points;
}
BubbleGtk::FrameStyle BubbleGtk::GetAllowedFrameStyle(
FrameStyle preferred_style,
int arrow_x,
int arrow_y,
int width,
int height) {
if (IsFixed(preferred_style))
return preferred_style;
const int screen_width = gdk_screen_get_width(gdk_screen_get_default());
const int screen_height = gdk_screen_get_height(gdk_screen_get_default());
// Choose whether to show the bubble above or below the specified location.
const bool prefer_top_arrow = IsArrowTop(preferred_style) ||
preferred_style == FLOAT_BELOW_RECT;
// The bleed measures the amount of bubble that would be shown offscreen.
const int top_arrow_bleed =
std::max(height + kArrowSize + arrow_y - screen_height, 0);
const int bottom_arrow_bleed = std::max(height + kArrowSize - arrow_y, 0);
FrameStyle frame_style_none = FLOAT_BELOW_RECT;
FrameStyle frame_style_left = ANCHOR_TOP_LEFT;
FrameStyle frame_style_middle = ANCHOR_TOP_MIDDLE;
FrameStyle frame_style_right = ANCHOR_TOP_RIGHT;
if ((prefer_top_arrow && (top_arrow_bleed > bottom_arrow_bleed)) ||
(!prefer_top_arrow && (top_arrow_bleed >= bottom_arrow_bleed))) {
frame_style_none = CENTER_OVER_RECT;
frame_style_left = ANCHOR_BOTTOM_LEFT;
frame_style_middle = ANCHOR_BOTTOM_MIDDLE;
frame_style_right = ANCHOR_BOTTOM_RIGHT;
}
if (!HasArrow(preferred_style))
return frame_style_none;
if (IsArrowMiddle(preferred_style))
return frame_style_middle;
// Choose whether to show the bubble left or right of the specified location.
const bool prefer_left_arrow = IsArrowLeft(preferred_style);
// The bleed measures the amount of bubble that would be shown offscreen.
const int left_arrow_bleed =
std::max(width + arrow_x - kArrowX - screen_width, 0);
const int right_arrow_bleed = std::max(width - arrow_x - kArrowX, 0);
// Use the preferred location if it doesn't bleed more than the opposite side.
return ((prefer_left_arrow && (left_arrow_bleed <= right_arrow_bleed)) ||
(!prefer_left_arrow && (left_arrow_bleed < right_arrow_bleed))) ?
frame_style_left : frame_style_right;
}
bool BubbleGtk::UpdateFrameStyle(bool force_move_and_reshape) {
if (!toplevel_window_ || !anchor_widget_)
return false;
gint toplevel_x = 0, toplevel_y = 0;
gdk_window_get_position(gtk_widget_get_window(toplevel_window_),
&toplevel_x, &toplevel_y);
int offset_x, offset_y;
gtk_widget_translate_coordinates(anchor_widget_, toplevel_window_,
rect_.x(), rect_.y(), &offset_x, &offset_y);
FrameStyle old_frame_style = actual_frame_style_;
GtkAllocation allocation;
gtk_widget_get_allocation(window_, &allocation);
actual_frame_style_ = GetAllowedFrameStyle(
requested_frame_style_,
toplevel_x + offset_x + (rect_.width() / 2), // arrow_x
toplevel_y + offset_y,
allocation.width,
allocation.height);
if (force_move_and_reshape || actual_frame_style_ != old_frame_style) {
UpdateWindowShape();
MoveWindow();
// We need to redraw the entire window to repaint its border.
gtk_widget_queue_draw(window_);
return true;
}
return false;
}
void BubbleGtk::UpdateWindowShape() {
if (mask_region_) {
gdk_region_destroy(mask_region_);
mask_region_ = NULL;
}
GtkAllocation allocation;
gtk_widget_get_allocation(window_, &allocation);
std::vector<GdkPoint> points = MakeFramePolygonPoints(
actual_frame_style_, allocation.width, allocation.height,
FRAME_MASK);
mask_region_ = gdk_region_polygon(&points[0],
points.size(),
GDK_EVEN_ODD_RULE);
GdkWindow* gdk_window = gtk_widget_get_window(window_);
gdk_window_shape_combine_region(gdk_window, NULL, 0, 0);
gdk_window_shape_combine_region(gdk_window, mask_region_, 0, 0);
}
void BubbleGtk::MoveWindow() {
if (!toplevel_window_ || !anchor_widget_)
return;
gint toplevel_x = 0, toplevel_y = 0;
gdk_window_get_position(gtk_widget_get_window(toplevel_window_),
&toplevel_x, &toplevel_y);
int offset_x, offset_y;
gtk_widget_translate_coordinates(anchor_widget_, toplevel_window_,
rect_.x(), rect_.y(), &offset_x, &offset_y);
gint screen_x = 0;
if (IsFixed(actual_frame_style_)) {
GtkAllocation toplevel_allocation;
gtk_widget_get_allocation(toplevel_window_, &toplevel_allocation);
GtkAllocation bubble_allocation;
gtk_widget_get_allocation(window_, &bubble_allocation);
int x_offset = actual_frame_style_ == FIXED_TOP_LEFT ?
kFixedPositionPaddingEnd :
toplevel_allocation.width - bubble_allocation.width -
kFixedPositionPaddingEnd;
screen_x = toplevel_x + x_offset;
} else if (!HasArrow(actual_frame_style_) ||
IsArrowMiddle(actual_frame_style_)) {
GtkAllocation allocation;
gtk_widget_get_allocation(window_, &allocation);
screen_x =
toplevel_x + offset_x + (rect_.width() / 2) - allocation.width / 2;
} else if (IsArrowLeft(actual_frame_style_)) {
screen_x = toplevel_x + offset_x + (rect_.width() / 2) - kArrowX;
} else if (IsArrowRight(actual_frame_style_)) {
GtkAllocation allocation;
gtk_widget_get_allocation(window_, &allocation);
screen_x = toplevel_x + offset_x + (rect_.width() / 2) -
allocation.width + kArrowX;
} else {
NOTREACHED();
}
gint screen_y = toplevel_y + offset_y + rect_.height();
if (IsFixed(actual_frame_style_)) {
screen_y = toplevel_y + kFixedPositionPaddingTop;
} else if (IsArrowTop(actual_frame_style_) ||
actual_frame_style_ == FLOAT_BELOW_RECT) {
screen_y += kArrowToContentPadding;
} else {
GtkAllocation allocation;
gtk_widget_get_allocation(window_, &allocation);
screen_y -= allocation.height + kArrowToContentPadding;
}
gtk_window_move(GTK_WINDOW(window_), screen_x, screen_y);
}
void BubbleGtk::StackWindow() {
// Stack our window directly above the toplevel window.
if (toplevel_window_)
ui::StackPopupWindow(window_, toplevel_window_);
}
void BubbleGtk::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(type, chrome::NOTIFICATION_BROWSER_THEME_CHANGED);
if (theme_service_->UsingNativeTheme() && match_system_theme_) {
gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, NULL);
} else {
// Set the background color, so we don't need to paint it manually.
gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, &kBackgroundColor);
}
}
void BubbleGtk::StopGrabbingInput() {
if (!grab_input_)
return;
grab_input_ = false;
gtk_grab_remove(window_);
}
GtkWindow* BubbleGtk::GetNativeWindow() {
return GTK_WINDOW(window_);
}
void BubbleGtk::Close() {
// We don't need to ungrab the pointer or keyboard here; the X server will
// automatically do that when we destroy our window.
DCHECK(window_);
gtk_widget_destroy(window_);
// |this| has been deleted, see OnDestroy.
}
void BubbleGtk::GrabPointerAndKeyboard() {
GdkWindow* gdk_window = gtk_widget_get_window(window_);
// Install X pointer and keyboard grabs to make sure that we have the focus
// and get all mouse and keyboard events until we're closed. As a hack, grab
// the pointer even if |grab_input_| is false to prevent a weird error
// rendering the bubble's frame. See
// https://code.google.com/p/chromium/issues/detail?id=130820.
GdkGrabStatus pointer_grab_status =
gdk_pointer_grab(gdk_window,
TRUE, // owner_events
GDK_BUTTON_PRESS_MASK, // event_mask
NULL, // confine_to
NULL, // cursor
GDK_CURRENT_TIME);
if (pointer_grab_status != GDK_GRAB_SUCCESS) {
// This will fail if someone else already has the pointer grabbed, but
// there's not really anything we can do about that.
DLOG(ERROR) << "Unable to grab pointer (status="
<< pointer_grab_status << ")";
}
// Only grab the keyboard input if |grab_input_| is true.
if (grab_input_) {
GdkGrabStatus keyboard_grab_status =
gdk_keyboard_grab(gdk_window,
FALSE, // owner_events
GDK_CURRENT_TIME);
if (keyboard_grab_status != GDK_GRAB_SUCCESS) {
DLOG(ERROR) << "Unable to grab keyboard (status="
<< keyboard_grab_status << ")";
}
}
}
gboolean BubbleGtk::OnGtkAccelerator(GtkAccelGroup* group,
GObject* acceleratable,
guint keyval,
GdkModifierType modifier) {
GdkEventKey msg;
GdkKeymapKey* keys;
gint n_keys;
switch (keyval) {
case GDK_Escape:
// Close on Esc and trap the accelerator
closed_by_escape_ = true;
Close();
return TRUE;
case GDK_w:
// Close on C-w and forward the accelerator
if (modifier & GDK_CONTROL_MASK) {
gdk_keymap_get_entries_for_keyval(NULL,
keyval,
&keys,
&n_keys);
if (n_keys) {
// Forward the accelerator to root window the bubble is anchored
// to for further processing
msg.type = GDK_KEY_PRESS;
msg.window = gtk_widget_get_window(toplevel_window_);
msg.send_event = TRUE;
msg.time = GDK_CURRENT_TIME;
msg.state = modifier | GDK_MOD2_MASK;
msg.keyval = keyval;
// length and string are deprecated and thus zeroed out
msg.length = 0;
msg.string = NULL;
msg.hardware_keycode = keys[0].keycode;
msg.group = keys[0].group;
msg.is_modifier = 0;
g_free(keys);
gtk_main_do_event(reinterpret_cast<GdkEvent*>(&msg));
} else {
// This means that there isn't a h/w code for the keyval in the
// current keymap, which is weird but possible if the keymap just
// changed. This isn't a critical error, but might be indicative
// of something off if it happens regularly.
DLOG(WARNING) << "Found no keys for value " << keyval;
}
Close();
}
break;
default:
return FALSE;
}
return TRUE;
}
gboolean BubbleGtk::OnExpose(GtkWidget* widget, GdkEventExpose* expose) {
// TODO(erg): This whole method will need to be rewritten in cairo.
GdkDrawable* drawable = GDK_DRAWABLE(gtk_widget_get_window(window_));
GdkGC* gc = gdk_gc_new(drawable);
gdk_gc_set_rgb_fg_color(gc, &kFrameColor);
// Stroke the frame border.
GtkAllocation allocation;
gtk_widget_get_allocation(window_, &allocation);
std::vector<GdkPoint> points = MakeFramePolygonPoints(
actual_frame_style_, allocation.width, allocation.height,
FRAME_STROKE);
gdk_draw_polygon(drawable, gc, FALSE, &points[0], points.size());
// If |grab_input_| is false, pointer input has been grabbed as a hack in
// |GrabPointerAndKeyboard()| to ensure that the polygon frame is drawn
// correctly. Since the intention is not actually to grab the pointer, release
// it now that the frame is drawn to prevent clicks from being missed. See
// https://code.google.com/p/chromium/issues/detail?id=130820.
if (!grab_input_)
gdk_pointer_ungrab(GDK_CURRENT_TIME);
g_object_unref(gc);
return FALSE; // Propagate so our children paint, etc.
}
// When our size is initially allocated or changed, we need to recompute
// and apply our shape mask region.
void BubbleGtk::OnSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation) {
if (!UpdateFrameStyle(false)) {
UpdateWindowShape();
MoveWindow();
}
}
gboolean BubbleGtk::OnButtonPress(GtkWidget* widget,
GdkEventButton* event) {
// If we got a click in our own window, that's okay (we need to additionally
// check that it falls within our bounds, since we've grabbed the pointer and
// some events that actually occurred in other windows will be reported with
// respect to our window).
GdkWindow* gdk_window = gtk_widget_get_window(window_);
if (event->window == gdk_window &&
(mask_region_ && gdk_region_point_in(mask_region_, event->x, event->y))) {
return FALSE; // Propagate.
}
// Our content widget got a click.
if (event->window != gdk_window &&
gdk_window_get_toplevel(event->window) == gdk_window) {
return FALSE;
}
if (grab_input_) {
// Otherwise we had a click outside of our window, close ourself.
Close();
return TRUE;
}
return FALSE;
}
gboolean BubbleGtk::OnDestroy(GtkWidget* widget) {
// We are self deleting, we have a destroy signal setup to catch when we
// destroy the widget manually, or the window was closed via X. This will
// delete the BubbleGtk object.
delete this;
return FALSE; // Propagate.
}
void BubbleGtk::OnHide(GtkWidget* widget) {
gtk_widget_destroy(widget);
}
gboolean BubbleGtk::OnGrabBroken(GtkWidget* widget,
GdkEventGrabBroken* grab_broken) {
// |grab_input_| may have been changed to false.
if (!grab_input_)
return false;
gpointer user_data;
gdk_window_get_user_data(grab_broken->grab_window, &user_data);
if (GTK_IS_WIDGET(user_data)) {
signals_.Connect(GTK_WIDGET(user_data), "hide",
G_CALLBACK(OnForeshadowWidgetHideThunk), this);
}
return FALSE;
}
void BubbleGtk::OnForeshadowWidgetHide(GtkWidget* widget) {
if (grab_input_)
GrabPointerAndKeyboard();
signals_.DisconnectAll(widget);
}
gboolean BubbleGtk::OnToplevelConfigure(GtkWidget* widget,
GdkEventConfigure* event) {
if (!UpdateFrameStyle(false))
MoveWindow();
StackWindow();
return FALSE;
}
gboolean BubbleGtk::OnToplevelUnmap(GtkWidget* widget, GdkEvent* event) {
Close();
return FALSE;
}
void BubbleGtk::OnAnchorAllocate(GtkWidget* widget,
GtkAllocation* allocation) {
if (!UpdateFrameStyle(false))
MoveWindow();
}
void BubbleGtk::OnAnchorDestroy(GtkWidget* widget) {
anchor_widget_ = NULL;
Close();
// |this| is deleted.
}
void BubbleGtk::OnToplevelDestroy(GtkWidget* widget) {
toplevel_window_ = NULL;
Close();
// |this| is deleted.
}
| {'content_hash': '9ddd453c48903d416dba85702c340fe5', 'timestamp': '', 'source': 'github', 'line_count': 759, 'max_line_length': 80, 'avg_line_length': 35.95915678524374, 'alnum_prop': 0.6422892316711245, 'repo_name': 'plxaye/chromium', 'id': 'eb9a040b0d9bcb2a6e0a48bed92865664c54d206', 'size': '28043', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/chrome/browser/ui/gtk/bubble/bubble_gtk.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '1176633'}, {'name': 'Awk', 'bytes': '9519'}, {'name': 'C', 'bytes': '75195981'}, {'name': 'C#', 'bytes': '36335'}, {'name': 'C++', 'bytes': '172360762'}, {'name': 'CSS', 'bytes': '740648'}, {'name': 'Dart', 'bytes': '12620'}, {'name': 'Emacs Lisp', 'bytes': '12454'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Java', 'bytes': '3671513'}, {'name': 'JavaScript', 'bytes': '16204541'}, {'name': 'Max', 'bytes': '39069'}, {'name': 'Mercury', 'bytes': '10299'}, {'name': 'Objective-C', 'bytes': '1133728'}, {'name': 'Objective-C++', 'bytes': '5771619'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '166372'}, {'name': 'Python', 'bytes': '11650532'}, {'name': 'Ragel in Ruby Host', 'bytes': '3641'}, {'name': 'Rebol', 'bytes': '262'}, {'name': 'Ruby', 'bytes': '14575'}, {'name': 'Shell', 'bytes': '1426780'}, {'name': 'Tcl', 'bytes': '277077'}, {'name': 'TeX', 'bytes': '43554'}, {'name': 'VimL', 'bytes': '4953'}, {'name': 'XSLT', 'bytes': '13493'}, {'name': 'nesC', 'bytes': '14650'}]} |
package service_test
import (
"github.com/nttlabs/cli/cf/i18n"
"github.com/nttlabs/cli/testhelpers/configuration"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestService(t *testing.T) {
config := configuration.NewRepositoryWithDefaults()
i18n.T = i18n.Init(config)
RegisterFailHandler(Fail)
RunSpecs(t, "Service Suite")
}
| {'content_hash': '924705813b620318fe58db9797d2c6c7', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 52, 'avg_line_length': 20.11111111111111, 'alnum_prop': 0.7403314917127072, 'repo_name': 'nttlabs/cli', 'id': '48af62013ed425323752c81f2f558f5ff8bae75f', 'size': '362', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cf/commands/service/service_suite_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '4313519'}, {'name': 'HTML', 'bytes': '1728'}, {'name': 'Inno Setup', 'bytes': '819'}, {'name': 'Makefile', 'bytes': '1938'}, {'name': 'NSIS', 'bytes': '10972'}, {'name': 'PowerShell', 'bytes': '682'}, {'name': 'Ruby', 'bytes': '5867'}, {'name': 'Shell', 'bytes': '16669'}]} |
lgtm,codescanning
* Added additional taint steps modeling the Spring `util` package (`org.springframework.util`).
| {'content_hash': '58211a4a6c30a7f2205738261da39048', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 95, 'avg_line_length': 57.0, 'alnum_prop': 0.7982456140350878, 'repo_name': 'github/codeql', 'id': 'f0e971b7f65f2d875ecc0511faaad83acd6d12ff', 'size': '114', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'java/old-change-notes/2021-05-31-add-spring-stringutils.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP.NET', 'bytes': '3739'}, {'name': 'Batchfile', 'bytes': '3534'}, {'name': 'C', 'bytes': '410440'}, {'name': 'C#', 'bytes': '21146000'}, {'name': 'C++', 'bytes': '1352639'}, {'name': 'CMake', 'bytes': '1809'}, {'name': 'CodeQL', 'bytes': '32583145'}, {'name': 'Dockerfile', 'bytes': '496'}, {'name': 'EJS', 'bytes': '1478'}, {'name': 'Emacs Lisp', 'bytes': '3445'}, {'name': 'Go', 'bytes': '697562'}, {'name': 'HTML', 'bytes': '58008'}, {'name': 'Handlebars', 'bytes': '1000'}, {'name': 'Java', 'bytes': '5417683'}, {'name': 'JavaScript', 'bytes': '2432320'}, {'name': 'Kotlin', 'bytes': '12163740'}, {'name': 'Lua', 'bytes': '13113'}, {'name': 'Makefile', 'bytes': '8631'}, {'name': 'Mustache', 'bytes': '17025'}, {'name': 'Nunjucks', 'bytes': '923'}, {'name': 'Perl', 'bytes': '1941'}, {'name': 'PowerShell', 'bytes': '1295'}, {'name': 'Python', 'bytes': '1649035'}, {'name': 'RAML', 'bytes': '2825'}, {'name': 'Ruby', 'bytes': '299268'}, {'name': 'Rust', 'bytes': '234024'}, {'name': 'Shell', 'bytes': '23973'}, {'name': 'Smalltalk', 'bytes': '23'}, {'name': 'Starlark', 'bytes': '27062'}, {'name': 'Swift', 'bytes': '204309'}, {'name': 'Thrift', 'bytes': '3020'}, {'name': 'TypeScript', 'bytes': '219623'}, {'name': 'Vim Script', 'bytes': '1949'}, {'name': 'Vue', 'bytes': '2881'}]} |
namespace llvm {
class raw_ostream;
}
namespace clang {
class ASTContext;
class BlockDecl;
class CXXConstructorDecl;
class CXXDestructorDecl;
class CXXMethodDecl;
class FunctionDecl;
struct MethodVFTableLocation;
class NamedDecl;
class ObjCMethodDecl;
class StringLiteral;
struct ThisAdjustment;
struct ThunkInfo;
class VarDecl;
/// MangleContext - Context for tracking state which persists across multiple
/// calls to the C++ name mangler.
class MangleContext {
public:
enum ManglerKind {
MK_Itanium,
MK_Microsoft
};
private:
virtual void anchor();
ASTContext &Context;
DiagnosticsEngine &Diags;
const ManglerKind Kind;
llvm::DenseMap<const BlockDecl*, unsigned> GlobalBlockIds;
llvm::DenseMap<const BlockDecl*, unsigned> LocalBlockIds;
llvm::DenseMap<const NamedDecl*, uint64_t> AnonStructIds;
public:
ManglerKind getKind() const { return Kind; }
explicit MangleContext(ASTContext &Context,
DiagnosticsEngine &Diags,
ManglerKind Kind)
: Context(Context), Diags(Diags), Kind(Kind) {}
virtual ~MangleContext() { }
ASTContext &getASTContext() const { return Context; }
DiagnosticsEngine &getDiags() const { return Diags; }
virtual void startNewFunction() { LocalBlockIds.clear(); }
unsigned getBlockId(const BlockDecl *BD, bool Local) {
llvm::DenseMap<const BlockDecl *, unsigned> &BlockIds
= Local? LocalBlockIds : GlobalBlockIds;
std::pair<llvm::DenseMap<const BlockDecl *, unsigned>::iterator, bool>
Result = BlockIds.insert(std::make_pair(BD, BlockIds.size()));
return Result.first->second;
}
uint64_t getAnonymousStructId(const NamedDecl *D) {
std::pair<llvm::DenseMap<const NamedDecl *, uint64_t>::iterator, bool>
Result = AnonStructIds.insert(std::make_pair(D, AnonStructIds.size()));
return Result.first->second;
}
/// @name Mangler Entry Points
/// @{
bool shouldMangleDeclName(const NamedDecl *D);
virtual bool shouldMangleCXXName(const NamedDecl *D) = 0;
virtual bool shouldMangleStringLiteral(const StringLiteral *SL) = 0;
// FIXME: consider replacing raw_ostream & with something like SmallString &.
void mangleName(GlobalDecl GD, raw_ostream &);
virtual void mangleCXXName(GlobalDecl GD, raw_ostream &) = 0;
virtual void mangleThunk(const CXXMethodDecl *MD,
const ThunkInfo &Thunk,
raw_ostream &) = 0;
virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
const ThisAdjustment &ThisAdjustment,
raw_ostream &) = 0;
virtual void mangleReferenceTemporary(const VarDecl *D,
unsigned ManglingNumber,
raw_ostream &) = 0;
virtual void mangleCXXRTTI(QualType T, raw_ostream &) = 0;
virtual void mangleCXXRTTIName(QualType T, raw_ostream &) = 0;
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &) = 0;
virtual void mangleMSGuidDecl(const MSGuidDecl *GD, raw_ostream&);
void mangleGlobalBlock(const BlockDecl *BD,
const NamedDecl *ID,
raw_ostream &Out);
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT,
const BlockDecl *BD, raw_ostream &Out);
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT,
const BlockDecl *BD, raw_ostream &Out);
void mangleBlock(const DeclContext *DC, const BlockDecl *BD,
raw_ostream &Out);
void mangleObjCMethodNameWithoutSize(const ObjCMethodDecl *MD, raw_ostream &);
void mangleObjCMethodName(const ObjCMethodDecl *MD, raw_ostream &);
virtual void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) = 0;
virtual void mangleDynamicInitializer(const VarDecl *D, raw_ostream &) = 0;
virtual void mangleDynamicAtExitDestructor(const VarDecl *D,
raw_ostream &) = 0;
virtual void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
raw_ostream &Out) = 0;
virtual void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
raw_ostream &Out) = 0;
/// Generates a unique string for an externally visible type for use with TBAA
/// or type uniquing.
/// TODO: Extend this to internal types by generating names that are unique
/// across translation units so it can be used with LTO.
virtual void mangleTypeName(QualType T, raw_ostream &) = 0;
/// @}
};
class ItaniumMangleContext : public MangleContext {
bool IsUniqueNameMangler = false;
public:
explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D)
: MangleContext(C, D, MK_Itanium) {}
explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D,
bool IsUniqueNameMangler)
: MangleContext(C, D, MK_Itanium),
IsUniqueNameMangler(IsUniqueNameMangler) {}
virtual void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) = 0;
virtual void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) = 0;
virtual void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
const CXXRecordDecl *Type,
raw_ostream &) = 0;
virtual void mangleItaniumThreadLocalInit(const VarDecl *D,
raw_ostream &) = 0;
virtual void mangleItaniumThreadLocalWrapper(const VarDecl *D,
raw_ostream &) = 0;
virtual void mangleCXXCtorComdat(const CXXConstructorDecl *D,
raw_ostream &) = 0;
virtual void mangleCXXDtorComdat(const CXXDestructorDecl *D,
raw_ostream &) = 0;
virtual void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) = 0;
bool isUniqueNameMangler() { return IsUniqueNameMangler; }
static bool classof(const MangleContext *C) {
return C->getKind() == MK_Itanium;
}
static ItaniumMangleContext *create(ASTContext &Context,
DiagnosticsEngine &Diags,
bool IsUniqueNameMangler = false);
};
class MicrosoftMangleContext : public MangleContext {
public:
explicit MicrosoftMangleContext(ASTContext &C, DiagnosticsEngine &D)
: MangleContext(C, D, MK_Microsoft) {}
/// Mangle vftable symbols. Only a subset of the bases along the path
/// to the vftable are included in the name. It's up to the caller to pick
/// them correctly.
virtual void mangleCXXVFTable(const CXXRecordDecl *Derived,
ArrayRef<const CXXRecordDecl *> BasePath,
raw_ostream &Out) = 0;
/// Mangle vbtable symbols. Only a subset of the bases along the path
/// to the vbtable are included in the name. It's up to the caller to pick
/// them correctly.
virtual void mangleCXXVBTable(const CXXRecordDecl *Derived,
ArrayRef<const CXXRecordDecl *> BasePath,
raw_ostream &Out) = 0;
virtual void mangleThreadSafeStaticGuardVariable(const VarDecl *VD,
unsigned GuardNum,
raw_ostream &Out) = 0;
virtual void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
const MethodVFTableLocation &ML,
raw_ostream &Out) = 0;
virtual void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
const CXXRecordDecl *DstRD,
raw_ostream &Out) = 0;
virtual void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
bool IsUnaligned, uint32_t NumEntries,
raw_ostream &Out) = 0;
virtual void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
raw_ostream &Out) = 0;
virtual void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
CXXCtorType CT, uint32_t Size,
uint32_t NVOffset, int32_t VBPtrOffset,
uint32_t VBIndex, raw_ostream &Out) = 0;
virtual void mangleCXXRTTIBaseClassDescriptor(
const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) = 0;
virtual void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
raw_ostream &Out) = 0;
virtual void
mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
raw_ostream &Out) = 0;
virtual void
mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
ArrayRef<const CXXRecordDecl *> BasePath,
raw_ostream &Out) = 0;
static bool classof(const MangleContext *C) {
return C->getKind() == MK_Microsoft;
}
static MicrosoftMangleContext *create(ASTContext &Context,
DiagnosticsEngine &Diags);
};
class ASTNameGenerator {
public:
explicit ASTNameGenerator(ASTContext &Ctx);
~ASTNameGenerator();
/// Writes name for \p D to \p OS.
/// \returns true on failure, false on success.
bool writeName(const Decl *D, raw_ostream &OS);
/// \returns name for \p D
std::string getName(const Decl *D);
/// \returns all applicable mangled names.
/// For example C++ constructors/destructors can have multiple.
std::vector<std::string> getAllManglings(const Decl *D);
private:
class Implementation;
std::unique_ptr<Implementation> Impl;
};
}
#endif
| {'content_hash': 'ed670712b4845b4e9fc11c9102c3ebd7', 'timestamp': '', 'source': 'github', 'line_count': 255, 'max_line_length': 80, 'avg_line_length': 39.490196078431374, 'alnum_prop': 0.6250248262164846, 'repo_name': 'endlessm/chromium-browser', 'id': 'b39a81462efdbbc6952db768ae2d4f836c8ef596', 'size': '10821', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'third_party/llvm/clang/include/clang/AST/Mangle.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
require('spotlight');
var
kind = require('enyo/kind'),
Button = require('enyo/Button');
module.exports = kind({
name : 'enyo.Spotlight.ContainerSample',
classes : 'spotlight-sample',
fit : true,
handlers: {
onSpotlightFocused: 'buttonFocused'
},
components: [
{name: 'c1', spotlight: 'container', onSpotlightContainerEnter: 'enterContainer', onSpotlightContainerLeave: 'leaveContainer', components: [
{name: 'c1b1', kind: Button, spotlight: true, content: 'c1b1'},
{name: 'c1b2', kind: Button, spotlight: true, content: 'c1b2'}
]},
{name: 'c2', spotlight: 'container', onSpotlightContainerEnter: 'enterContainer', onSpotlightContainerLeave: 'leaveContainer', components: [
{name: 'c2b1', kind: Button, spotlight: true, content: 'c2b1'},
{name: 'c2b2', kind: Button, spotlight: true, content: 'c2b2'},
{name: 'c2c1', spotlight: 'container', onSpotlightContainerEnter: 'enterContainer', onSpotlightContainerLeave: 'leaveContainer', components: [
{name: 'c2c1b1', kind: Button, spotlight: true, content: 'c2c1b1'},
{name: 'c2c1b2', kind: Button, spotlight: true, content: 'c2c1b1'}
]}
]}
],
buttonFocused: function (sender, ev) {
this.log('Button Focused', ev.originator.id);
},
enterContainer: function (sender, ev) {
this.log('Container Entered:', ev.originator.id);
sender.applyStyle('border', '2px solid red');
},
leaveContainer: function (sender, ev) {
this.log('Container Left:', ev.originator.id);
sender.applyStyle('border', null);
}
}); | {'content_hash': '86378171adcbef330bcd5b7c46567e95', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 145, 'avg_line_length': 34.47727272727273, 'alnum_prop': 0.6849044166117337, 'repo_name': 'enyojs/enyo-strawman', 'id': '273f07076b07a186cdf8fb254188deebc96405b3', 'size': '1517', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/spotlight-samples/src/ContainerSample.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '104991'}, {'name': 'JavaScript', 'bytes': '958907'}]} |
using System;
using ChartDirector;
namespace CSharpChartExplorer
{
public class iconpie : DemoModule
{
//Name of demo module
public string getName() { return "Icon Pie Chart (1)"; }
//Number of charts produced in this demo module
public int getNoOfCharts() { return 1; }
//Main code for creating chart.
//Note: the argument chartIndex is unused because this demo only has 1 chart.
public void createChart(WinChartViewer viewer, int chartIndex)
{
// The data for the pie chart
double[] data = {72, 18, 15, 12};
// The depths for the sectors
double[] depths = {30, 20, 10, 10};
// The labels for the pie chart
string[] labels = {"Sunny", "Cloudy", "Rainy", "Snowy"};
// The icons for the sectors
string[] icons = {"sun.png", "cloud.png", "rain.png", "snowy.png"};
// Create a PieChart object of size 400 x 310 pixels, with a blue (CCCCFF) vertical
// metal gradient background, black border, 1 pixel 3D border effect and rounded corners
PieChart c = new PieChart(400, 310, Chart.metalColor(0xccccff, 0), 0x000000, 1);
c.setRoundedFrame();
// Set the center of the pie at (200, 180) and the radius to 100 pixels
c.setPieSize(200, 180, 100);
// Add a title box using 15pt Times Bold Italic font, on a blue (CCCCFF) background with
// glass effect
c.addTitle("Weather Profile in Wonderland", "Times New Roman Bold Italic", 15
).setBackground(0xccccff, 0x000000, Chart.glassEffect());
// Set the pie data and the pie labels
c.setData(data, labels);
// Add icons to the chart as a custom field
c.addExtraField(icons);
// Configure the sector labels using CDML to include the icon images
c.setLabelFormat(
"<*block,valign=absmiddle*><*img={field0}*> <*block*>{label}\n{percent}%<*/*><*/*>")
;
// Draw the pie in 3D with variable 3D depths
c.set3D2(depths);
// Set the start angle to 225 degrees may improve layout when the depths of the sector
// are sorted in descending order, because it ensures the tallest sector is at the back.
c.setStartAngle(225);
// Output the chart
viewer.Chart = c;
//include tool tip for the chart
viewer.ImageMap = c.getHTMLImageMap("clickable", "",
"title='{label}: {value} days ({percent}%)'");
}
}
}
| {'content_hash': '09becbceca6a765f6955e724b02c7cb1', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 100, 'avg_line_length': 38.18571428571428, 'alnum_prop': 0.5750093527871306, 'repo_name': 'jojogreen/Orbital-Mechanix-Suite', 'id': '2f97bc70c5b17980fef59b934459cbfe0c69809f', 'size': '2673', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'NetWinCharts/CSharpWinCharts/iconpie.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '40380'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>metacoq-pcuic: 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.2 / metacoq-pcuic - 1.0~beta1+8.12</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
metacoq-pcuic
<small>
1.0~beta1+8.12
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-12 10:00:58 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-12 10:00:58 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 2 Virtual package relying on perl
coq 8.7.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://metacoq.github.io/metacoq"
dev-repo: "git+https://github.com/MetaCoq/metacoq.git#coq-8.12"
bug-reports: "https://github.com/MetaCoq/metacoq/issues"
authors: ["Abhishek Anand <[email protected]>"
"Simon Boulier <[email protected]>"
"Cyril Cohen <[email protected]>"
"Yannick Forster <[email protected]>"
"Fabian Kunze <[email protected]>"
"Gregory Malecha <[email protected]>"
"Matthieu Sozeau <[email protected]>"
"Nicolas Tabareau <[email protected]>"
"Théo Winterhalter <[email protected]>"
]
license: "MIT"
build: [
["sh" "./configure.sh"]
[make "-j%{jobs}%" "-C" "pcuic"]
]
install: [
[make "-C" "pcuic" "install"]
]
depends: [
"ocaml" {>= "4.07.1"}
"coq" {>= "8.12" & < "8.13~"}
"coq-equations" { = "1.2.3+8.12" }
"coq-metacoq-template" {= version}
"coq-metacoq-checker" {= version}
]
synopsis: "A type system equivalent to Coq's and its metatheory"
description: """
MetaCoq is a meta-programming framework for Coq.
The PCUIC module provides a cleaned-up specification of Coq's typing algorithm along
with a certified typechecker for it. This module includes the standard metatheory of
PCUIC: Weakening, Substitution, Confluence and Subject Reduction are proven here.
"""
url {
src: "https://github.com/MetaCoq/metacoq/archive/v1.0-beta1-8.12.tar.gz"
checksum: "sha256=19fc4475ae81677018e21a1e20503716a47713ec8b2081e7506f5c9390284c7a"
}
</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-metacoq-pcuic.1.0~beta1+8.12 coq.8.7.2</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.2).
The following dependencies couldn't be met:
- coq-metacoq-pcuic -> ocaml >= 4.07.1
base of this switch (use `--unlock-base' 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-metacoq-pcuic.1.0~beta1+8.12</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>
| {'content_hash': 'e2d19dea515868d65bb7da9f1de75e11', 'timestamp': '', 'source': 'github', 'line_count': 181, 'max_line_length': 159, 'avg_line_length': 42.68508287292818, 'alnum_prop': 0.5548796272327207, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '99b61101f742f7abb026eac729778d1db077042f', 'size': '7752', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.2/metacoq-pcuic/1.0~beta1+8.12.html', 'mode': '33188', 'license': 'mit', 'language': []} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_CN" sourcelanguage="en" version="2.0">
<context>
<name>AddAddressDialog</name>
<message>
<location filename="../bitmessageqt/addaddressdialog.py" line="62"/>
<source>Add new entry</source>
<translation>添加新条目</translation>
</message>
<message>
<location filename="../bitmessageqt/addaddressdialog.py" line="63"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location filename="../bitmessageqt/addaddressdialog.py" line="64"/>
<source>Address</source>
<translation>地址</translation>
</message>
</context>
<context>
<name>EmailGatewayDialog</name>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="67"/>
<source>Email gateway</source>
<translation>电子邮件网关</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="68"/>
<source>Register on email gateway</source>
<translation>注册电子邮件网关</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="69"/>
<source>Account status at email gateway</source>
<translation>电子邮件网关帐户状态</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="70"/>
<source>Change account settings at email gateway</source>
<translation>更改电子邮件网关帐户设置</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="71"/>
<source>Unregister from email gateway</source>
<translation>取消电子邮件网关注册</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="72"/>
<source>Email gateway allows you to communicate with email users. Currently, only the Mailchuck email gateway (@mailchuck.com) is available.</source>
<translation>电子邮件网关允许您与电子邮件用户通信。目前,只有Mailchuck电子邮件网关(@mailchuck.com)可用。</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="73"/>
<source>Desired email address (including @mailchuck.com):</source>
<translation>所需的电子邮件地址(包括 @mailchuck.com):</translation>
</message>
</context>
<context>
<name>EmailGatewayRegistrationDialog</name>
<message>
<location filename="../bitmessageqt/__init__.py" line="2232"/>
<source>Registration failed:</source>
<translation>注册失败:</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2232"/>
<source>The requested email address is not available, please try a new one. Fill out the new desired email address (including @mailchuck.com) below:</source>
<translation>要求的电子邮件地址不详,请尝试一个新的。填写新的所需电子邮件地址(包括 @mailchuck.com)如下:</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="102"/>
<source>Email gateway registration</source>
<translation>电子邮件网关注册</translation>
</message>
<message>
<location filename="../bitmessageqt/emailgateway.py" line="103"/>
<source>Email gateway allows you to communicate with email users. Currently, only the Mailchuck email gateway (@mailchuck.com) is available.
Please type the desired email address (including @mailchuck.com) below:</source>
<translation>电子邮件网关允许您与电子邮件用户通信。目前,只有Mailchuck电子邮件网关(@mailchuck.com)可用。请键入所需的电子邮件地址(包括 @mailchuck.com)如下:</translation>
</message>
</context>
<context>
<name>Mailchuck</name>
<message>
<location filename="../bitmessageqt/account.py" line="225"/>
<source># You can use this to configure your email gateway account
# Uncomment the setting you want to use
# Here are the options:
#
# pgp: server
# The email gateway will create and maintain PGP keys for you and sign, verify,
# encrypt and decrypt on your behalf. When you want to use PGP but are lazy,
# use this. Requires subscription.
#
# pgp: local
# The email gateway will not conduct PGP operations on your behalf. You can
# either not use PGP at all, or use it locally.
#
# attachments: yes
# Incoming attachments in the email will be uploaded to MEGA.nz, and you can
# download them from there by following the link. Requires a subscription.
#
# attachments: no
# Attachments will be ignored.
#
# archive: yes
# Your incoming emails will be archived on the server. Use this if you need
# help with debugging problems or you need a third party proof of emails. This
# however means that the operator of the service will be able to read your
# emails even after they have been delivered to you.
#
# archive: no
# Incoming emails will be deleted from the server as soon as they are relayed
# to you.
#
# masterpubkey_btc: BIP44 xpub key or electrum v1 public seed
# offset_btc: integer (defaults to 0)
# feeamount: number with up to 8 decimal places
# feecurrency: BTC, XBT, USD, EUR or GBP
# Use these if you want to charge people who send you emails. If this is on and
# an unknown person sends you an email, they will be requested to pay the fee
# specified. As this scheme uses deterministic public keys, you will receive
# the money directly. To turn it off again, set "feeamount" to 0. Requires
# subscription.
</source>
<translation>#您可以用它来配置你的电子邮件网关帐户
#取消您要使用的设定
#这里的选项:
#
# pgp: server
#电子邮件网关将创建和维护PGP密钥,为您签名和验证,
#代表加密和解密。当你想使用PGP,但懒惰,
#用这个。需要订阅。
#
# pgp: local
#电子邮件网关不会代你进行PGP操作。您可以
#选择或者不使用PGP, 或在本地使用它。
#
# attachement: yes
#传入附件的电子邮件将会被上传到MEGA.nz,您可以从
# 按照那里链接下载。需要订阅。
#
# attachement: no
#附件将被忽略。
#
# archive: yes
#您收到的邮件将在服务器上存档。如果您有需要请使用
#帮助调试问题,或者您需要第三方电子邮件的证明。这
#然而,意味着服务的操作运将能够读取您的
#电子邮件即使电子邮件已经传送给你。
#
# archive: no
# 已传入的电子邮件将从服务器被删除只要他们已中继。
#
# masterpubkey_btc:BIP44 XPUB键或琥珀金V1公共种子
#offset_btc:整数(默认为0)
#feeamount:多达8位小数
#feecurrency号:BTC,XBT,美元,欧元或英镑
#用这些,如果你想主管谁送你的电子邮件的人。如果这是在和
#一个不明身份的人向您发送一封电子邮件,他们将被要求支付规定的费用
#。由于这个方案使用确定性的公共密钥,你会直接接收
#钱。要再次将其关闭,设置“feeamount”0
#需要订阅。</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../bitmessageqt/__init__.py" line="190"/>
<source>Reply to sender</source>
<translation>回复发件人</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="192"/>
<source>Reply to channel</source>
<translation>回复通道</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="194"/>
<source>Add sender to your Address Book</source>
<translation>将发送者添加到您的通讯簿</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="198"/>
<source>Add sender to your Blacklist</source>
<translation>将发件人添加到您的黑名单</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="380"/>
<source>Move to Trash</source>
<translation>移入回收站</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="205"/>
<source>Undelete</source>
<translation>取消删除</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="208"/>
<source>View HTML code as formatted text</source>
<translation>作为HTML查看</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="212"/>
<source>Save message as...</source>
<translation>将消息保存为...</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="216"/>
<source>Mark Unread</source>
<translation>标记为未读</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="352"/>
<source>New</source>
<translation>新建</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="122"/>
<source>Enable</source>
<translation>启用</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="125"/>
<source>Disable</source>
<translation>禁用</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="128"/>
<source>Set avatar...</source>
<translation>设置头像...</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="118"/>
<source>Copy address to clipboard</source>
<translation>将地址复制到剪贴板</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="303"/>
<source>Special address behavior...</source>
<translation>特别的地址行为...</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="264"/>
<source>Email gateway</source>
<translation>电子邮件网关</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="115"/>
<source>Delete</source>
<translation>删除</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="319"/>
<source>Send message to this address</source>
<translation>发送消息到这个地址</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="327"/>
<source>Subscribe to this address</source>
<translation>订阅到这个地址</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="335"/>
<source>Add New Address</source>
<translation>创建新地址</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="383"/>
<source>Copy destination address to clipboard</source>
<translation>复制目标地址到剪贴板</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="387"/>
<source>Force send</source>
<translation>强制发送</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="599"/>
<source>One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer supported. May we delete it now?</source>
<translation>您的地址中的一个, %1,是一个过时的版本1地址. 版本1地址已经不再受到支持了. 我们可以将它删除掉么?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="992"/>
<source>Waiting for their encryption key. Will request it again soon.</source>
<translation>正在等待他们的加密密钥,我们会在稍后再次请求。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="990"/>
<source>Encryption key request queued.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="998"/>
<source>Queued.</source>
<translation>已经添加到队列。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1001"/>
<source>Message sent. Waiting for acknowledgement. Sent at %1</source>
<translation>消息已经发送. 正在等待回执. 发送于 %1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1004"/>
<source>Message sent. Sent at %1</source>
<translation>消息已经发送. 发送于 %1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1002"/>
<source>Need to do work to send message. Work is queued.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1010"/>
<source>Acknowledgement of the message received %1</source>
<translation>消息的回执已经收到于 %1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2101"/>
<source>Broadcast queued.</source>
<translation>广播已经添加到队列中。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1019"/>
<source>Broadcast on %1</source>
<translation>已经广播于 %1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1022"/>
<source>Problem: The work demanded by the recipient is more difficult than you are willing to do. %1</source>
<translation>错误: 收件人要求的做工量大于我们的最大接受做工量。 %1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1025"/>
<source>Problem: The recipient's encryption key is no good. Could not encrypt message. %1</source>
<translation>错误: 收件人的加密密钥是无效的。不能加密消息。 %1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1028"/>
<source>Forced difficulty override. Send should start soon.</source>
<translation>已经忽略最大做工量限制。发送很快就会开始。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1031"/>
<source>Unknown status: %1 %2</source>
<translation>未知状态: %1 %2</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1653"/>
<source>Not Connected</source>
<translation>未连接</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1160"/>
<source>Show Bitmessage</source>
<translation>显示比特信</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="688"/>
<source>Send</source>
<translation>发送</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1175"/>
<source>Subscribe</source>
<translation>订阅</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1181"/>
<source>Channel</source>
<translation>频道</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="734"/>
<source>Quit</source>
<translation>退出</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1531"/>
<source>You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file.</source>
<translation>您可以通过编辑和程序储存在同一个目录的 keys.dat 来编辑密钥。备份这个文件十分重要。 </translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1535"/>
<source>You may manage your keys by editing the keys.dat file stored in
%1
It is important that you back up this file.</source>
<translation>您可以通过编辑储存在 %1 的 keys.dat 来编辑密钥。备份这个文件十分重要。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1542"/>
<source>Open keys.dat?</source>
<translation>打开 keys.dat ? </translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1539"/>
<source>You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)</source>
<translation>您可以通过编辑和程序储存在同一个目录的 keys.dat 来编辑密钥。备份这个文件十分重要。您现在想打开这个文件么?(请在进行任何修改前关闭比特信)</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1542"/>
<source>You may manage your keys by editing the keys.dat file stored in
%1
It is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)</source>
<translation>您可以通过编辑储存在 %1 的 keys.dat 来编辑密钥。备份这个文件十分重要。您现在想打开这个文件么?(请在进行任何修改前关闭比特信)</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1549"/>
<source>Delete trash?</source>
<translation>清空回收站?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1549"/>
<source>Are you sure you want to delete all trashed messages?</source>
<translation>您确定要删除全部被回收的消息么?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1569"/>
<source>bad passphrase</source>
<translation>错误的密钥</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1569"/>
<source>You must type your passphrase. If you don't have one then this is not the form for you.</source>
<translation>您必须输入您的密钥。如果您没有的话,这个表单不适用于您。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1582"/>
<source>Bad address version number</source>
<translation>地址的版本号无效</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1578"/>
<source>Your address version number must be a number: either 3 or 4.</source>
<translation>您的地址的版本号必须是一个数字: 3 或 4.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1582"/>
<source>Your address version number must be either 3 or 4.</source>
<translation>您的地址的版本号必须是 3 或 4.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1608"/>
<source>Chan name needed</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1608"/>
<source>You didn't enter a chan name.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1628"/>
<source>Address already present</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1628"/>
<source>Could not add chan because it appears to already be one of your identities.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1632"/>
<source>Success</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1603"/>
<source>Successfully created chan. To let others join your chan, give them the chan name and this Bitmessage address: %1. This address also appears in 'Your Identities'.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1612"/>
<source>Address too new</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1612"/>
<source>Although that Bitmessage address might be valid, its version number is too new for us to handle. Perhaps you need to upgrade Bitmessage.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1616"/>
<source>Address invalid</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1616"/>
<source>That Bitmessage address is not valid.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1624"/>
<source>Address does not match chan name</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1624"/>
<source>Although the Bitmessage address you entered was valid, it doesn't match the chan name.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1632"/>
<source>Successfully joined chan. </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1647"/>
<source>Connection lost</source>
<translation>连接已丢失</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1686"/>
<source>Connected</source>
<translation>已经连接</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1803"/>
<source>Message trashed</source>
<translation>消息已经移入回收站</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1887"/>
<source>The TTL, or Time-To-Live is the length of time that the network will hold the message.
The recipient must get it during this time. If your Bitmessage client does not hear an acknowledgement, it
will resend the message automatically. The longer the Time-To-Live, the
more work your computer must do to send the message. A Time-To-Live of four or five days is often appropriate.</source>
<translation>這TTL,或Time-To-Time是保留信息网络时间的长度.
收件人必须在此期间得到它. 如果您的Bitmessage客户沒有听到确认, 它会自动重新发送信息. Time-To-Live的时间越长, 您的电脑必须要做更多工作來发送信息. 四天或五天的 Time-To-Time, 经常是合适的.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1925"/>
<source>Message too long</source>
<translation>信息太长</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1925"/>
<source>The message that you are trying to send is too long by %1 bytes. (The maximum is 261644 bytes). Please cut it down before sending.</source>
<translation>你正在尝试发送的信息已超过%1个字节太长, (最大为261644个字节). 发送前请剪下来。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1957"/>
<source>Error: Your account wasn't registered at an email gateway. Sending registration now as %1, please wait for the registration to be processed before retrying sending.</source>
<translation>错误: 您的帐户没有在电子邮件网关注册。现在发送注册为%1, 注册正在处理请稍候重试发送.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2008"/>
<source>Error: Bitmessage addresses start with BM- Please check %1</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2011"/>
<source>Error: The address %1 is not typed or copied correctly. Please check it.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2014"/>
<source>Error: The address %1 contains invalid characters. Please check it.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2017"/>
<source>Error: The address version in %1 is too high. Either you need to upgrade your Bitmessage software or your acquaintance is being clever.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2020"/>
<source>Error: Some data encoded in the address %1 is too short. There might be something wrong with the software of your acquaintance.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2023"/>
<source>Error: Some data encoded in the address %1 is too long. There might be something wrong with the software of your acquaintance.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2026"/>
<source>Error: Some data encoded in the address %1 is malformed. There might be something wrong with the software of your acquaintance.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2029"/>
<source>Error: Something is wrong with the address %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2059"/>
<source>Error: You must specify a From address. If you don't have one, go to the 'Your Identities' tab.</source>
<translation>错误: 您必须指出一个表单地址, 如果您没有,请到“您的身份”标签页。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2000"/>
<source>Address version number</source>
<translation>地址版本号</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2000"/>
<source>Concerning the address %1, Bitmessage cannot understand address version numbers of %2. Perhaps upgrade Bitmessage to the latest version.</source>
<translation>地址 %1 的地址版本号 %2 无法被比特信理解。也许你应该升级你的比特信到最新版本。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2004"/>
<source>Stream number</source>
<translation>节点流序号</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2004"/>
<source>Concerning the address %1, Bitmessage cannot handle stream numbers of %2. Perhaps upgrade Bitmessage to the latest version.</source>
<translation>地址 %1 的节点流序号 %2 无法被比特信理解。也许你应该升级你的比特信到最新版本。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2009"/>
<source>Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won't send until you connect.</source>
<translation>警告: 您尚未连接。 比特信将做足够的功来发送消息,但是消息不会被发出直到您连接。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2051"/>
<source>Message queued.</source>
<translation>信息排队。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2055"/>
<source>Your 'To' field is empty.</source>
<translation>“收件人"是空的。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2110"/>
<source>Right click one or more entries in your address book and select 'Send message to this address'.</source>
<translation>在您的地址本的一个条目上右击,之后选择”发送消息到这个地址“。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2123"/>
<source>Fetched address from namecoin identity.</source>
<translation>已经自namecoin接收了地址。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2226"/>
<source>New Message</source>
<translation>新消息</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2226"/>
<source>From </source>
<translation>来自</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2606"/>
<source>Sending email gateway registration request</source>
<translation>发送电子邮件网关注册请求</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="60"/>
<source>Address is valid.</source>
<translation>地址有效。</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="94"/>
<source>The address you entered was invalid. Ignoring it.</source>
<translation>您输入的地址是无效的,将被忽略。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3028"/>
<source>Error: You cannot add the same address to your address book twice. Try renaming the existing one if you want.</source>
<translation>错误:您无法将一个地址添加到您的地址本两次,请尝试重命名已经存在的那个。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3276"/>
<source>Error: You cannot add the same address to your subscriptions twice. Perhaps rename the existing one if you want.</source>
<translation>错误: 您不能在同一地址添加到您的订阅两次. 也许您可重命名现有之一.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2366"/>
<source>Restart</source>
<translation>重启</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2352"/>
<source>You must restart Bitmessage for the port number change to take effect.</source>
<translation>您必须重启以便使比特信对于使用的端口的改变生效。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2366"/>
<source>Bitmessage will use your proxy from now on but you may want to manually restart Bitmessage now to close existing connections (if any).</source>
<translation>比特信将会从现在开始使用代理,但是您可能想手动重启比特信以便使之前的连接关闭(如果有的话)。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2394"/>
<source>Number needed</source>
<translation>需求数字</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2394"/>
<source>Your maximum download and upload rate must be numbers. Ignoring what you typed.</source>
<translation>您最大的下载和上传速率必须是数字. 忽略您键入的内容.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2467"/>
<source>Will not resend ever</source>
<translation>不尝试再次发送</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2467"/>
<source>Note that the time limit you entered is less than the amount of time Bitmessage waits for the first resend attempt therefore your messages will never be resent.</source>
<translation>请注意,您所输入的时间限制小于比特信的最小重试时间,因此您将永远不会重发消息。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2579"/>
<source>Sending email gateway unregistration request</source>
<translation>发送电子邮件网关注销请求</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2583"/>
<source>Sending email gateway status request</source>
<translation>发送电子邮件网关状态请求</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2672"/>
<source>Passphrase mismatch</source>
<translation>密钥不匹配</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2672"/>
<source>The passphrase you entered twice doesn't match. Try again.</source>
<translation>您两次输入的密码并不匹配,请再试一次。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2675"/>
<source>Choose a passphrase</source>
<translation>选择一个密钥</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2675"/>
<source>You really do need a passphrase.</source>
<translation>您真的需要一个密码。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2969"/>
<source>Address is gone</source>
<translation>已经失去了地址</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2969"/>
<source>Bitmessage cannot find your address %1. Perhaps you removed it?</source>
<translation>比特信无法找到你的地址 %1。 也许你已经把它删掉了?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2972"/>
<source>Address disabled</source>
<translation>地址已经禁用</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2972"/>
<source>Error: The address from which you are trying to send is disabled. You'll have to enable it on the 'Your Identities' tab before using it.</source>
<translation>错误: 您想以一个您已经禁用的地址发出消息。在使用之前您需要在“您的身份”处再次启用。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3025"/>
<source>Entry added to the Address Book. Edit the label to your liking.</source>
<translation>条目已经添加到地址本。您可以去修改您的标签。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3050"/>
<source>Entry added to the blacklist. Edit the label to your liking.</source>
<translation>条目添加到黑名单. 根据自己的喜好编辑标签.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3053"/>
<source>Error: You cannot add the same address to your blacklist twice. Try renaming the existing one if you want.</source>
<translation>错误: 您不能在同一地址添加到您的黑名单两次. 也许您可重命名现有之一.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3181"/>
<source>Moved items to trash.</source>
<translation>已经移动项目到回收站。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3121"/>
<source>Undeleted item.</source>
<translation>未删除的项目。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3149"/>
<source>Save As...</source>
<translation>另存为...</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3158"/>
<source>Write error.</source>
<translation>写入失败。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3262"/>
<source>No addresses selected.</source>
<translation>没有选择地址。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3308"/>
<source>If you delete the subscription, messages that you already received will become inaccessible. Maybe you can consider disabling the subscription instead. Disabled subscriptions will not receive new messages, but you can still view messages you already received.
Are you sure you want to delete the subscription?</source>
<translation>如果删除订阅, 您已经收到的信息将无法访问. 也许你可以考虑禁用订阅.禁用订阅将不会收到新信息, 但您仍然可以看到你已经收到的信息.
你确定要删除订阅?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3538"/>
<source>If you delete the channel, messages that you already received will become inaccessible. Maybe you can consider disabling the channel instead. Disabled channels will not receive new messages, but you can still view messages you already received.
Are you sure you want to delete the channel?</source>
<translation>如果您删除的频道, 你已经收到的信息将无法访问. 也许你可以考虑禁用频道. 禁用频道将不会收到新信息, 但你仍然可以看到你已经收到的信息.
你确定要删除频道?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3652"/>
<source>Do you really want to remove this avatar?</source>
<translation>您真的想移除这个头像么?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="3660"/>
<source>You have already set an avatar for this address. Do you really want to overwrite it?</source>
<translation>您已经为这个地址设置了头像了。您真的想移除么?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4039"/>
<source>Start-on-login not yet supported on your OS.</source>
<translation>登录时启动尚未支持您在使用的操作系统。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4032"/>
<source>Minimize-to-tray not yet supported on your OS.</source>
<translation>最小化到托盘尚未支持您的操作系统。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4035"/>
<source>Tray notifications not yet supported on your OS.</source>
<translation>托盘提醒尚未支持您所使用的操作系统。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4208"/>
<source>Testing...</source>
<translation>正在测试...</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4248"/>
<source>This is a chan address. You cannot use it as a pseudo-mailing list.</source>
<translation>这是一个频道地址,您无法把它作为伪邮件列表。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4308"/>
<source>The address should start with ''BM-''</source>
<translation>地址应该以"BM-"开始</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4311"/>
<source>The address is not typed or copied correctly (the checksum failed).</source>
<translation>地址没有被正确的键入或复制(校验码校验失败)。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4314"/>
<source>The version number of this address is higher than this software can support. Please upgrade Bitmessage.</source>
<translation>这个地址的版本号大于此软件的最大支持。 请升级比特信。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4317"/>
<source>The address contains invalid characters.</source>
<translation>这个地址中包含无效字符。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4320"/>
<source>Some data encoded in the address is too short.</source>
<translation>在这个地址中编码的部分信息过少。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4323"/>
<source>Some data encoded in the address is too long.</source>
<translation>在这个地址中编码的部分信息过长。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4326"/>
<source>Some data encoded in the address is malformed.</source>
<translation>在地址编码的某些数据格式不正确.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4300"/>
<source>Enter an address above.</source>
<translation>请在上方键入地址。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4332"/>
<source>Address is an old type. We cannot display its past broadcasts.</source>
<translation>地址没有近期的广播。我们无法显示之间的广播。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4341"/>
<source>There are no recent broadcasts from this address to display.</source>
<translation>没有可以显示的近期广播。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4375"/>
<source>You are using TCP port %1. (This can be changed in the settings).</source>
<translation>您正在使用TCP端口 %1 。(可以在设置中修改)。</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="645"/>
<source>Bitmessage</source>
<translation>比特信</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="646"/>
<source>Identities</source>
<translation>身份标识</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="647"/>
<source>New Identity</source>
<translation>新身份标识</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="709"/>
<source>Search</source>
<translation>搜索</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="710"/>
<source>All</source>
<translation>全部</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="717"/>
<source>To</source>
<translation>至</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="719"/>
<source>From</source>
<translation>来自</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="721"/>
<source>Subject</source>
<translation>标题</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="714"/>
<source>Message</source>
<translation>消息</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="723"/>
<source>Received</source>
<translation>接收时间</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="663"/>
<source>Messages</source>
<translation>信息</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="666"/>
<source>Address book</source>
<translation>地址簿</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="668"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="669"/>
<source>Add Contact</source>
<translation>增加联系人</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="670"/>
<source>Fetch Namecoin ID</source>
<translation>接收Namecoin ID</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="677"/>
<source>Subject:</source>
<translation>标题:</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="676"/>
<source>From:</source>
<translation>来自:</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="673"/>
<source>To:</source>
<translation>至:</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="675"/>
<source>Send ordinary Message</source>
<translation>发送普通信息</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="679"/>
<source>Send Message to your Subscribers</source>
<translation>发送信息给您的订户</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="680"/>
<source>TTL:</source>
<translation>TTL:</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="706"/>
<source>Subscriptions</source>
<translation>订阅</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="690"/>
<source>Add new Subscription</source>
<translation>添加新的订阅</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="724"/>
<source>Chans</source>
<translation>Chans</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="708"/>
<source>Add Chan</source>
<translation>添加 Chans</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="729"/>
<source>File</source>
<translation>文件</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="740"/>
<source>Settings</source>
<translation>设置</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="736"/>
<source>Help</source>
<translation>帮助</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="732"/>
<source>Import keys</source>
<translation>导入密钥</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="733"/>
<source>Manage keys</source>
<translation>管理密钥</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="735"/>
<source>Ctrl+Q</source>
<translation>Ctrl+Q</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="737"/>
<source>F1</source>
<translation>F1</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="738"/>
<source>Contact support</source>
<translation>联系支持</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="739"/>
<source>About</source>
<translation>关于</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="741"/>
<source>Regenerate deterministic addresses</source>
<translation>重新生成静态地址</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="742"/>
<source>Delete all trashed messages</source>
<translation>彻底删除全部回收站中的消息</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="743"/>
<source>Join / Create chan</source>
<translation>加入或创建一个频道</translation>
</message>
<message>
<location filename="../bitmessageqt/foldertree.py" line="172"/>
<source>All accounts</source>
<translation>所有帐户</translation>
</message>
<message>
<location filename="../bitmessageqt/messageview.py" line="47"/>
<source>Zoom level %1%</source>
<translation>缩放级别%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="91"/>
<source>Error: You cannot add the same address to your list twice. Perhaps rename the existing one if you want.</source>
<translation>错误: 您不能在同一地址添加到列表中两次. 也许您可重命名现有之一.</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="112"/>
<source>Add new entry</source>
<translation>添加新条目</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="4345"/>
<source>Display the %1 recent broadcast(s) from this address.</source>
<translation>显示从这个地址%1的最近广播</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1812"/>
<source>New version of PyBitmessage is available: %1. Download it from https://github.com/Bitmessage/PyBitmessage/releases/latest</source>
<translation>PyBitmessage的新版本可用: %1. 从https://github.com/Bitmessage/PyBitmessage/releases/latest下载</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2763"/>
<source>Waiting for PoW to finish... %1%</source>
<translation>等待PoW完成...%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2767"/>
<source>Shutting down Pybitmessage... %1%</source>
<translation>关闭Pybitmessage ...%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2783"/>
<source>Waiting for objects to be sent... %1%</source>
<translation>等待要发送对象...%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2793"/>
<source>Saving settings... %1%</source>
<translation>保存设置...%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2802"/>
<source>Shutting down core... %1%</source>
<translation>关闭核心...%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2805"/>
<source>Stopping notifications... %1%</source>
<translation>停止通知...%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2811"/>
<source>Shutdown imminent... %1%</source>
<translation>关闭即将来临...%1%</translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/bitmessageui.py" line="686"/>
<source>%n hour(s)</source>
<translation><numerusform>%n 小时</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/__init__.py" line="824"/>
<source>%n day(s)</source>
<translation><numerusform>%n 天</numerusform></translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2735"/>
<source>Shutting down PyBitmessage... %1%</source>
<translation>关闭PyBitmessage...%1%</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1105"/>
<source>Sent</source>
<translation>发送</translation>
</message>
<message>
<location filename="../class_addressGenerator.py" line="87"/>
<source>Generating one new address</source>
<translation>生成一个新的地址</translation>
</message>
<message>
<location filename="../class_addressGenerator.py" line="149"/>
<source>Done generating address. Doing work necessary to broadcast it...</source>
<translation>完成生成地址. 做必要的工作, 以播放它...</translation>
</message>
<message>
<location filename="../class_addressGenerator.py" line="166"/>
<source>Generating %1 new addresses.</source>
<translation>生成%1个新地址.</translation>
</message>
<message>
<location filename="../class_addressGenerator.py" line="243"/>
<source>%1 is already in 'Your Identities'. Not adding it again.</source>
<translation>%1已经在'您的身份'. 不必重新添加.</translation>
</message>
<message>
<location filename="../class_addressGenerator.py" line="279"/>
<source>Done generating address</source>
<translation>完成生成地址</translation>
</message>
<message>
<location filename="../class_outgoingSynSender.py" line="228"/>
<source>SOCKS5 Authentication problem: %1</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../class_sqlThread.py" line="567"/>
<source>Disk full</source>
<translation>磁盘已满</translation>
</message>
<message>
<location filename="../class_sqlThread.py" line="567"/>
<source>Alert: Your disk or data storage volume is full. Bitmessage will now exit.</source>
<translation>警告: 您的磁盘或数据存储量已满. 比特信将立即退出.</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="723"/>
<source>Error! Could not find sender address (your address) in the keys.dat file.</source>
<translation>错误! 找不到在keys.dat 件发件人的地址 ( 您的地址).</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="469"/>
<source>Doing work necessary to send broadcast...</source>
<translation>做必要的工作, 以发送广播...</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="492"/>
<source>Broadcast sent on %1</source>
<translation>广播发送%1</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="561"/>
<source>Encryption key was requested earlier.</source>
<translation>加密密钥已请求.</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="598"/>
<source>Sending a request for the recipient's encryption key.</source>
<translation>发送收件人的加密密钥的请求.</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="615"/>
<source>Looking up the receiver's public key</source>
<translation>展望接收方的公钥</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="649"/>
<source>Problem: Destination is a mobile device who requests that the destination be included in the message but this is disallowed in your settings. %1</source>
<translation>问题: 目标是移动电话设备所请求的目的地包括在消息中, 但是这是在你的设置禁止. %1</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="663"/>
<source>Doing work necessary to send message.
There is no required difficulty for version 2 addresses like this.</source>
<translation>做必要的工作, 以发送信息.
这样第2版的地址没有难度.</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="677"/>
<source>Doing work necessary to send message.
Receiver's required difficulty: %1 and %2</source>
<translation>做必要的工作, 以发送短信.
接收者的要求难度: %1与%2</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="686"/>
<source>Problem: The work demanded by the recipient (%1 and %2) is more difficult than you are willing to do. %3</source>
<translation>问题: 由接收者(%1%2)要求的工作量比您愿意做的工作量來得更困难. %3</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="698"/>
<source>Problem: You are trying to send a message to yourself or a chan but your encryption key could not be found in the keys.dat file. Could not encrypt message. %1</source>
<translation>问题: 您正在尝试将信息发送给自己或频道, 但您的加密密钥无法在keys.dat文件中找到. 无法加密信息. %1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1007"/>
<source>Doing work necessary to send message.</source>
<translation>做必要的工作, 以发送信息.</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="820"/>
<source>Message sent. Waiting for acknowledgement. Sent on %1</source>
<translation>信息发送. 等待确认. 已发送%1</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="995"/>
<source>Doing work necessary to request encryption key.</source>
<translation>做必要的工作以要求加密密钥.</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="941"/>
<source>Broadcasting the public key request. This program will auto-retry if they are offline.</source>
<translation>广播公钥请求. 这个程序将自动重试, 如果他们处于离线状态.</translation>
</message>
<message>
<location filename="../class_singleWorker.py" line="943"/>
<source>Sending public key request. Waiting for reply. Requested at %1</source>
<translation>发送公钥的请求. 等待回复. 请求在%1</translation>
</message>
<message>
<location filename="../upnp.py" line="220"/>
<source>UPnP port mapping established on port %1</source>
<translation>UPnP端口映射建立在端口%1</translation>
</message>
<message>
<location filename="../upnp.py" line="244"/>
<source>UPnP port mapping removed</source>
<translation>UPnP端口映射被删除</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="268"/>
<source>Mark all messages as read</source>
<translation>标记全部信息为已读</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2615"/>
<source>Are you sure you would like to mark all messages read?</source>
<translation>确定将所有信息标记为已读吗?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1016"/>
<source>Doing work necessary to send broadcast.</source>
<translation>持续进行必要的工作,以发送广播。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2704"/>
<source>Proof of work pending</source>
<translation>待传输内容的校验</translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/__init__.py" line="2704"/>
<source>%n object(s) pending proof of work</source>
<translation><numerusform>%n 待传输内容校验任务</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/__init__.py" line="2704"/>
<source>%n object(s) waiting to be distributed</source>
<translation><numerusform>%n 任务等待分配</numerusform></translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2704"/>
<source>Wait until these tasks finish?</source>
<translation>等待所有任务执行完?</translation>
</message>
<message>
<location filename="../class_outgoingSynSender.py" line="216"/>
<source>Problem communicating with proxy: %1. Please check your network settings.</source>
<translation>与代理通信故障率:%1。请检查你的网络连接。</translation>
</message>
<message>
<location filename="../class_outgoingSynSender.py" line="245"/>
<source>SOCKS5 Authentication problem: %1. Please check your SOCKS5 settings.</source>
<translation>SOCK5认证错误:%1。请检查你的SOCK5设置。</translation>
</message>
<message>
<location filename="../class_receiveDataThread.py" line="165"/>
<source>The time on your computer, %1, may be wrong. Please verify your settings.</source>
<translation>你电脑上时间有误:%1。请检查你的设置。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1970"/>
<source>Error: Bitmessage addresses start with BM- Please check the recipient address %1</source>
<translation>错误:Bitmessage地址是以BM-开头的,请检查收信地址%1.</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1973"/>
<source>Error: The recipient address %1 is not typed or copied correctly. Please check it.</source>
<translation>错误:收信地址%1未填写或复制错误。请检查。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1976"/>
<source>Error: The recipient address %1 contains invalid characters. Please check it.</source>
<translation>错误:收信地址%1还有非法字符。请检查。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1979"/>
<source>Error: The version of the recipient address %1 is too high. Either you need to upgrade your Bitmessage software or your acquaintance is being clever.</source>
<translation>错误:收信地址%1版本太高。要么你需要更新你的软件,要么对方需要降级 。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1982"/>
<source>Error: Some data encoded in the recipient address %1 is too short. There might be something wrong with the software of your acquaintance.</source>
<translation>错误:收信地址%1编码数据太短。可能对方使用的软件有问题。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1985"/>
<source>Error: Some data encoded in the recipient address %1 is too long. There might be something wrong with the software of your acquaintance.</source>
<translation>错误:</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1988"/>
<source>Error: Some data encoded in the recipient address %1 is malformed. There might be something wrong with the software of your acquaintance.</source>
<translation>错误:收信地址%1编码数据太长。可能对方使用的软件有问题。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="1991"/>
<source>Error: Something is wrong with the recipient address %1.</source>
<translation>错误:收信地址%1有问题。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2717"/>
<source>Synchronisation pending</source>
<translation>待同步</translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/__init__.py" line="2717"/>
<source>Bitmessage hasn't synchronised with the network, %n object(s) to be downloaded. If you quit now, it may cause delivery delays. Wait until the synchronisation finishes?</source>
<translation><numerusform>Bitmessage还没有与网络同步,%n 件任务需要下载。如果你现在退出软件,可能会造成传输延时。是否等同步完成?</numerusform></translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2726"/>
<source>Not connected</source>
<translation>未连接成功。</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2726"/>
<source>Bitmessage isn't connected to the network. If you quit now, it may cause delivery delays. Wait until connected and the synchronisation finishes?</source>
<translation>Bitmessage未连接到网络。如果现在退出软件,可能会造成传输延时。是否等待同步完成?</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2739"/>
<source>Waiting for network connection...</source>
<translation>等待网络连接……</translation>
</message>
<message>
<location filename="../bitmessageqt/__init__.py" line="2747"/>
<source>Waiting for finishing synchronisation...</source>
<translation>等待同步完成……</translation>
</message>
</context>
<context>
<name>MessageView</name>
<message>
<location filename="../bitmessageqt/messageview.py" line="67"/>
<source>Follow external link</source>
<translation>查看外部链接</translation>
</message>
<message>
<location filename="../bitmessageqt/messageview.py" line="67"/>
<source>The link "%1" will open in a browser. It may be a security risk, it could de-anonymise you or download malicious data. Are you sure?</source>
<translation>此链接“%1”将在浏览器中打开。可能会有安全风险,可能会暴露你或下载恶意数据。确定吗?</translation>
</message>
<message>
<location filename="../bitmessageqt/messageview.py" line="112"/>
<source>HTML detected, click here to display</source>
<translation>检测到HTML,单击此处来显示内容。</translation>
</message>
<message>
<location filename="../bitmessageqt/messageview.py" line="121"/>
<source>Click here to disable HTML</source>
<translation>单击此处以禁止HTML。</translation>
</message>
</context>
<context>
<name>MsgDecode</name>
<message>
<location filename="../helper_msgcoding.py" line="61"/>
<source>The message has an unknown encoding.
Perhaps you should upgrade Bitmessage.</source>
<translation>这些消息使用了未知编码方式。
你可能需要更新Bitmessage软件。</translation>
</message>
<message>
<location filename="../helper_msgcoding.py" line="62"/>
<source>Unknown encoding</source>
<translation>未知编码</translation>
</message>
</context>
<context>
<name>NewAddressDialog</name>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="173"/>
<source>Create new Address</source>
<translation>创建新地址</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="174"/>
<source>Here you may generate as many addresses as you like. Indeed, creating and abandoning addresses is encouraged. You may generate addresses by using either random numbers or by using a passphrase. If you use a passphrase, the address is called a "deterministic" address.
The 'Random Number' option is selected by default but deterministic addresses have several pros and cons:</source>
<translation>在这里,您想创建多少地址就创建多少。诚然,创建和丢弃地址受到鼓励。你既可以使用随机数来创建地址,也可以使用密钥。如果您使用密钥的话,生成的地址叫“静态地址”。随机数选项默认为选择,不过相比而言静态地址既有缺点也有优点:</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="176"/>
<source><html><head/><body><p><span style=" font-weight:600;">Pros:<br/></span>You can recreate your addresses on any computer from memory. <br/>You need-not worry about backing up your keys.dat file as long as you can remember your passphrase. <br/><span style=" font-weight:600;">Cons:<br/></span>You must remember (or write down) your passphrase if you expect to be able to recreate your keys if they are lost. <br/>You must remember the address version number and the stream number along with your passphrase. <br/>If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you.</p></body></html></source>
<translation><html><head/><body><p><span style=" font-weight:600;">优点:<br/></span>您可以通过记忆在任何电脑再次得到您的地址. <br/>您不需要注意备份您的 keys.dat 只要您能记住您的密钥。 <br/><span style=" font-weight:600;">缺点:<br/></span>您若要再次得到您的地址,您必须牢记(或写下您的密钥)。 <br/>您必须牢记密钥的同时也牢记地址版本号和the stream number . <br/>如果您选择了一个弱的密钥的话,一些在互联网我那个的人可能有机会暴力破解, 他们将可以阅读您的消息并且以您的身份发送消息.</p></body></html></translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="177"/>
<source>Use a random number generator to make an address</source>
<translation>使用随机数生成地址</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="178"/>
<source>Use a passphrase to make addresses</source>
<translation>使用密钥生成地址</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="179"/>
<source>Spend several minutes of extra computing time to make the address(es) 1 or 2 characters shorter</source>
<translation>花费数分钟的计算使地址短1-2个字母</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="180"/>
<source>Make deterministic addresses</source>
<translation>创建静态地址</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="181"/>
<source>Address version number: 4</source>
<translation>地址版本号:4</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="182"/>
<source>In addition to your passphrase, you must remember these numbers:</source>
<translation>在记住您的密钥的同时,您还需要记住以下数字:</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="183"/>
<source>Passphrase</source>
<translation>密钥</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="184"/>
<source>Number of addresses to make based on your passphrase:</source>
<translation>使用该密钥生成的地址数:</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="185"/>
<source>Stream number: 1</source>
<translation>节点流序号:1</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="186"/>
<source>Retype passphrase</source>
<translation>再次输入密钥</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="187"/>
<source>Randomly generate address</source>
<translation>随机生成地址</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="188"/>
<source>Label (not shown to anyone except you)</source>
<translation>标签(只有您看的到)</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="189"/>
<source>Use the most available stream</source>
<translation>使用最可用的节点流</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="190"/>
<source> (best if this is the first of many addresses you will create)</source>
<translation>如果这是您创建的数个地址中的第一个时最佳</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="191"/>
<source>Use the same stream as an existing address</source>
<translation>使用和如下地址一样的节点流</translation>
</message>
<message>
<location filename="../bitmessageqt/newaddressdialog.py" line="192"/>
<source>(saves you some bandwidth and processing power)</source>
<translation>(节省你的带宽和处理能力)</translation>
</message>
</context>
<context>
<name>NewSubscriptionDialog</name>
<message>
<location filename="../bitmessageqt/newsubscriptiondialog.py" line="65"/>
<source>Add new entry</source>
<translation>添加新条目</translation>
</message>
<message>
<location filename="../bitmessageqt/newsubscriptiondialog.py" line="66"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location filename="../bitmessageqt/newsubscriptiondialog.py" line="67"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../bitmessageqt/newsubscriptiondialog.py" line="68"/>
<source>Enter an address above.</source>
<translation>输入上述地址.</translation>
</message>
</context>
<context>
<name>SpecialAddressBehaviorDialog</name>
<message>
<location filename="../bitmessageqt/specialaddressbehavior.py" line="59"/>
<source>Special Address Behavior</source>
<translation>特别的地址行为</translation>
</message>
<message>
<location filename="../bitmessageqt/specialaddressbehavior.py" line="60"/>
<source>Behave as a normal address</source>
<translation>作为普通地址</translation>
</message>
<message>
<location filename="../bitmessageqt/specialaddressbehavior.py" line="61"/>
<source>Behave as a pseudo-mailing-list address</source>
<translation>作为伪邮件列表地址</translation>
</message>
<message>
<location filename="../bitmessageqt/specialaddressbehavior.py" line="62"/>
<source>Mail received to a pseudo-mailing-list address will be automatically broadcast to subscribers (and thus will be public).</source>
<translation>伪邮件列表收到消息时会自动将其公开的广播给订阅者。</translation>
</message>
<message>
<location filename="../bitmessageqt/specialaddressbehavior.py" line="63"/>
<source>Name of the pseudo-mailing-list:</source>
<translation>伪邮件列表名称:</translation>
</message>
</context>
<context>
<name>aboutDialog</name>
<message>
<location filename="../bitmessageqt/about.py" line="67"/>
<source>About</source>
<translation>关于</translation>
</message>
<message>
<location filename="../bitmessageqt/about.py" line="68"/>
<source>PyBitmessage</source>
<translation>PyBitmessage</translation>
</message>
<message>
<location filename="../bitmessageqt/about.py" line="69"/>
<source>version ?</source>
<translation>版本 ?</translation>
</message>
<message>
<location filename="../bitmessageqt/about.py" line="71"/>
<source><html><head/><body><p>Distributed under the MIT/X11 software license; see <a href="http://www.opensource.org/licenses/mit-license.php"><span style=" text-decoration: underline; color:#0000ff;">http://www.opensource.org/licenses/mit-license.php</span></a></p></body></html></source>
<translation><html><head/><body><p>以 MIT/X11 软件授权发布; 详情参见 <a href="http://www.opensource.org/licenses/mit-license.php"><span style=" text-decoration: underline; color:#0000ff;">http://www.opensource.org/licenses/mit-license.php</span></a></p></body></html></translation>
</message>
<message>
<location filename="../bitmessageqt/about.py" line="72"/>
<source>This is Beta software.</source>
<translation>本软件处于Beta阶段。</translation>
</message>
<message>
<location filename="../bitmessageqt/about.py" line="70"/>
<source><html><head/><body><p>Copyright © 2012-2016 Jonathan Warren<br/>Copyright © 2013-2016 The Bitmessage Developers</p></body></html></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/about.py" line="70"/>
<source><html><head/><body><p>Copyright &copy; 2012-2016 Jonathan Warren<br/>Copyright &copy; 2013-2016 The Bitmessage Developers</p></body></html></source>
<translation><html><head/><body><p>版权:2012-2016 Jonathan Warren<br/>版权: 2013-2016 The Bitmessage Developers</p></body></html></translation>
</message>
</context>
<context>
<name>blacklist</name>
<message>
<location filename="../bitmessageqt/blacklist.ui" line="17"/>
<source>Use a Blacklist (Allow all incoming messages except those on the Blacklist)</source>
<translation>使用黑名单 (允许所有传入的信息除了那些在黑名单)</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.ui" line="27"/>
<source>Use a Whitelist (Block all incoming messages except those on the Whitelist)</source>
<translation>使用白名单 (阻止所有传入的消息除了那些在白名单)</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.ui" line="34"/>
<source>Add new entry</source>
<translation>添加新条目</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.ui" line="85"/>
<source>Name or Label</source>
<translation>名称或标签</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.ui" line="90"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="151"/>
<source>Blacklist</source>
<translation>黑名单</translation>
</message>
<message>
<location filename="../bitmessageqt/blacklist.py" line="153"/>
<source>Whitelist</source>
<translation>白名单</translation>
</message>
</context>
<context>
<name>connectDialog</name>
<message>
<location filename="../bitmessageqt/connect.py" line="56"/>
<source>Bitmessage</source>
<translation>比特信</translation>
</message>
<message>
<location filename="../bitmessageqt/connect.py" line="57"/>
<source>Bitmessage won't connect to anyone until you let it. </source>
<translation>除非您允许,比特信不会连接到任何人。</translation>
</message>
<message>
<location filename="../bitmessageqt/connect.py" line="58"/>
<source>Connect now</source>
<translation>现在连接</translation>
</message>
<message>
<location filename="../bitmessageqt/connect.py" line="59"/>
<source>Let me configure special network settings first</source>
<translation>请先让我进行特别的网络设置</translation>
</message>
</context>
<context>
<name>helpDialog</name>
<message>
<location filename="../bitmessageqt/help.py" line="45"/>
<source>Help</source>
<translation>帮助</translation>
</message>
<message>
<location filename="../bitmessageqt/help.py" line="46"/>
<source><a href="https://bitmessage.org/wiki/PyBitmessage_Help">https://bitmessage.org/wiki/PyBitmessage_Help</a></source>
<translation><a href="https://bitmessage.org/wiki/PyBitmessage_Help">https://bitmessage.org/wiki/PyBitmessage_Help</a></translation>
</message>
<message>
<location filename="../bitmessageqt/help.py" line="47"/>
<source>As Bitmessage is a collaborative project, help can be found online in the Bitmessage Wiki:</source>
<translation>鉴于比特信是一个共同完成的项目,您可以在比特信的Wiki上了解如何帮助比特信:</translation>
</message>
</context>
<context>
<name>iconGlossaryDialog</name>
<message>
<location filename="../bitmessageqt/iconglossary.py" line="82"/>
<source>Icon Glossary</source>
<translation>图标含义</translation>
</message>
<message>
<location filename="../bitmessageqt/iconglossary.py" line="83"/>
<source>You have no connections with other peers. </source>
<translation>您没有和其他节点的连接.</translation>
</message>
<message>
<location filename="../bitmessageqt/iconglossary.py" line="84"/>
<source>You have made at least one connection to a peer using an outgoing connection but you have not yet received any incoming connections. Your firewall or home router probably isn't configured to forward incoming TCP connections to your computer. Bitmessage will work just fine but it would help the Bitmessage network if you allowed for incoming connections and will help you be a better-connected node.</source>
<translation>你有至少一个到其他节点的出站连接,但是尚未收到入站连接。您的防火墙或路由器可能尚未设置转发入站TCP连接到您的电脑。比特信将正常运行,不过如果您允许入站连接的话将帮助比特信网络并成为一个通信状态更好的节点。</translation>
</message>
<message>
<location filename="../bitmessageqt/iconglossary.py" line="85"/>
<source>You are using TCP port ?. (This can be changed in the settings).</source>
<translation>您正在使用TCP端口 ? 。(可以在设置中更改).</translation>
</message>
<message>
<location filename="../bitmessageqt/iconglossary.py" line="86"/>
<source>You do have connections with other peers and your firewall is correctly configured.</source>
<translation>您有和其他节点的连接且您的防火墙已经正确配置。</translation>
</message>
</context>
<context>
<name>networkstatus</name>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="39"/>
<source>Total connections:</source>
<translation>总连接:</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="143"/>
<source>Since startup:</source>
<translation>自启动:</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="159"/>
<source>Processed 0 person-to-person messages.</source>
<translation>处理0人对人的信息.</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="188"/>
<source>Processed 0 public keys.</source>
<translation>处理0公钥。</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="175"/>
<source>Processed 0 broadcasts.</source>
<translation>处理0广播.</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="240"/>
<source>Inventory lookups per second: 0</source>
<translation>每秒库存查询: 0</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="201"/>
<source>Objects to be synced:</source>
<translation>对象 已同步:</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="111"/>
<source>Stream #</source>
<translation>数据流 #</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="116"/>
<source>Connections</source>
<translation>连接</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.py" line="137"/>
<source>Since startup on %1</source>
<translation>自从%1启动</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.py" line="71"/>
<source>Down: %1/s Total: %2</source>
<translation>下: %1/秒 总计: %2</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.py" line="73"/>
<source>Up: %1/s Total: %2</source>
<translation>上: %1/秒 总计: %2</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.py" line="120"/>
<source>Total Connections: %1</source>
<translation>总的连接数: %1</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.py" line="129"/>
<source>Inventory lookups per second: %1</source>
<translation>每秒库存查询: %1</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="214"/>
<source>Up: 0 kB/s</source>
<translation>上载: 0 kB /秒</translation>
</message>
<message>
<location filename="../bitmessageqt/networkstatus.ui" line="227"/>
<source>Down: 0 kB/s</source>
<translation>下载: 0 kB /秒</translation>
</message>
<message>
<location filename="../bitmessageqt/bitmessageui.py" line="728"/>
<source>Network Status</source>
<translation>网络状态</translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/networkstatus.py" line="38"/>
<source>byte(s)</source>
<translation><numerusform>字节</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/networkstatus.py" line="49"/>
<source>Object(s) to be synced: %n</source>
<translation><numerusform>要同步的对象: %n</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/networkstatus.py" line="53"/>
<source>Processed %n person-to-person message(s).</source>
<translation><numerusform>处理%n人对人的信息.</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/networkstatus.py" line="58"/>
<source>Processed %n broadcast message(s).</source>
<translation><numerusform>处理%n广播信息.</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitmessageqt/networkstatus.py" line="63"/>
<source>Processed %n public key(s).</source>
<translation><numerusform>处理%n公钥.</numerusform></translation>
</message>
</context>
<context>
<name>newChanDialog</name>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="97"/>
<source>Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="98"/>
<source>Create a new chan</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="103"/>
<source>Join a chan</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="100"/>
<source>Create a chan</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="101"/>
<source><html><head/><body><p>Enter a name for your chan. If you choose a sufficiently complex chan name (like a strong and unique passphrase) and none of your friends share it publicly then the chan will be secure and private. If you and someone else both create a chan with the same chan name then it is currently very likely that they will be the same chan.</p></body></html></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="105"/>
<source>Chan name:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="104"/>
<source><html><head/><body><p>A chan exists when a group of people share the same decryption keys. The keys and bitmessage address used by a chan are generated from a human-friendly word or phrase (the chan name). To send a message to everyone in the chan, send a normal person-to-person message to the chan address.</p><p>Chans are experimental and completely unmoderatable.</p></body></html></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="106"/>
<source>Chan bitmessage address:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.ui" line="26"/>
<source>Create or join a chan</source>
<translation>创建或加入一个频道</translation>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.ui" line="41"/>
<source><html><head/><body><p>A chan exists when a group of people share the same decryption keys. The keys and bitmessage address used by a chan are generated from a human-friendly word or phrase (the chan name). To send a message to everyone in the chan, send a message to the chan address.</p><p>Chans are experimental and completely unmoderatable.</p><p>Enter a name for your chan. If you choose a sufficiently complex chan name (like a strong and unique passphrase) and none of your friends share it publicly, then the chan will be secure and private. However if you and someone else both create a chan with the same chan name, the same chan will be shared.</p></body></html></source>
<translation><html><head/><body><p>当一群人共享同一样的加密钥匙时会创建一个频道。使用一个词组来命名密钥和bitmessage地址。发送信息到频道地址就可以发送消息给每个成员。</p><p>频道功能为实验性功能,也不稳定。</p><p>为你的频道命名。如果你选择使用一个十分复杂的名字命令并且你的朋友不会公开它,那这个频道就是安全和私密的。然而如果你和其他人都创建了一个同样命名的频道,那么相同名字的频道将会被共享。</p></body></html></translation>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.ui" line="56"/>
<source>Chan passhphrase/name:</source>
<translation>频道命名:</translation>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.ui" line="63"/>
<source>Optional, for advanced usage</source>
<translation>可选,适用于高级应用</translation>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.ui" line="76"/>
<source>Chan address</source>
<translation>频道地址</translation>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.ui" line="101"/>
<source>Please input chan name/passphrase:</source>
<translation>请输入频道名字:</translation>
</message>
</context>
<context>
<name>newchandialog</name>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="40"/>
<source>Successfully created / joined chan %1</source>
<translation>成功创建或加入频道%1</translation>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="45"/>
<source>Chan creation / joining failed</source>
<translation>频道创建或加入失败</translation>
</message>
<message>
<location filename="../bitmessageqt/newchandialog.py" line="51"/>
<source>Chan creation / joining cancelled</source>
<translation>频道创建或加入已取消</translation>
</message>
</context>
<context>
<name>regenerateAddressesDialog</name>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="114"/>
<source>Regenerate Existing Addresses</source>
<translation>重新生成已经存在的地址</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="115"/>
<source>Regenerate existing addresses</source>
<translation>重新生成已经存在的地址</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="116"/>
<source>Passphrase</source>
<translation>密钥</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="117"/>
<source>Number of addresses to make based on your passphrase:</source>
<translation>您想要要使用这个密钥生成的地址数:</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="118"/>
<source>Address version number:</source>
<translation>地址版本号:</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="119"/>
<source>Stream number:</source>
<translation>节点流序号:</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="120"/>
<source>1</source>
<translation>1</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="121"/>
<source>Spend several minutes of extra computing time to make the address(es) 1 or 2 characters shorter</source>
<translation>花费数分钟的计算使地址短1-2个字母</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="122"/>
<source>You must check (or not check) this box just like you did (or didn't) when you made your addresses the first time.</source>
<translation>这个选项需要和您第一次生成的时候相同。</translation>
</message>
<message>
<location filename="../bitmessageqt/regenerateaddresses.py" line="123"/>
<source>If you have previously made deterministic addresses but lost them due to an accident (like hard drive failure), you can regenerate them here. If you used the random number generator to make your addresses then this form will be of no use to you.</source>
<translation>如果您之前创建了静态地址,但是因为一些意外失去了它们(比如硬盘坏了),您可以在这里将他们再次生成。如果您使用随机数来生成的地址的话,那么这个表格对您没有帮助。</translation>
</message>
</context>
<context>
<name>settingsDialog</name>
<message>
<location filename="../bitmessageqt/settings.py" line="440"/>
<source>Settings</source>
<translation>设置</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="441"/>
<source>Start Bitmessage on user login</source>
<translation>在用户登录时启动比特信</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="442"/>
<source>Tray</source>
<translation>任务栏</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="443"/>
<source>Start Bitmessage in the tray (don't show main window)</source>
<translation>启动比特信到托盘 (不要显示主窗口)</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="444"/>
<source>Minimize to tray</source>
<translation>最小化到托盘</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="445"/>
<source>Close to tray</source>
<translation>关闭任务栏</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="447"/>
<source>Show notification when message received</source>
<translation>在收到消息时提示</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="448"/>
<source>Run in Portable Mode</source>
<translation>以便携方式运行</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="449"/>
<source>In Portable Mode, messages and config files are stored in the same directory as the program rather than the normal application-data folder. This makes it convenient to run Bitmessage from a USB thumb drive.</source>
<translation>在便携模式下, 消息和配置文件和程序保存在同一个目录而不是通常的程序数据文件夹。 这使在U盘中允许比特信很方便。</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="450"/>
<source>Willingly include unencrypted destination address when sending to a mobile device</source>
<translation>愿意在发送到手机时使用不加密的目标地址</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="451"/>
<source>Use Identicons</source>
<translation>用户身份</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="452"/>
<source>Reply below Quote</source>
<translation>回复 引述如下</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="453"/>
<source>Interface Language</source>
<translation>界面语言</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="454"/>
<source>System Settings</source>
<comment>system</comment>
<translation>系统设置</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="455"/>
<source>User Interface</source>
<translation>用户界面</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="456"/>
<source>Listening port</source>
<translation>监听端口</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="457"/>
<source>Listen for connections on port:</source>
<translation>监听连接于端口:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="458"/>
<source>UPnP:</source>
<translation>UPnP:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="459"/>
<source>Bandwidth limit</source>
<translation>带宽限制</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="460"/>
<source>Maximum download rate (kB/s): [0: unlimited]</source>
<translation>最大下载速率(kB/秒): [0: 无限制]</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="461"/>
<source>Maximum upload rate (kB/s): [0: unlimited]</source>
<translation>最大上传速度 (kB/秒): [0: 无限制]</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="462"/>
<source>Proxy server / Tor</source>
<translation>代理服务器 / Tor</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="463"/>
<source>Type:</source>
<translation>类型:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="464"/>
<source>Server hostname:</source>
<translation>服务器主机名:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="487"/>
<source>Port:</source>
<translation>端口:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="466"/>
<source>Authentication</source>
<translation>认证</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="488"/>
<source>Username:</source>
<translation>用户名:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="468"/>
<source>Pass:</source>
<translation>密码:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="469"/>
<source>Listen for incoming connections when using proxy</source>
<translation>在使用代理时仍然监听入站连接</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="470"/>
<source>none</source>
<translation>无</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="471"/>
<source>SOCKS4a</source>
<translation>SOCKS4a</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="472"/>
<source>SOCKS5</source>
<translation>SOCKS5</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="473"/>
<source>Network Settings</source>
<translation>网络设置</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="474"/>
<source>Total difficulty:</source>
<translation>总难度:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="475"/>
<source>The 'Total difficulty' affects the absolute amount of work the sender must complete. Doubling this value doubles the amount of work.</source>
<translation>“总难度”影响发送者所需要的做工总数。当这个值翻倍时,做工的总数也翻倍。</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="476"/>
<source>Small message difficulty:</source>
<translation>小消息难度:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="477"/>
<source>When someone sends you a message, their computer must first complete some work. The difficulty of this work, by default, is 1. You may raise this default for new addresses you create by changing the values here. Any new addresses you create will require senders to meet the higher difficulty. There is one exception: if you add a friend or acquaintance to your address book, Bitmessage will automatically notify them when you next send a message that they need only complete the minimum amount of work: difficulty 1. </source>
<translation>当一个人向您发送消息的时候, 他们的电脑必须先做工。这个难度的默认值是1,您可以在创建新的地址前提高这个值。任何新创建的地址都会要求更高的做工量。这里有一个例外,当您将您的朋友添加到地址本的时候,比特信将自动提示他们,当他们下一次向您发送的时候,他们需要的做功量将总是1.</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="478"/>
<source>The 'Small message difficulty' mostly only affects the difficulty of sending small messages. Doubling this value makes it almost twice as difficult to send a small message but doesn't really affect large messages.</source>
<translation>“小消息困难度”几乎仅影响发送消息。当这个值翻倍时,发小消息时做工的总数也翻倍,但是并不影响大的消息。</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="479"/>
<source>Demanded difficulty</source>
<translation>要求的难度</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="480"/>
<source>Here you may set the maximum amount of work you are willing to do to send a message to another person. Setting these values to 0 means that any value is acceptable.</source>
<translation>你可以在这里设置您所愿意接受的发送消息的最大难度。0代表接受任何难度。</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="481"/>
<source>Maximum acceptable total difficulty:</source>
<translation>最大接受难度:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="482"/>
<source>Maximum acceptable small message difficulty:</source>
<translation>最大接受的小消息难度:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="483"/>
<source>Max acceptable difficulty</source>
<translation>最大可接受难度</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="473"/>
<source>Hardware GPU acceleration (OpenCL)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="485"/>
<source><html><head/><body><p>Bitmessage can utilize a different Bitcoin-based program called Namecoin to make addresses human-friendly. For example, instead of having to tell your friend your long Bitmessage address, you can simply tell him to send a message to <span style=" font-style:italic;">test. </span></p><p>(Getting your own Bitmessage address into Namecoin is still rather difficult).</p><p>Bitmessage can use either namecoind directly or a running nmcontrol instance.</p></body></html></source>
<translation><html><head/><body><p>比特信可以利用基于比特币的Namecoin让地址更加友好。比如除了告诉您的朋友您的长长的比特信地址,您还可以告诉他们发消息给 <span style=" font-style:italic;">test. </span></p><p>把您的地址放入Namecoin还是相当的难的.</p><p>比特信可以不但直接连接到namecoin守护程序或者连接到运行中的nmcontrol实例.</p></body></html></translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="486"/>
<source>Host:</source>
<translation>主机名:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="489"/>
<source>Password:</source>
<translation>密码:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="490"/>
<source>Test</source>
<translation>测试</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="491"/>
<source>Connect to:</source>
<translation>连接到:</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="492"/>
<source>Namecoind</source>
<translation>Namecoind</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="493"/>
<source>NMControl</source>
<translation>NMControl</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="494"/>
<source>Namecoin integration</source>
<translation>Namecoin整合</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="495"/>
<source><html><head/><body><p>By default, if you send a message to someone and he is offline for more than two days, Bitmessage will send the message again after an additional two days. This will be continued with exponential backoff forever; messages will be resent after 5, 10, 20 days ect. until the receiver acknowledges them. Here you may change that behavior by having Bitmessage give up after a certain number of days or months.</p><p>Leave these input fields blank for the default behavior. </p></body></html></source>
<translation><html><head/><body><p>您发给他们的消息默认会在网络上保存两天,之后比特信会再重发一次. 重发时间会随指数上升; 消息会在5, 10, 20... 天后重发并以此类推. 直到收到收件人的回执. 你可以在这里改变这一行为,让比特信在尝试一段时间后放弃.</p><p>留空意味着默认行为. </p></body></html></translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="496"/>
<source>Give up after</source>
<translation>在</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="497"/>
<source>and</source>
<translation>和</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="498"/>
<source>days</source>
<translation>天</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="499"/>
<source>months.</source>
<translation>月后放弃。</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="500"/>
<source>Resends Expire</source>
<translation>重发超时</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="446"/>
<source>Hide connection notifications</source>
<translation>隐藏连接通知</translation>
</message>
<message>
<location filename="../bitmessageqt/settings.py" line="484"/>
<source>Hardware GPU acceleration (OpenCL):</source>
<translation>硬件GPU加速(OpenCL):</translation>
</message>
</context>
</TS> | {'content_hash': 'a59a3ed01c4d5794cb5111015f0dfd4c', 'timestamp': '', 'source': 'github', 'line_count': 2323, 'max_line_length': 809, 'avg_line_length': 45.68058544984933, 'alnum_prop': 0.6510705265935391, 'repo_name': 'bmng-dev/PyBitmessage', 'id': '323bf123563efd093ce1da0c44dcbc96ca32c092', 'size': '117500', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/bitmessageqt/translations/bitmessage_zh_cn.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '7456'}, {'name': 'C++', 'bytes': '4482'}, {'name': 'Makefile', 'bytes': '711'}, {'name': 'Python', 'bytes': '1057896'}, {'name': 'QMake', 'bytes': '1650'}]} |
package com.github.weisj.darklaf.ui.cell;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
public interface ComponentBasedTableCellRenderer extends TableCellRenderer, ComponentBackedRenderer {
}
| {'content_hash': '6044fde1c97d3172fac7543a4fe24442', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 101, 'avg_line_length': 26.875, 'alnum_prop': 0.8418604651162791, 'repo_name': 'weisJ/darklaf', 'id': '0879a872835d3b07f0208803b419600026601585', 'size': '1344', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/com/github/weisj/darklaf/ui/cell/ComponentBasedTableCellRenderer.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2609'}, {'name': 'C++', 'bytes': '40050'}, {'name': 'CSS', 'bytes': '4031'}, {'name': 'Java', 'bytes': '3992909'}, {'name': 'Kotlin', 'bytes': '70507'}, {'name': 'Objective-C', 'bytes': '2779'}, {'name': 'Objective-C++', 'bytes': '21437'}]} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using WebApp.Controller;
namespace WebApp.customer
{
public partial class TimeListing : System.Web.UI.Page
{
Route route;
protected void Page_Load(object sender, EventArgs e)
{
route = Route.getRouteByID(int.Parse(Request.QueryString["routeID"]));
WebControlGenerator.showInfo(route, infoPanel, false);
List<TimeOfWeek> schedule = TimeOfWeek.getTimesByRouteIDAsList(route.Id);
foreach (TimeOfWeek t in schedule)
{
t.setNextOperations();
WebControlGenerator.addTimesToPanel(route, t, timesPanel, true);
}
}
protected void InfoLinkClicked(object sender, EventArgs e)
{
if (infoPanel.Visible == false)
{
infoPanel.Visible = true;
}
else
{
infoPanel.Visible = false;
}
}
}
} | {'content_hash': '1965652a48a16a89d89ab68f8b868940', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 85, 'avg_line_length': 27.878048780487806, 'alnum_prop': 0.5634295713035871, 'repo_name': 'HopefulLlama/EuropeBus', 'id': '86b0bb66e4bec147a7a73f5f060317a0cae0615b', 'size': '1145', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'WebApp/customer/TimeListing.aspx.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '34955'}, {'name': 'C#', 'bytes': '201567'}, {'name': 'CSS', 'bytes': '14431'}, {'name': 'JavaScript', 'bytes': '164026'}]} |
package com.alibaba.dubbo.common.utils;
import java.util.concurrent.atomic.AtomicInteger;
/**
* AtomicPositiveInteger
*/
public class AtomicPositiveInteger extends Number {
private static final long serialVersionUID = -3038533876489105940L;
private final AtomicInteger i;
public AtomicPositiveInteger() {
i = new AtomicInteger();
}
public AtomicPositiveInteger(int initialValue) {
i = new AtomicInteger(initialValue);
}
public final int getAndIncrement() {
for (; ; ) {
int current = i.get();
int next = (current >= Integer.MAX_VALUE ? 0 : current + 1);
if (i.compareAndSet(current, next)) {
return current;
}
}
}
public final int getAndDecrement() {
for (; ; ) {
int current = i.get();
int next = (current <= 0 ? Integer.MAX_VALUE : current - 1);
if (i.compareAndSet(current, next)) {
return current;
}
}
}
public final int incrementAndGet() {
for (; ; ) {
int current = i.get();
int next = (current >= Integer.MAX_VALUE ? 0 : current + 1);
if (i.compareAndSet(current, next)) {
return next;
}
}
}
public final int decrementAndGet() {
for (; ; ) {
int current = i.get();
int next = (current <= 0 ? Integer.MAX_VALUE : current - 1);
if (i.compareAndSet(current, next)) {
return next;
}
}
}
public final int get() {
return i.get();
}
public final void set(int newValue) {
if (newValue < 0) {
throw new IllegalArgumentException("new value " + newValue + " < 0");
}
i.set(newValue);
}
public final int getAndSet(int newValue) {
if (newValue < 0) {
throw new IllegalArgumentException("new value " + newValue + " < 0");
}
return i.getAndSet(newValue);
}
public final int getAndAdd(int delta) {
if (delta < 0) {
throw new IllegalArgumentException("delta " + delta + " < 0");
}
for (; ; ) {
int current = i.get();
int next = (current >= Integer.MAX_VALUE - delta + 1 ? delta - 1 : current + delta);
if (i.compareAndSet(current, next)) {
return current;
}
}
}
public final int addAndGet(int delta) {
if (delta < 0) {
throw new IllegalArgumentException("delta " + delta + " < 0");
}
for (; ; ) {
int current = i.get();
int next = (current >= Integer.MAX_VALUE - delta + 1 ? delta - 1 : current + delta);
if (i.compareAndSet(current, next)) {
return next;
}
}
}
public final boolean compareAndSet(int expect, int update) {
if (update < 0) {
throw new IllegalArgumentException("update value " + update + " < 0");
}
return i.compareAndSet(expect, update);
}
public final boolean weakCompareAndSet(int expect, int update) {
if (update < 0) {
throw new IllegalArgumentException("update value " + update + " < 0");
}
return i.weakCompareAndSet(expect, update);
}
public byte byteValue() {
return i.byteValue();
}
public short shortValue() {
return i.shortValue();
}
public int intValue() {
return i.intValue();
}
public long longValue() {
return i.longValue();
}
public float floatValue() {
return i.floatValue();
}
public double doubleValue() {
return i.doubleValue();
}
public String toString() {
return i.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + i.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof AtomicPositiveInteger)) return false;
AtomicPositiveInteger other = (AtomicPositiveInteger) obj;
return i.intValue() == other.i.intValue();
}
} | {'content_hash': '1563a774f45aac6be20a4d61d2cb3103', 'timestamp': '', 'source': 'github', 'line_count': 165, 'max_line_length': 96, 'avg_line_length': 27.187878787878788, 'alnum_prop': 0.5057958091841284, 'repo_name': 'dadarom/dubbo', 'id': 'f9bc27a02d955b84b82373c4973e6feb834a51c0', 'size': '5302', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/AtomicPositiveInteger.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3447'}, {'name': 'CSS', 'bytes': '18582'}, {'name': 'Java', 'bytes': '5301948'}, {'name': 'JavaScript', 'bytes': '63148'}, {'name': 'Lex', 'bytes': '2077'}, {'name': 'Shell', 'bytes': '7011'}, {'name': 'Thrift', 'bytes': '668'}]} |
package org.tensorflow.lite.support.image;
import com.google.android.odml.image.BitmapExtractor;
import com.google.android.odml.image.ByteBufferExtractor;
import com.google.android.odml.image.MediaImageExtractor;
import com.google.android.odml.image.MlImage;
import com.google.android.odml.image.MlImage.ImageFormat;
import com.google.auto.value.AutoValue;
import java.nio.ByteBuffer;
/** Converts {@code MlImage} to {@link TensorImage} and vice versa. */
public class MlImageAdapter {
/** Proxies an {@link ImageFormat} and its equivalent {@link ColorSpaceType}. */
@AutoValue
abstract static class ImageFormatProxy {
abstract ColorSpaceType getColorSpaceType();
@ImageFormat
abstract int getImageFormat();
static ImageFormatProxy createFromImageFormat(@ImageFormat int format) {
switch (format) {
case MlImage.IMAGE_FORMAT_RGB:
return new AutoValue_MlImageAdapter_ImageFormatProxy(
ColorSpaceType.RGB, format);
case MlImage.IMAGE_FORMAT_NV12:
return new AutoValue_MlImageAdapter_ImageFormatProxy(
ColorSpaceType.NV12, format);
case MlImage.IMAGE_FORMAT_NV21:
return new AutoValue_MlImageAdapter_ImageFormatProxy(
ColorSpaceType.NV21, format);
case MlImage.IMAGE_FORMAT_YV12:
return new AutoValue_MlImageAdapter_ImageFormatProxy(
ColorSpaceType.YV12, format);
case MlImage.IMAGE_FORMAT_YV21:
return new AutoValue_MlImageAdapter_ImageFormatProxy(
ColorSpaceType.YV21, format);
case MlImage.IMAGE_FORMAT_YUV_420_888:
return new AutoValue_MlImageAdapter_ImageFormatProxy(
ColorSpaceType.YUV_420_888, format);
case MlImage.IMAGE_FORMAT_ALPHA:
return new AutoValue_MlImageAdapter_ImageFormatProxy(
ColorSpaceType.GRAYSCALE, format);
case MlImage.IMAGE_FORMAT_RGBA:
case MlImage.IMAGE_FORMAT_JPEG:
case MlImage.IMAGE_FORMAT_UNKNOWN:
throw new IllegalArgumentException(
"Cannot create ColorSpaceType from MlImage format: " + format);
default:
throw new AssertionError("Illegal @ImageFormat: " + format);
}
}
}
/**
* Creates a {@link TensorImage} from an {@link MlImage}.
*
* <p>IMPORTANT: The returned {@link TensorImage} shares storage with {@code mlImage}, so do not
* modify the contained object in the {@link TensorImage}, as {@code MlImage} expects its
* contained data are immutable. Also, callers should use {@code
* MlImage#getInternal()#acquire()} and {@code MlImage#release()} to avoid the {@code mlImage}
* being released unexpectedly.
*
* @throws IllegalArgumentException if the {@code mlImage} is built from an unsupported
* container.
*/
public static TensorImage createTensorImageFrom(MlImage mlImage) {
// TODO(b/190670174): Choose the best storage from multiple containers.
com.google.android.odml.image.ImageProperties mlImageProperties =
mlImage.getContainedImageProperties().get(0);
switch (mlImageProperties.getStorageType()) {
case MlImage.STORAGE_TYPE_BITMAP:
return TensorImage.fromBitmap(BitmapExtractor.extract(mlImage));
case MlImage.STORAGE_TYPE_MEDIA_IMAGE:
TensorImage mediaTensorImage = new TensorImage();
mediaTensorImage.load(MediaImageExtractor.extract(mlImage));
return mediaTensorImage;
case MlImage.STORAGE_TYPE_BYTEBUFFER:
ByteBuffer buffer = ByteBufferExtractor.extract(mlImage);
ImageFormatProxy formatProxy =
ImageFormatProxy.createFromImageFormat(mlImageProperties.getImageFormat());
TensorImage byteBufferTensorImage = new TensorImage();
ImageProperties properties =
ImageProperties.builder()
.setColorSpaceType(formatProxy.getColorSpaceType())
.setHeight(mlImage.getHeight())
.setWidth(mlImage.getWidth())
.build();
byteBufferTensorImage.load(buffer, properties);
return byteBufferTensorImage;
default:
throw new IllegalArgumentException(
"Illegal storage type: " + mlImageProperties.getStorageType());
}
}
/** Creatas a {@link ColorSpaceType} from {@code MlImage.ImageFormat}. */
public static ColorSpaceType createColorSpaceTypeFrom(@ImageFormat int imageFormat) {
return ImageFormatProxy.createFromImageFormat(imageFormat).getColorSpaceType();
}
private MlImageAdapter() {}
}
| {'content_hash': '5443c0fe4acf8acc00962c188789d5ad', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 100, 'avg_line_length': 48.660377358490564, 'alnum_prop': 0.6170996510275301, 'repo_name': 'scheib/chromium', 'id': '03017bf733f02a35a99d80f5be2195364371f0dc', 'size': '5826', 'binary': False, 'copies': '8', 'ref': 'refs/heads/main', 'path': 'third_party/tflite_support/src/tensorflow_lite_support/java/src/java/org/tensorflow/lite/support/image/MlImageAdapter.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
package com.pacificmetrics.orca.mbeans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import com.pacificmetrics.common.OperationResult;
import com.pacificmetrics.orca.IBMetafileServicesStatus;
import com.pacificmetrics.orca.ejb.IBMetafileServices;
import com.pacificmetrics.orca.ejb.PassageServices;
import com.pacificmetrics.orca.entities.ItemBankMetafile;
import com.pacificmetrics.orca.entities.Passage;
import com.pacificmetrics.orca.entities.PassageMetafileAssociation;
@ManagedBean(name="metafilePassageAssoc")
@ViewScoped
public class IBMetafilePassageAssociationManager extends AbstractManager implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
private transient IBMetafileServices metafileServices;
@EJB
private transient PassageServices passageServices;
private List<Passage> allPassages = new ArrayList<Passage>();
private List<PassageMetafileAssociation> existingPassageAssociations;
private List<PassageMetafileAssociation> outdatedPassageAssociations;
private int metafileId;
private int version;
private ItemBankMetafile metafile;
private int selectedPageIndex;
private List<Integer> selectedPassages;
private List<Integer> selectedExistingPassages;
private List<Integer> selectedOutdatedPassages;
@PostConstruct
public void load() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> paramMap = context.getExternalContext().getRequestParameterMap();
String metafileParamValue = paramMap.get("metafile");
String versionParamValue = paramMap.get("version");
if (metafileParamValue != null && versionParamValue != null) {
metafileId = Integer.parseInt(metafileParamValue);
version = Integer.parseInt(versionParamValue);
metafile = metafileServices.findMetafileByIdAndVersion(metafileId, version);
//
allPassages = passageServices.getPassagesByBankId(metafile.getItemBankId());
updateAssociations();
}
}
private void clear() {
selectedPassages = null;
selectedExistingPassages = null;
}
public List<Passage> getAllPassages() {
return allPassages;
}
public void setAllPassages(List<Passage> allPassages) {
this.allPassages = allPassages;
}
public int getMetafileId() {
return metafileId;
}
public void setMetafileId(int metafileId) {
this.metafileId = metafileId;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public ItemBankMetafile getMetafile() {
return metafile;
}
public void setMetafile(ItemBankMetafile metafile) {
this.metafile = metafile;
}
public int getSelectedPageIndex() {
return selectedPageIndex;
}
public void setSelectedPageIndex(int selectedPageIndex) {
this.selectedPageIndex = selectedPageIndex;
}
public void confirmNewIDs() {
if (selectedPassages == null || selectedPassages.isEmpty()) {
error(IBMetafileServicesStatus.NOTHING_TO_PROCESS);
return;
}
OperationResult res = metafileServices.associatePassagesWithMetafile(metafileId, version, selectedPassages);
handleOperationResult(res);
selectedPageIndex = 0;
selectedPassages = null;
updateAssociations();
}
private void updateAssociations() {
existingPassageAssociations = metafileServices.getPassageAssociations(metafileId, version);
outdatedPassageAssociations = metafileServices.getPassageAssociationsOutdated(metafileId);
}
public List<Integer> getSelectedPassages() {
return selectedPassages;
}
public void setSelectedPassages(List<Integer> selectedPassages) {
this.selectedPassages = selectedPassages;
}
public List<PassageMetafileAssociation> getExistingPassageAssociations() {
return existingPassageAssociations;
}
public void setExistingPassageAssociations(List<PassageMetafileAssociation> existingPassageAssociations) {
this.existingPassageAssociations = existingPassageAssociations;
}
public List<Integer> getSelectedExistingPassages() {
return selectedExistingPassages;
}
public void setSelectedExistingPassages(List<Integer> selectedExistingPassages) {
this.selectedExistingPassages = selectedExistingPassages;
}
public void removeSelected() {
remove(selectedExistingPassages);
}
public void removeAll() {
List<Integer> associationIds = new ArrayList<Integer>();
for (PassageMetafileAssociation pma: existingPassageAssociations) {
associationIds.add(pma.getId());
}
remove(associationIds);
}
private void remove(List<Integer> associationIds) {
OperationResult res = metafileServices.unassociatePassages(metafileId, version, associationIds);
handleOperationResult(res);
updateAssociations();
clear();
selectedPageIndex = 1;
}
public List<PassageMetafileAssociation> getOutdatedPassageAssociations() {
return outdatedPassageAssociations;
}
public void setOutdatedPassageAssociations(
List<PassageMetafileAssociation> outdatedPassageAssociations) {
this.outdatedPassageAssociations = outdatedPassageAssociations;
}
public List<Integer> getSelectedOutdatedPassages() {
return selectedOutdatedPassages;
}
public void setSelectedOutdatedPassages(List<Integer> selectedOutdatedPassages) {
this.selectedOutdatedPassages = selectedOutdatedPassages;
}
public void updateSelected() {
update(selectedOutdatedPassages);
}
public void updateAll() {
List<Integer> associationIds = new ArrayList<Integer>();
for (PassageMetafileAssociation pma: outdatedPassageAssociations) {
associationIds.add(pma.getId());
}
update(associationIds);
}
private void update(List<Integer> associationIds) {
OperationResult res = metafileServices.updatePassageAssociations(metafileId, version, associationIds);
handleOperationResult(res);
updateAssociations();
clear();
selectedPageIndex = 2;
}
}
| {'content_hash': '8a1af7f3f3261ea00cbe38586c45a1c6', 'timestamp': '', 'source': 'github', 'line_count': 205, 'max_line_length': 110, 'avg_line_length': 29.53170731707317, 'alnum_prop': 0.7872481004294681, 'repo_name': 'SmarterApp/ItemAuthoring', 'id': '02513d1350d0f6cb5103280655e32f45e8677141', 'size': '6054', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sbac-iaip-rpm-installer/sbac-iaip/java/src/main/java/com/pacificmetrics/orca/mbeans/IBMetafilePassageAssociationManager.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '147410'}, {'name': 'CSS', 'bytes': '1164986'}, {'name': 'Java', 'bytes': '26209067'}, {'name': 'JavaScript', 'bytes': '14650137'}, {'name': 'Makefile', 'bytes': '9954'}, {'name': 'PHP', 'bytes': '231796'}, {'name': 'Perl', 'bytes': '3585185'}, {'name': 'Perl6', 'bytes': '1379686'}, {'name': 'Prolog', 'bytes': '202152'}, {'name': 'Python', 'bytes': '17544'}, {'name': 'Shell', 'bytes': '204272'}, {'name': 'TeX', 'bytes': '185'}, {'name': 'XSLT', 'bytes': '875701'}]} |
@interface NSObject (IBMemberIntegration)
+ (id)ibClassDefaultImage;
+ (id)ibDefaultImageForInstance:(id)arg1;
+ (void)ibPopulateAdditionalInspectors:(id)arg1 forCategory:(id)arg2;
+ (long long)ibMemberType;
- (id)ibDefaultImage;
- (BOOL)ibIsInspectorApplicable:(id)arg1 forCategory:(id)arg2;
- (id)ibApplicableInspectorsForCategory:(id)arg1 suggestion:(id)arg2;
- (void)ibRestoreDevelopmentStringArraysDuringCompilingInDocument:(id)arg1 usingContext:(id)arg2;
- (void)ibSwapInLocalizableStringArraysDuringCompilingInDocument:(id)arg1 usingContext:(id)arg2;
- (void)ibRestoreDevelopmentStringsDuringCompilingInDocument:(id)arg1 usingContext:(id)arg2;
- (void)ibSwapInLocalizableStringsDuringCompilingInDocument:(id)arg1 usingContext:(id)arg2;
- (void)ibRestoreLocalizableStringsIfNeededInDocument:(id)arg1 withContext:(id)arg2;
- (void)ibSwapInLocalizableStringsIfNeededInDocument:(id)arg1 withContext:(id)arg2;
- (id)ibCoerceValueToPlistTypeForIBToolDisplay:(id)arg1 forKeyPath:(id)arg2 strictness:(long long)arg3;
- (void)ibWillRemoveObject:(id)arg1 fromNonChildToManyRelation:(id)arg2;
- (void)ibWillRemoveObject:(id)arg1 fromNonChildToOneRelation:(id)arg2;
@end
| {'content_hash': 'dfeecefe8db0da5d5e2332ce1e7236a6', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 103, 'avg_line_length': 61.421052631578945, 'alnum_prop': 0.8303341902313625, 'repo_name': 'wczekalski/Distraction-Free-Xcode-plugin', 'id': 'ba35cd595e9ab4e6c68d49cda1a7aa0a41d826e4', 'size': '1328', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDEInterfaceBuilderKit/NSObject-IBMemberIntegration.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '81011'}, {'name': 'C++', 'bytes': '588495'}, {'name': 'DTrace', 'bytes': '1835'}, {'name': 'Objective-C', 'bytes': '10151940'}, {'name': 'Ruby', 'bytes': '1105'}]} |
using System;
using MyoSharp.Communication;
using MyoSharp.Device;
using MyoSharp.ConsoleSample.Internal;
using MyoSharp.Poses;
using MyoSharp.Exceptions;
namespace MyoSharp.ConsoleSample
{
/// <summary>
/// Myo devices can notify you every time the device detects that the user
/// is performing a different pose. However, sometimes it's useful to know
/// when a user has performed a series of poses. A
/// <see cref="PoseSequence"/> can monitor a Myo for a series of poses and
/// notify you when that sequence has completed.
/// </summary>
/// <remarks>
/// Not sure how to use this example?
/// - Open Visual Studio
/// - Go to the solution explorer
/// - Find the project that this file is contained within
/// - Right click on the project in the solution explorer, go to "properties"
/// - Go to the "Application" tab
/// - Under "Startup object" pick this example from the list
/// - Hit F5 and you should be good to go!
/// </remarks>
internal class PoseSequenceExample
{
#region Methods
private static void Main()
{
// create a hub to manage Myos
using (var channel = Channel.Create(
ChannelDriver.Create(ChannelBridge.Create(),
MyoErrorHandlerDriver.Create(MyoErrorHandlerBridge.Create()))))
using (var hub = Hub.Create(channel))
{
// listen for when a Myo connects
hub.MyoConnected += (sender, e) =>
{
Console.WriteLine("Myo {0} has connected!", e.Myo.Handle);
// for every Myo that connects, listen for special sequences
var sequence = PoseSequence.Create(
e.Myo,
Pose.WaveOut,
Pose.WaveIn);
sequence.PoseSequenceCompleted += Sequence_PoseSequenceCompleted;
};
// start listening for Myo data
channel.StartListening();
ConsoleHelper.UserInputLoop(hub);
}
}
#endregion
#region Event Handlers
private static void Sequence_PoseSequenceCompleted(object sender, PoseSequenceEventArgs e)
{
Console.WriteLine("{0} arm Myo has performed a pose sequence!", e.Myo.Arm);
e.Myo.Vibrate(VibrationType.Medium);
}
#endregion
}
} | {'content_hash': '1e7db2c159444e2d023680da152ec5c7', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 98, 'avg_line_length': 36.4264705882353, 'alnum_prop': 0.5841744045215987, 'repo_name': 'tayfuzun/MyoSharp', 'id': 'dba39c3bd09deadd3c923fcd284f3da8e6c0900a', 'size': '2479', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'MyoSharp.ConsoleSample/PoseSequenceExample.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '360122'}]} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.oos.types._1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Публично-правовые образования (ОКТМО ППО)
*
* <p>Java class for zfcs_nsiOKTMOPPOType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="zfcs_nsiOKTMOPPOType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="code">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <maxLength value="11"/>
* <minLength value="1"/>
* </restriction>
* </simpleType>
* </element>
* <element name="parentCode" minOccurs="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <maxLength value="11"/>
* <minLength value="1"/>
* </restriction>
* </simpleType>
* </element>
* <element name="name" type="{http://zakupki.gov.ru/oos/types/1}zfcs_longTextMinType"/>
* <element name="OKTMOCode">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <maxLength value="11"/>
* <minLength value="1"/>
* </restriction>
* </simpleType>
* </element>
* <element name="settlementType" minOccurs="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <minLength value="1"/>
* <maxLength value="500"/>
* </restriction>
* </simpleType>
* </element>
* <element name="registerName" type="{http://zakupki.gov.ru/oos/types/1}zfcs_longTextMinType" minOccurs="0"/>
* <element name="actual" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "zfcs_nsiOKTMOPPOType", propOrder = {
"code",
"parentCode",
"name",
"oktmoCode",
"settlementType",
"registerName",
"actual"
})
public class ZfcsNsiOKTMOPPOType {
@XmlElement(required = true)
protected String code;
protected String parentCode;
@XmlElement(required = true)
protected String name;
@XmlElement(name = "OKTMOCode", required = true)
protected String oktmoCode;
protected String settlementType;
protected String registerName;
protected boolean actual;
/**
* Gets the value of the code property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the parentCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getParentCode() {
return parentCode;
}
/**
* Sets the value of the parentCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParentCode(String value) {
this.parentCode = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the oktmoCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOKTMOCode() {
return oktmoCode;
}
/**
* Sets the value of the oktmoCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOKTMOCode(String value) {
this.oktmoCode = value;
}
/**
* Gets the value of the settlementType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSettlementType() {
return settlementType;
}
/**
* Sets the value of the settlementType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSettlementType(String value) {
this.settlementType = value;
}
/**
* Gets the value of the registerName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRegisterName() {
return registerName;
}
/**
* Sets the value of the registerName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRegisterName(String value) {
this.registerName = value;
}
/**
* Gets the value of the actual property.
*
*/
public boolean isActual() {
return actual;
}
/**
* Sets the value of the actual property.
*
*/
public void setActual(boolean value) {
this.actual = value;
}
}
| {'content_hash': '104b6f988b0058f1061f771efccdf6e4', 'timestamp': '', 'source': 'github', 'line_count': 255, 'max_line_length': 122, 'avg_line_length': 25.11764705882353, 'alnum_prop': 0.5433255269320844, 'repo_name': 'simokhov/schemas44', 'id': '83da1bda5c93abf82f3e4abab08d68ed68a4459e', 'size': '6440', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/ru/gov/zakupki/oos/types/_1/ZfcsNsiOKTMOPPOType.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '22048974'}]} |
#ifndef __RTL92CE_HW_H__
#define __RTL92CE_HW_H__
static inline u8 rtl92c_get_chnl_group(u8 chnl)
{
u8 group;
if (chnl < 3)
group = 0;
else if (chnl < 9)
group = 1;
else
group = 2;
return group;
}
void rtl92ce_get_hw_reg(struct ieee80211_hw *hw, u8 variable, u8 *val);
void rtl92ce_read_eeprom_info(struct ieee80211_hw *hw);
void rtl92ce_interrupt_recognized(struct ieee80211_hw *hw,
u32 *p_inta, u32 *p_intb);
int rtl92ce_hw_init(struct ieee80211_hw *hw);
void rtl92ce_card_disable(struct ieee80211_hw *hw);
void rtl92ce_enable_interrupt(struct ieee80211_hw *hw);
void rtl92ce_disable_interrupt(struct ieee80211_hw *hw);
int rtl92ce_set_network_type(struct ieee80211_hw *hw, enum nl80211_iftype type);
void rtl92ce_set_check_bssid(struct ieee80211_hw *hw, bool check_bssid);
void rtl92ce_set_qos(struct ieee80211_hw *hw, int aci);
void rtl92ce_set_beacon_related_registers(struct ieee80211_hw *hw);
void rtl92ce_set_beacon_interval(struct ieee80211_hw *hw);
void rtl92ce_update_interrupt_mask(struct ieee80211_hw *hw,
u32 add_msr, u32 rm_msr);
void rtl92ce_set_hw_reg(struct ieee80211_hw *hw, u8 variable, u8 *val);
void rtl92ce_update_hal_rate_tbl(struct ieee80211_hw *hw,
struct ieee80211_sta *sta, u8 rssi_level);
void rtl92ce_update_hal_rate_tbl(struct ieee80211_hw *hw,
struct ieee80211_sta *sta, u8 rssi_level);
void rtl92ce_update_channel_access_setting(struct ieee80211_hw *hw);
bool rtl92ce_gpio_radio_on_off_checking(struct ieee80211_hw *hw, u8 *valid);
void rtl92ce_enable_hw_security_config(struct ieee80211_hw *hw);
void rtl92ce_set_key(struct ieee80211_hw *hw, u32 key_index,
u8 *p_macaddr, bool is_group, u8 enc_algo,
bool is_wepkey, bool clear_all);
void rtl8192ce_read_bt_coexist_info_from_hwpg(struct ieee80211_hw *hw,
bool autoload_fail, u8 *hwinfo);
void rtl8192ce_bt_reg_init(struct ieee80211_hw *hw);
void rtl8192ce_bt_hw_init(struct ieee80211_hw *hw);
void rtl92ce_suspend(struct ieee80211_hw *hw);
void rtl92ce_resume(struct ieee80211_hw *hw);
#endif
| {'content_hash': 'b1def775b60a9ea72256ff1197985c8e', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 80, 'avg_line_length': 38.37735849056604, 'alnum_prop': 0.73992133726647, 'repo_name': 'publicloudapp/csrutil', 'id': '98a086822aaceb5172e1d040352ab2d3f4bce283', 'size': '3210', 'binary': False, 'copies': '1602', 'ref': 'refs/heads/master', 'path': 'linux-4.3/drivers/net/wireless/rtlwifi/rtl8192ce/hw.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '3984'}, {'name': 'Awk', 'bytes': '29136'}, {'name': 'C', 'bytes': '532969471'}, {'name': 'C++', 'bytes': '3352303'}, {'name': 'Clojure', 'bytes': '1489'}, {'name': 'Cucumber', 'bytes': '4701'}, {'name': 'Groff', 'bytes': '46775'}, {'name': 'Lex', 'bytes': '55199'}, {'name': 'Makefile', 'bytes': '1576284'}, {'name': 'Objective-C', 'bytes': '521540'}, {'name': 'Perl', 'bytes': '715196'}, {'name': 'Perl6', 'bytes': '3783'}, {'name': 'Python', 'bytes': '273092'}, {'name': 'Shell', 'bytes': '343618'}, {'name': 'SourcePawn', 'bytes': '4687'}, {'name': 'UnrealScript', 'bytes': '12797'}, {'name': 'XS', 'bytes': '1239'}, {'name': 'Yacc', 'bytes': '114559'}]} |
/**
* @name defaults
* @kind function
*
* @description
* defaults allows to specify a default fallback value for properties that resolve to undefined.
*/
function defaults(array, defaults) {
if(!isArray(array) || !isObject(defaults)) {
return array;
}
//get defaults keys(include nested).
var keys = deepKeys(defaults);
array.forEach(function(elm) {
//loop through all the keys
keys.forEach(function(key) {
var getter = $parse(key);
var setter = getter.assign;
//if it's not exist
if(isUndefined(getter(elm))) {
//get from defaults, and set to the returned object
setter(elm, getter(defaults))
}
});
});
return array;
} | {'content_hash': '337b36b8b7dfd937d96770d4632bf244', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 96, 'avg_line_length': 22.741935483870968, 'alnum_prop': 0.6354609929078014, 'repo_name': 'a8m/agile', 'id': '22d51232fdde7c9cc20e70e2eff081b0c771d4af', 'size': '705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/_agile/array/defaults.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '242103'}]} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket_streambuf::non_blocking (3 of 3 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../non_blocking.html" title="basic_socket_streambuf::non_blocking">
<link rel="prev" href="overload2.html" title="basic_socket_streambuf::non_blocking (2 of 3 overloads)">
<link rel="next" href="../non_blocking_io.html" title="basic_socket_streambuf::non_blocking_io">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload2.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../non_blocking.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../non_blocking_io.html"><img src="../../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="asio.reference.basic_socket_streambuf.non_blocking.overload3"></a><a class="link" href="overload3.html" title="basic_socket_streambuf::non_blocking (3 of 3 overloads)">basic_socket_streambuf::non_blocking
(3 of 3 overloads)</a>
</h5></div></div></div>
<p>
<span class="emphasis"><em>Inherited from basic_socket.</em></span>
</p>
<p>
Sets the non-blocking mode of the socket.
</p>
<pre class="programlisting"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">non_blocking</span><span class="special">(</span>
<span class="keyword">bool</span> <span class="identifier">mode</span><span class="special">,</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
<h6>
<a name="asio.reference.basic_socket_streambuf.non_blocking.overload3.h0"></a>
<span><a name="asio.reference.basic_socket_streambuf.non_blocking.overload3.parameters"></a></span><a class="link" href="overload3.html#asio.reference.basic_socket_streambuf.non_blocking.overload3.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">mode</span></dt>
<dd><p>
If <code class="computeroutput"><span class="keyword">true</span></code>, the socket's
synchronous operations will fail with <code class="computeroutput"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">would_block</span></code>
if they are unable to perform the requested operation immediately.
If <code class="computeroutput"><span class="keyword">false</span></code>, synchronous
operations will block until complete.
</p></dd>
<dt><span class="term">ec</span></dt>
<dd><p>
Set to indicate what error occurred, if any.
</p></dd>
</dl>
</div>
<h6>
<a name="asio.reference.basic_socket_streambuf.non_blocking.overload3.h1"></a>
<span><a name="asio.reference.basic_socket_streambuf.non_blocking.overload3.remarks"></a></span><a class="link" href="overload3.html#asio.reference.basic_socket_streambuf.non_blocking.overload3.remarks">Remarks</a>
</h6>
<p>
The non-blocking mode has no effect on the behaviour of asynchronous
operations. Asynchronous operations will never fail with the error <code class="computeroutput"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">would_block</span></code>.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2013 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload2.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../non_blocking.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../non_blocking_io.html"><img src="../../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| {'content_hash': '2e0017dc8927c2a91d4bc7fc0bdd9ce8', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 363, 'avg_line_length': 68.67105263157895, 'alnum_prop': 0.6441847097145047, 'repo_name': 'laeotropic/HTTP-Proxy', 'id': '6884afb93537033e1cd6c5a18d71897eb8bedd91', 'size': '5219', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'deps/asio-1.10.1/doc/asio/reference/basic_socket_streambuf/non_blocking/overload3.html', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C++', 'bytes': '25868'}]} |
#include "test.h"
#include "rdkafka.h"
/**
* @brief Admin API local dry-run unit-tests.
*/
#define MY_SOCKET_TIMEOUT_MS 100
#define MY_SOCKET_TIMEOUT_MS_STR "100"
static mtx_t last_event_lock;
static cnd_t last_event_cnd;
static rd_kafka_event_t *last_event = NULL;
/**
* @brief The background event callback is called automatically
* by librdkafka from a background thread.
*/
static void background_event_cb (rd_kafka_t *rk, rd_kafka_event_t *rkev,
void *opaque) {
mtx_lock(&last_event_lock);
TEST_ASSERT(!last_event, "Multiple events seen in background_event_cb "
"(existing %s, new %s)",
rd_kafka_event_name(last_event), rd_kafka_event_name(rkev));
last_event = rkev;
mtx_unlock(&last_event_lock);
cnd_broadcast(&last_event_cnd);
rd_sleep(1);
}
static rd_kafka_event_t *wait_background_event_cb (void) {
rd_kafka_event_t *rkev;
mtx_lock(&last_event_lock);
while (!(rkev = last_event))
cnd_wait(&last_event_cnd, &last_event_lock);
last_event = NULL;
mtx_unlock(&last_event_lock);
return rkev;
}
/**
* @brief CreateTopics tests
*
*
*
*/
static void do_test_CreateTopics (const char *what,
rd_kafka_t *rk, rd_kafka_queue_t *useq,
int with_background_event_cb,
int with_options) {
rd_kafka_queue_t *q = useq ? useq : rd_kafka_queue_new(rk);
#define MY_NEW_TOPICS_CNT 6
rd_kafka_NewTopic_t *new_topics[MY_NEW_TOPICS_CNT];
rd_kafka_AdminOptions_t *options = NULL;
int exp_timeout = MY_SOCKET_TIMEOUT_MS;
int i;
char errstr[512];
const char *errstr2;
rd_kafka_resp_err_t err;
test_timing_t timing;
rd_kafka_event_t *rkev;
const rd_kafka_CreateTopics_result_t *res;
const rd_kafka_topic_result_t **restopics;
size_t restopic_cnt;
void *my_opaque = NULL, *opaque;
TEST_SAY(_C_MAG "[ %s CreateTopics with %s, timeout %dms ]\n",
rd_kafka_name(rk), what, exp_timeout);
/**
* Construct NewTopic array with different properties for
* different partitions.
*/
for (i = 0 ; i < MY_NEW_TOPICS_CNT ; i++) {
const char *topic = test_mk_topic_name(__FUNCTION__, 1);
int num_parts = i * 51 + 1;
int num_replicas = jitter(1, MY_NEW_TOPICS_CNT-1);
int set_config = (i & 2);
int set_replicas = !(i % 1);
new_topics[i] = rd_kafka_NewTopic_new(topic,
num_parts,
set_replicas ? -1 :
num_replicas,
NULL, 0);
if (set_config) {
/*
* Add various (unverified) configuration properties
*/
err = rd_kafka_NewTopic_set_config(new_topics[i],
"dummy.doesntexist",
"butThere'sNothing "
"to verify that");
TEST_ASSERT(!err, "%s", rd_kafka_err2str(err));
err = rd_kafka_NewTopic_set_config(new_topics[i],
"try.a.null.value",
NULL);
TEST_ASSERT(!err, "%s", rd_kafka_err2str(err));
err = rd_kafka_NewTopic_set_config(new_topics[i],
"or.empty", "");
TEST_ASSERT(!err, "%s", rd_kafka_err2str(err));
}
if (set_replicas) {
int32_t p;
int32_t replicas[MY_NEW_TOPICS_CNT];
int j;
for (j = 0 ; j < num_replicas ; j++)
replicas[j] = j;
/*
* Set valid replica assignments
*/
for (p = 0 ; p < num_parts ; p++) {
/* Try adding an existing out of order,
* should fail */
if (p == 1) {
err = rd_kafka_NewTopic_set_replica_assignment(
new_topics[i], p+1,
replicas, num_replicas,
errstr, sizeof(errstr));
TEST_ASSERT(err == RD_KAFKA_RESP_ERR__INVALID_ARG,
"%s", rd_kafka_err2str(err));
}
err = rd_kafka_NewTopic_set_replica_assignment(
new_topics[i], p,
replicas, num_replicas,
errstr, sizeof(errstr));
TEST_ASSERT(!err, "%s", errstr);
}
/* Try to add an existing partition, should fail */
err = rd_kafka_NewTopic_set_replica_assignment(
new_topics[i], 0,
replicas, num_replicas, NULL, 0);
TEST_ASSERT(err == RD_KAFKA_RESP_ERR__INVALID_ARG,
"%s", rd_kafka_err2str(err));
} else {
int32_t dummy_replicas[1] = {1};
/* Test invalid partition */
err = rd_kafka_NewTopic_set_replica_assignment(
new_topics[i], num_parts+1, dummy_replicas, 1,
errstr, sizeof(errstr));
TEST_ASSERT(err == RD_KAFKA_RESP_ERR__INVALID_ARG,
"%s: %s", rd_kafka_err2str(err),
err == RD_KAFKA_RESP_ERR_NO_ERROR ?
"" : errstr);
/* Setting replicas with with default replicas != -1
* is an error. */
err = rd_kafka_NewTopic_set_replica_assignment(
new_topics[i], 0, dummy_replicas, 1,
errstr, sizeof(errstr));
TEST_ASSERT(err == RD_KAFKA_RESP_ERR__INVALID_ARG,
"%s: %s", rd_kafka_err2str(err),
err == RD_KAFKA_RESP_ERR_NO_ERROR ?
"" : errstr);
}
}
if (with_options) {
options = rd_kafka_AdminOptions_new(rk, RD_KAFKA_ADMIN_OP_ANY);
exp_timeout = MY_SOCKET_TIMEOUT_MS * 2;
err = rd_kafka_AdminOptions_set_request_timeout(
options, exp_timeout, errstr, sizeof(errstr));
TEST_ASSERT(!err, "%s", rd_kafka_err2str(err));
my_opaque = (void *)123;
rd_kafka_AdminOptions_set_opaque(options, my_opaque);
}
TIMING_START(&timing, "CreateTopics");
TEST_SAY("Call CreateTopics, timeout is %dms\n", exp_timeout);
rd_kafka_CreateTopics(rk, new_topics, MY_NEW_TOPICS_CNT,
options, q);
TIMING_ASSERT_LATER(&timing, 0, 50);
if (with_background_event_cb) {
/* Result event will be triggered by callback from
* librdkafka background queue thread. */
TIMING_START(&timing, "CreateTopics.wait_background_event_cb");
rkev = wait_background_event_cb();
} else {
/* Poll result queue */
TIMING_START(&timing, "CreateTopics.queue_poll");
rkev = rd_kafka_queue_poll(q, exp_timeout + 1000);
}
TIMING_ASSERT_LATER(&timing, exp_timeout-100, exp_timeout+100);
TEST_ASSERT(rkev != NULL, "expected result in %dms",
exp_timeout);
TEST_SAY("CreateTopics: got %s in %.3fs\n",
rd_kafka_event_name(rkev),
TIMING_DURATION(&timing) / 1000.0f);
/* Convert event to proper result */
res = rd_kafka_event_CreateTopics_result(rkev);
TEST_ASSERT(res, "expected CreateTopics_result, not %s",
rd_kafka_event_name(rkev));
opaque = rd_kafka_event_opaque(rkev);
TEST_ASSERT(opaque == my_opaque, "expected opaque to be %p, not %p",
my_opaque, opaque);
/* Expecting error */
err = rd_kafka_event_error(rkev);
errstr2 = rd_kafka_event_error_string(rkev);
TEST_ASSERT(err == RD_KAFKA_RESP_ERR__TIMED_OUT,
"expected CreateTopics to return error %s, not %s (%s)",
rd_kafka_err2str(RD_KAFKA_RESP_ERR__TIMED_OUT),
rd_kafka_err2str(err),
err ? errstr2 : "n/a");
/* Attempt to extract topics anyway, should return NULL. */
restopics = rd_kafka_CreateTopics_result_topics(res, &restopic_cnt);
TEST_ASSERT(!restopics && restopic_cnt == 0,
"expected no result_topics, got %p cnt %"PRIusz,
restopics, restopic_cnt);
rd_kafka_event_destroy(rkev);
rd_kafka_NewTopic_destroy_array(new_topics, MY_NEW_TOPICS_CNT);
if (options)
rd_kafka_AdminOptions_destroy(options);
if (!useq)
rd_kafka_queue_destroy(q);
}
/**
* @brief DeleteTopics tests
*
*
*
*/
static void do_test_DeleteTopics (const char *what,
rd_kafka_t *rk, rd_kafka_queue_t *useq,
int with_options) {
rd_kafka_queue_t *q = useq ? useq : rd_kafka_queue_new(rk);
#define MY_DEL_TOPICS_CNT 4
rd_kafka_DeleteTopic_t *del_topics[MY_DEL_TOPICS_CNT];
rd_kafka_AdminOptions_t *options = NULL;
int exp_timeout = MY_SOCKET_TIMEOUT_MS;
int i;
char errstr[512];
const char *errstr2;
rd_kafka_resp_err_t err;
test_timing_t timing;
rd_kafka_event_t *rkev;
const rd_kafka_DeleteTopics_result_t *res;
const rd_kafka_topic_result_t **restopics;
size_t restopic_cnt;
void *my_opaque = NULL, *opaque;
TEST_SAY(_C_MAG "[ %s DeleteTopics with %s, timeout %dms ]\n",
rd_kafka_name(rk), what, exp_timeout);
for (i = 0 ; i < MY_DEL_TOPICS_CNT ; i++)
del_topics[i] = rd_kafka_DeleteTopic_new(test_mk_topic_name(__FUNCTION__, 1));
if (with_options) {
options = rd_kafka_AdminOptions_new(
rk, RD_KAFKA_ADMIN_OP_DELETETOPICS);
exp_timeout = MY_SOCKET_TIMEOUT_MS * 2;
err = rd_kafka_AdminOptions_set_request_timeout(
options, exp_timeout, errstr, sizeof(errstr));
TEST_ASSERT(!err, "%s", rd_kafka_err2str(err));
if (useq) {
my_opaque = (void *)456;
rd_kafka_AdminOptions_set_opaque(options, my_opaque);
}
}
TIMING_START(&timing, "DeleteTopics");
TEST_SAY("Call DeleteTopics, timeout is %dms\n", exp_timeout);
rd_kafka_DeleteTopics(rk, del_topics, MY_DEL_TOPICS_CNT,
options, q);
TIMING_ASSERT_LATER(&timing, 0, 50);
/* Poll result queue */
TIMING_START(&timing, "DeleteTopics.queue_poll");
rkev = rd_kafka_queue_poll(q, exp_timeout + 1000);
TIMING_ASSERT_LATER(&timing, exp_timeout-100, exp_timeout+100);
TEST_ASSERT(rkev != NULL, "expected result in %dms", exp_timeout);
TEST_SAY("DeleteTopics: got %s in %.3fs\n",
rd_kafka_event_name(rkev), TIMING_DURATION(&timing) / 1000.0f);
/* Convert event to proper result */
res = rd_kafka_event_DeleteTopics_result(rkev);
TEST_ASSERT(res, "expected DeleteTopics_result, not %s",
rd_kafka_event_name(rkev));
opaque = rd_kafka_event_opaque(rkev);
TEST_ASSERT(opaque == my_opaque, "expected opaque to be %p, not %p",
my_opaque, opaque);
/* Expecting error */
err = rd_kafka_event_error(rkev);
errstr2 = rd_kafka_event_error_string(rkev);
TEST_ASSERT(err == RD_KAFKA_RESP_ERR__TIMED_OUT,
"expected DeleteTopics to return error %s, not %s (%s)",
rd_kafka_err2str(RD_KAFKA_RESP_ERR__TIMED_OUT),
rd_kafka_err2str(err),
err ? errstr2 : "n/a");
/* Attempt to extract topics anyway, should return NULL. */
restopics = rd_kafka_DeleteTopics_result_topics(res, &restopic_cnt);
TEST_ASSERT(!restopics && restopic_cnt == 0,
"expected no result_topics, got %p cnt %"PRIusz,
restopics, restopic_cnt);
rd_kafka_event_destroy(rkev);
rd_kafka_DeleteTopic_destroy_array(del_topics, MY_DEL_TOPICS_CNT);
if (options)
rd_kafka_AdminOptions_destroy(options);
if (!useq)
rd_kafka_queue_destroy(q);
}
/**
* @brief Test a mix of APIs using the same replyq.
*
* - Create topics A,B
* - Delete topic B
* - Create topic C
* - Create extra partitions for topic D
*/
static void do_test_mix (rd_kafka_t *rk, rd_kafka_queue_t *rkqu) {
char *topics[] = { "topicA", "topicB", "topicC" };
int cnt = 0;
struct waiting {
rd_kafka_event_type_t evtype;
int seen;
};
struct waiting id1 = {RD_KAFKA_EVENT_CREATETOPICS_RESULT};
struct waiting id2 = {RD_KAFKA_EVENT_DELETETOPICS_RESULT};
struct waiting id3 = {RD_KAFKA_EVENT_CREATETOPICS_RESULT};
struct waiting id4 = {RD_KAFKA_EVENT_CREATEPARTITIONS_RESULT};
TEST_SAY(_C_MAG "[ Mixed mode test on %s]\n", rd_kafka_name(rk));
test_CreateTopics_simple(rk, rkqu, topics, 2, 1, &id1);
test_DeleteTopics_simple(rk, rkqu, &topics[1], 1, &id2);
test_CreateTopics_simple(rk, rkqu, &topics[2], 1, 1, &id3);
test_CreatePartitions_simple(rk, rkqu, "topicD", 15, &id4);
while (cnt < 4) {
rd_kafka_event_t *rkev;
struct waiting *w;
rkev = rd_kafka_queue_poll(rkqu, -1);
TEST_ASSERT(rkev);
TEST_SAY("Got event %s: %s\n",
rd_kafka_event_name(rkev),
rd_kafka_event_error_string(rkev));
w = rd_kafka_event_opaque(rkev);
TEST_ASSERT(w);
TEST_ASSERT(w->evtype == rd_kafka_event_type(rkev),
"Expected evtype %d, not %d (%s)",
w->evtype, rd_kafka_event_type(rkev),
rd_kafka_event_name(rkev));
TEST_ASSERT(w->seen == 0, "Duplicate results");
w->seen++;
cnt++;
rd_kafka_event_destroy(rkev);
}
}
/**
* @brief Test AlterConfigs and DescribeConfigs
*/
static void do_test_configs (rd_kafka_t *rk, rd_kafka_queue_t *rkqu) {
#define MY_CONFRES_CNT RD_KAFKA_RESOURCE__CNT + 2
rd_kafka_ConfigResource_t *configs[MY_CONFRES_CNT];
rd_kafka_AdminOptions_t *options;
rd_kafka_event_t *rkev;
rd_kafka_resp_err_t err;
const rd_kafka_AlterConfigs_result_t *res;
const rd_kafka_ConfigResource_t **rconfigs;
size_t rconfig_cnt;
char errstr[128];
int i;
/* Check invalids */
configs[0] = rd_kafka_ConfigResource_new(
(rd_kafka_ResourceType_t)-1, "something");
TEST_ASSERT(!configs[0]);
configs[0] = rd_kafka_ConfigResource_new(
(rd_kafka_ResourceType_t)0, NULL);
TEST_ASSERT(!configs[0]);
for (i = 0 ; i < MY_CONFRES_CNT ; i++) {
int set_config = !(i % 2);
/* librdkafka shall not limit the use of illogical
* or unknown settings, they are enforced by the broker. */
configs[i] = rd_kafka_ConfigResource_new(
(rd_kafka_ResourceType_t)i, "3");
TEST_ASSERT(configs[i] != NULL);
if (set_config) {
rd_kafka_ConfigResource_set_config(configs[i],
"some.conf",
"which remains "
"unchecked");
rd_kafka_ConfigResource_set_config(configs[i],
"some.conf.null",
NULL);
}
}
options = rd_kafka_AdminOptions_new(rk, RD_KAFKA_ADMIN_OP_ANY);
err = rd_kafka_AdminOptions_set_request_timeout(options, 1000, errstr,
sizeof(errstr));
TEST_ASSERT(!err, "%s", errstr);
/* AlterConfigs */
rd_kafka_AlterConfigs(rk, configs, MY_CONFRES_CNT,
options, rkqu);
rkev = test_wait_admin_result(rkqu, RD_KAFKA_EVENT_ALTERCONFIGS_RESULT,
2000);
TEST_ASSERT(rd_kafka_event_error(rkev) == RD_KAFKA_RESP_ERR__TIMED_OUT,
"Expected timeout, not %s",
rd_kafka_event_error_string(rkev));
res = rd_kafka_event_AlterConfigs_result(rkev);
TEST_ASSERT(res);
rconfigs = rd_kafka_AlterConfigs_result_resources(res, &rconfig_cnt);
TEST_ASSERT(!rconfigs && !rconfig_cnt,
"Expected no result resources, got %"PRIusz,
rconfig_cnt);
rd_kafka_event_destroy(rkev);
/* DescribeConfigs: reuse same configs and options */
rd_kafka_DescribeConfigs(rk, configs, MY_CONFRES_CNT,
options, rkqu);
rd_kafka_AdminOptions_destroy(options);
rd_kafka_ConfigResource_destroy_array(configs, MY_CONFRES_CNT);
rkev = test_wait_admin_result(rkqu,
RD_KAFKA_EVENT_DESCRIBECONFIGS_RESULT,
2000);
TEST_ASSERT(rd_kafka_event_error(rkev) == RD_KAFKA_RESP_ERR__TIMED_OUT,
"Expected timeout, not %s",
rd_kafka_event_error_string(rkev));
res = rd_kafka_event_DescribeConfigs_result(rkev);
TEST_ASSERT(res);
rconfigs = rd_kafka_DescribeConfigs_result_resources(res, &rconfig_cnt);
TEST_ASSERT(!rconfigs && !rconfig_cnt,
"Expected no result resources, got %"PRIusz,
rconfig_cnt);
rd_kafka_event_destroy(rkev);
}
/**
* @brief Verify that an unclean rd_kafka_destroy() does not hang.
*/
static void do_test_unclean_destroy (rd_kafka_type_t cltype, int with_mainq) {
rd_kafka_t *rk;
char errstr[512];
rd_kafka_conf_t *conf;
rd_kafka_queue_t *q;
rd_kafka_event_t *rkev;
rd_kafka_DeleteTopic_t *topic;
test_timing_t t_destroy;
test_conf_init(&conf, NULL, 0);
/* Remove brokers, if any, since this is a local test and we
* rely on the controller not being found. */
test_conf_set(conf, "bootstrap.servers", "");
test_conf_set(conf, "socket.timeout.ms", "60000");
rk = rd_kafka_new(cltype, conf, errstr, sizeof(errstr));
TEST_ASSERT(rk, "kafka_new(%d): %s", cltype, errstr);
TEST_SAY(_C_MAG "[ Test unclean destroy for %s using %s]\n", rd_kafka_name(rk),
with_mainq ? "mainq" : "tempq");
if (with_mainq)
q = rd_kafka_queue_get_main(rk);
else
q = rd_kafka_queue_new(rk);
topic = rd_kafka_DeleteTopic_new("test");
rd_kafka_DeleteTopics(rk, &topic, 1, NULL, q);
rd_kafka_DeleteTopic_destroy(topic);
/* We're not expecting a result yet since DeleteTopics will attempt
* to look up the controller for socket.timeout.ms (1 minute). */
rkev = rd_kafka_queue_poll(q, 100);
TEST_ASSERT(!rkev, "Did not expect result: %s", rd_kafka_event_name(rkev));
rd_kafka_queue_destroy(q);
TEST_SAY("Giving rd_kafka_destroy() 5s to finish, "
"despite Admin API request being processed\n");
test_timeout_set(5);
TIMING_START(&t_destroy, "rd_kafka_destroy()");
rd_kafka_destroy(rk);
TIMING_STOP(&t_destroy);
/* Restore timeout */
test_timeout_set(60);
}
/**
* @brief Test AdminOptions
*/
static void do_test_options (rd_kafka_t *rk) {
#define _all_apis { RD_KAFKA_ADMIN_OP_CREATETOPICS, \
RD_KAFKA_ADMIN_OP_DELETETOPICS, \
RD_KAFKA_ADMIN_OP_CREATEPARTITIONS, \
RD_KAFKA_ADMIN_OP_ALTERCONFIGS, \
RD_KAFKA_ADMIN_OP_DESCRIBECONFIGS, \
RD_KAFKA_ADMIN_OP_ANY /* Must be last */}
struct {
const char *setter;
const rd_kafka_admin_op_t valid_apis[8];
} matrix[] = {
{ "request_timeout", _all_apis },
{ "operation_timeout", { RD_KAFKA_ADMIN_OP_CREATETOPICS,
RD_KAFKA_ADMIN_OP_DELETETOPICS,
RD_KAFKA_ADMIN_OP_CREATEPARTITIONS } },
{ "validate_only", { RD_KAFKA_ADMIN_OP_CREATETOPICS,
RD_KAFKA_ADMIN_OP_CREATEPARTITIONS,
RD_KAFKA_ADMIN_OP_ALTERCONFIGS } },
{ "broker", _all_apis },
{ "opaque", _all_apis },
{ NULL },
};
int i;
rd_kafka_AdminOptions_t *options;
for (i = 0 ; matrix[i].setter ; i++) {
static const rd_kafka_admin_op_t all_apis[] = _all_apis;
const rd_kafka_admin_op_t *for_api;
for (for_api = all_apis ; ; for_api++) {
rd_kafka_resp_err_t err = RD_KAFKA_RESP_ERR_NO_ERROR;
rd_kafka_resp_err_t exp_err = RD_KAFKA_RESP_ERR_NO_ERROR;
char errstr[512];
int fi;
options = rd_kafka_AdminOptions_new(rk, *for_api);
TEST_ASSERT(options,
"AdminOptions_new(%d) failed", *for_api);
if (!strcmp(matrix[i].setter, "request_timeout"))
err = rd_kafka_AdminOptions_set_request_timeout(
options, 1234, errstr, sizeof(errstr));
else if (!strcmp(matrix[i].setter, "operation_timeout"))
err = rd_kafka_AdminOptions_set_operation_timeout(
options, 12345, errstr, sizeof(errstr));
else if (!strcmp(matrix[i].setter, "validate_only"))
err = rd_kafka_AdminOptions_set_validate_only(
options, 1, errstr, sizeof(errstr));
else if (!strcmp(matrix[i].setter, "broker"))
err = rd_kafka_AdminOptions_set_broker(
options, 5, errstr, sizeof(errstr));
else if (!strcmp(matrix[i].setter, "opaque")) {
rd_kafka_AdminOptions_set_opaque(
options, (void *)options);
err = RD_KAFKA_RESP_ERR_NO_ERROR;
} else
TEST_FAIL("Invalid setter: %s",
matrix[i].setter);
TEST_SAYL(3, "AdminOptions_set_%s on "
"RD_KAFKA_ADMIN_OP_%d options "
"returned %s: %s\n",
matrix[i].setter,
*for_api,
rd_kafka_err2name(err),
err ? errstr : "success");
/* Scan matrix valid_apis to see if this
* setter should be accepted or not. */
if (exp_err) {
/* An expected error is already set */
} else if (*for_api != RD_KAFKA_ADMIN_OP_ANY) {
exp_err = RD_KAFKA_RESP_ERR__INVALID_ARG;
for (fi = 0 ; matrix[i].valid_apis[fi] ; fi++) {
if (matrix[i].valid_apis[fi] ==
*for_api)
exp_err = RD_KAFKA_RESP_ERR_NO_ERROR;
}
} else {
exp_err = RD_KAFKA_RESP_ERR_NO_ERROR;
}
if (err != exp_err)
TEST_FAIL_LATER("Expected AdminOptions_set_%s "
"for RD_KAFKA_ADMIN_OP_%d "
"options to return %s, "
"not %s",
matrix[i].setter,
*for_api,
rd_kafka_err2name(exp_err),
rd_kafka_err2name(err));
rd_kafka_AdminOptions_destroy(options);
if (*for_api == RD_KAFKA_ADMIN_OP_ANY)
break; /* This was the last one */
}
}
/* Try an invalid for_api */
options = rd_kafka_AdminOptions_new(rk, (rd_kafka_admin_op_t)1234);
TEST_ASSERT(!options, "Expectred AdminOptions_new() to fail "
"with an invalid for_api, didn't.");
TEST_LATER_CHECK();
}
static void do_test_apis (rd_kafka_type_t cltype) {
rd_kafka_t *rk;
char errstr[512];
rd_kafka_queue_t *mainq, *backgroundq;
rd_kafka_conf_t *conf;
mtx_init(&last_event_lock, mtx_plain);
cnd_init(&last_event_cnd);
do_test_unclean_destroy(cltype, 0/*tempq*/);
do_test_unclean_destroy(cltype, 1/*mainq*/);
test_conf_init(&conf, NULL, 0);
/* Remove brokers, if any, since this is a local test and we
* rely on the controller not being found. */
test_conf_set(conf, "bootstrap.servers", "");
test_conf_set(conf, "socket.timeout.ms", MY_SOCKET_TIMEOUT_MS_STR);
/* For use with the background queue */
rd_kafka_conf_set_background_event_cb(conf, background_event_cb);
rk = rd_kafka_new(cltype, conf, errstr, sizeof(errstr));
TEST_ASSERT(rk, "kafka_new(%d): %s", cltype, errstr);
mainq = rd_kafka_queue_get_main(rk);
backgroundq = rd_kafka_queue_get_background(rk);
do_test_options(rk);
do_test_CreateTopics("temp queue, no options", rk, NULL, 0, 0);
do_test_CreateTopics("temp queue, no options, background_event_cb",
rk, backgroundq, 1, 0);
do_test_CreateTopics("temp queue, options", rk, NULL, 0, 1);
do_test_CreateTopics("main queue, options", rk, mainq, 0, 1);
do_test_DeleteTopics("temp queue, no options", rk, NULL, 0);
do_test_DeleteTopics("temp queue, options", rk, NULL, 1);
do_test_DeleteTopics("main queue, options", rk, mainq, 1);
do_test_mix(rk, mainq);
do_test_configs(rk, mainq);
rd_kafka_queue_destroy(backgroundq);
rd_kafka_queue_destroy(mainq);
rd_kafka_destroy(rk);
mtx_destroy(&last_event_lock);
cnd_destroy(&last_event_cnd);
}
int main_0080_admin_ut (int argc, char **argv) {
do_test_apis(RD_KAFKA_PRODUCER);
do_test_apis(RD_KAFKA_CONSUMER);
return 0;
}
| {'content_hash': '73f748f690974e6063da5750db9d16ad', 'timestamp': '', 'source': 'github', 'line_count': 725, 'max_line_length': 94, 'avg_line_length': 40.14758620689655, 'alnum_prop': 0.4737348404163947, 'repo_name': 'LiberatorUSA/GUCEF', 'id': 'c62f67ddf2de004c8ced58c53fe05ebff6d74e36', 'size': '30527', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dependencies/librdkafka/tests/0080-admin_ut.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '68139'}, {'name': 'C', 'bytes': '2158073'}, {'name': 'C++', 'bytes': '14978976'}, {'name': 'CMake', 'bytes': '7671056'}, {'name': 'Cuda', 'bytes': '297'}, {'name': 'Dockerfile', 'bytes': '349'}, {'name': 'Emacs Lisp', 'bytes': '29494'}, {'name': 'Fortran', 'bytes': '4029'}, {'name': 'Java', 'bytes': '1389'}, {'name': 'Lua', 'bytes': '750004'}, {'name': 'M4', 'bytes': '1460'}, {'name': 'Makefile', 'bytes': '295122'}, {'name': 'NSIS', 'bytes': '35409'}, {'name': 'Shell', 'bytes': '181211'}, {'name': 'Tcl', 'bytes': '6493'}, {'name': 'Vim Script', 'bytes': '121243'}]} |
namespace InstrumentationRuntime
{
public ref class CMethodResultImpl sealed: public IMethodResult
{
rho::apiGenerator::CMethodResult* oResult;
public:
CMethodResultImpl(int64 native);
virtual void set(Platform::String^ res);
virtual void set(Windows::Foundation::Collections::IVectorView<Platform::String^>^ res);
virtual void set(Windows::Foundation::Collections::IMapView<Platform::String^, Platform::String^>^ res);
};
}
| {'content_hash': 'e879a1b13ed91cd9c569f1b2f1277507', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 112, 'avg_line_length': 32.266666666666666, 'alnum_prop': 0.6983471074380165, 'repo_name': 'tauplatform/tau', 'id': '7508a407609c8ca1e340097fec2bdb3057182dfc', 'size': '546', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'extensions/instrumentation/ext/platform/wp8/lib/MethodResultImpl.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '6291'}, {'name': 'Batchfile', 'bytes': '117803'}, {'name': 'C', 'bytes': '58276168'}, {'name': 'C#', 'bytes': '695670'}, {'name': 'C++', 'bytes': '17458941'}, {'name': 'COBOL', 'bytes': '187'}, {'name': 'CSS', 'bytes': '641054'}, {'name': 'GAP', 'bytes': '76344'}, {'name': 'HTML', 'bytes': '1756465'}, {'name': 'Java', 'bytes': '6450324'}, {'name': 'JavaScript', 'bytes': '1670149'}, {'name': 'Makefile', 'bytes': '330343'}, {'name': 'Matlab', 'bytes': '123'}, {'name': 'NSIS', 'bytes': '85403'}, {'name': 'Objective-C', 'bytes': '4133620'}, {'name': 'Objective-C++', 'bytes': '417934'}, {'name': 'Perl', 'bytes': '1710'}, {'name': 'QMake', 'bytes': '79603'}, {'name': 'Rebol', 'bytes': '130'}, {'name': 'Roff', 'bytes': '328967'}, {'name': 'Ruby', 'bytes': '17284489'}, {'name': 'Shell', 'bytes': '33635'}, {'name': 'XSLT', 'bytes': '4315'}, {'name': 'Yacc', 'bytes': '257479'}]} |
<?php
/**
* PHP Template.
* Author: Sheetal Patil. Sun Microsystems, Inc.
*
* This page is to collect the details of the event.
* The uploaded literature file and the image are stored in LocalFS storage.
* All the file types are handled in a file called fileService.php.
* If you want to open any file, you just need to call this and pass the file name.
* Once you submit this page, the event gets added and will be directed to the home page.
*
*/
?>
<script type="text/javascript">
//<![CDATA[
tinyMCE.init({
mode : 'textareas',
theme : 'simple'
});
//]]>
</script>
<script src="js/validateform.js" type="text/javascript"></script>
<script src="js/httpobject.js" type="text/javascript"></script>
<h1>New event</h1>
<form name="addEvent" action="addEventResult.php" method="POST" enctype="multipart/form-data" onsubmit="return checkEventFields()">
<fieldset id="event_form">
<legend>Event Details</legend>
<div id="basic_event_form">
<p><label for="title">Title</label><br/>
<? echo '<input id="title" name="title" size="30" type="text" value="'.$title.'" /></p>'; ?>
<p><label for="summary">Summary</label><br />
<? echo '<textarea cols="37" id="summary" name="summary" rows="20" >'.$summary.'</textarea></p>'; ?>
<p><label for="description">Description</label><br/>
<? echo '<textarea cols="37" id="description" name="description" rows="20" >'.$description.'</textarea></p>'; ?>
</div>
<div id="misc_event_form">
<p>
<label for="event_timestamp">Event date and time</label><br/>
<select id="year" name="year">
<?
require(Olio::$config['includes'] . "year.php");
?>
</select>
<select id="month" name="month">
<?
require(Olio::$config['includes'] . "month.php");
?>
</select>
<select id="day" name="day">
<?
require(Olio::$config['includes'] . "day.php");
?>
</select>
—<br/>
<select id="hour" name="hour">
<?
require(Olio::$config['includes'] . "hour.php");
?>
</select>
: <select id="minute" name="minute">
<?
require(Olio::$config['includes'] . "minute.php");
?>
</select>
</p>
<p>
<label for="telephone">Telephone</label><br/>
<? echo '<input id="telephone" name="telephone" size="30" type="text" value="'.$telephone.'" onblur="isValidTelephone();" />'; ?>
<p id="isvalidtelephone"></p>
</p>
<br /><hr /><br />
<p>
<label for="upload_image">Image</label><br/>
<? echo '<input name="upload_image" id="upload_image" type="file" />'; ?>
</p>
<p>
<label for="upload_literature">
Document <sup><em>(only PDF, Word, and plain text documents)</em></sup>
</label><br/>
<? echo '<input name="upload_literature" id="upload_literature" type="file" />'; ?>
</p>
<p><label for="tags">Tags</label><br/>
<? echo '<input id="tags" name="tags" size="40" type="text" value="'.$tags.'"/>'; ?>
</p>
</div>
</fieldset>
<fieldset id="address_form">
<legend>Address</legend>
<label for="street1">Street 1</label>
<? echo '<input id="street1" name="street1" size="30" type="text" value="'.$street1.'" /><br />'; ?>
<label for="street2">Street 2</label>
<? echo '<input id="street2" name="street2" size="30" type="text" value="'.$street2.'" /><br />'; ?>
<label for="zip">Zip</label>
<? echo '<input id="zip" name="zip" size="30" type="text" value="'.$zip.'" onblur="isValidZip();fillCityState();" /><br />'; ?>
<p id="isvalidzip"></p>
<label for="city">City</label>
<? echo '<input id="city" name="city" size="30" type="text" value="'.$city.'" /><br />'; ?>
<label for="state">State</label>
<? echo '<input id="state" name="state" size="30" type="text" value="'.$state.'" /><br />'; ?>
<label for="country">Country</label>
<select id="country" name="country">
<?
readfile(Olio::$config['includes'] . "countries.html");
if(!is_null($se)){
echo '<option selected="selected" value="'.$country.'">'.$country.'</option>';
}
?>
</select><br />
</fieldset>
<div class="clr"></div>
<?if(is_null($se)){?>
<input type="submit" value="Create" name="addeventsubmit" />
<?}else{?>
<input type="submit" value="Update" name="addeventsubmitupdate"/>
<?}?>
<input type='reset' value='Reset' name="addeventreset" />
</form>
| {'content_hash': 'b08a1fdf3a737ebb1cec333538fd6077', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 135, 'avg_line_length': 34.50381679389313, 'alnum_prop': 0.5657079646017699, 'repo_name': 'shanti/olio', 'id': '8133b5ccd598f1d53b3d836e804a4d47317c2ac2', 'size': '5325', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tags/0.1-final/tags/release-0.1/webapp/php/trunk/views/addEvent.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2669517'}, {'name': 'JavaScript', 'bytes': '1058343'}, {'name': 'PHP', 'bytes': '1001174'}, {'name': 'Perl', 'bytes': '252989'}, {'name': 'Ruby', 'bytes': '2400328'}, {'name': 'Shell', 'bytes': '57800'}]} |
package org.optaplanner.benchmark.impl.statistic.subsingle.pickedmovetypestepscore;
import org.optaplanner.benchmark.impl.aggregator.BenchmarkAggregator;
import org.optaplanner.benchmark.impl.statistic.StatisticPoint;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.impl.heuristic.move.CompositeMove;
import org.optaplanner.core.impl.heuristic.move.Move;
public class PickedMoveTypeStepScoreDiffStatisticPoint extends StatisticPoint {
private final long timeMillisSpent;
/**
* Not a {@link Class}{@code <}{@link Move}{@code >} because {@link CompositeMove}s need to be atomized
* and because that {@link Class} might no longer exist when {@link BenchmarkAggregator} aggregates.
*/
private final String moveType;
private final Score stepScoreDiff;
public PickedMoveTypeStepScoreDiffStatisticPoint(long timeMillisSpent, String moveType, Score stepScoreDiff) {
this.timeMillisSpent = timeMillisSpent;
this.moveType = moveType;
this.stepScoreDiff = stepScoreDiff;
}
public long getTimeMillisSpent() {
return timeMillisSpent;
}
public String getMoveType() {
return moveType;
}
public Score getStepScoreDiff() {
return stepScoreDiff;
}
@Override
public String toCsvLine() {
return buildCsvLineWithStrings(timeMillisSpent, moveType, stepScoreDiff.toString());
}
}
| {'content_hash': 'b25f83ea72b7f637b86ace78ba2860b5', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 114, 'avg_line_length': 32.36363636363637, 'alnum_prop': 0.7394662921348315, 'repo_name': 'droolsjbpm/optaplanner', 'id': '8108b07aa697db9ad2bdf48ab39dfe790ea95250', 'size': '2044', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/subsingle/pickedmovetypestepscore/PickedMoveTypeStepScoreDiffStatisticPoint.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2602'}, {'name': 'CSS', 'bytes': '13781'}, {'name': 'FreeMarker', 'bytes': '114386'}, {'name': 'HTML', 'bytes': '678'}, {'name': 'Java', 'bytes': '6988206'}, {'name': 'JavaScript', 'bytes': '215434'}, {'name': 'Shell', 'bytes': '1548'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'd4f2630f564d84936794d0bce7068928', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': '333250877239d27b565ae6d217c99abb86c0f1ea', 'size': '188', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Cyrtandra/Cyrtandra dilatata/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
Change Log
======
This project adheres to [Semantic Versioning](http://semver.org/).
Every release is documented on the GitHub [Releases](https://github.com/stremann/react-flypro/releases) page. | {'content_hash': '37a7df8393fc952a2a46f1176c3c8194', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 109, 'avg_line_length': 39.0, 'alnum_prop': 0.7589743589743589, 'repo_name': 'stremann/react-flypro', 'id': '61677c09630d4dfa23eb014b93e7d6c88b64a482', 'size': '195', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CHANGELOG.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '5736'}]} |
@interface GBObjectiveCParserIvarsParsingTesting : GBObjectsAssertor
@end
@implementation GBObjectiveCParserIvarsParsingTesting
#pragma mark Ivars parsing testing
- (void)testParseObjectsFromString_shouldIgnoreIVar {
// setup
GBObjectiveCParser *parser = [GBObjectiveCParser parserWithSettingsProvider:[GBTestObjectsRegistry mockSettingsProvider]];
GBStore *store = [[GBStore alloc] init];
// execute
[parser parseObjectsFromString:@"@interface MyClass { int _var; } @end" sourceFile:@"filename.h" toStore:store];
// verify
GBClassData *class = [[store classes] anyObject];
NSArray *ivars = [[class ivars] ivars];
assertThatInteger([ivars count], equalToInteger(0));
}
- (void)testParseObjectsFromString_shouldIgnoreAllIVars {
// setup
GBObjectiveCParser *parser = [GBObjectiveCParser parserWithSettingsProvider:[GBTestObjectsRegistry mockSettingsProvider]];
GBStore *store = [[GBStore alloc] init];
// execute
[parser parseObjectsFromString:@"@interface MyClass { int _var1; long _var2; } @end" sourceFile:@"filename.h" toStore:store];
// verify
GBClassData *class = [[store classes] anyObject];
NSArray *ivars = [[class ivars] ivars];
assertThatInteger([ivars count], equalToInteger(0));
}
- (void)testParseObjectsFromString_shouldIgnoreComplexIVar {
// setup
GBObjectiveCParser *parser = [GBObjectiveCParser parserWithSettingsProvider:[GBTestObjectsRegistry mockSettingsProvider]];
GBStore *store = [[GBStore alloc] init];
// execute
[parser parseObjectsFromString:@"@interface MyClass { id<Protocol>* _var; } @end" sourceFile:@"filename.h" toStore:store];
// verify
GBClassData *class = [[store classes] anyObject];
NSArray *ivars = [[class ivars] ivars];
assertThatInteger([ivars count], equalToInteger(0));
}
- (void)testParseObjectsFromString_shouldIgnoreIVarEndingWithParenthesis {
// setup
GBObjectiveCParser *parser = [GBObjectiveCParser parserWithSettingsProvider:[GBTestObjectsRegistry mockSettingsProvider]];
GBStore *store = [[GBStore alloc] init];
// execute
[parser parseObjectsFromString:@"@interface MyClass { void (^_name)(id obj, NSUInteger idx, BOOL *stop); } @end" sourceFile:@"filename.h" toStore:store];
// verify
GBClassData *class = [[store classes] anyObject];
NSArray *ivars = [[class ivars] ivars];
assertThatInteger([ivars count], equalToInteger(0));
}
@end
| {'content_hash': '74e9b9169dd022a1fe697021e853bbba', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 154, 'avg_line_length': 41.625, 'alnum_prop': 0.7674817674817674, 'repo_name': 'Popdeem/Popdeem-SDK-iOS', 'id': '5ddc58d3b9873f3ed78a6e7e496d37bf83c54251', 'size': '2929', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'Carthage/Checkouts/facebook-ios-sdk/vendor/appledoc/Testing/GBObjectiveCParser-IvarsParsingTesting.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2534'}, {'name': 'C++', 'bytes': '1307'}, {'name': 'Objective-C', 'bytes': '3002029'}, {'name': 'Ruby', 'bytes': '4490'}]} |
const helpers = require('./helpers')
const webpackConfig = require('./webpack.config.base')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const DefinePlugin = require('webpack/lib/DefinePlugin')
const env = require('../environment/dev.env')
webpackConfig.module.rules = [...webpackConfig.module.rules,
{
test: /\.scss$/,
use: [{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(jpg|png|gif|eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
webpackConfig.plugins = [...webpackConfig.plugins,
new HtmlWebpackPlugin({
inject: true,
template: helpers.root('/src/index.html'),
favicon: helpers.root('/src/favicon.ico')
}),
new DefinePlugin({
'process.env': env
})
]
webpackConfig.devServer = {
port: 8889,
host: 'localhost',
historyApiFallback: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
contentBase: './src',
open: true,
}
module.exports = webpackConfig
| {'content_hash': 'b77f674fb4acff79e046a82c1d8814ac', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 60, 'avg_line_length': 20.84, 'alnum_prop': 0.6314779270633397, 'repo_name': 'weexteam/weex-toolkit', 'id': 'd1dbcb0e26e6b79dc8c1a03c3a4b0ea61bf8b3b0', 'size': '1042', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'packages/@weex/plugins/debug/frontend/config/webpack.config.dev.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '510216'}, {'name': 'HTML', 'bytes': '60414'}, {'name': 'JavaScript', 'bytes': '10092059'}, {'name': 'Python', 'bytes': '3359'}, {'name': 'Shell', 'bytes': '230'}, {'name': 'TypeScript', 'bytes': '584132'}]} |
namespace Story
{
class CDlgNode: public Core::CObject
{
public:
enum ELinkMode
{
Link_Switch = 0, // First valid link
Link_Random = 1, // Random valid link
Link_Select = 2 // Valid link explicitly selected, for example in answer selection UI
};
struct CLink
{
CString Condition; // Scripted function name
CString Action; // Scripted function name
CDlgNode* pTargetNode;
};
CStrID SpeakerEntity; // May be entity UID or dlg context participator alias
CString Phrase;
//float Timeout; //???here or in associated sound resource?
ELinkMode LinkMode;
CArray<CLink> Links;
};
}
#endif
| {'content_hash': '10f725a707eb17e029b7509047b06e21', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 88, 'avg_line_length': 20.0, 'alnum_prop': 0.7032258064516129, 'repo_name': 'niello/deusexmachina', 'id': '17799a613396c8ee5e50ab5d323949042db6bbd2', 'size': '962', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DEM/RPG/src/Dlg/DlgNode.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '122533'}, {'name': 'Awk', 'bytes': '688'}, {'name': 'Batchfile', 'bytes': '7513'}, {'name': 'C', 'bytes': '16388375'}, {'name': 'C#', 'bytes': '398813'}, {'name': 'C++', 'bytes': '36890379'}, {'name': 'CMake', 'bytes': '561047'}, {'name': 'CSS', 'bytes': '10638'}, {'name': 'Fortran', 'bytes': '87'}, {'name': 'FreeBasic', 'bytes': '3789'}, {'name': 'HTML', 'bytes': '1351597'}, {'name': 'Lua', 'bytes': '135757'}, {'name': 'M4', 'bytes': '52785'}, {'name': 'Makefile', 'bytes': '52318'}, {'name': 'Mathematica', 'bytes': '4491'}, {'name': 'NSIS', 'bytes': '4683'}, {'name': 'Objective-C', 'bytes': '55376'}, {'name': 'Pascal', 'bytes': '29093'}, {'name': 'Perl', 'bytes': '39592'}, {'name': 'PowerShell', 'bytes': '7410'}, {'name': 'Python', 'bytes': '160966'}, {'name': 'Roff', 'bytes': '5263'}, {'name': 'Ruby', 'bytes': '39'}, {'name': 'SWIG', 'bytes': '11981'}, {'name': 'Shell', 'bytes': '7830'}, {'name': 'TeX', 'bytes': '149544'}, {'name': 'VBA', 'bytes': '41547'}, {'name': 'Visual Basic .NET', 'bytes': '8505'}]} |
/**
* @author Dan Nuffer
*/
#ifndef OW_DL_SHAREDLIBRARY_HPP_INCLUDE_GUARD_
#define OW_DL_SHAREDLIBRARY_HPP_INCLUDE_GUARD_
#include "OW_config.h"
#if defined(OW_USE_DL)
#include "OW_SharedLibrary.hpp"
#include "OW_Types.hpp"
#if defined(OW_USE_FAKE_LIBS)
#include "OW_Map.hpp"
#endif /* defined(OW_USE_FAKE_LIBS) */
// The classes and functions defined in this file are not meant for general
// use, they are internal implementation details. They may change at any time.
namespace OW_NAMESPACE
{
/**
* dlSharedLibrary loads and queries shared libraries. Using dlsym &
* friends.
*/
class dlSharedLibrary : public SharedLibrary
{
public:
dlSharedLibrary(void * libhandle, const String& libName);
virtual ~dlSharedLibrary();
/**
* on some platforms (e.g. glibc 2.2.x), there are bugs in the dl* functions,
* and the workaround is to not call dlclose. Setting this variable to 0
* will cause dlclose to never be called. Doing this has some problems:
* memory mapped to the shared library will never be freed up. New versions
* of the library can't be loaded (if a provider is updated)
*/
static void setCallDlclose(bool callDlclose)
{
s_call_dlclose = callDlclose;
}
/**
* Returns if the given path is a fake library or not.
*/
static bool isFakeLibrary(const String& library_path);
protected:
/**
* Derived classes have to override this function to implement
* the symbol loading. The symbol to be looked up is contained in
* functionName, and the pointer to the function should be written
* into *fp. Return true if the function succeeded, false otherwise.
* @param functionName The name of the function to resolve.
* @param fp Where to store the function pointer.
* @return true if function succeeded, false otherwise.
*/
virtual bool doGetFunctionPointer( const String& functionName,
void** fp ) const;
private:
void* m_libhandle;
String m_libName;
// non-copyable
dlSharedLibrary(const dlSharedLibrary&);
dlSharedLibrary& operator=(const dlSharedLibrary&);
#if defined(OW_USE_FAKE_LIBS)
bool m_fakeLibrary;
Map<String, String> m_symbolMap;
void initializeSymbolMap();
#endif /* defined(OW_USE_FAKE_LIBS) */
static bool s_call_dlclose;
};
} // end namespace OW_NAMESPACE
#endif // OW_USE_DL
#endif
| {'content_hash': '0da5d2100487ea328c676db26d3e40a3', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 79, 'avg_line_length': 26.732558139534884, 'alnum_prop': 0.7220530665506742, 'repo_name': 'kkaempf/openwbem', 'id': 'be7861262b046c93ff83beb3dfaf66683c90e517', 'size': '4004', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/common/OW_dlSharedLibrary.hpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '447743'}, {'name': 'C++', 'bytes': '8054531'}, {'name': 'Perl', 'bytes': '2789'}, {'name': 'Shell', 'bytes': '102214'}]} |
package com.google.refine.expr.functions.math;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONWriter;
import com.google.refine.expr.EvalError;
import com.google.refine.grel.ControlFunctionRegistry;
import com.google.refine.grel.Function;
public class FactN implements Function {
@Override
public Object call(Properties bindings, Object[] args) {
if (args.length != 2) {
return new EvalError(ControlFunctionRegistry.getFunctionName(this) + " expects two numbers");
}
if (args[0] == null || !(args[0] instanceof Number)) {
return new EvalError(ControlFunctionRegistry.getFunctionName(this) + " expects the first parameter to be a number");
}
if (args[1] == null || !(args[1] instanceof Number)) {
return new EvalError(ControlFunctionRegistry.getFunctionName(this) + " expects the second parameter to be a number");
}
return FactN.factorial(((Number) args[0]).intValue(), ((Number) args[1]).intValue());
}
/*
* Calculates the factorial of an integer, i, for a decreasing step of n.
* e.g. A double factorial would have a step of 2.
* Returns 1 for zero and negative integers.
*/
public static long factorial(long i, long step){
if (i < 0) {
throw new IllegalArgumentException("Can't compute the factorial of a negative number");
} else if(i <= 1) {
return 1;
} else {
long result = i * FactN.factorial(i - step, step);
if (result < 0) {
throw new ArithmeticException("Integer overflow computing factorial");
}
return result;
}
}
@Override
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("description"); writer.value("Returns the factorial of a number");
writer.key("params"); writer.value("number i");
writer.key("returns"); writer.value("number");
writer.endObject();
}
} | {'content_hash': '810a76dc7e42f83f94eeadbebcb5f2f8', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 129, 'avg_line_length': 34.26229508196721, 'alnum_prop': 0.6291866028708134, 'repo_name': 'DTL-FAIRData/FAIRifier', 'id': '9b225452656205b55f326ea4f18f7a69adba88b1', 'size': '3572', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'main/src/com/google/refine/expr/functions/math/FactN.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '169'}, {'name': 'Batchfile', 'bytes': '4771'}, {'name': 'CSS', 'bytes': '134159'}, {'name': 'HTML', 'bytes': '333450'}, {'name': 'Java', 'bytes': '3514431'}, {'name': 'JavaScript', 'bytes': '967765'}, {'name': 'PHP', 'bytes': '8799'}, {'name': 'Ruby', 'bytes': '2559'}, {'name': 'Shell', 'bytes': '28836'}]} |
package org.jbpm.workflow.core;
import org.kie.api.definition.process.Node;
import org.jbpm.process.core.Context;
/**
*
*/
public interface NodeContainer extends org.kie.api.definition.process.NodeContainer {
/**
* Method for adding a node to this node container.
* Note that the node will get an id unique for this node container.
*
* @param node the node to be added
* @throws IllegalArgumentException if <code>node</code> is null
*/
void addNode(Node node);
/**
* Method for removing a node from this node container
*
* @param node the node to be removed
* @throws IllegalArgumentException if <code>node</code> is null or unknown
*/
void removeNode(Node node);
Context resolveContext(String contextId, Object param);
Node internalGetNode(long id);
}
| {'content_hash': '41e62dc393bfbc433221baa042800dc2', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 85, 'avg_line_length': 25.352941176470587, 'alnum_prop': 0.6670533642691415, 'repo_name': 'domhanak/jbpm', 'id': '00d972262f4b9f76a142edf5eccd2c6f53e07620', 'size': '1481', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'jbpm-flow/src/main/java/org/jbpm/workflow/core/NodeContainer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '24447'}, {'name': 'HTML', 'bytes': '271'}, {'name': 'Java', 'bytes': '14344879'}, {'name': 'PLSQL', 'bytes': '34719'}, {'name': 'PLpgSQL', 'bytes': '11997'}, {'name': 'Protocol Buffer', 'bytes': '6518'}, {'name': 'Shell', 'bytes': '98'}, {'name': 'Visual Basic', 'bytes': '2545'}]} |
package org.lucidfox.jpromises.core;
import org.lucidfox.jpromises.Promise;
/**
* A callback to be invoked when a {@link Promise} or arbitrary {@link Thenable} is resolved.
*
* @param <V> the value type of the promise the callback is being bound to via {@link Thenable#then}
* @param <R> the type of the returned value for chaining
*/
public interface ValueResolveCallback<V, R> {
/**
* Called when the promise (thenable) is resolved.
*
* @param value the value with which the promise is resolved
* @return the value to pass to the promise returned by {@code thenApply}, and thus the next resolve callback
* in the {@code then} chain
* @throws Exception Signals that an error occurred when handling the result of the promise execution.
*/
R onResolve(V value) throws Exception;
}
| {'content_hash': 'ddb3e766af1e21416d1345710d34c718', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 110, 'avg_line_length': 35.04347826086956, 'alnum_prop': 0.728287841191067, 'repo_name': 'lucidfox/jpromises', 'id': '02d9da0f1f5510f00c27bcee9c20c5ea16f1ec15', 'size': '1938', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/lucidfox/jpromises/core/ValueResolveCallback.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '184833'}]} |
package org.pentaho.di.core.database;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.pentaho.di.core.row.value.ValueMetaBigNumber;
import org.pentaho.di.core.row.value.ValueMetaBoolean;
import org.pentaho.di.core.row.value.ValueMetaDate;
import org.pentaho.di.core.row.value.ValueMetaInteger;
import org.pentaho.di.core.row.value.ValueMetaInternetAddress;
import org.pentaho.di.core.row.value.ValueMetaNumber;
import org.pentaho.di.core.row.value.ValueMetaString;
public class UniVerseDatabaseMetaTest {
private UniVerseDatabaseMeta nativeMeta, odbcMeta;
@Before
public void setupBefore() {
nativeMeta = new UniVerseDatabaseMeta();
nativeMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_NATIVE );
odbcMeta = new UniVerseDatabaseMeta();
odbcMeta.setAccessType( DatabaseMeta.TYPE_ACCESS_ODBC );
}
@Test
public void testSettings() throws Exception {
assertArrayEquals( new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI },
nativeMeta.getAccessTypeList() );
assertEquals( 65535, nativeMeta.getMaxVARCHARLength() );
assertEquals( -1, nativeMeta.getDefaultDatabasePort() );
assertEquals( -1, odbcMeta.getDefaultDatabasePort() );
assertTrue( nativeMeta.supportsAutoInc() );
assertEquals( 1, nativeMeta.getNotFoundTK( true ) );
assertEquals( 0, nativeMeta.getNotFoundTK( false ) );
assertEquals( "com.ibm.u2.jdbc.UniJDBCDriver", nativeMeta.getDriverClass() );
assertEquals( "sun.jdbc.odbc.JdbcOdbcDriver", odbcMeta.getDriverClass() );
assertEquals( "jdbc:odbc:FOO", odbcMeta.getURL( "IGNORED", "IGNORED", "FOO" ) );
assertEquals( "jdbc:ibm-u2://FOO/WIBBLE", nativeMeta.getURL( "FOO", "IGNORED", "WIBBLE" ) );
assertEquals( "\"FOO\".\"BAR\"", nativeMeta.getSchemaTableCombination( "FOO", "BAR" ) );
assertFalse( nativeMeta.isFetchSizeSupported() );
assertFalse( nativeMeta.supportsBitmapIndex() );
assertFalse( nativeMeta.supportsSynonyms() );
assertTrue( nativeMeta.supportsNewLinesInSQL() );
assertFalse( nativeMeta.supportsTimeStampToDateConversion() );
assertArrayEquals( new String[] {
"@NEW", "@OLD", "ACTION", "ADD", "AL", "ALL", "ALTER", "AND", "AR", "AS", "ASC", "ASSOC", "ASSOCIATED",
"ASSOCIATION", "AUTHORIZATION", "AVERAGE", "AVG", "BEFORE", "BETWEEN", "BIT", "BOTH", "BY", "CALC",
"CASCADE", "CASCADED", "CAST", "CHAR", "CHAR_LENGTH", "CHARACTER", "CHARACTER_LENGTH", "CHECK", "COL.HDG",
"COL.SPACES", "COL.SPCS", "COL.SUP", "COLUMN", "COMPILED", "CONNECT", "CONSTRAINT", "CONV", "CONVERSION",
"COUNT", "COUNT.SUP", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "DATA", "DATE", "DBA", "DBL.SPC",
"DEC", "DECIMAL", "DEFAULT", "DELETE", "DESC", "DET.SUP", "DICT", "DISPLAY.NAME", "DISPLAYLIKE",
"DISPLAYNAME", "DISTINCT", "DL", "DOUBLE", "DR", "DROP", "DYNAMIC", "E.EXIST", "EMPTY", "EQ", "EQUAL",
"ESCAPE", "EVAL", "EVERY", "EXISTING", "EXISTS", "EXPLAIN", "EXPLICIT", "FAILURE", "FIRST", "FLOAT",
"FMT", "FOOTER", "FOOTING", "FOR", "FOREIGN", "FORMAT", "FROM", "FULL", "GE", "GENERAL", "GRAND",
"GRAND.TOTAL", "GRANT", "GREATER", "GROUP", "GROUP.SIZE", "GT", "HAVING", "HEADER", "HEADING", "HOME",
"IMPLICIT", "IN", "INDEX", "INNER", "INQUIRING", "INSERT", "INT", "INTEGER", "INTO", "IS", "JOIN", "KEY",
"LARGE.RECORD", "LAST", "LE", "LEADING", "LEFT", "LESS", "LIKE", "LOCAL", "LOWER", "LPTR", "MARGIN",
"MATCHES", "MATCHING", "MAX", "MERGE.LOAD", "MIN", "MINIMIZE.SPACE", "MINIMUM.MODULUS", "MODULO",
"MULTI.VALUE", "MULTIVALUED", "NATIONAL", "NCHAR", "NE", "NO", "NO.INDEX", "NO.OPTIMIZE", "NO.PAGE",
"NOPAGE", "NOT", "NRKEY", "NULL", "NUMERIC", "NVARCHAR", "ON", "OPTION", "OR", "ORDER", "OUTER", "PCT",
"PRECISION", "PRESERVING", "PRIMARY", "PRIVILEGES", "PUBLIC", "REAL", "RECORD.SIZE", "REFERENCES",
"REPORTING", "RESOURCE", "RESTORE", "RESTRICT", "REVOKE", "RIGHT", "ROWUNIQUE", "SAID", "SAMPLE",
"SAMPLED", "SCHEMA", "SELECT", "SEPARATION", "SEQ.NUM", "SET", "SINGLE.VALUE", "SINGLEVALUED", "SLIST",
"SMALLINT", "SOME", "SPLIT.LOAD", "SPOKEN", "SUBSTRING", "SUCCESS", "SUM", "SUPPRESS", "SYNONYM", "TABLE",
"TIME", "TO", "TOTAL", "TRAILING", "TRIM", "TYPE", "UNION", "UNIQUE", "UNNEST", "UNORDERED", "UPDATE",
"UPPER", "USER", "USING", "VALUES", "VARBIT", "VARCHAR", "VARYING", "VERT", "VERTICALLY", "VIEW", "WHEN",
"WHERE", "WITH", }, nativeMeta.getReservedWords() );
assertArrayEquals( new String[] { "unijdbc.jar", "asjava.zip" }, nativeMeta.getUsedLibraries() );
}
@Test
public void testSQLStatements() {
assertEquals( "ALTER TABLE FOO ADD BAR VARCHAR(15)",
nativeMeta.getAddColumnStatement( "FOO", new ValueMetaString( "BAR", 15, 0 ), "", false, "", false ) );
assertEquals( "ALTER TABLE FOO MODIFY BAR VARCHAR(15)",
nativeMeta.getModifyColumnStatement( "FOO", new ValueMetaString( "BAR", 15, 0 ), "", false, "", false ) );
assertEquals( "insert into FOO(FOOKEY, FOOVERSION) values (0, 1)",
nativeMeta.getSQLInsertAutoIncUnknownDimensionRow( "FOO", "FOOKEY", "FOOVERSION" ) );
assertEquals( "DELETE FROM FOO",
nativeMeta.getTruncateTableStatement( "FOO" ) );
}
@Test
public void testGetFieldDefinition() {
assertEquals( "FOO DATE",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, true, false ) );
assertEquals( "DATE",
nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, false, false ) ); // Note - Rocket U2 does *not* support timestamps ...
assertEquals( "CHAR(1)",
nativeMeta.getFieldDefinition( new ValueMetaBoolean( "FOO" ), "", "", false, false, false ) );
assertEquals( "INTEGER",
nativeMeta.getFieldDefinition( new ValueMetaNumber( "FOO", 10, 0 ), "FOO", "", false, false, false ) );
assertEquals( "INTEGER",
nativeMeta.getFieldDefinition( new ValueMetaNumber( "FOO", 10, 0 ), "", "FOO", false, false, false ) );
// Numeric Types
assertEquals( "DECIMAL(5, 5)",
nativeMeta.getFieldDefinition( new ValueMetaNumber( "FOO", 5, 5 ), "", "", false, false, false ) );
assertEquals( "DECIMAL(19, 0)",
nativeMeta.getFieldDefinition( new ValueMetaBigNumber( "FOO", 19, 0 ), "", "", false, false, false ) );
assertEquals( "INTEGER",
nativeMeta.getFieldDefinition( new ValueMetaInteger( "FOO", 18, 0 ), "", "", false, false, false ) );
assertEquals( "DOUBLE PRECISION",
nativeMeta.getFieldDefinition( new ValueMetaNumber( "FOO", -7, -3 ), "", "", false, false, false ) );
assertEquals( "VARCHAR(15)",
nativeMeta.getFieldDefinition( new ValueMetaString( "FOO", 15, 0 ), "", "", false, false, false ) );
assertEquals( "VARCHAR(65535)",
nativeMeta.getFieldDefinition( new ValueMetaString( "FOO", 65537, 0 ), "", "", false, false, false ) );
assertEquals( " UNKNOWN",
nativeMeta.getFieldDefinition( new ValueMetaInternetAddress( "FOO" ), "", "", false, false, false ) );
assertEquals( " UNKNOWN" + System.getProperty( "line.separator" ),
nativeMeta.getFieldDefinition( new ValueMetaInternetAddress( "FOO" ), "", "", false, false, true ) );
}
}
| {'content_hash': '9e194d2ee9d8cfbd87c52d7a958273ee', 'timestamp': '', 'source': 'github', 'line_count': 130, 'max_line_length': 153, 'avg_line_length': 58.23076923076923, 'alnum_prop': 0.6398943196829591, 'repo_name': 'hudak/pentaho-kettle', 'id': '5d6cd530491511c9552f7f70262dede17888d6ef', 'size': '8494', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'core/test-src/org/pentaho/di/core/database/UniVerseDatabaseMetaTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '14382'}, {'name': 'CSS', 'bytes': '30418'}, {'name': 'GAP', 'bytes': '4005'}, {'name': 'HTML', 'bytes': '55153'}, {'name': 'Java', 'bytes': '40046715'}, {'name': 'JavaScript', 'bytes': '49292'}, {'name': 'Shell', 'bytes': '19927'}, {'name': 'XSLT', 'bytes': '5600'}]} |
#pragma once
void hexDump ( char* data, int lines, char* buffer, bool forward );
| {'content_hash': '41a4dbf65b1fb9186ff9f17c09bf2aee', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 67, 'avg_line_length': 12.285714285714286, 'alnum_prop': 0.6744186046511628, 'repo_name': 'haoch/kylin', 'id': 'cbf7d0588d81ef55bea812f3f9f3a902e47a12f2', 'size': '893', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'odbc/Common/Dump.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '4736'}, {'name': 'C++', 'bytes': '595793'}, {'name': 'CSS', 'bytes': '134220'}, {'name': 'HTML', 'bytes': '293311'}, {'name': 'Java', 'bytes': '5355152'}, {'name': 'JavaScript', 'bytes': '343978'}, {'name': 'Objective-C', 'bytes': '27913'}, {'name': 'PLSQL', 'bytes': '905'}, {'name': 'Protocol Buffer', 'bytes': '5581'}, {'name': 'Shell', 'bytes': '43666'}]} |
<!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 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.cloudera.oryx.example.batch.ExampleBatchLayerUpdate (Oryx 2.8.0 API)</title>
<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="Uses of Class com.cloudera.oryx.example.batch.ExampleBatchLayerUpdate (Oryx 2.8.0 API)";
}
}
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><a href="../../../../../../com/cloudera/oryx/example/batch/ExampleBatchLayerUpdate.html" title="class in com.cloudera.oryx.example.batch">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/cloudera/oryx/example/batch/class-use/ExampleBatchLayerUpdate.html" target="_top">Frames</a></li>
<li><a href="ExampleBatchLayerUpdate.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All 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">
<h2 title="Uses of Class com.cloudera.oryx.example.batch.ExampleBatchLayerUpdate" class="title">Uses of Class<br>com.cloudera.oryx.example.batch.ExampleBatchLayerUpdate</h2>
</div>
<div class="classUseContainer">No usage of com.cloudera.oryx.example.batch.ExampleBatchLayerUpdate</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><a href="../../../../../../com/cloudera/oryx/example/batch/ExampleBatchLayerUpdate.html" title="class in com.cloudera.oryx.example.batch">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/cloudera/oryx/example/batch/class-use/ExampleBatchLayerUpdate.html" target="_top">Frames</a></li>
<li><a href="ExampleBatchLayerUpdate.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All 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 ======= -->
<p class="legalCopy"><small>Copyright © 2014–2018. All rights reserved.</small></p>
</body>
</html>
| {'content_hash': '17a447cc6578c466c34fee4f941b7570', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 173, 'avg_line_length': 37.824, 'alnum_prop': 0.620346869712352, 'repo_name': 'srowen/oryx', 'id': '1b33d8666fc2436ad1301df16d18f1a4cd6a75dd', 'size': '4728', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'docs/apidocs/com/cloudera/oryx/example/batch/class-use/ExampleBatchLayerUpdate.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1204068'}, {'name': 'Scala', 'bytes': '17286'}, {'name': 'Shell', 'bytes': '15828'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="https://just2us.com/img/favicon-180.png" />
<link rel="apple-touch-icon" href="https://just2us.com/img/favicon-192.png"/>
<!-- CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/clean-blog.min.css">
<link rel="stylesheet" href="/css/syntax.css">
<!-- Fonts -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&display=swap' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&display=swap' rel='stylesheet' type='text/css'>
<!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link type="application/atom+xml" rel="alternate" href="https://just2me.com/feed.xml" title="Just2me" />
<!-- Begin Jekyll SEO tag v2.6.1 -->
<title>How to Make Money Buying Groupon Deals? | Just2me</title>
<meta name="generator" content="Jekyll v4.0.0" />
<meta property="og:title" content="How to Make Money Buying Groupon Deals?" />
<meta name="author" content="Junda Ong" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="The trick is to earn $10 referral fee for every deal." />
<meta property="og:description" content="The trick is to earn $10 referral fee for every deal." />
<link rel="canonical" href="https://just2me.com/2011/09/03/how-to-make-money-buying-groupon-deals/" />
<meta property="og:url" content="https://just2me.com/2011/09/03/how-to-make-money-buying-groupon-deals/" />
<meta property="og:site_name" content="Just2me" />
<meta property="og:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2011-09-03T01:13:00+08:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="twitter:title" content="How to Make Money Buying Groupon Deals?" />
<meta name="twitter:site" content="@samwize" />
<meta name="twitter:creator" content="@Junda Ong" />
<meta property="fb:admins" content="704185456" />
<script type="application/ld+json">
{"description":"The trick is to earn $10 referral fee for every deal.","@type":"BlogPosting","publisher":{"@type":"Organization","logo":{"@type":"ImageObject","url":"https://just2us.com/img/favicon-192.png"},"name":"Junda Ong"},"image":"https://just2me.com/img/jewel-fountain.jpeg","url":"https://just2me.com/2011/09/03/how-to-make-money-buying-groupon-deals/","headline":"How to Make Money Buying Groupon Deals?","dateModified":"2011-09-03T01:13:00+08:00","datePublished":"2011-09-03T01:13:00+08:00","author":{"@type":"Person","name":"Junda Ong"},"mainEntityOfPage":{"@type":"WebPage","@id":"https://just2me.com/2011/09/03/how-to-make-money-buying-groupon-deals/"},"@context":"https://schema.org"}</script>
<!-- End Jekyll SEO tag -->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Just2me</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="/stories">Stories</a>
</li>
<li>
<a href="https://just2us.com/apps">Apps</a>
</li>
<li>
<a href="/quotes">Quotes</a>
</li>
<li>
<a href="/about">About</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Post Header -->
<header class="intro-header" style="background-image: url('/img/jewel-fountain.jpeg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-heading">
<h1>How to Make Money Buying Groupon Deals?</h1>
<span class="meta">Published on September 3, 2011</span>
</div>
</div>
</div>
</div>
</header>
<!-- Post Content -->
<article>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>The trick is to earn $10 referral fee for every deal.</p>
<p>There is loophole with Groupon that makes it very easy to earn the referral fee for every deal. Read the <a href="http://blog.just2us.com/2011/07/how-to-always-earn-10-for-each-groupon-deal/">step-by-step instruction</a>.</p>
<p>So, if you buy a deal that cost below $10, you are effectively earning money, on top of the voucher.</p>
<p>You can then convert the vouchers to cash, by selling to others :)</p>
<hr>
<div class="post-tags">
<div class="label">
<span>TAGGED WITH</span>
</div>
<div class="tags">
<a href="/stories/#groupon">groupon</a>
</div>
</div>
<ul class="pager">
<li class="next">
<a href="/2011/09/06/my-review-of-review-in-haiku/" data-toggle="tooltip" data-placement="top" title="Next Post">My Review of Review in Haiku →</a>
</li>
<li class="previous">
<a href="/2011/08/30/groupon-copywriting-is-awesomely-absurd/" data-toggle="tooltip" data-placement="top" title="Previous Post">← Groupon Copywriting is Awesomely Absurd</a>
</li>
</ul>
<!-- Adsense-->
<div class="ads">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Just2me.com -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-8504591086876220"
data-ad-slot="7773704700"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<!-- Disqus -->
<hr>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'just2me2';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
</div>
</article>
<hr>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center">
<li>
<a href="/feed.xml">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-rss fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://twitter.com/samwize">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://www.facebook.com/ongjunda">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://github.com/samwize">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="mailto:[email protected]">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-envelope fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © Junda Ong 1983-2021</p>
</div>
</div>
</div>
</footer>
<!-- JS -->
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/clean-blog.min.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3313418-3', 'auto');
ga('send', 'pageview');
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-8504591086876220",
enable_page_level_ads: true
});
</script>
</body>
</html>
| {'content_hash': '2d6f0cc6b21e9bff0248006e4498688d', 'timestamp': '', 'source': 'github', 'line_count': 284, 'max_line_length': 707, 'avg_line_length': 42.08098591549296, 'alnum_prop': 0.5216299891222492, 'repo_name': 'samwize/just2me.com', 'id': '160a3713d490e6dc2bfbcced4732d5d85fdba6b2', 'size': '11951', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '2011/09/03/how-to-make-money-buying-groupon-deals/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13264'}, {'name': 'HTML', 'bytes': '24351597'}, {'name': 'JavaScript', 'bytes': '51755'}, {'name': 'Shell', 'bytes': '74'}]} |
(function() {
module.exports = {
Selector: require('./selector')
};
}).call(this);
| {'content_hash': '769788ef86bb5bc8b8a2c264c2c2b875', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 35, 'avg_line_length': 15.333333333333334, 'alnum_prop': 0.5652173913043478, 'repo_name': 'luizpicolo/.atom', 'id': 'ff78c3fcbef3adaa68e697a7a4d051d51dd6be8f', 'size': '92', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/autocomplete-plus/node_modules/selector-kit/lib/selector-kit.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13945'}, {'name': 'CoffeeScript', 'bytes': '148952'}, {'name': 'HTML', 'bytes': '2243'}, {'name': 'JavaScript', 'bytes': '687130'}, {'name': 'PHP', 'bytes': '335'}]} |
function selectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
} | {'content_hash': '12a071591768ecd2499d01bdd6f82cf3', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 50, 'avg_line_length': 32.705882352941174, 'alnum_prop': 0.5809352517985612, 'repo_name': 'saydulk/saydulk.github.io', 'id': 'aabb1eea88a1f323d1da2e27eadda50261dc5c47', 'size': '556', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'select-text.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '16842'}, {'name': 'HTML', 'bytes': '54314'}, {'name': 'JavaScript', 'bytes': '73052'}, {'name': 'PHP', 'bytes': '12569'}]} |
Partiendo del código de la actividad 0074, nuestro objetivo es conseguir que nuestra aplicación sea capaz de analizar archivos de log que presenten un campo de datos adicional.
La mayoría de servidores web incluyen en sus registros de log un valor numérico que indica si el acceso fue un acceso exitoso o no. Por ejemplo, el valor 200 indica que el acceso fue exitoso mientras que el valor 403 indica que se solicito un documento a cuyo acceso no se tenía permiso y el 404 significa que el documento solicitado no pudo encontrarse en el servidor.
Lo primero que debes hacer es que tu aplicación sea capaz de crear archivos de log que incluyan aleatoriamente al final de cada línea uno de los 3 valores comentados anteriormente. Luego, debes hacer que la clase `LogAnalyzer` sea capaz de hacer:
1. Un análisis por horas de los accesos exitosos al servidor web.
2. Un análisis por horas del resto de accesos al servidor web.
Esta actividad es una actividad bastante compleja ya que se requieren cambios en la mayoría de clases del proyecto: `LogEntry`, `LogFileCreator` y `LogAnalyzer`.
Realiza tantos commits como consideres oportunos. Deberías ser capaz de pensar en el mensaje del commit antes incluso de llevar a cabo los cambios. No te olvides de testear adecuadamente el código.
Una vez que tengas acabada la actividad sube el repositorio a Github e indica la URL del último commit.
| {'content_hash': 'f2e6bb298d8ed1df321d08ef240a598b', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 369, 'avg_line_length': 99.5, 'alnum_prop': 0.8068916008614501, 'repo_name': 'miguelbayon/pro015', 'id': '5da6c626ea2662fa1fa920da39a2628ec30c7a86', 'size': '1415', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'actividades/0075.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '7722'}]} |
(function() {
'use strict';
/**
* @ngdoc overview
* @name ui.grid.autoResize
*
* @description
*
* #ui.grid.autoResize
*
* <div class="alert alert-warning" role="alert"><strong>Beta</strong> This feature is ready for testing, but it either hasn't seen a lot of use or has some known bugs.</div>
*
* This module provides auto-resizing functionality to UI-Grid.
*/
var module = angular.module('ui.grid.autoResize', ['ui.grid']);
/**
* @ngdoc directive
* @name ui.grid.autoResize.directive:uiGridAutoResize
* @element div
* @restrict A
*
* @description Stacks on top of the ui-grid directive and
* adds the a watch to the grid's height and width which refreshes
* the grid content whenever its dimensions change.
*
*/
module.directive('uiGridAutoResize', ['gridUtil', function(gridUtil) {
return {
require: 'uiGrid',
scope: false,
link: function($scope, $elm, $attrs, uiGridCtrl) {
var debouncedRefresh;
function getDimensions() {
return {
width: gridUtil.elementWidth($elm),
height: gridUtil.elementHeight($elm)
};
}
function refreshGrid(prevWidth, prevHeight, width, height) {
if ($elm[0].offsetParent !== null) {
uiGridCtrl.grid.gridWidth = width;
uiGridCtrl.grid.gridHeight = height;
uiGridCtrl.grid.queueGridRefresh()
.then(function() {
uiGridCtrl.grid.api.core.raise.gridDimensionChanged(prevHeight, prevWidth, height, width);
});
}
}
debouncedRefresh = gridUtil.debounce(refreshGrid, 400);
$scope.$watchCollection(getDimensions, function(newValues, oldValues) {
if (!angular.equals(newValues, oldValues)) {
debouncedRefresh(oldValues.width, oldValues.height, newValues.width, newValues.height);
}
});
}
};
}]);
})();
| {'content_hash': '2ffc5e8cb357ce2e01f0c854709de903', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 177, 'avg_line_length': 30.56923076923077, 'alnum_prop': 0.6024157020634122, 'repo_name': 'cdnjs/cdnjs', 'id': '6820952cee7ac3725da246ddd00b72108f8460a0', 'size': '2065', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ajax/libs/angular-ui-grid/4.8.5/i18n/ui-grid.auto-resize.js', 'mode': '33188', 'license': 'mit', 'language': []} |
package com.hazelcast.concurrent.lock;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.ObjectNamespace;
import java.util.Collections;
import java.util.Set;
public final class LockStoreProxy implements LockStore {
private final LockStoreContainer container;
private final ObjectNamespace namespace;
public LockStoreProxy(LockStoreContainer container, ObjectNamespace namespace) {
this.container = container;
this.namespace = namespace;
}
@Override
public boolean lock(Data key, String caller, long threadId, long referenceId, long leaseTime) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.lock(key, caller, threadId, referenceId, leaseTime);
}
@Override
public boolean localLock(Data key, String caller, long threadId, long referenceId, long leaseTime) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.localLock(key, caller, threadId, referenceId, leaseTime);
}
@Override
public boolean txnLock(Data key, String caller, long threadId, long referenceId, long leaseTime, boolean blockReads) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.txnLock(key, caller, threadId, referenceId, leaseTime, blockReads);
}
@Override
public boolean extendLeaseTime(Data key, String caller, long threadId, long leaseTime) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.extendLeaseTime(key, caller, threadId, leaseTime);
}
@Override
public boolean unlock(Data key, String caller, long threadId, long referenceId) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.unlock(key, caller, threadId, referenceId);
}
@Override
public boolean isLocked(Data key) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.isLocked(key);
}
@Override
public boolean isLockedBy(Data key, String caller, long threadId) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.isLockedBy(key, caller, threadId);
}
@Override
public int getLockCount(Data key) {
LockStore lockStore = getLockStoreOrNull();
if (lockStore == null) {
return 0;
}
return lockStore.getLockCount(key);
}
@Override
public int getLockedEntryCount() {
LockStore lockStore = getLockStoreOrNull();
if (lockStore == null) {
return 0;
}
return lockStore.getLockedEntryCount();
}
@Override
public long getRemainingLeaseTime(Data key) {
LockStore lockStore = getLockStoreOrNull();
if (lockStore == null) {
return 0;
}
return lockStore.getRemainingLeaseTime(key);
}
@Override
public boolean canAcquireLock(Data key, String caller, long threadId) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.canAcquireLock(key, caller, threadId);
}
@Override
public boolean shouldBlockReads(Data key) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.shouldBlockReads(key);
}
@Override
public Set<Data> getLockedKeys() {
LockStore lockStore = getLockStoreOrNull();
if (lockStore == null) {
return Collections.emptySet();
}
return lockStore.getLockedKeys();
}
@Override
public boolean forceUnlock(Data key) {
LockStore lockStore = getLockStoreOrNull();
return lockStore != null && lockStore.forceUnlock(key);
}
@Override
public String getOwnerInfo(Data dataKey) {
LockStore lockStore = getLockStoreOrNull();
if (lockStore == null) {
return "<not-locked>";
}
return lockStore.getOwnerInfo(dataKey);
}
private LockStore getLockStoreOrNull() {
return container.getLockStore(namespace);
}
}
| {'content_hash': '85344829384d4d8a8b48b7b3ae1469ba', 'timestamp': '', 'source': 'github', 'line_count': 129, 'max_line_length': 122, 'avg_line_length': 32.21705426356589, 'alnum_prop': 0.6662656400384985, 'repo_name': 'tkountis/hazelcast', 'id': 'a3f1802a593da3fa51229a011b262105af0becc3', 'size': '4781', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'hazelcast/src/main/java/com/hazelcast/concurrent/lock/LockStoreProxy.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1438'}, {'name': 'C', 'bytes': '344'}, {'name': 'Java', 'bytes': '39789402'}, {'name': 'Shell', 'bytes': '15150'}]} |
<html>
<head>
<title>Nalini Joshi's panel show appearances</title>
<script type="text/javascript" src="../common.js"></script>
<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>
<script type="text/javascript" src="../people.js"></script>
<!--#include virtual="head.txt" -->
</head>
<body>
<!--#include virtual="nav.txt" -->
<div class="page">
<h1>Nalini Joshi's panel show appearances</h1>
<p>Nalini Joshi has appeared in <span class="total">1</span> episodes between 2014-2014. <a href="https://en.wikipedia.org/wiki/Nalini_Joshi">Nalini Joshi on Wikipedia</a>.</p>
<div class="performerholder">
<table class="performer">
<tr style="vertical-align:bottom;">
<td><div style="height:100px;" class="performances female" title="1"></div><span class="year">2014</span></td>
</tr>
</table>
</div>
<ol class="episodes">
<li><strong>2014-10-20</strong> / <a href="../shows/qanda.html">Q&A</a></li>
</ol>
</div>
</body>
</html>
| {'content_hash': 'eb2f06697b476914651d42afb99d957b', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 178, 'avg_line_length': 32.266666666666666, 'alnum_prop': 0.65599173553719, 'repo_name': 'slowe/panelshows', 'id': '20ad136773071a8174188b652cbc18d0a68f0842', 'size': '968', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'people/m05w8h3i.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8431'}, {'name': 'HTML', 'bytes': '25483901'}, {'name': 'JavaScript', 'bytes': '95028'}, {'name': 'Perl', 'bytes': '19899'}]} |
"""
CLI interface for nova management.
"""
from __future__ import print_function
import argparse
import decorator
import os
import sys
import netaddr
from oslo.config import cfg
from oslo import messaging
import six
from nova.api.ec2 import ec2utils
from nova import availability_zones
from nova.compute import flavors
from nova import config
from nova import context
from nova import db
from nova.db import migration
from nova import exception
from nova import objects
from nova.openstack.common import cliutils
from nova.openstack.common.db import exception as db_exc
from nova.openstack.common.gettextutils import _
from nova.openstack.common import importutils
from nova.openstack.common import log as logging
from nova import quota
from nova import rpc
from nova import servicegroup
from nova import utils
from nova import version
CONF = cfg.CONF
CONF.import_opt('network_manager', 'nova.service')
CONF.import_opt('service_down_time', 'nova.service')
CONF.import_opt('flat_network_bridge', 'nova.network.manager')
CONF.import_opt('num_networks', 'nova.network.manager')
CONF.import_opt('multi_host', 'nova.network.manager')
CONF.import_opt('network_size', 'nova.network.manager')
CONF.import_opt('vlan_start', 'nova.network.manager')
CONF.import_opt('vpn_start', 'nova.network.manager')
CONF.import_opt('default_floating_pool', 'nova.network.floating_ips')
CONF.import_opt('public_interface', 'nova.network.linux_net')
QUOTAS = quota.QUOTAS
# Decorators for actions
def args(*args, **kwargs):
def _decorator(func):
func.__dict__.setdefault('args', []).insert(0, (args, kwargs))
return func
return _decorator
def param2id(object_id):
"""Helper function to convert various volume id types to internal id.
args: [object_id], e.g. 'vol-0000000a' or 'volume-0000000a' or '10'
"""
if '-' in object_id:
return ec2utils.ec2_vol_id_to_uuid(object_id)
else:
return object_id
class VpnCommands(object):
"""Class for managing VPNs."""
@args('--project', dest='project_id', metavar='<Project name>',
help='Project name')
@args('--ip', metavar='<IP Address>', help='IP Address')
@args('--port', metavar='<Port>', help='Port')
def change(self, project_id, ip, port):
"""Change the ip and port for a vpn.
this will update all networks associated with a project
not sure if that's the desired behavior or not, patches accepted
"""
# TODO(tr3buchet): perhaps this shouldn't update all networks
# associated with a project in the future
admin_context = context.get_admin_context()
networks = db.project_get_networks(admin_context, project_id)
for network in networks:
db.network_update(admin_context,
network['id'],
{'vpn_public_address': ip,
'vpn_public_port': int(port)})
class ShellCommands(object):
def bpython(self):
"""Runs a bpython shell.
Falls back to Ipython/python shell if unavailable
"""
self.run('bpython')
def ipython(self):
"""Runs an Ipython shell.
Falls back to Python shell if unavailable
"""
self.run('ipython')
def python(self):
"""Runs a python shell.
Falls back to Python shell if unavailable
"""
self.run('python')
@args('--shell', metavar='<bpython|ipython|python >',
help='Python shell')
def run(self, shell=None):
"""Runs a Python interactive interpreter."""
if not shell:
shell = 'bpython'
if shell == 'bpython':
try:
import bpython
bpython.embed()
except ImportError:
shell = 'ipython'
if shell == 'ipython':
try:
import IPython
# Explicitly pass an empty list as arguments, because
# otherwise IPython would use sys.argv from this script.
shell = IPython.Shell.IPShell(argv=[])
shell.mainloop()
except ImportError:
shell = 'python'
if shell == 'python':
import code
try:
# Try activating rlcompleter, because it's handy.
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try',
# because we already know 'readline' was imported successfully.
readline.parse_and_bind("tab:complete")
code.interact()
@args('--path', metavar='<path>', help='Script path')
def script(self, path):
"""Runs the script from the specified path with flags set properly.
arguments: path
"""
exec(compile(open(path).read(), path, 'exec'), locals(), globals())
def _db_error(caught_exception):
print(caught_exception)
print(_("The above error may show that the database has not "
"been created.\nPlease create a database using "
"'nova-manage db sync' before running this command."))
exit(1)
class ProjectCommands(object):
"""Class for managing projects."""
@args('--project', dest='project_id', metavar='<Project name>',
help='Project name')
@args('--user', dest='user_id', metavar='<User name>',
help='User name')
@args('--key', metavar='<key>', help='Key')
@args('--value', metavar='<value>', help='Value')
def quota(self, project_id, user_id=None, key=None, value=None):
"""Create, update or display quotas for project/user
If no quota key is provided, the quota will be displayed.
If a valid quota key is provided and it does not exist,
it will be created. Otherwise, it will be updated.
"""
ctxt = context.get_admin_context()
if user_id:
quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id)
else:
user_id = None
quota = QUOTAS.get_project_quotas(ctxt, project_id)
# if key is None, that means we need to show the quotas instead
# of updating them
if key:
settable_quotas = QUOTAS.get_settable_quotas(ctxt,
project_id,
user_id=user_id)
if key in quota:
minimum = settable_quotas[key]['minimum']
maximum = settable_quotas[key]['maximum']
if value.lower() == 'unlimited':
value = -1
if int(value) < -1:
print(_('Quota limit must be -1 or greater.'))
return(2)
if ((int(value) < minimum) and
(maximum != -1 or (maximum == -1 and int(value) != -1))):
print(_('Quota limit must be greater than %s.') % minimum)
return(2)
if maximum != -1 and int(value) > maximum:
print(_('Quota limit must be less than %s.') % maximum)
return(2)
try:
db.quota_create(ctxt, project_id, key, value,
user_id=user_id)
except exception.QuotaExists:
db.quota_update(ctxt, project_id, key, value,
user_id=user_id)
else:
print(_('%(key)s is not a valid quota key. Valid options are: '
'%(options)s.') % {'key': key,
'options': ', '.join(quota)})
return(2)
print_format = "%-36s %-10s %-10s %-10s"
print(print_format % (
_('Quota'),
_('Limit'),
_('In Use'),
_('Reserved')))
# Retrieve the quota after update
if user_id:
quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id)
else:
quota = QUOTAS.get_project_quotas(ctxt, project_id)
for key, value in quota.iteritems():
if value['limit'] < 0 or value['limit'] is None:
value['limit'] = 'unlimited'
print(print_format % (key, value['limit'], value['in_use'],
value['reserved']))
@args('--project', dest='project_id', metavar='<Project name>',
help='Project name')
def scrub(self, project_id):
"""Deletes data associated with project."""
admin_context = context.get_admin_context()
networks = db.project_get_networks(admin_context, project_id)
for network in networks:
db.network_disassociate(admin_context, network['id'])
groups = db.security_group_get_by_project(admin_context, project_id)
for group in groups:
db.security_group_destroy(admin_context, group['id'])
AccountCommands = ProjectCommands
class FixedIpCommands(object):
"""Class for managing fixed ip."""
@args('--host', metavar='<host>', help='Host')
def list(self, host=None):
"""Lists all fixed ips (optionally by host)."""
ctxt = context.get_admin_context()
try:
if host is None:
fixed_ips = db.fixed_ip_get_all(ctxt)
else:
fixed_ips = db.fixed_ip_get_by_host(ctxt, host)
except exception.NotFound as ex:
print(_("error: %s") % ex)
return(2)
instances = db.instance_get_all(context.get_admin_context())
instances_by_uuid = {}
for instance in instances:
instances_by_uuid[instance['uuid']] = instance
print("%-18s\t%-15s\t%-15s\t%s" % (_('network'),
_('IP address'),
_('hostname'),
_('host')))
all_networks = {}
try:
# use network_get_all to retrieve all existing networks
# this is to ensure that IPs associated with deleted networks
# will not throw exceptions.
for network in db.network_get_all(context.get_admin_context()):
all_networks[network.id] = network
except exception.NoNetworksFound:
# do not have any networks, so even if there are IPs, these
# IPs should have been deleted ones, so return.
print(_('No fixed IP found.'))
return
has_ip = False
for fixed_ip in fixed_ips:
hostname = None
host = None
network = all_networks.get(fixed_ip['network_id'])
if network:
has_ip = True
if fixed_ip.get('instance_uuid'):
instance = instances_by_uuid.get(fixed_ip['instance_uuid'])
if instance:
hostname = instance['hostname']
host = instance['host']
else:
print(_('WARNING: fixed ip %s allocated to missing'
' instance') % str(fixed_ip['address']))
print("%-18s\t%-15s\t%-15s\t%s" % (
network['cidr'],
fixed_ip['address'],
hostname, host))
if not has_ip:
print(_('No fixed IP found.'))
@args('--address', metavar='<ip address>', help='IP address')
def reserve(self, address):
"""Mark fixed ip as reserved
arguments: address
"""
return self._set_reserved(address, True)
@args('--address', metavar='<ip address>', help='IP address')
def unreserve(self, address):
"""Mark fixed ip as free to use
arguments: address
"""
return self._set_reserved(address, False)
def _set_reserved(self, address, reserved):
ctxt = context.get_admin_context()
try:
fixed_ip = db.fixed_ip_get_by_address(ctxt, address)
if fixed_ip is None:
raise exception.NotFound('Could not find address')
db.fixed_ip_update(ctxt, fixed_ip['address'],
{'reserved': reserved})
except exception.NotFound as ex:
print(_("error: %s") % ex)
return(2)
class FloatingIpCommands(object):
"""Class for managing floating ip."""
@staticmethod
def address_to_hosts(addresses):
"""Iterate over hosts within an address range.
If an explicit range specifier is missing, the parameter is
interpreted as a specific individual address.
"""
try:
return [netaddr.IPAddress(addresses)]
except ValueError:
net = netaddr.IPNetwork(addresses)
if net.size < 4:
reason = _("/%s should be specified as single address(es) "
"not in cidr format") % net.prefixlen
raise exception.InvalidInput(reason=reason)
elif net.size >= 1000000:
# NOTE(dripton): If we generate a million IPs and put them in
# the database, the system will slow to a crawl and/or run
# out of memory and crash. This is clearly a misconfiguration.
reason = _("Too many IP addresses will be generated. Please "
"increase /%s to reduce the number generated."
) % net.prefixlen
raise exception.InvalidInput(reason=reason)
else:
return net.iter_hosts()
@args('--ip_range', metavar='<range>', help='IP range')
@args('--pool', metavar='<pool>', help='Optional pool')
@args('--interface', metavar='<interface>', help='Optional interface')
def create(self, ip_range, pool=None, interface=None):
"""Creates floating ips for zone by range."""
admin_context = context.get_admin_context()
if not pool:
pool = CONF.default_floating_pool
if not interface:
interface = CONF.public_interface
ips = ({'address': str(address), 'pool': pool, 'interface': interface}
for address in self.address_to_hosts(ip_range))
try:
db.floating_ip_bulk_create(admin_context, ips)
except exception.FloatingIpExists as exc:
# NOTE(simplylizz): Maybe logging would be better here
# instead of printing, but logging isn't used here and I
# don't know why.
print('error: %s' % exc)
return(1)
@args('--ip_range', metavar='<range>', help='IP range')
def delete(self, ip_range):
"""Deletes floating ips by range."""
admin_context = context.get_admin_context()
ips = ({'address': str(address)}
for address in self.address_to_hosts(ip_range))
db.floating_ip_bulk_destroy(admin_context, ips)
@args('--host', metavar='<host>', help='Host')
def list(self, host=None):
"""Lists all floating ips (optionally by host).
Note: if host is given, only active floating IPs are returned
"""
ctxt = context.get_admin_context()
try:
if host is None:
floating_ips = db.floating_ip_get_all(ctxt)
else:
floating_ips = db.floating_ip_get_all_by_host(ctxt, host)
except exception.NoFloatingIpsDefined:
print(_("No floating IP addresses have been defined."))
return
for floating_ip in floating_ips:
instance_uuid = None
if floating_ip['fixed_ip_id']:
fixed_ip = db.fixed_ip_get(ctxt, floating_ip['fixed_ip_id'])
instance_uuid = fixed_ip['instance_uuid']
print("%s\t%s\t%s\t%s\t%s" % (floating_ip['project_id'],
floating_ip['address'],
instance_uuid,
floating_ip['pool'],
floating_ip['interface']))
@decorator.decorator
def validate_network_plugin(f, *args, **kwargs):
"""Decorator to validate the network plugin."""
if utils.is_neutron():
print(_("ERROR: Network commands are not supported when using the "
"Neutron API. Use python-neutronclient instead."))
return(2)
return f(*args, **kwargs)
class NetworkCommands(object):
"""Class for managing networks."""
@validate_network_plugin
@args('--label', metavar='<label>', help='Label for network (ex: public)')
@args('--fixed_range_v4', dest='cidr', metavar='<x.x.x.x/yy>',
help='IPv4 subnet (ex: 10.0.0.0/8)')
@args('--num_networks', metavar='<number>',
help='Number of networks to create')
@args('--network_size', metavar='<number>',
help='Number of IPs per network')
@args('--vlan', dest='vlan_start', metavar='<vlan id>', help='vlan id')
@args('--vpn', dest='vpn_start', help='vpn start')
@args('--fixed_range_v6', dest='cidr_v6',
help='IPv6 subnet (ex: fe80::/64')
@args('--gateway', help='gateway')
@args('--gateway_v6', help='ipv6 gateway')
@args('--bridge', metavar='<bridge>',
help='VIFs on this network are connected to this bridge')
@args('--bridge_interface', metavar='<bridge interface>',
help='the bridge is connected to this interface')
@args('--multi_host', metavar="<'T'|'F'>",
help='Multi host')
@args('--dns1', metavar="<DNS Address>", help='First DNS')
@args('--dns2', metavar="<DNS Address>", help='Second DNS')
@args('--uuid', metavar="<network uuid>", help='Network UUID')
@args('--fixed_cidr', metavar='<x.x.x.x/yy>',
help='IPv4 subnet for fixed IPS (ex: 10.20.0.0/16)')
@args('--project_id', metavar="<project id>",
help='Project id')
@args('--priority', metavar="<number>", help='Network interface priority')
def create(self, label=None, cidr=None, num_networks=None,
network_size=None, multi_host=None, vlan_start=None,
vpn_start=None, cidr_v6=None, gateway=None,
gateway_v6=None, bridge=None, bridge_interface=None,
dns1=None, dns2=None, project_id=None, priority=None,
uuid=None, fixed_cidr=None):
"""Creates fixed ips for host by range."""
kwargs = dict(((k, v) for k, v in locals().iteritems()
if v and k != "self"))
if multi_host is not None:
kwargs['multi_host'] = multi_host == 'T'
net_manager = importutils.import_object(CONF.network_manager)
net_manager.create_networks(context.get_admin_context(), **kwargs)
@validate_network_plugin
def list(self):
"""List all created networks."""
_fmt = "%-5s\t%-18s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s\t%-15s"
print(_fmt % (_('id'),
_('IPv4'),
_('IPv6'),
_('start address'),
_('DNS1'),
_('DNS2'),
_('VlanID'),
_('project'),
_("uuid")))
try:
# Since network_get_all can throw exception.NoNetworksFound
# for this command to show a nice result, this exception
# should be caught and handled as such.
networks = db.network_get_all(context.get_admin_context())
except exception.NoNetworksFound:
print(_('No networks found'))
else:
for network in networks:
print(_fmt % (network.id,
network.cidr,
network.cidr_v6,
network.dhcp_start,
network.dns1,
network.dns2,
network.vlan,
network.project_id,
network.uuid))
@validate_network_plugin
@args('--fixed_range', metavar='<x.x.x.x/yy>', help='Network to delete')
@args('--uuid', metavar='<uuid>', help='UUID of network to delete')
def delete(self, fixed_range=None, uuid=None):
"""Deletes a network."""
if fixed_range is None and uuid is None:
raise Exception(_("Please specify either fixed_range or uuid"))
net_manager = importutils.import_object(CONF.network_manager)
if "NeutronManager" in CONF.network_manager:
if uuid is None:
raise Exception(_("UUID is required to delete "
"Neutron Networks"))
if fixed_range:
raise Exception(_("Deleting by fixed_range is not supported "
"with the NeutronManager"))
# delete the network
net_manager.delete_network(context.get_admin_context(),
fixed_range, uuid)
@validate_network_plugin
@args('--fixed_range', metavar='<x.x.x.x/yy>', help='Network to modify')
@args('--project', metavar='<project name>',
help='Project name to associate')
@args('--host', metavar='<host>', help='Host to associate')
@args('--disassociate-project', action="store_true", dest='dis_project',
default=False, help='Disassociate Network from Project')
@args('--disassociate-host', action="store_true", dest='dis_host',
default=False, help='Disassociate Host from Project')
def modify(self, fixed_range, project=None, host=None,
dis_project=None, dis_host=None):
"""Associate/Disassociate Network with Project and/or Host
arguments: network project host
leave any field blank to ignore it
"""
admin_context = context.get_admin_context()
network = db.network_get_by_cidr(admin_context, fixed_range)
net = {}
#User can choose the following actions each for project and host.
#1) Associate (set not None value given by project/host parameter)
#2) Disassociate (set None by disassociate parameter)
#3) Keep unchanged (project/host key is not added to 'net')
if dis_project:
net['project_id'] = None
if dis_host:
net['host'] = None
# The --disassociate-X are boolean options, but if they user
# mistakenly provides a value, it will be used as a positional argument
# and be erroneously interepreted as some other parameter (e.g.
# a project instead of host value). The safest thing to do is error-out
# with a message indicating that there is probably a problem with
# how the disassociate modifications are being used.
if dis_project or dis_host:
if project or host:
error_msg = "ERROR: Unexpected arguments provided. Please " \
"use separate commands."
print(error_msg)
return(1)
db.network_update(admin_context, network['id'], net)
return
if project:
net['project_id'] = project
if host:
net['host'] = host
db.network_update(admin_context, network['id'], net)
class VmCommands(object):
"""Class for mangaging VM instances."""
@args('--host', metavar='<host>', help='Host')
def list(self, host=None):
"""Show a list of all instances."""
print(("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s"
" %-10s %-10s %-10s %-5s" % (_('instance'),
_('node'),
_('type'),
_('state'),
_('launched'),
_('image'),
_('kernel'),
_('ramdisk'),
_('project'),
_('user'),
_('zone'),
_('index'))))
if host is None:
instances = db.instance_get_all(context.get_admin_context())
else:
instances = db.instance_get_all_by_host(
context.get_admin_context(), host)
for instance in instances:
instance_type = flavors.extract_flavor(instance)
print(("%-10s %-15s %-10s %-10s %-26s %-9s %-9s %-9s"
" %-10s %-10s %-10s %-5d" % (instance['display_name'],
instance['host'],
instance_type['name'],
instance['vm_state'],
instance['launched_at'],
instance['image_ref'],
instance['kernel_id'],
instance['ramdisk_id'],
instance['project_id'],
instance['user_id'],
instance['availability_zone'],
instance['launch_index'])))
class ServiceCommands(object):
"""Enable and disable running services."""
@args('--host', metavar='<host>', help='Host')
@args('--service', metavar='<service>', help='Nova service')
def list(self, host=None, service=None):
"""Show a list of all running services. Filter by host & service
name
"""
servicegroup_api = servicegroup.API()
ctxt = context.get_admin_context()
services = db.service_get_all(ctxt)
services = availability_zones.set_availability_zones(ctxt, services)
if host:
services = [s for s in services if s['host'] == host]
if service:
services = [s for s in services if s['binary'] == service]
print_format = "%-16s %-36s %-16s %-10s %-5s %-10s"
print(print_format % (
_('Binary'),
_('Host'),
_('Zone'),
_('Status'),
_('State'),
_('Updated_At')))
for svc in services:
alive = servicegroup_api.service_is_up(svc)
art = (alive and ":-)") or "XXX"
active = 'enabled'
if svc['disabled']:
active = 'disabled'
print(print_format % (svc['binary'], svc['host'],
svc['availability_zone'], active, art,
svc['updated_at']))
@args('--host', metavar='<host>', help='Host')
@args('--service', metavar='<service>', help='Nova service')
def enable(self, host, service):
"""Enable scheduling for a service."""
ctxt = context.get_admin_context()
try:
svc = db.service_get_by_args(ctxt, host, service)
db.service_update(ctxt, svc['id'], {'disabled': False})
except exception.NotFound as ex:
print(_("error: %s") % ex)
return(2)
print((_("Service %(service)s on host %(host)s enabled.") %
{'service': service, 'host': host}))
@args('--host', metavar='<host>', help='Host')
@args('--service', metavar='<service>', help='Nova service')
def disable(self, host, service):
"""Disable scheduling for a service."""
ctxt = context.get_admin_context()
try:
svc = db.service_get_by_args(ctxt, host, service)
db.service_update(ctxt, svc['id'], {'disabled': True})
except exception.NotFound as ex:
print(_("error: %s") % ex)
return(2)
print((_("Service %(service)s on host %(host)s disabled.") %
{'service': service, 'host': host}))
def _show_host_resources(self, context, host):
"""Shows the physical/usage resource given by hosts.
:param context: security context
:param host: hostname
:returns:
example format is below::
{'resource':D, 'usage':{proj_id1:D, proj_id2:D}}
D: {'vcpus': 3, 'memory_mb': 2048, 'local_gb': 2048,
'vcpus_used': 12, 'memory_mb_used': 10240,
'local_gb_used': 64}
"""
# Getting compute node info and related instances info
service_ref = db.service_get_by_compute_host(context, host)
instance_refs = db.instance_get_all_by_host(context,
service_ref['host'])
# Getting total available/used resource
compute_ref = service_ref['compute_node'][0]
resource = {'vcpus': compute_ref['vcpus'],
'memory_mb': compute_ref['memory_mb'],
'local_gb': compute_ref['local_gb'],
'vcpus_used': compute_ref['vcpus_used'],
'memory_mb_used': compute_ref['memory_mb_used'],
'local_gb_used': compute_ref['local_gb_used']}
usage = dict()
if not instance_refs:
return {'resource': resource, 'usage': usage}
# Getting usage resource per project
project_ids = [i['project_id'] for i in instance_refs]
project_ids = list(set(project_ids))
for project_id in project_ids:
vcpus = [i['vcpus'] for i in instance_refs
if i['project_id'] == project_id]
mem = [i['memory_mb'] for i in instance_refs
if i['project_id'] == project_id]
root = [i['root_gb'] for i in instance_refs
if i['project_id'] == project_id]
ephemeral = [i['ephemeral_gb'] for i in instance_refs
if i['project_id'] == project_id]
usage[project_id] = {'vcpus': sum(vcpus),
'memory_mb': sum(mem),
'root_gb': sum(root),
'ephemeral_gb': sum(ephemeral)}
return {'resource': resource, 'usage': usage}
@args('--host', metavar='<host>', help='Host')
def describe_resource(self, host):
"""Describes cpu/memory/hdd info for host.
:param host: hostname.
"""
try:
result = self._show_host_resources(context.get_admin_context(),
host=host)
except exception.NovaException as ex:
print(_("error: %s") % ex)
return 2
if not isinstance(result, dict):
print(_('An unexpected error has occurred.'))
print(_('[Result]'), result)
else:
# Printing a total and used_now
# (NOTE)The host name width 16 characters
print('%(a)-25s%(b)16s%(c)8s%(d)8s%(e)8s' % {"a": _('HOST'),
"b": _('PROJECT'),
"c": _('cpu'),
"d": _('mem(mb)'),
"e": _('hdd')})
print(('%(a)-16s(total)%(b)26s%(c)8s%(d)8s' %
{"a": host,
"b": result['resource']['vcpus'],
"c": result['resource']['memory_mb'],
"d": result['resource']['local_gb']}))
print(('%(a)-16s(used_now)%(b)23s%(c)8s%(d)8s' %
{"a": host,
"b": result['resource']['vcpus_used'],
"c": result['resource']['memory_mb_used'],
"d": result['resource']['local_gb_used']}))
# Printing a used_max
cpu_sum = 0
mem_sum = 0
hdd_sum = 0
for p_id, val in result['usage'].items():
cpu_sum += val['vcpus']
mem_sum += val['memory_mb']
hdd_sum += val['root_gb']
hdd_sum += val['ephemeral_gb']
print('%(a)-16s(used_max)%(b)23s%(c)8s%(d)8s' % {"a": host,
"b": cpu_sum,
"c": mem_sum,
"d": hdd_sum})
for p_id, val in result['usage'].items():
print('%(a)-25s%(b)16s%(c)8s%(d)8s%(e)8s' % {
"a": host,
"b": p_id,
"c": val['vcpus'],
"d": val['memory_mb'],
"e": val['root_gb'] + val['ephemeral_gb']})
class HostCommands(object):
"""List hosts."""
def list(self, zone=None):
"""Show a list of all physical hosts. Filter by zone.
args: [zone]
"""
print("%-25s\t%-15s" % (_('host'),
_('zone')))
ctxt = context.get_admin_context()
services = db.service_get_all(ctxt)
services = availability_zones.set_availability_zones(ctxt, services)
if zone:
services = [s for s in services if s['availability_zone'] == zone]
hosts = []
for srv in services:
if not [h for h in hosts if h['host'] == srv['host']]:
hosts.append(srv)
for h in hosts:
print("%-25s\t%-15s" % (h['host'], h['availability_zone']))
class DbCommands(object):
"""Class for managing the database."""
def __init__(self):
pass
@args('--version', metavar='<version>', help='Database version')
def sync(self, version=None):
"""Sync the database up to the most recent version."""
return migration.db_sync(version)
def version(self):
"""Print the current database version."""
print(migration.db_version())
@args('--max_rows', metavar='<number>',
help='Maximum number of deleted rows to archive')
def archive_deleted_rows(self, max_rows):
"""Move up to max_rows deleted rows from production tables to shadow
tables.
"""
if max_rows is not None:
max_rows = int(max_rows)
if max_rows < 0:
print(_("Must supply a positive value for max_rows"))
return(1)
admin_context = context.get_admin_context()
db.archive_deleted_rows(admin_context, max_rows)
class FlavorCommands(object):
"""Class for managing flavors.
Note instance type is a deprecated synonym for flavor.
"""
description = ('DEPRECATED: Use the nova flavor-* commands from '
'python-novaclient instead. The flavor subcommand will be '
'removed in the 2015.1 release')
def _print_flavors(self, val):
is_public = ('private', 'public')[val["is_public"] == 1]
print(("%s: Memory: %sMB, VCPUS: %s, Root: %sGB, Ephemeral: %sGb, "
"FlavorID: %s, Swap: %sMB, RXTX Factor: %s, %s, ExtraSpecs %s") % (
val["name"], val["memory_mb"], val["vcpus"], val["root_gb"],
val["ephemeral_gb"], val["flavorid"], val["swap"],
val["rxtx_factor"], is_public, val["extra_specs"]))
@args('--name', metavar='<name>',
help='Name of flavor')
@args('--memory', metavar='<memory size>', help='Memory size')
@args('--cpu', dest='vcpus', metavar='<num cores>', help='Number cpus')
@args('--root_gb', metavar='<root_gb>', help='Root disk size')
@args('--ephemeral_gb', metavar='<ephemeral_gb>',
help='Ephemeral disk size')
@args('--flavor', dest='flavorid', metavar='<flavor id>',
help='Flavor ID')
@args('--swap', metavar='<swap>', help='Swap')
@args('--rxtx_factor', metavar='<rxtx_factor>', help='rxtx_factor')
@args('--is_public', metavar='<is_public>',
help='Make flavor accessible to the public')
def create(self, name, memory, vcpus, root_gb, ephemeral_gb=0,
flavorid=None, swap=0, rxtx_factor=1.0, is_public=True):
"""Creates flavors."""
try:
flavors.create(name, memory, vcpus, root_gb,
ephemeral_gb=ephemeral_gb, flavorid=flavorid,
swap=swap, rxtx_factor=rxtx_factor,
is_public=is_public)
except exception.InvalidInput as e:
print(_("Must supply valid parameters to create flavor"))
print(e)
return 1
except exception.FlavorExists:
print(_("Flavor exists."))
print(_("Please ensure flavor name and flavorid are "
"unique."))
print(_("Currently defined flavor names and flavorids:"))
print()
self.list()
return 2
except Exception:
print(_("Unknown error"))
return 3
else:
print(_("%s created") % name)
@args('--name', metavar='<name>', help='Name of flavor')
def delete(self, name):
"""Marks flavors as deleted."""
try:
flavors.destroy(name)
except exception.FlavorNotFound:
print(_("Valid flavor name is required"))
return 1
except db_exc.DBError as e:
print(_("DB Error: %s") % e)
return(2)
except Exception:
return(3)
else:
print(_("%s deleted") % name)
@args('--name', metavar='<name>', help='Name of flavor')
def list(self, name=None):
"""Lists all active or specific flavors."""
try:
if name is None:
inst_types = flavors.get_all_flavors()
else:
inst_types = flavors.get_flavor_by_name(name)
except db_exc.DBError as e:
_db_error(e)
if isinstance(inst_types.values()[0], dict):
for k, v in inst_types.iteritems():
self._print_flavors(v)
else:
self._print_flavors(inst_types)
@args('--name', metavar='<name>', help='Name of flavor')
@args('--key', metavar='<key>', help='The key of the key/value pair')
@args('--value', metavar='<value>', help='The value of the key/value pair')
def set_key(self, name, key, value=None):
"""Add key/value pair to specified flavor's extra_specs."""
try:
try:
inst_type = flavors.get_flavor_by_name(name)
except exception.FlavorNotFoundByName as e:
print(e)
return(2)
ctxt = context.get_admin_context()
ext_spec = {key: value}
db.flavor_extra_specs_update_or_create(
ctxt,
inst_type["flavorid"],
ext_spec)
print((_("Key %(key)s set to %(value)s on instance "
"type %(name)s") %
{'key': key, 'value': value, 'name': name}))
except db_exc.DBError as e:
_db_error(e)
@args('--name', metavar='<name>', help='Name of flavor')
@args('--key', metavar='<key>', help='The key to be deleted')
def unset_key(self, name, key):
"""Delete the specified extra spec for flavor."""
try:
try:
inst_type = flavors.get_flavor_by_name(name)
except exception.FlavorNotFoundByName as e:
print(e)
return(2)
ctxt = context.get_admin_context()
db.flavor_extra_specs_delete(
ctxt,
inst_type["flavorid"],
key)
print((_("Key %(key)s on flavor %(name)s unset") %
{'key': key, 'name': name}))
except db_exc.DBError as e:
_db_error(e)
class AgentBuildCommands(object):
"""Class for managing agent builds."""
@args('--os', metavar='<os>', help='os')
@args('--architecture', dest='architecture',
metavar='<architecture>', help='architecture')
@args('--version', metavar='<version>', help='version')
@args('--url', metavar='<url>', help='url')
@args('--md5hash', metavar='<md5hash>', help='md5hash')
@args('--hypervisor', metavar='<hypervisor>',
help='hypervisor(default: xen)')
def create(self, os, architecture, version, url, md5hash,
hypervisor='xen'):
"""Creates a new agent build."""
ctxt = context.get_admin_context()
db.agent_build_create(ctxt, {'hypervisor': hypervisor,
'os': os,
'architecture': architecture,
'version': version,
'url': url,
'md5hash': md5hash})
@args('--os', metavar='<os>', help='os')
@args('--architecture', dest='architecture',
metavar='<architecture>', help='architecture')
@args('--hypervisor', metavar='<hypervisor>',
help='hypervisor(default: xen)')
def delete(self, os, architecture, hypervisor='xen'):
"""Deletes an existing agent build."""
ctxt = context.get_admin_context()
agent_build_ref = db.agent_build_get_by_triple(ctxt,
hypervisor, os, architecture)
db.agent_build_destroy(ctxt, agent_build_ref['id'])
@args('--hypervisor', metavar='<hypervisor>',
help='hypervisor(default: None)')
def list(self, hypervisor=None):
"""Lists all agent builds.
arguments: <none>
"""
fmt = "%-10s %-8s %12s %s"
ctxt = context.get_admin_context()
by_hypervisor = {}
for agent_build in db.agent_build_get_all(ctxt):
buildlist = by_hypervisor.get(agent_build.hypervisor)
if not buildlist:
buildlist = by_hypervisor[agent_build.hypervisor] = []
buildlist.append(agent_build)
for key, buildlist in by_hypervisor.iteritems():
if hypervisor and key != hypervisor:
continue
print(_('Hypervisor: %s') % key)
print(fmt % ('-' * 10, '-' * 8, '-' * 12, '-' * 32))
for agent_build in buildlist:
print(fmt % (agent_build.os, agent_build.architecture,
agent_build.version, agent_build.md5hash))
print(' %s' % agent_build.url)
print()
@args('--os', metavar='<os>', help='os')
@args('--architecture', dest='architecture',
metavar='<architecture>', help='architecture')
@args('--version', metavar='<version>', help='version')
@args('--url', metavar='<url>', help='url')
@args('--md5hash', metavar='<md5hash>', help='md5hash')
@args('--hypervisor', metavar='<hypervisor>',
help='hypervisor(default: xen)')
def modify(self, os, architecture, version, url, md5hash,
hypervisor='xen'):
"""Update an existing agent build."""
ctxt = context.get_admin_context()
agent_build_ref = db.agent_build_get_by_triple(ctxt,
hypervisor, os, architecture)
db.agent_build_update(ctxt, agent_build_ref['id'],
{'version': version,
'url': url,
'md5hash': md5hash})
class GetLogCommands(object):
"""Get logging information."""
def errors(self):
"""Get all of the errors from the log files."""
error_found = 0
if CONF.log_dir:
logs = [x for x in os.listdir(CONF.log_dir) if x.endswith('.log')]
for file in logs:
log_file = os.path.join(CONF.log_dir, file)
lines = [line.strip() for line in open(log_file, "r")]
lines.reverse()
print_name = 0
for index, line in enumerate(lines):
if line.find(" ERROR ") > 0:
error_found += 1
if print_name == 0:
print(log_file + ":-")
print_name = 1
linenum = len(lines) - index
print((_('Line %(linenum)d : %(line)s') %
{'linenum': linenum, 'line': line}))
if error_found == 0:
print(_('No errors in logfiles!'))
@args('--num_entries', metavar='<number of entries>',
help='number of entries(default: 10)')
def syslog(self, num_entries=10):
"""Get <num_entries> of the nova syslog events."""
entries = int(num_entries)
count = 0
log_file = ''
if os.path.exists('/var/log/syslog'):
log_file = '/var/log/syslog'
elif os.path.exists('/var/log/messages'):
log_file = '/var/log/messages'
else:
print(_('Unable to find system log file!'))
return(1)
lines = [line.strip() for line in open(log_file, "r")]
lines.reverse()
print(_('Last %s nova syslog entries:-') % (entries))
for line in lines:
if line.find("nova") > 0:
count += 1
print("%s" % (line))
if count == entries:
break
if count == 0:
print(_('No nova entries in syslog!'))
class CellCommands(object):
"""Commands for managing cells."""
@args('--name', metavar='<name>', help='Name for the new cell')
@args('--cell_type', metavar='<parent|child>',
help='Whether the cell is a parent or child')
@args('--username', metavar='<username>',
help='Username for the message broker in this cell')
@args('--password', metavar='<password>',
help='Password for the message broker in this cell')
@args('--hostname', metavar='<hostname>',
help='Address of the message broker in this cell')
@args('--port', metavar='<number>',
help='Port number of the message broker in this cell')
@args('--virtual_host', metavar='<virtual_host>',
help='The virtual host of the message broker in this cell')
@args('--woffset', metavar='<float>')
@args('--wscale', metavar='<float>')
def create(self, name, cell_type='child', username=None, password=None,
hostname=None, port=None, virtual_host=None,
woffset=None, wscale=None):
if cell_type not in ['parent', 'child']:
print("Error: cell type must be 'parent' or 'child'")
return(2)
# Set up the transport URL
transport_host = messaging.TransportHost(hostname=hostname,
port=int(port),
username=username,
password=password)
transport_url = rpc.get_transport_url()
transport_url.hosts.append(transport_host)
transport_url.virtual_host = virtual_host
is_parent = cell_type == 'parent'
values = {'name': name,
'is_parent': is_parent,
'transport_url': str(transport_url),
'weight_offset': float(woffset),
'weight_scale': float(wscale)}
ctxt = context.get_admin_context()
db.cell_create(ctxt, values)
@args('--cell_name', metavar='<cell_name>',
help='Name of the cell to delete')
def delete(self, cell_name):
ctxt = context.get_admin_context()
db.cell_delete(ctxt, cell_name)
def list(self):
ctxt = context.get_admin_context()
cells = db.cell_get_all(ctxt)
fmt = "%3s %-10s %-6s %-10s %-15s %-5s %-10s"
print(fmt % ('Id', 'Name', 'Type', 'Username', 'Hostname',
'Port', 'VHost'))
print(fmt % ('-' * 3, '-' * 10, '-' * 6, '-' * 10, '-' * 15,
'-' * 5, '-' * 10))
for cell in cells:
url = rpc.get_transport_url(cell.transport_url)
host = url.hosts[0] if url.hosts else messaging.TransportHost()
print(fmt % (cell.id, cell.name,
'parent' if cell.is_parent else 'child',
host.username, host.hostname,
host.port, url.virtual_host))
print(fmt % ('-' * 3, '-' * 10, '-' * 6, '-' * 10, '-' * 15,
'-' * 5, '-' * 10))
CATEGORIES = {
'account': AccountCommands,
'agent': AgentBuildCommands,
'cell': CellCommands,
'db': DbCommands,
'fixed': FixedIpCommands,
'flavor': FlavorCommands,
'floating': FloatingIpCommands,
'host': HostCommands,
'logs': GetLogCommands,
'network': NetworkCommands,
'project': ProjectCommands,
'service': ServiceCommands,
'shell': ShellCommands,
'vm': VmCommands,
'vpn': VpnCommands,
}
def methods_of(obj):
"""Get all callable methods of an object that don't start with underscore
returns a list of tuples of the form (method_name, method)
"""
result = []
for i in dir(obj):
if callable(getattr(obj, i)) and not i.startswith('_'):
result.append((i, getattr(obj, i)))
return result
def add_command_parsers(subparsers):
parser = subparsers.add_parser('version')
parser = subparsers.add_parser('bash-completion')
parser.add_argument('query_category', nargs='?')
for category in CATEGORIES:
command_object = CATEGORIES[category]()
desc = getattr(command_object, 'description', None)
parser = subparsers.add_parser(category, description=desc)
parser.set_defaults(command_object=command_object)
category_subparsers = parser.add_subparsers(dest='action')
for (action, action_fn) in methods_of(command_object):
parser = category_subparsers.add_parser(action, description=desc)
action_kwargs = []
for args, kwargs in getattr(action_fn, 'args', []):
# FIXME(markmc): hack to assume dest is the arg name without
# the leading hyphens if no dest is supplied
kwargs.setdefault('dest', args[0][2:])
if kwargs['dest'].startswith('action_kwarg_'):
action_kwargs.append(
kwargs['dest'][len('action_kwarg_'):])
else:
action_kwargs.append(kwargs['dest'])
kwargs['dest'] = 'action_kwarg_' + kwargs['dest']
parser.add_argument(*args, **kwargs)
parser.set_defaults(action_fn=action_fn)
parser.set_defaults(action_kwargs=action_kwargs)
parser.add_argument('action_args', nargs='*',
help=argparse.SUPPRESS)
category_opt = cfg.SubCommandOpt('category',
title='Command categories',
help='Available categories',
handler=add_command_parsers)
def main():
"""Parse options and call the appropriate class/method."""
CONF.register_cli_opt(category_opt)
try:
config.parse_args(sys.argv)
logging.setup("nova")
except cfg.ConfigFilesNotFoundError:
cfgfile = CONF.config_file[-1] if CONF.config_file else None
if cfgfile and not os.access(cfgfile, os.R_OK):
st = os.stat(cfgfile)
print(_("Could not read %s. Re-running with sudo") % cfgfile)
try:
os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv)
except Exception:
print(_('sudo failed, continuing as if nothing happened'))
print(_('Please re-run nova-manage as root.'))
return(2)
objects.register_all()
if CONF.category.name == "version":
print(version.version_string_with_package())
return(0)
if CONF.category.name == "bash-completion":
if not CONF.category.query_category:
print(" ".join(CATEGORIES.keys()))
elif CONF.category.query_category in CATEGORIES:
fn = CATEGORIES[CONF.category.query_category]
command_object = fn()
actions = methods_of(command_object)
print(" ".join([k for (k, v) in actions]))
return(0)
fn = CONF.category.action_fn
fn_args = [arg.decode('utf-8') for arg in CONF.category.action_args]
fn_kwargs = {}
for k in CONF.category.action_kwargs:
v = getattr(CONF.category, 'action_kwarg_' + k)
if v is None:
continue
if isinstance(v, six.string_types):
v = v.decode('utf-8')
fn_kwargs[k] = v
# call the action with the remaining arguments
# check arguments
try:
cliutils.validate_args(fn, *fn_args, **fn_kwargs)
except cliutils.MissingArgs as e:
# NOTE(mikal): this isn't the most helpful error message ever. It is
# long, and tells you a lot of things you probably don't want to know
# if you just got a single arg wrong.
print(fn.__doc__)
CONF.print_help()
print(e)
return(1)
try:
ret = fn(*fn_args, **fn_kwargs)
rpc.cleanup()
return(ret)
except Exception:
print(_("Command failed, please check log for more info"))
raise
| {'content_hash': '716a38e2146e774ab57a1a951668a4b1', 'timestamp': '', 'source': 'github', 'line_count': 1354, 'max_line_length': 79, 'avg_line_length': 39.91285081240768, 'alnum_prop': 0.5168572591687947, 'repo_name': 'afrolov1/nova', 'id': 'b41684541ae067b4ddf6669a92e94380e7435f72', 'size': '56488', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'nova/cmd/manage.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '14057622'}, {'name': 'Shell', 'bytes': '17451'}]} |
<?php
namespace DesignPatterns\Behavioral\Memento;
/**
* Class Record
* @package DesignPatterns\Behavioral\Memento
*/
final class Record {
/**
* @var mixed
*/
private $_state;
/**
* Record constructor.
* @param $state
*/
final public function __construct($state) {
$this->_state = $state;
}
/**
* @return mixed
*/
final public function get_state() {
return $this->_state;
}
}
| {'content_hash': 'f3357194116ea5563ff35dfc949fcf46', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 47, 'avg_line_length': 16.566666666666666, 'alnum_prop': 0.5130784708249497, 'repo_name': 'JShadowMan/PHPDesignPatterns', 'id': 'f503b09dade0356862169b357b8b36f287e9dfed', 'size': '734', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Behavioral/Memento/Record.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '211033'}]} |
import os
import sys
import asciichartpy
# -----------------------------------------------------------------------------
this_folder = os.path.dirname(os.path.abspath(__file__))
root_folder = os.path.dirname(os.path.dirname(this_folder))
sys.path.append(root_folder + '/python')
sys.path.append(this_folder)
# -----------------------------------------------------------------------------
import ccxt # noqa: E402
# -----------------------------------------------------------------------------
exchange = ccxt.kraken()
symbol = 'LTC/EUR'
# each ohlcv candle is a list of [ timestamp, open, high, low, close, volume ]
index = 4 # use close price from each ohlcv candle
length = 80
height = 15
def print_chart(exchange, symbol, timeframe):
# get a list of ohlcv candles
ohlcv = exchange.fetch_ohlcv(symbol, timeframe)
# get the ohlCv (closing price, index == 4)
series = [x[index] for x in ohlcv]
# print datetime and other values
for x in ohlcv:
print(exchange.iso8601(x[0]), x)
print("\n" + exchange.name + ' ' + symbol + ' ' + timeframe + ' chart:')
# print the chart
print("\n" + asciichartpy.plot(series[-length:], {'height': height})) # print the chart
last = ohlcv[len(ohlcv) - 1][index] # last closing price
return last
last = print_chart(exchange, symbol, '1m')
print("\n" + exchange.name + ' last price: ' + str(last) + "\n") # print last closing price
| {'content_hash': '47b31d29ed0e5699e5465ec6c0841e5e', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 92, 'avg_line_length': 28.7, 'alnum_prop': 0.5463414634146342, 'repo_name': 'ccxt/ccxt', 'id': '73e314b75aee8fe3f07239a6705004055a9c25c4', 'size': '1460', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/py/fetch-ohlcv-kraken.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '1724'}, {'name': 'HTML', 'bytes': '246'}, {'name': 'JavaScript', 'bytes': '11619228'}, {'name': 'PHP', 'bytes': '10272973'}, {'name': 'Python', 'bytes': '9037496'}, {'name': 'Shell', 'bytes': '6887'}]} |
/*! @license Firebase v4.3.1
Build: rev-b4fe95f
Terms: https://firebase.google.com/terms/ */
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UploadTask = undefined;
var _taskenums = require('./implementation/taskenums');
var fbsTaskEnums = _interopRequireWildcard(_taskenums);
var _observer = require('./implementation/observer');
var _tasksnapshot = require('./tasksnapshot');
var _args = require('./implementation/args');
var fbsArgs = _interopRequireWildcard(_args);
var _array = require('./implementation/array');
var fbsArray = _interopRequireWildcard(_array);
var _async = require('./implementation/async');
var _error = require('./implementation/error');
var errors = _interopRequireWildcard(_error);
var _promise_external = require('./implementation/promise_external');
var fbsPromiseimpl = _interopRequireWildcard(_promise_external);
var _requests = require('./implementation/requests');
var fbsRequests = _interopRequireWildcard(_requests);
var _type = require('./implementation/type');
var typeUtils = _interopRequireWildcard(_type);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* Represents a blob being uploaded. Can be used to pause/resume/cancel the
* upload and manage callbacks for various events.
*/
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Defines types for interacting with blob transfer tasks.
*/
var UploadTask = function () {
/**
* @param ref The firebaseStorage.Reference object this task came
* from, untyped to avoid cyclic dependencies.
* @param blob The blob to upload.
*/
function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {
if (metadata === void 0) {
metadata = null;
}
var _this = this;
this.transferred_ = 0;
this.needToFetchStatus_ = false;
this.needToFetchMetadata_ = false;
this.observers_ = [];
this.error_ = null;
this.uploadUrl_ = null;
this.request_ = null;
this.chunkMultiplier_ = 1;
this.resolve_ = null;
this.reject_ = null;
this.ref_ = ref;
this.authWrapper_ = authWrapper;
this.location_ = location;
this.blob_ = blob;
this.metadata_ = metadata;
this.mappings_ = mappings;
this.resumable_ = this.shouldDoResumable_(this.blob_);
this.state_ = _taskenums.InternalTaskState.RUNNING;
this.errorHandler_ = function (error) {
_this.request_ = null;
_this.chunkMultiplier_ = 1;
if (error.codeEquals(errors.Code.CANCELED)) {
_this.needToFetchStatus_ = true;
_this.completeTransitions_();
} else {
_this.error_ = error;
_this.transition_(_taskenums.InternalTaskState.ERROR);
}
};
this.metadataErrorHandler_ = function (error) {
_this.request_ = null;
if (error.codeEquals(errors.Code.CANCELED)) {
_this.completeTransitions_();
} else {
_this.error_ = error;
_this.transition_(_taskenums.InternalTaskState.ERROR);
}
};
this.promise_ = fbsPromiseimpl.make(function (resolve, reject) {
_this.resolve_ = resolve;
_this.reject_ = reject;
_this.start_();
});
// Prevent uncaught rejections on the internal promise from bubbling out
// to the top level with a dummy handler.
this.promise_.then(null, function () {});
}
UploadTask.prototype.makeProgressCallback_ = function () {
var _this = this;
var sizeBefore = this.transferred_;
return function (loaded, total) {
_this.updateProgress_(sizeBefore + loaded);
};
};
UploadTask.prototype.shouldDoResumable_ = function (blob) {
return blob.size() > 256 * 1024;
};
UploadTask.prototype.start_ = function () {
if (this.state_ !== _taskenums.InternalTaskState.RUNNING) {
// This can happen if someone pauses us in a resume callback, for example.
return;
}
if (this.request_ !== null) {
return;
}
if (this.resumable_) {
if (this.uploadUrl_ === null) {
this.createResumable_();
} else {
if (this.needToFetchStatus_) {
this.fetchStatus_();
} else {
if (this.needToFetchMetadata_) {
// Happens if we miss the metadata on upload completion.
this.fetchMetadata_();
} else {
this.continueUpload_();
}
}
}
} else {
this.oneShotUpload_();
}
};
UploadTask.prototype.resolveToken_ = function (callback) {
var _this = this;
this.authWrapper_.getAuthToken().then(function (authToken) {
switch (_this.state_) {
case _taskenums.InternalTaskState.RUNNING:
callback(authToken);
break;
case _taskenums.InternalTaskState.CANCELING:
_this.transition_(_taskenums.InternalTaskState.CANCELED);
break;
case _taskenums.InternalTaskState.PAUSING:
_this.transition_(_taskenums.InternalTaskState.PAUSED);
break;
default:
}
});
};
// TODO(andysoto): assert false
UploadTask.prototype.createResumable_ = function () {
var _this = this;
this.resolveToken_(function (authToken) {
var requestInfo = fbsRequests.createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);
var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
_this.request_ = createRequest;
createRequest.getPromise().then(function (url) {
_this.request_ = null;
_this.uploadUrl_ = url;
_this.needToFetchStatus_ = false;
_this.completeTransitions_();
}, _this.errorHandler_);
});
};
UploadTask.prototype.fetchStatus_ = function () {
var _this = this;
// TODO(andysoto): assert(this.uploadUrl_ !== null);
var url = this.uploadUrl_;
this.resolveToken_(function (authToken) {
var requestInfo = fbsRequests.getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);
var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
_this.request_ = statusRequest;
statusRequest.getPromise().then(function (status) {
status = status;
_this.request_ = null;
_this.updateProgress_(status.current);
_this.needToFetchStatus_ = false;
if (status.finalized) {
_this.needToFetchMetadata_ = true;
}
_this.completeTransitions_();
}, _this.errorHandler_);
});
};
UploadTask.prototype.continueUpload_ = function () {
var _this = this;
var chunkSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;
var status = new fbsRequests.ResumableUploadStatus(this.transferred_, this.blob_.size());
// TODO(andysoto): assert(this.uploadUrl_ !== null);
var url = this.uploadUrl_;
this.resolveToken_(function (authToken) {
var requestInfo;
try {
requestInfo = fbsRequests.continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());
} catch (e) {
_this.error_ = e;
_this.transition_(_taskenums.InternalTaskState.ERROR);
return;
}
var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
_this.request_ = uploadRequest;
uploadRequest.getPromise().then(function (newStatus) {
_this.increaseMultiplier_();
_this.request_ = null;
_this.updateProgress_(newStatus.current);
if (newStatus.finalized) {
_this.metadata_ = newStatus.metadata;
_this.transition_(_taskenums.InternalTaskState.SUCCESS);
} else {
_this.completeTransitions_();
}
}, _this.errorHandler_);
});
};
UploadTask.prototype.increaseMultiplier_ = function () {
var currentSize = fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;
// Max chunk size is 32M.
if (currentSize < 32 * 1024 * 1024) {
this.chunkMultiplier_ *= 2;
}
};
UploadTask.prototype.fetchMetadata_ = function () {
var _this = this;
this.resolveToken_(function (authToken) {
var requestInfo = fbsRequests.getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);
var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
_this.request_ = metadataRequest;
metadataRequest.getPromise().then(function (metadata) {
_this.request_ = null;
_this.metadata_ = metadata;
_this.transition_(_taskenums.InternalTaskState.SUCCESS);
}, _this.metadataErrorHandler_);
});
};
UploadTask.prototype.oneShotUpload_ = function () {
var _this = this;
this.resolveToken_(function (authToken) {
var requestInfo = fbsRequests.multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);
var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);
_this.request_ = multipartRequest;
multipartRequest.getPromise().then(function (metadata) {
_this.request_ = null;
_this.metadata_ = metadata;
_this.updateProgress_(_this.blob_.size());
_this.transition_(_taskenums.InternalTaskState.SUCCESS);
}, _this.errorHandler_);
});
};
UploadTask.prototype.updateProgress_ = function (transferred) {
var old = this.transferred_;
this.transferred_ = transferred;
// A progress update can make the "transferred" value smaller (e.g. a
// partial upload not completed by server, after which the "transferred"
// value may reset to the value at the beginning of the request).
if (this.transferred_ !== old) {
this.notifyObservers_();
}
};
UploadTask.prototype.transition_ = function (state) {
if (this.state_ === state) {
return;
}
switch (state) {
case _taskenums.InternalTaskState.CANCELING:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.RUNNING ||
// this.state_ === InternalTaskState.PAUSING);
this.state_ = state;
if (this.request_ !== null) {
this.request_.cancel();
}
break;
case _taskenums.InternalTaskState.PAUSING:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.RUNNING);
this.state_ = state;
if (this.request_ !== null) {
this.request_.cancel();
}
break;
case _taskenums.InternalTaskState.RUNNING:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.PAUSED ||
// this.state_ === InternalTaskState.PAUSING);
var wasPaused = this.state_ === _taskenums.InternalTaskState.PAUSED;
this.state_ = state;
if (wasPaused) {
this.notifyObservers_();
this.start_();
}
break;
case _taskenums.InternalTaskState.PAUSED:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.PAUSING);
this.state_ = state;
this.notifyObservers_();
break;
case _taskenums.InternalTaskState.CANCELED:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.PAUSED ||
// this.state_ === InternalTaskState.CANCELING);
this.error_ = errors.canceled();
this.state_ = state;
this.notifyObservers_();
break;
case _taskenums.InternalTaskState.ERROR:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.RUNNING ||
// this.state_ === InternalTaskState.PAUSING ||
// this.state_ === InternalTaskState.CANCELING);
this.state_ = state;
this.notifyObservers_();
break;
case _taskenums.InternalTaskState.SUCCESS:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.RUNNING ||
// this.state_ === InternalTaskState.PAUSING ||
// this.state_ === InternalTaskState.CANCELING);
this.state_ = state;
this.notifyObservers_();
break;
}
};
UploadTask.prototype.completeTransitions_ = function () {
switch (this.state_) {
case _taskenums.InternalTaskState.PAUSING:
this.transition_(_taskenums.InternalTaskState.PAUSED);
break;
case _taskenums.InternalTaskState.CANCELING:
this.transition_(_taskenums.InternalTaskState.CANCELED);
break;
case _taskenums.InternalTaskState.RUNNING:
this.start_();
break;
default:
// TODO(andysoto): assert(false);
break;
}
};
Object.defineProperty(UploadTask.prototype, "snapshot", {
get: function get() {
var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);
return new _tasksnapshot.UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);
},
enumerable: true,
configurable: true
});
/**
* Adds a callback for an event.
* @param type The type of event to listen for.
*/
UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {
if (nextOrObserver === void 0) {
nextOrObserver = undefined;
}
if (error === void 0) {
error = undefined;
}
if (completed === void 0) {
completed = undefined;
}
function typeValidator(_p) {
if (type !== _taskenums.TaskEvent.STATE_CHANGED) {
throw "Expected one of the event types: [" + _taskenums.TaskEvent.STATE_CHANGED + "].";
}
}
var nextOrObserverMessage = 'Expected a function or an Object with one of ' + '`next`, `error`, `complete` properties.';
var nextValidator = fbsArgs.nullFunctionSpec(true).validator;
var observerValidator = fbsArgs.looseObjectSpec(null, true).validator;
function nextOrObserverValidator(p) {
try {
nextValidator(p);
return;
} catch (e) {}
try {
observerValidator(p);
var anyDefined = typeUtils.isJustDef(p['next']) || typeUtils.isJustDef(p['error']) || typeUtils.isJustDef(p['complete']);
if (!anyDefined) {
throw '';
}
return;
} catch (e) {
throw nextOrObserverMessage;
}
}
var specs = [fbsArgs.stringSpec(typeValidator), fbsArgs.looseObjectSpec(nextOrObserverValidator, true), fbsArgs.nullFunctionSpec(true), fbsArgs.nullFunctionSpec(true)];
fbsArgs.validate('on', specs, arguments);
var self = this;
function makeBinder(specs) {
function binder(nextOrObserver, error, opt_complete) {
if (specs !== null) {
fbsArgs.validate('on', specs, arguments);
}
var observer = new _observer.Observer(nextOrObserver, error, completed);
self.addObserver_(observer);
return function () {
self.removeObserver_(observer);
};
}
return binder;
}
function binderNextOrObserverValidator(p) {
if (p === null) {
throw nextOrObserverMessage;
}
nextOrObserverValidator(p);
}
var binderSpecs = [fbsArgs.looseObjectSpec(binderNextOrObserverValidator), fbsArgs.nullFunctionSpec(true), fbsArgs.nullFunctionSpec(true)];
var typeOnly = !(typeUtils.isJustDef(nextOrObserver) || typeUtils.isJustDef(error) || typeUtils.isJustDef(completed));
if (typeOnly) {
return makeBinder(binderSpecs);
} else {
return makeBinder(null)(nextOrObserver, error, completed);
}
};
/**
* This object behaves like a Promise, and resolves with its snapshot data
* when the upload completes.
* @param onFulfilled The fulfillment callback. Promise chaining works as normal.
* @param onRejected The rejection callback.
*/
UploadTask.prototype.then = function (onFulfilled, onRejected) {
// These casts are needed so that TypeScript can infer the types of the
// resulting Promise.
return this.promise_.then(onFulfilled, onRejected);
};
/**
* Equivalent to calling `then(null, onRejected)`.
*/
UploadTask.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};
/**
* Adds the given observer.
*/
UploadTask.prototype.addObserver_ = function (observer) {
this.observers_.push(observer);
this.notifyObserver_(observer);
};
/**
* Removes the given observer.
*/
UploadTask.prototype.removeObserver_ = function (observer) {
fbsArray.remove(this.observers_, observer);
};
UploadTask.prototype.notifyObservers_ = function () {
var _this = this;
this.finishPromise_();
var observers = fbsArray.clone(this.observers_);
observers.forEach(function (observer) {
_this.notifyObserver_(observer);
});
};
UploadTask.prototype.finishPromise_ = function () {
if (this.resolve_ !== null) {
var triggered = true;
switch (fbsTaskEnums.taskStateFromInternalTaskState(this.state_)) {
case _taskenums.TaskState.SUCCESS:
(0, _async.async)(this.resolve_.bind(null, this.snapshot))();
break;
case _taskenums.TaskState.CANCELED:
case _taskenums.TaskState.ERROR:
var toCall = this.reject_;
(0, _async.async)(toCall.bind(null, this.error_))();
break;
default:
triggered = false;
break;
}
if (triggered) {
this.resolve_ = null;
this.reject_ = null;
}
}
};
UploadTask.prototype.notifyObserver_ = function (observer) {
var externalState = fbsTaskEnums.taskStateFromInternalTaskState(this.state_);
switch (externalState) {
case _taskenums.TaskState.RUNNING:
case _taskenums.TaskState.PAUSED:
if (observer.next !== null) {
(0, _async.async)(observer.next.bind(observer, this.snapshot))();
}
break;
case _taskenums.TaskState.SUCCESS:
if (observer.complete !== null) {
(0, _async.async)(observer.complete.bind(observer))();
}
break;
case _taskenums.TaskState.CANCELED:
case _taskenums.TaskState.ERROR:
if (observer.error !== null) {
(0, _async.async)(observer.error.bind(observer, this.error_))();
}
break;
default:
// TODO(andysoto): assert(false);
if (observer.error !== null) {
(0, _async.async)(observer.error.bind(observer, this.error_))();
}
}
};
/**
* Resumes a paused task. Has no effect on a currently running or failed task.
* @return True if the operation took effect, false if ignored.
*/
UploadTask.prototype.resume = function () {
fbsArgs.validate('resume', [], arguments);
var valid = this.state_ === _taskenums.InternalTaskState.PAUSED || this.state_ === _taskenums.InternalTaskState.PAUSING;
if (valid) {
this.transition_(_taskenums.InternalTaskState.RUNNING);
}
return valid;
};
/**
* Pauses a currently running task. Has no effect on a paused or failed task.
* @return True if the operation took effect, false if ignored.
*/
UploadTask.prototype.pause = function () {
fbsArgs.validate('pause', [], arguments);
var valid = this.state_ === _taskenums.InternalTaskState.RUNNING;
if (valid) {
this.transition_(_taskenums.InternalTaskState.PAUSING);
}
return valid;
};
/**
* Cancels a currently running or paused task. Has no effect on a complete or
* failed task.
* @return True if the operation took effect, false if ignored.
*/
UploadTask.prototype.cancel = function () {
fbsArgs.validate('cancel', [], arguments);
var valid = this.state_ === _taskenums.InternalTaskState.RUNNING || this.state_ === _taskenums.InternalTaskState.PAUSING;
if (valid) {
this.transition_(_taskenums.InternalTaskState.CANCELING);
}
return valid;
};
return UploadTask;
}();
exports.UploadTask = UploadTask;
//# sourceMappingURL=task.js.map
| {'content_hash': '9185c15402d6d213b4b0322598ffb5c7', 'timestamp': '', 'source': 'github', 'line_count': 575, 'max_line_length': 269, 'avg_line_length': 40.80347826086957, 'alnum_prop': 0.5613332196743671, 'repo_name': 'gest01/HackZurich', 'id': 'd2f028c5a6dd9a94bc03929cadf0f3b58978b80e', 'size': '23462', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'HackZurich.Web/app/node_modules/firebase/storage/task.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '108'}, {'name': 'C#', 'bytes': '3063'}, {'name': 'CSS', 'bytes': '3420'}, {'name': 'HTML', 'bytes': '13085'}, {'name': 'JavaScript', 'bytes': '6831'}, {'name': 'TypeScript', 'bytes': '22324'}]} |
/// <reference path="../projectile.ts" />
describe("Projectile", () => {
it("should construct a new projectile", () => {
var p:Projectile = new Projectile( new PolarCoordinate(0.1, 0.2) );
expect(p.position.angle).toEqual(0.1);
expect(p.position.radius).toEqual(0.2);
});
it("should animate position", () => {
var p:Projectile = new Projectile( new PolarCoordinate(1.0, 1.0) );
p.animate(0.1, 0.0);
expect(p.position.radius).toEqual(0.9);
});
it("should respond to 'discard?' communication", () => {
var p:Projectile = new Projectile( new PolarCoordinate() );
expect( p.ask({verb: "discard?"}) ).toEqual( {verb: "smile!"} );
p.animate(2.0, 0.0);
expect( p.ask({verb: "discard?"}) ).toEqual({verb: "discard!"});
});
it("should respond to 'collide?' communication", () => {
var p1:Projectile = new Projectile( new PolarCoordinate() );
var p2:Projectile = new Projectile( new PolarCoordinate() );
var s2:Spaceship = new Spaceship( new PolarCoordinate(0.0, 0.05) );
expect( p1.ask({verb: "collide?", argument: p2}) ).toEqual( {verb: "smile!"} );
expect( p1.ask({verb: "collide?", argument: s2}) ).toEqual( {verb: "smile!"} );
p1.speed = 0.0;
p1.animate(0.5, 0.0); // .5 is "Ghost" time
expect( p1.ask({verb: "collide?", argument: p2}) ).toEqual( {verb: "smile!"} );
expect( p1.ask({verb: "collide?", argument: s2}) ).toEqual( {verb: "collide!", argument:1} );
p1.position.radius = p1.position.areal*1.1;
expect( p1.ask({verb: "collide?", argument: p2}) ).toEqual({verb: "smile!"});
expect( p1.ask({verb: "collide?", argument: s2}) ).toEqual({verb: "smile!"});
});
it("should detect collisions", () => {
var p:Projectile = new Projectile( new PolarCoordinate(0.0, 1.0) );
var s:Spaceship = new Spaceship( new PolarCoordinate() );
var distanceToAngle = (d: number) => {
return Math.acos( (2.0-d*d)/2.0 );
}
s.position = new PolarCoordinateAreal(0.0, 1.0, p.position.areal);
expect( p.isCollision(s) ).toBeTruthy();
s.position = new PolarCoordinateAreal( 0.0, 1.0 + p.position.areal * 1.99, p.position.areal);
expect( p.isCollision(s) ).toBeTruthy();
s.position = new PolarCoordinateAreal( 0.0, 1.0 - p.position.areal * 1.99, p.position.areal);
expect( p.isCollision(s) ).toBeTruthy();
s.position = new PolarCoordinateAreal( distanceToAngle(p.position.areal) * 1.99, 1.0, p.position.areal);
expect( p.isCollision(s) ).toBeTruthy();
s.position = new PolarCoordinateAreal( 0.0, 1.0 + p.position.areal * 2.10, p.position.areal);
expect( p.isCollision(s) ).toBeFalsy();
s.position = new PolarCoordinateAreal( distanceToAngle(p.position.areal) * 2.10, 1.0, p.position.areal);
expect( p.isCollision(s) ).toBeFalsy();
});
});
| {'content_hash': 'b16f881233421ec244d9aab1662c65db', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 108, 'avg_line_length': 38.52054794520548, 'alnum_prop': 0.6237553342816501, 'repo_name': 'latanas/frontliner', 'id': 'cbd36f6e156b917e93e0922ac13abc49ca8bac88', 'size': '2980', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/projectile_spec.ts', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '851'}, {'name': 'HTML', 'bytes': '740'}, {'name': 'Shell', 'bytes': '131'}, {'name': 'TypeScript', 'bytes': '53474'}]} |
package com.ocpsoft.pretty.faces.config.convert;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import com.ocpsoft.pretty.faces.config.rewrite.Case;
public class CaseConverter implements Converter
{
@SuppressWarnings("rawtypes")
public Object convert(final Class type, final Object value)
{
if (value instanceof String)
{
return Enum.valueOf(Case.class, ((String) value).toUpperCase());
}
throw new ConversionException("Could not convert value: [" + value + "] to Case type.");
}
} | {'content_hash': '592d9676b064142f9dcdabb8257258ec', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 94, 'avg_line_length': 28.0, 'alnum_prop': 0.7210884353741497, 'repo_name': 'jsight/rewrite', 'id': '155488ec37e2031d450ba45438c723967c49bcac', 'size': '1193', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'config-prettyfaces/src/main/java/com/ocpsoft/pretty/faces/config/convert/CaseConverter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '7370'}, {'name': 'HTML', 'bytes': '59894'}, {'name': 'Java', 'bytes': '2692689'}, {'name': 'JavaScript', 'bytes': '697545'}, {'name': 'Ruby', 'bytes': '1234887'}, {'name': 'Shell', 'bytes': '1268'}]} |
curr_dir=$(pwd)
work_dir=$HOME/cluster/
echo $curr_dir
echo $work_dir
if [ ! -d $work_dir ]; then
mkdir -p $work_dir
fi
cd $work_dir
########################
# common input variables
########################
project_dir="$CBIG_CODE_DIR/stable_projects/preprocessing/Li2019_GSR"
replication_dir="$project_dir/unit_tests/intelligence_score"
test_dir=$CBIG_TESTDATA_DIR/stable_projects/preprocessing/Li2019_GSR/intelligence_score/KernelRidgeRegression/GSP
subject_list="$test_dir/lists/subject_list_862.txt"
FD_file="$test_dir/lists/FD_regressor_862.txt"
DVARS_file="$test_dir/lists/DV_regressor_862.txt"
data_csv="$test_dir/lists/GSP_phenotypes_shuffled.csv"
#RSFC_file="$test_dir/cort+subcort_new_S1200_862_Fisher.mat"
with_bias=0
top_outdir=$1
#top_outdir=$test_dir/ref_output
for pipeline in GSR Baseline ; do
RSFC_file=$test_dir/RSFC_862_Fisher_${pipeline}.mat
outdir=$top_outdir/$pipeline
##########################
# call the GSP wrapper
##########################
cog_list="$replication_dir/scripts/GSP_lists/intelligence_score.txt"
covariate_list="$replication_dir/scripts/GSP_lists/covariates.txt"
outstem=2intelligence
for seed in $(seq 1 1 3); do
log_file="${top_outdir}/CBIG_LiGSR_KRR_unittest_intelligence_score_GSP_${seed}.log"
cmd="$project_dir/KernelRidgeRegression/GSP/scripts/CBIG_LiGSR_KRR_workflowGSP.sh -subject_list $subject_list "
cmd="$cmd -RSFC_file $RSFC_file -y_list $cog_list -covariate_list $covariate_list -FD_file $FD_file -DVARS_file "
cmd="$cmd $DVARS_file -outdir $outdir -outstem $outstem -seed $seed -num_test_folds 5 -num_inner_folds 5"
cmd="$cmd -with_bias $with_bias -data_csv $data_csv"
cmd="$cmd | tee -a ${log_file}"
$CBIG_CODE_DIR/setup/CBIG_pbsubmit -cmd "$cmd" -walltime 1:00:00 -mem 6G \
-name "LiGSRUT_KR"
if [ ! -f $outdir/covariates_${outstem}.mat ] || [ ! -f $outdir/y_${outstem}.mat ]; then
# wait for the files shared across random splits to be saved
sleep 1m
else
sleep 3s
fi
done
done
| {'content_hash': '0733c0f793bc9508a419dce4500b1efe', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 115, 'avg_line_length': 32.564516129032256, 'alnum_prop': 0.678058444774641, 'repo_name': 'ThomasYeoLab/CBIG', 'id': '84c2ce61b5ad79041ceee84c21bfcfba16a7e98b', 'size': '2404', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'stable_projects/preprocessing/Li2019_GSR/unit_tests/intelligence_score/scripts/CBIG_LiGSR_KRR_unittest_intelligence_score_GSP.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '35378'}, {'name': 'C', 'bytes': '2076236'}, {'name': 'C++', 'bytes': '1461097'}, {'name': 'CSS', 'bytes': '6852'}, {'name': 'Fortran', 'bytes': '598090'}, {'name': 'HTML', 'bytes': '287918'}, {'name': 'Jupyter Notebook', 'bytes': '569200'}, {'name': 'MATLAB', 'bytes': '10013692'}, {'name': 'Makefile', 'bytes': '7902'}, {'name': 'Objective-C', 'bytes': '77'}, {'name': 'PostScript', 'bytes': '8416'}, {'name': 'Python', 'bytes': '2499129'}, {'name': 'R', 'bytes': '33929'}, {'name': 'Shell', 'bytes': '1923688'}, {'name': 'TeX', 'bytes': '8993'}, {'name': 'Vim Script', 'bytes': '2859'}, {'name': 'XSLT', 'bytes': '19506'}]} |
package com.smartdevicelink.proxy.rpc.enums;
public enum PowerModeQualificationStatus {
POWER_MODE_UNDEFINED,
POWER_MODE_EVALUATION_IN_PROGRESS,
NOT_DEFINED,
POWER_MODE_OK;
public static PowerModeQualificationStatus valueForString(String value) {
try{
return valueOf(value);
}catch(Exception e){
return null;
}
}
}
| {'content_hash': '16e81f16f970703add3b9b28ae1d081e', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 77, 'avg_line_length': 24.5625, 'alnum_prop': 0.648854961832061, 'repo_name': 'mrapitis/sdl_android', 'id': '381a0293e2ea633b3a2a3ee0158976ccdc52e84d', 'size': '393', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sdl_android_lib/src/com/smartdevicelink/proxy/rpc/enums/PowerModeQualificationStatus.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '1342681'}]} |
package org.apache.hadoop.crypto;
import java.security.GeneralSecurityException;
import java.util.List;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_KEY;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_DEFAULT;
/**
* Crypto codec class, encapsulates encryptor/decryptor pair.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public abstract class CryptoCodec implements Configurable {
public static Logger LOG = LoggerFactory.getLogger(CryptoCodec.class);
/**
* Get crypto codec for specified algorithm/mode/padding.
*
* @param conf
* the configuration
* @param CipherSuite
* algorithm/mode/padding
* @return CryptoCodec the codec object. Null value will be returned if no
* crypto codec classes with cipher suite configured.
*/
public static CryptoCodec getInstance(Configuration conf,
CipherSuite cipherSuite) {
List<Class<? extends CryptoCodec>> klasses = getCodecClasses(
conf, cipherSuite);
if (klasses == null) {
return null;
}
CryptoCodec codec = null;
for (Class<? extends CryptoCodec> klass : klasses) {
try {
CryptoCodec c = ReflectionUtils.newInstance(klass, conf);
if (c.getCipherSuite().getName().equals(cipherSuite.getName())) {
if (codec == null) {
LOG.debug("Using crypto codec {}.", klass.getName());
codec = c;
}
} else {
LOG.warn("Crypto codec {} doesn't meet the cipher suite {}.",
klass.getName(), cipherSuite.getName());
}
} catch (Exception e) {
LOG.warn("Crypto codec {} is not available.", klass.getName());
}
}
if (codec != null) {
return codec;
}
throw new RuntimeException("No available crypto codec which meets " +
"the cipher suite " + cipherSuite.getName() + ".");
}
/**
* Get crypto codec for algorithm/mode/padding in config value
* hadoop.security.crypto.cipher.suite
*
* @param conf
* the configuration
* @return CryptoCodec the codec object Null value will be returned if no
* crypto codec classes with cipher suite configured.
*/
public static CryptoCodec getInstance(Configuration conf) {
String name = conf.get(HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_KEY,
HADOOP_SECURITY_CRYPTO_CIPHER_SUITE_DEFAULT);
return getInstance(conf, CipherSuite.convert(name));
}
private static List<Class<? extends CryptoCodec>> getCodecClasses(
Configuration conf, CipherSuite cipherSuite) {
List<Class<? extends CryptoCodec>> result = Lists.newArrayList();
String configName = HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX +
cipherSuite.getConfigSuffix();
String codecString = conf.get(configName);
if (codecString == null) {
LOG.warn("No crypto codec classes with cipher suite configured.");
return null;
}
for (String c : Splitter.on(',').trimResults().omitEmptyStrings().
split(codecString)) {
try {
Class<?> cls = conf.getClassByName(c);
result.add(cls.asSubclass(CryptoCodec.class));
} catch (ClassCastException e) {
LOG.warn("Class " + c + " is not a CryptoCodec.");
} catch (ClassNotFoundException e) {
LOG.warn("Crypto codec " + c + " not found.");
}
}
return result;
}
/**
* @return the CipherSuite for this codec.
*/
public abstract CipherSuite getCipherSuite();
/**
* Create a {@link org.apache.hadoop.crypto.Encryptor}.
* @return Encryptor the encryptor
*/
public abstract Encryptor createEncryptor() throws GeneralSecurityException;
/**
* Create a {@link org.apache.hadoop.crypto.Decryptor}.
* @return Decryptor the decryptor
*/
public abstract Decryptor createDecryptor() throws GeneralSecurityException;
/**
* This interface is only for Counter (CTR) mode. Generally the Encryptor
* or Decryptor calculates the IV and maintain encryption context internally.
* For example a {@link javax.crypto.Cipher} will maintain its encryption
* context internally when we do encryption/decryption using the
* Cipher#update interface.
* <p/>
* Encryption/Decryption is not always on the entire file. For example,
* in Hadoop, a node may only decrypt a portion of a file (i.e. a split).
* In these situations, the counter is derived from the file position.
* <p/>
* The IV can be calculated by combining the initial IV and the counter with
* a lossless operation (concatenation, addition, or XOR).
* @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29
*
* @param initIV initial IV
* @param counter counter for input stream position
* @param IV the IV for input stream position
*/
public abstract void calculateIV(byte[] initIV, long counter, byte[] IV);
/**
* Generate a number of secure, random bytes suitable for cryptographic use.
* This method needs to be thread-safe.
*
* @param bytes byte array to populate with random data
*/
public abstract void generateSecureRandom(byte[] bytes);
}
| {'content_hash': 'ce240f1e6d5d047cf4a515aa07b3adf0', 'timestamp': '', 'source': 'github', 'line_count': 158, 'max_line_length': 113, 'avg_line_length': 36.60126582278481, 'alnum_prop': 0.6883970257651738, 'repo_name': 'jonathangizmo/HadoopDistJ', 'id': '9de7f95200f5f44e440619269fbc2ae1135f599d', 'size': '6589', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/CryptoCodec.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AspectJ', 'bytes': '29602'}, {'name': 'C', 'bytes': '1201880'}, {'name': 'C++', 'bytes': '87387'}, {'name': 'CSS', 'bytes': '44021'}, {'name': 'Erlang', 'bytes': '232'}, {'name': 'Java', 'bytes': '43792925'}, {'name': 'JavaScript', 'bytes': '22681'}, {'name': 'Perl', 'bytes': '19540'}, {'name': 'Python', 'bytes': '11309'}, {'name': 'Shell', 'bytes': '273691'}, {'name': 'TeX', 'bytes': '19322'}, {'name': 'XSLT', 'bytes': '20949'}]} |
package org.apache.kafka.common.config;
/**
* <p>Keys that can be used to configure a topic. These keys are useful when creating or reconfiguring a
* topic using the AdminClient.
*
* <p>The intended pattern is for broker configs to include a <code>`log.`</code> prefix. For example, to set the default broker
* cleanup policy, one would set <code>log.cleanup.policy</code> instead of <code>cleanup.policy</code>. Unfortunately, there are many cases
* where this pattern is not followed.
*/
// This is a public API, so we should not remove or alter keys without a discussion and a deprecation period.
// Eventually this should replace LogConfig.scala.
public class TopicConfig {
public static final String SEGMENT_BYTES_CONFIG = "segment.bytes";
public static final String SEGMENT_BYTES_DOC = "This configuration controls the segment file size for " +
"the log. Retention and cleaning is always done a file at a time so a larger segment size means " +
"fewer files but less granular control over retention.";
public static final String SEGMENT_MS_CONFIG = "segment.ms";
public static final String SEGMENT_MS_DOC = "This configuration controls the period of time after " +
"which Kafka will force the log to roll even if the segment file isn't full to ensure that retention " +
"can delete or compact old data.";
public static final String SEGMENT_JITTER_MS_CONFIG = "segment.jitter.ms";
public static final String SEGMENT_JITTER_MS_DOC = "The maximum random jitter subtracted from the scheduled " +
"segment roll time to avoid thundering herds of segment rolling";
public static final String SEGMENT_INDEX_BYTES_CONFIG = "segment.index.bytes";
public static final String SEGMENT_INDEX_BYTES_DOC = "This configuration controls the size of the index that " +
"maps offsets to file positions. We preallocate this index file and shrink it only after log " +
"rolls. You generally should not need to change this setting.";
public static final String FLUSH_MESSAGES_INTERVAL_CONFIG = "flush.messages";
public static final String FLUSH_MESSAGES_INTERVAL_DOC = "This setting allows specifying an interval at " +
"which we will force an fsync of data written to the log. For example if this was set to 1 " +
"we would fsync after every message; if it were 5 we would fsync after every five messages. " +
"In general we recommend you not set this and use replication for durability and allow the " +
"operating system's background flush capabilities as it is more efficient. This setting can " +
"be overridden on a per-topic basis (see <a href=\"#topicconfigs\">the per-topic configuration section</a>).";
public static final String FLUSH_MS_CONFIG = "flush.ms";
public static final String FLUSH_MS_DOC = "This setting allows specifying a time interval at which we will " +
"force an fsync of data written to the log. For example if this was set to 1000 " +
"we would fsync after 1000 ms had passed. In general we recommend you not set " +
"this and use replication for durability and allow the operating system's background " +
"flush capabilities as it is more efficient.";
public static final String RETENTION_BYTES_CONFIG = "retention.bytes";
public static final String RETENTION_BYTES_DOC = "This configuration controls the maximum size a partition " +
"(which consists of log segments) can grow to before we will discard old log segments to free up space if we " +
"are using the \"delete\" retention policy. By default there is no size limit only a time limit. " +
"Since this limit is enforced at the partition level, multiply it by the number of partitions to compute " +
"the topic retention in bytes.";
public static final String RETENTION_MS_CONFIG = "retention.ms";
public static final String RETENTION_MS_DOC = "This configuration controls the maximum time we will retain a " +
"log before we will discard old log segments to free up space if we are using the " +
"\"delete\" retention policy. This represents an SLA on how soon consumers must read " +
"their data. If set to -1, no time limit is applied.";
public static final String MAX_MESSAGE_BYTES_CONFIG = "max.message.bytes";
public static final String MAX_MESSAGE_BYTES_DOC = "<p>The largest record batch size allowed by Kafka. If this " +
"is increased and there are consumers older than 0.10.2, the consumers' fetch size must also be increased so that " +
"the they can fetch record batches this large.</p>" +
"<p>In the latest message format version, records are always grouped into batches for efficiency. In previous " +
"message format versions, uncompressed records are not grouped into batches and this limit only applies to a " +
"single record in that case.</p>";
public static final String INDEX_INTERVAL_BYTES_CONFIG = "index.interval.bytes";
public static final String INDEX_INTERVAL_BYTES_DOCS = "This setting controls how frequently " +
"Kafka adds an index entry to its offset index. The default setting ensures that we index a " +
"message roughly every 4096 bytes. More indexing allows reads to jump closer to the exact " +
"position in the log but makes the index larger. You probably don't need to change this.";
public static final String FILE_DELETE_DELAY_MS_CONFIG = "file.delete.delay.ms";
public static final String FILE_DELETE_DELAY_MS_DOC = "The time to wait before deleting a file from the " +
"filesystem";
public static final String DELETE_RETENTION_MS_CONFIG = "delete.retention.ms";
public static final String DELETE_RETENTION_MS_DOC = "The amount of time to retain delete tombstone markers " +
"for <a href=\"#compaction\">log compacted</a> topics. This setting also gives a bound " +
"on the time in which a consumer must complete a read if they begin from offset 0 " +
"to ensure that they get a valid snapshot of the final stage (otherwise delete " +
"tombstones may be collected before they complete their scan).";
public static final String MIN_COMPACTION_LAG_MS_CONFIG = "min.compaction.lag.ms";
public static final String MIN_COMPACTION_LAG_MS_DOC = "The minimum time a message will remain " +
"uncompacted in the log. Only applicable for logs that are being compacted.";
public static final String MIN_CLEANABLE_DIRTY_RATIO_CONFIG = "min.cleanable.dirty.ratio";
public static final String MIN_CLEANABLE_DIRTY_RATIO_DOC = "This configuration controls how frequently " +
"the log compactor will attempt to clean the log (assuming <a href=\"#compaction\">log " +
"compaction</a> is enabled). By default we will avoid cleaning a log where more than " +
"50% of the log has been compacted. This ratio bounds the maximum space wasted in " +
"the log by duplicates (at 50% at most 50% of the log could be duplicates). A " +
"higher ratio will mean fewer, more efficient cleanings but will mean more wasted " +
"space in the log.";
public static final String CLEANUP_POLICY_CONFIG = "cleanup.policy";
public static final String CLEANUP_POLICY_COMPACT = "compact";
public static final String CLEANUP_POLICY_DELETE = "delete";
public static final String CLEANUP_POLICY_DOC = "A string that is either \"" + CLEANUP_POLICY_DELETE +
"\" or \"" + CLEANUP_POLICY_COMPACT + "\" or both. This string designates the retention policy to use on " +
"old log segments. The default policy (\"delete\") will discard old segments when their retention " +
"time or size limit has been reached. The \"compact\" setting will enable <a href=\"#compaction\">log " +
"compaction</a> on the topic.";
public static final String UNCLEAN_LEADER_ELECTION_ENABLE_CONFIG = "unclean.leader.election.enable";
public static final String UNCLEAN_LEADER_ELECTION_ENABLE_DOC = "Indicates whether to enable replicas " +
"not in the ISR set to be elected as leader as a last resort, even though doing so may result in data " +
"loss.";
public static final String MIN_IN_SYNC_REPLICAS_CONFIG = "min.insync.replicas";
public static final String MIN_IN_SYNC_REPLICAS_DOC = "When a producer sets acks to \"all\" (or \"-1\"), " +
"this configuration specifies the minimum number of replicas that must acknowledge " +
"a write for the write to be considered successful. If this minimum cannot be met, " +
"then the producer will raise an exception (either NotEnoughReplicas or " +
"NotEnoughReplicasAfterAppend).<br>When used together, <code>min.insync.replicas</code> and <code>acks</code> " +
"allow you to enforce greater durability guarantees. A typical scenario would be to " +
"create a topic with a replication factor of 3, set <code>min.insync.replicas</code> to 2, and " +
"produce with <code>acks</code> of \"all\". This will ensure that the producer raises an exception " +
"if a majority of replicas do not receive a write.";
public static final String COMPRESSION_TYPE_CONFIG = "compression.type";
public static final String COMPRESSION_TYPE_DOC = "Specify the final compression type for a given topic. " +
"This configuration accepts the standard compression codecs ('gzip', 'snappy', 'lz4', 'zstd'). It additionally " +
"accepts 'uncompressed' which is equivalent to no compression; and 'producer' which means retain the " +
"original compression codec set by the producer.";
public static final String PREALLOCATE_CONFIG = "preallocate";
public static final String PREALLOCATE_DOC = "True if we should preallocate the file on disk when " +
"creating a new log segment.";
public static final String MESSAGE_FORMAT_VERSION_CONFIG = "message.format.version";
public static final String MESSAGE_FORMAT_VERSION_DOC = "Specify the message format version the broker " +
"will use to append messages to the logs. The value should be a valid ApiVersion. Some examples are: " +
"0.8.2, 0.9.0.0, 0.10.0, check ApiVersion for more details. By setting a particular message format " +
"version, the user is certifying that all the existing messages on disk are smaller or equal than the " +
"specified version. Setting this value incorrectly will cause consumers with older versions to break as " +
"they will receive messages with a format that they don't understand.";
public static final String MESSAGE_TIMESTAMP_TYPE_CONFIG = "message.timestamp.type";
public static final String MESSAGE_TIMESTAMP_TYPE_DOC = "Define whether the timestamp in the message is " +
"message create time or log append time. The value should be either `CreateTime` or `LogAppendTime`";
public static final String MESSAGE_TIMESTAMP_DIFFERENCE_MAX_MS_CONFIG = "message.timestamp.difference.max.ms";
public static final String MESSAGE_TIMESTAMP_DIFFERENCE_MAX_MS_DOC = "The maximum difference allowed between " +
"the timestamp when a broker receives a message and the timestamp specified in the message. If " +
"message.timestamp.type=CreateTime, a message will be rejected if the difference in timestamp " +
"exceeds this threshold. This configuration is ignored if message.timestamp.type=LogAppendTime.";
public static final String MESSAGE_DOWNCONVERSION_ENABLE_CONFIG = "message.downconversion.enable";
public static final String MESSAGE_DOWNCONVERSION_ENABLE_DOC = "This configuration controls whether " +
"down-conversion of message formats is enabled to satisfy consume requests. When set to <code>false</code>, " +
"broker will not perform down-conversion for consumers expecting an older message format. The broker responds " +
"with <code>UNSUPPORTED_VERSION</code> error for consume requests from such older clients. This configuration" +
"does not apply to any message format conversion that might be required for replication to followers.";
}
| {'content_hash': 'cbb9c7f271cb090b169893daaa9855f9', 'timestamp': '', 'source': 'github', 'line_count': 160, 'max_line_length': 140, 'avg_line_length': 76.26875, 'alnum_prop': 0.7168729001065312, 'repo_name': 'gf53520/kafka', 'id': '57662d5a8663c684f0c49b78bee055a508ca4b86', 'size': '13001', 'binary': False, 'copies': '1', 'ref': 'refs/heads/trunk', 'path': 'clients/src/main/java/org/apache/kafka/common/config/TopicConfig.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '19756'}, {'name': 'HTML', 'bytes': '5443'}, {'name': 'Java', 'bytes': '1311715'}, {'name': 'Python', 'bytes': '370708'}, {'name': 'Scala', 'bytes': '2370228'}, {'name': 'Shell', 'bytes': '83830'}, {'name': 'XSLT', 'bytes': '7116'}]} |
"""Convert Jenkins config into prow config. """
import argparse
import copy
import fileinput
import json
import subprocess
import sys
import yaml
TEMPLATE = {
'name': '',
'interval': '30m',
'spec': {
'containers': [{
'image': 'gcr.io/k8s-testimages/kubekins-e2e-prow:v20170606-e69a3df0',
'args': [],
'volumeMounts': [{
'readOnly': True,
'mountPath': '/etc/service-account',
'name': 'service'
}, {
'readOnly': True,
'mountPath': '/etc/ssh-key-secret',
'name': 'ssh'
}],
'env': [{
'name': 'GOOGLE_APPLICATION_CREDENTIALS',
'value': '/etc/service-account/service-account.json'
}, {
'name': 'USER',
'value': 'prow'
}, {
'name': 'JENKINS_GCE_SSH_PRIVATE_KEY_FILE',
'value': '/etc/ssh-key-secret/ssh-private'
}, {
'name': 'JENKINS_GCE_SSH_PUBLIC_KEY_FILE',
'value': '/etc/ssh-key-secret/ssh-public'
}]
}],
'volumes': [{
'secret': {
'secretName': 'service-account'
},
'name': 'service'
}, {
'secret': {
'defaultMode': 256,
'secretName': 'ssh-key-secret'
},
'name': 'ssh'
}]
}
}
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
def main(job, jenkins_path, suffix, prow_path, config_path, delete):
"""Convert Jenkins config to prow config."""
with open(jenkins_path) as fp:
doc = yaml.safe_load(fp)
project = None
for item in doc:
if not isinstance(item, dict):
continue
if not isinstance(item.get('project'), dict):
continue
project = item['project']
break
else:
raise ValueError('Cannot find any project from %r', jenkins_path)
jenkins_jobs = project.get(suffix)
dump = []
job_names = []
for jenkins_job in jenkins_jobs:
name = jenkins_job.keys()[0]
real_job = jenkins_job[name]
if job in real_job['job-name']:
output = copy.deepcopy(TEMPLATE)
output['name'] = real_job['job-name']
args = output['spec']['containers'][0]['args']
if 'timeout' in real_job:
args.append('--timeout=%s' % real_job['timeout'])
if 'repo-name' not in real_job and 'branch' not in real_job:
args.append('--bare')
else:
if 'repo-name' in real_job:
repo_arg = '--repo=%s=%s' % real_job['repo_name']
if 'branch' in real_job:
repo_arg += '=' + real_job['branch']
args.append(repo_arg)
dump.append(output)
job_names.append(real_job['job-name'])
if prow_path:
with open(prow_path, 'a') as fp:
fp.write('\n')
yaml.safe_dump(dump, fp, default_flow_style=False)
else:
print yaml.safe_dump(dump, default_flow_style=False)
# delete jenkins config, try to keep format & comments
if delete:
deleting = False
for line in fileinput.input(jenkins_path, inplace=True):
if line.strip().startswith('-'):
deleting = job in line.strip()
if not deleting:
sys.stdout.write(line)
# remove mode=docker from config.json
if config_path:
with open(config_path, 'r+') as fp:
configs = json.loads(fp.read())
for jobn in job_names:
if jobn in configs:
if '--mode=docker' in configs[jobn]['args']:
configs[jobn]['args'].remove('--mode=docker')
fp.seek(0)
fp.write(json.dumps(configs, sort_keys=True, indent=2, separators=(',', ': ')))
fp.write('\n')
fp.truncate()
for old_name in job_names:
if '.' in old_name:
new_name = old_name.replace('.', '-')
files = ['jobs/config.json', 'testgrid/config/config.yaml', 'prow/config.yaml']
for fname in files:
with open(fname) as fp:
content = fp.read()
content = content.replace(old_name, new_name)
with open(fname, "w") as fp:
fp.write(content)
subprocess.check_call(['git', 'mv', 'jobs/%s.env' % old_name, 'jobs/%s.env' % new_name])
if __name__ == '__main__':
PARSER = argparse.ArgumentParser(
description='Convert Jenkins config into prow config')
PARSER.add_argument(
'--config',
help='Path to config.json',
default=None)
PARSER.add_argument(
'--delete',
action='store_true',
help='If delete Jenkins entry')
PARSER.add_argument(
'--job',
help='Job to convert, empty for all jobs in Jenkins config',
default='')
PARSER.add_argument(
'--jenkins',
help='Path to Jenkins config',
required=True)
PARSER.add_argument(
'--suffix',
help='Suffix of a jenkins job',
default='suffix')
PARSER.add_argument(
'--prow',
help='Path to output prow config, empty for stdout',
default=None)
ARGS = PARSER.parse_args()
main(ARGS.job, ARGS.jenkins, ARGS.suffix, ARGS.prow, ARGS.config, ARGS.delete)
| {'content_hash': '7880c0593c269af77e794e49a2006e8f', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 100, 'avg_line_length': 32.870588235294115, 'alnum_prop': 0.5046528274874732, 'repo_name': 'shashidharatd/test-infra', 'id': '97ca060130e8aeab6e6c796f50019f66b9a1d257', 'size': '6199', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'experiment/jenkins_to_prow.py', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9585'}, {'name': 'Go', 'bytes': '2224451'}, {'name': 'HTML', 'bytes': '49500'}, {'name': 'JavaScript', 'bytes': '86834'}, {'name': 'Makefile', 'bytes': '45132'}, {'name': 'Nginx', 'bytes': '1573'}, {'name': 'Protocol Buffer', 'bytes': '7639'}, {'name': 'Python', 'bytes': '819317'}, {'name': 'Roff', 'bytes': '17196'}, {'name': 'Shell', 'bytes': '104229'}, {'name': 'Smarty', 'bytes': '516'}]} |
import sys
import os
import numpy as np
sys.path.append('/home/joao/Work/OPEN')
from OPEN.classes import rvSeries
data_path = '/home/joao/Work/bicerin/data/'
def get_system(filename=None, number=None, ms=True):
if filename is not None:
assert os.path.exists(filename)
system = rvSeries(filename, skip=2)
if number is not None:
filename = os.path.join(data_path, 'PlSy%d.rdb' % number)
assert os.path.exists(filename)
system = rvSeries(filename, skip=2)
system.number = number
if ms:
mean_vrad = system.vrad.mean()
system.vrad = (system.vrad - mean_vrad)*1e3
system.error *= 1e3
return system
| {'content_hash': '5772cffaecc4d1303e29477c6db7baf1', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 59, 'avg_line_length': 23.037037037037038, 'alnum_prop': 0.7138263665594855, 'repo_name': 'j-faria/bicerin', 'id': '29bffa5293e54af49e7887d1a0297f7fdb4cbcc1', 'size': '622', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scripts/data_handler.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '34067'}, {'name': 'Makefile', 'bytes': '876'}, {'name': 'Python', 'bytes': '79629'}, {'name': 'Shell', 'bytes': '161'}, {'name': 'TeX', 'bytes': '1122512'}]} |
/**
*/
package com.example.example.importreferences;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* <div xmlns="http://www.w3.org/1999/xhtml">
* <h1>About the XML namespace</h1>
*
* <div class="bodytext">
* <p>
* This schema document describes the XML namespace, in a form
* suitable for import by other schema documents.
* </p>
* <p>
* See <a href="http://www.w3.org/XML/1998/namespace.html">
* http://www.w3.org/XML/1998/namespace.html</a> and
* <a href="http://www.w3.org/TR/REC-xml">
* http://www.w3.org/TR/REC-xml</a> for information
* about this namespace.
* </p>
* <p>
* Note that local names in this namespace are intended to be
* defined only by the World Wide Web Consortium or its subgroups.
* The names currently defined in this namespace are listed below.
* They should not be used with conflicting semantics by any Working
* Group, specification, or document instance.
* </p>
* <p>
* See further below in this document for more information about <a href="#usage">how to refer to this schema document from your own
* XSD schema documents</a> and about <a href="#nsversioning">the
* namespace-versioning policy governing this schema document</a>.
* </p>
* </div>
* </div>
*
*
* <div xmlns="http://www.w3.org/1999/xhtml">
*
* <h3>Father (in any context at all)</h3>
*
* <div class="bodytext">
* <p>
* denotes Jon Bosak, the chair of
* the original XML Working Group. This name is reserved by
* the following decision of the W3C XML Plenary and
* XML Coordination groups:
* </p>
* <blockquote>
* <p>
* In appreciation for his vision, leadership and
* dedication the W3C XML Plenary on this 10th day of
* February, 2000, reserves for Jon Bosak in perpetuity
* the XML name "xml:Father".
* </p>
* </blockquote>
* </div>
* </div>
*
*
* <div id="usage" xml:id="usage" xmlns="http://www.w3.org/1999/xhtml">
* <h2>
* <a name="usage">About this schema document</a>
* </h2>
*
* <div class="bodytext">
* <p>
* This schema defines attributes and an attribute group suitable
* for use by schemas wishing to allow <code>xml:base</code>,
* <code>xml:lang</code>, <code>xml:space</code> or
* <code>xml:id</code> attributes on elements they define.
* </p>
* <p>
* To enable this, such a schema must import this schema for
* the XML namespace, e.g. as follows:
* </p>
* <pre>
* <schema . . .>
* . . .
* <import namespace="http://www.w3.org/XML/1998/namespace"
* schemaLocation="http://www.w3.org/2001/xml.xsd"/>
* </pre>
* <p>
* or
* </p>
* <pre>
* <import namespace="http://www.w3.org/XML/1998/namespace"
* schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
* </pre>
* <p>
* Subsequently, qualified reference to any of the attributes or the
* group defined below will have the desired effect, e.g.
* </p>
* <pre>
* <type . . .>
* . . .
* <attributeGroup ref="xml:specialAttrs"/>
* </pre>
* <p>
* will define a type which will schema-validate an instance element
* with any of those attributes.
* </p>
* </div>
* </div>
*
*
* <div id="nsversioning" xml:id="nsversioning" xmlns="http://www.w3.org/1999/xhtml">
* <h2>
* <a name="nsversioning">Versioning policy for this schema document</a>
* </h2>
* <div class="bodytext">
* <p>
* In keeping with the XML Schema WG's standard versioning
* policy, this schema document will persist at
* <a href="http://www.w3.org/2009/01/xml.xsd">
* http://www.w3.org/2009/01/xml.xsd</a>.
* </p>
* <p>
* At the date of issue it can also be found at
* <a href="http://www.w3.org/2001/xml.xsd">
* http://www.w3.org/2001/xml.xsd</a>.
* </p>
* <p>
* The schema document at that URI may however change in the future,
* in order to remain compatible with the latest version of XML
* Schema itself, or with the XML namespace itself. In other words,
* if the XML Schema or XML namespaces change, the version of this
* document at <a href="http://www.w3.org/2001/xml.xsd">
* http://www.w3.org/2001/xml.xsd
* </a>
* will change accordingly; the version at
* <a href="http://www.w3.org/2009/01/xml.xsd">
* http://www.w3.org/2009/01/xml.xsd
* </a>
* will not change.
* </p>
* <p>
* Previous dated (and unchanging) versions of this schema
* document are at:
* </p>
* <ul>
* <li>
* <a href="http://www.w3.org/2009/01/xml.xsd">
* http://www.w3.org/2009/01/xml.xsd</a>
* </li>
* <li>
* <a href="http://www.w3.org/2007/08/xml.xsd">
* http://www.w3.org/2007/08/xml.xsd</a>
* </li>
* <li>
* <a href="http://www.w3.org/2004/10/xml.xsd">
* http://www.w3.org/2004/10/xml.xsd</a>
* </li>
* <li>
* <a href="http://www.w3.org/2001/03/xml.xsd">
* http://www.w3.org/2001/03/xml.xsd</a>
* </li>
* </ul>
* </div>
* </div>
*
* <!-- end-model-doc -->
* @see com.example.example.importreferences.ImportreferencesFactory
* @model kind="package"
* @generated
*/
public interface ImportreferencesPackage extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "importreferences";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://example.com/example-importreferences";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "importreferences";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
ImportreferencesPackage eINSTANCE = com.example.example.importreferences.impl.ImportreferencesPackageImpl.init();
/**
* The meta object id for the '{@link com.example.example.importreferences.impl.DocumentRootImpl <em>Document Root</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.DocumentRootImpl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getDocumentRoot()
* @generated
*/
int DOCUMENT_ROOT = 0;
/**
* The feature id for the '<em><b>Mixed</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__MIXED = 0;
/**
* The feature id for the '<em><b>XMLNS Prefix Map</b></em>' map.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__XMLNS_PREFIX_MAP = 1;
/**
* The feature id for the '<em><b>XSI Schema Location</b></em>' map.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__XSI_SCHEMA_LOCATION = 2;
/**
* The feature id for the '<em><b>Orders</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT__ORDERS = 3;
/**
* The number of structural features of the '<em>Document Root</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT_FEATURE_COUNT = 4;
/**
* The number of operations of the '<em>Document Root</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int DOCUMENT_ROOT_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link com.example.example.importreferences.impl.OrderDetail1Impl <em>Order Detail1</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderDetail1Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderDetail1()
* @generated
*/
int ORDER_DETAIL1 = 1;
/**
* The feature id for the '<em><b>Customer Address</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL1__CUSTOMER_ADDRESS = 0;
/**
* The feature id for the '<em><b>Customer Contact</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL1__CUSTOMER_CONTACT = 1;
/**
* The feature id for the '<em><b>Customer Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL1__CUSTOMER_NAME = 2;
/**
* The feature id for the '<em><b>Order ID</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL1__ORDER_ID = 3;
/**
* The number of structural features of the '<em>Order Detail1</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL1_FEATURE_COUNT = 4;
/**
* The number of operations of the '<em>Order Detail1</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL1_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link com.example.example.importreferences.impl.OrderDetail2Impl <em>Order Detail2</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderDetail2Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderDetail2()
* @generated
*/
int ORDER_DETAIL2 = 2;
/**
* The feature id for the '<em><b>Customer Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL2__CUSTOMER_NAME = 0;
/**
* The feature id for the '<em><b>Order ID</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL2__ORDER_ID = 1;
/**
* The number of structural features of the '<em>Order Detail2</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL2_FEATURE_COUNT = 2;
/**
* The number of operations of the '<em>Order Detail2</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_DETAIL2_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link com.example.example.importreferences.impl.OrderRef1Impl <em>Order Ref1</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderRef1Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderRef1()
* @generated
*/
int ORDER_REF1 = 3;
/**
* The feature id for the '<em><b>Order Detail1</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_REF1__ORDER_DETAIL1 = 0;
/**
* The number of structural features of the '<em>Order Ref1</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_REF1_FEATURE_COUNT = 1;
/**
* The number of operations of the '<em>Order Ref1</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_REF1_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link com.example.example.importreferences.impl.OrderRef2Impl <em>Order Ref2</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderRef2Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderRef2()
* @generated
*/
int ORDER_REF2 = 4;
/**
* The feature id for the '<em><b>Order Detail2</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_REF2__ORDER_DETAIL2 = 0;
/**
* The number of structural features of the '<em>Order Ref2</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_REF2_FEATURE_COUNT = 1;
/**
* The number of operations of the '<em>Order Ref2</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDER_REF2_OPERATION_COUNT = 0;
/**
* The meta object id for the '{@link com.example.example.importreferences.impl.OrdersTypeImpl <em>Orders Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrdersTypeImpl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrdersType()
* @generated
*/
int ORDERS_TYPE = 5;
/**
* The feature id for the '<em><b>Order1</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDERS_TYPE__ORDER1 = 0;
/**
* The feature id for the '<em><b>Order2</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDERS_TYPE__ORDER2 = 1;
/**
* The feature id for the '<em><b>Order Reference1</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDERS_TYPE__ORDER_REFERENCE1 = 2;
/**
* The feature id for the '<em><b>Order Reference2</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDERS_TYPE__ORDER_REFERENCE2 = 3;
/**
* The feature id for the '<em><b>Imported Namespace</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDERS_TYPE__IMPORTED_NAMESPACE = 4;
/**
* The number of structural features of the '<em>Orders Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDERS_TYPE_FEATURE_COUNT = 5;
/**
* The number of operations of the '<em>Orders Type</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ORDERS_TYPE_OPERATION_COUNT = 0;
/**
* Returns the meta object for class '{@link com.example.example.importreferences.DocumentRoot <em>Document Root</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Document Root</em>'.
* @see com.example.example.importreferences.DocumentRoot
* @generated
*/
EClass getDocumentRoot();
/**
* Returns the meta object for the attribute list '{@link com.example.example.importreferences.DocumentRoot#getMixed <em>Mixed</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>Mixed</em>'.
* @see com.example.example.importreferences.DocumentRoot#getMixed()
* @see #getDocumentRoot()
* @generated
*/
EAttribute getDocumentRoot_Mixed();
/**
* Returns the meta object for the map '{@link com.example.example.importreferences.DocumentRoot#getXMLNSPrefixMap <em>XMLNS Prefix Map</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the map '<em>XMLNS Prefix Map</em>'.
* @see com.example.example.importreferences.DocumentRoot#getXMLNSPrefixMap()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_XMLNSPrefixMap();
/**
* Returns the meta object for the map '{@link com.example.example.importreferences.DocumentRoot#getXSISchemaLocation <em>XSI Schema Location</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the map '<em>XSI Schema Location</em>'.
* @see com.example.example.importreferences.DocumentRoot#getXSISchemaLocation()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_XSISchemaLocation();
/**
* Returns the meta object for the containment reference '{@link com.example.example.importreferences.DocumentRoot#getOrders <em>Orders</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Orders</em>'.
* @see com.example.example.importreferences.DocumentRoot#getOrders()
* @see #getDocumentRoot()
* @generated
*/
EReference getDocumentRoot_Orders();
/**
* Returns the meta object for class '{@link com.example.example.importreferences.OrderDetail1 <em>Order Detail1</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Order Detail1</em>'.
* @see com.example.example.importreferences.OrderDetail1
* @generated
*/
EClass getOrderDetail1();
/**
* Returns the meta object for the attribute '{@link com.example.example.importreferences.OrderDetail1#getCustomerAddress <em>Customer Address</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Customer Address</em>'.
* @see com.example.example.importreferences.OrderDetail1#getCustomerAddress()
* @see #getOrderDetail1()
* @generated
*/
EAttribute getOrderDetail1_CustomerAddress();
/**
* Returns the meta object for the attribute '{@link com.example.example.importreferences.OrderDetail1#getCustomerContact <em>Customer Contact</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Customer Contact</em>'.
* @see com.example.example.importreferences.OrderDetail1#getCustomerContact()
* @see #getOrderDetail1()
* @generated
*/
EAttribute getOrderDetail1_CustomerContact();
/**
* Returns the meta object for the attribute '{@link com.example.example.importreferences.OrderDetail1#getCustomerName <em>Customer Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Customer Name</em>'.
* @see com.example.example.importreferences.OrderDetail1#getCustomerName()
* @see #getOrderDetail1()
* @generated
*/
EAttribute getOrderDetail1_CustomerName();
/**
* Returns the meta object for the attribute '{@link com.example.example.importreferences.OrderDetail1#getOrderID <em>Order ID</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Order ID</em>'.
* @see com.example.example.importreferences.OrderDetail1#getOrderID()
* @see #getOrderDetail1()
* @generated
*/
EAttribute getOrderDetail1_OrderID();
/**
* Returns the meta object for class '{@link com.example.example.importreferences.OrderDetail2 <em>Order Detail2</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Order Detail2</em>'.
* @see com.example.example.importreferences.OrderDetail2
* @generated
*/
EClass getOrderDetail2();
/**
* Returns the meta object for the attribute '{@link com.example.example.importreferences.OrderDetail2#getCustomerName <em>Customer Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Customer Name</em>'.
* @see com.example.example.importreferences.OrderDetail2#getCustomerName()
* @see #getOrderDetail2()
* @generated
*/
EAttribute getOrderDetail2_CustomerName();
/**
* Returns the meta object for the attribute '{@link com.example.example.importreferences.OrderDetail2#getOrderID <em>Order ID</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Order ID</em>'.
* @see com.example.example.importreferences.OrderDetail2#getOrderID()
* @see #getOrderDetail2()
* @generated
*/
EAttribute getOrderDetail2_OrderID();
/**
* Returns the meta object for class '{@link com.example.example.importreferences.OrderRef1 <em>Order Ref1</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Order Ref1</em>'.
* @see com.example.example.importreferences.OrderRef1
* @generated
*/
EClass getOrderRef1();
/**
* Returns the meta object for the reference '{@link com.example.example.importreferences.OrderRef1#getOrderDetail1 <em>Order Detail1</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Order Detail1</em>'.
* @see com.example.example.importreferences.OrderRef1#getOrderDetail1()
* @see #getOrderRef1()
* @generated
*/
EReference getOrderRef1_OrderDetail1();
/**
* Returns the meta object for class '{@link com.example.example.importreferences.OrderRef2 <em>Order Ref2</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Order Ref2</em>'.
* @see com.example.example.importreferences.OrderRef2
* @generated
*/
EClass getOrderRef2();
/**
* Returns the meta object for the reference '{@link com.example.example.importreferences.OrderRef2#getOrderDetail2 <em>Order Detail2</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Order Detail2</em>'.
* @see com.example.example.importreferences.OrderRef2#getOrderDetail2()
* @see #getOrderRef2()
* @generated
*/
EReference getOrderRef2_OrderDetail2();
/**
* Returns the meta object for class '{@link com.example.example.importreferences.OrdersType <em>Orders Type</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Orders Type</em>'.
* @see com.example.example.importreferences.OrdersType
* @generated
*/
EClass getOrdersType();
/**
* Returns the meta object for the containment reference list '{@link com.example.example.importreferences.OrdersType#getOrder1 <em>Order1</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Order1</em>'.
* @see com.example.example.importreferences.OrdersType#getOrder1()
* @see #getOrdersType()
* @generated
*/
EReference getOrdersType_Order1();
/**
* Returns the meta object for the containment reference list '{@link com.example.example.importreferences.OrdersType#getOrder2 <em>Order2</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Order2</em>'.
* @see com.example.example.importreferences.OrdersType#getOrder2()
* @see #getOrdersType()
* @generated
*/
EReference getOrdersType_Order2();
/**
* Returns the meta object for the containment reference list '{@link com.example.example.importreferences.OrdersType#getOrderReference1 <em>Order Reference1</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Order Reference1</em>'.
* @see com.example.example.importreferences.OrdersType#getOrderReference1()
* @see #getOrdersType()
* @generated
*/
EReference getOrdersType_OrderReference1();
/**
* Returns the meta object for the containment reference list '{@link com.example.example.importreferences.OrdersType#getOrderReference2 <em>Order Reference2</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Order Reference2</em>'.
* @see com.example.example.importreferences.OrdersType#getOrderReference2()
* @see #getOrdersType()
* @generated
*/
EReference getOrdersType_OrderReference2();
/**
* Returns the meta object for the attribute '{@link com.example.example.importreferences.OrdersType#getImportedNamespace <em>Imported Namespace</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Imported Namespace</em>'.
* @see com.example.example.importreferences.OrdersType#getImportedNamespace()
* @see #getOrdersType()
* @generated
*/
EAttribute getOrdersType_ImportedNamespace();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
ImportreferencesFactory getImportreferencesFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each operation of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link com.example.example.importreferences.impl.DocumentRootImpl <em>Document Root</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.DocumentRootImpl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getDocumentRoot()
* @generated
*/
EClass DOCUMENT_ROOT = eINSTANCE.getDocumentRoot();
/**
* The meta object literal for the '<em><b>Mixed</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute DOCUMENT_ROOT__MIXED = eINSTANCE.getDocumentRoot_Mixed();
/**
* The meta object literal for the '<em><b>XMLNS Prefix Map</b></em>' map feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__XMLNS_PREFIX_MAP = eINSTANCE.getDocumentRoot_XMLNSPrefixMap();
/**
* The meta object literal for the '<em><b>XSI Schema Location</b></em>' map feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__XSI_SCHEMA_LOCATION = eINSTANCE.getDocumentRoot_XSISchemaLocation();
/**
* The meta object literal for the '<em><b>Orders</b></em>' containment reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference DOCUMENT_ROOT__ORDERS = eINSTANCE.getDocumentRoot_Orders();
/**
* The meta object literal for the '{@link com.example.example.importreferences.impl.OrderDetail1Impl <em>Order Detail1</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderDetail1Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderDetail1()
* @generated
*/
EClass ORDER_DETAIL1 = eINSTANCE.getOrderDetail1();
/**
* The meta object literal for the '<em><b>Customer Address</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ORDER_DETAIL1__CUSTOMER_ADDRESS = eINSTANCE.getOrderDetail1_CustomerAddress();
/**
* The meta object literal for the '<em><b>Customer Contact</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ORDER_DETAIL1__CUSTOMER_CONTACT = eINSTANCE.getOrderDetail1_CustomerContact();
/**
* The meta object literal for the '<em><b>Customer Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ORDER_DETAIL1__CUSTOMER_NAME = eINSTANCE.getOrderDetail1_CustomerName();
/**
* The meta object literal for the '<em><b>Order ID</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ORDER_DETAIL1__ORDER_ID = eINSTANCE.getOrderDetail1_OrderID();
/**
* The meta object literal for the '{@link com.example.example.importreferences.impl.OrderDetail2Impl <em>Order Detail2</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderDetail2Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderDetail2()
* @generated
*/
EClass ORDER_DETAIL2 = eINSTANCE.getOrderDetail2();
/**
* The meta object literal for the '<em><b>Customer Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ORDER_DETAIL2__CUSTOMER_NAME = eINSTANCE.getOrderDetail2_CustomerName();
/**
* The meta object literal for the '<em><b>Order ID</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ORDER_DETAIL2__ORDER_ID = eINSTANCE.getOrderDetail2_OrderID();
/**
* The meta object literal for the '{@link com.example.example.importreferences.impl.OrderRef1Impl <em>Order Ref1</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderRef1Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderRef1()
* @generated
*/
EClass ORDER_REF1 = eINSTANCE.getOrderRef1();
/**
* The meta object literal for the '<em><b>Order Detail1</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ORDER_REF1__ORDER_DETAIL1 = eINSTANCE.getOrderRef1_OrderDetail1();
/**
* The meta object literal for the '{@link com.example.example.importreferences.impl.OrderRef2Impl <em>Order Ref2</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrderRef2Impl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrderRef2()
* @generated
*/
EClass ORDER_REF2 = eINSTANCE.getOrderRef2();
/**
* The meta object literal for the '<em><b>Order Detail2</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ORDER_REF2__ORDER_DETAIL2 = eINSTANCE.getOrderRef2_OrderDetail2();
/**
* The meta object literal for the '{@link com.example.example.importreferences.impl.OrdersTypeImpl <em>Orders Type</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see com.example.example.importreferences.impl.OrdersTypeImpl
* @see com.example.example.importreferences.impl.ImportreferencesPackageImpl#getOrdersType()
* @generated
*/
EClass ORDERS_TYPE = eINSTANCE.getOrdersType();
/**
* The meta object literal for the '<em><b>Order1</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ORDERS_TYPE__ORDER1 = eINSTANCE.getOrdersType_Order1();
/**
* The meta object literal for the '<em><b>Order2</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ORDERS_TYPE__ORDER2 = eINSTANCE.getOrdersType_Order2();
/**
* The meta object literal for the '<em><b>Order Reference1</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ORDERS_TYPE__ORDER_REFERENCE1 = eINSTANCE.getOrdersType_OrderReference1();
/**
* The meta object literal for the '<em><b>Order Reference2</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference ORDERS_TYPE__ORDER_REFERENCE2 = eINSTANCE.getOrdersType_OrderReference2();
/**
* The meta object literal for the '<em><b>Imported Namespace</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute ORDERS_TYPE__IMPORTED_NAMESPACE = eINSTANCE.getOrdersType_ImportedNamespace();
}
} //ImportreferencesPackage
| {'content_hash': '9a07eec6820858658f618df2edd5fff9', 'timestamp': '', 'source': 'github', 'line_count': 1007, 'max_line_length': 166, 'avg_line_length': 32.333664349553125, 'alnum_prop': 0.6315110565110565, 'repo_name': 'patrickneubauer/XMLIntellEdit', 'id': 'e630bbf48112f910c2904da7eef9087341ee5a9e', 'size': '32560', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'individual-experiments/SandboxProject/src/com/example/example/importreferences/ImportreferencesPackage.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '94'}, {'name': 'C', 'bytes': '20422'}, {'name': 'GAP', 'bytes': '2260869'}, {'name': 'HTML', 'bytes': '91232'}, {'name': 'Java', 'bytes': '35159898'}, {'name': 'Makefile', 'bytes': '848'}, {'name': 'Roff', 'bytes': '7706'}, {'name': 'Xtend', 'bytes': '53972'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="cache-control" content="no-cache">
<title>Member List</title>
<link href="doxygen_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="doxygen.css" rel="stylesheet" type="text/css">
<link href="doxygen_content.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="top">
<div id="titlearea">
<table height="72px" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="10%"> </td>
<td><a href="https://github.com/Genivia/RE-flex"><img src="reflex-logo.png"/></a></td>
<td>
<div style="float: right; font-size: 18px; font-weight: bold;">Member List</div>
<br>
<div style="float: right; font-size: 10px;">updated Sun Aug 21 2022 by Robert van Engelen</div>
</td>
<td width="10%"> </td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.8.11 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacereflex.html">reflex</a></li><li class="navelem"><a class="el" href="classreflex_1_1_input.html">Input</a></li><li class="navelem"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">dos_streambuf</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">reflex::Input::dos_streambuf Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#af2d56c17b2d5e7bdddcc0930fb807e82">ch1_</a></td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a6e33241a957bc21adb4f4762bdc0d434">ch2_</a></td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a07b6c9614e2af5435d96d3b32b3ce522">dos_streambuf</a>(const reflex::Input &input)</td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a523c875513a74cdf578f507e7a03cc6a">get</a>()</td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a0d85f9098d122fa86ae89323c6f5f2b8">input_</a></td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a6dc969b4e9e01673e0d10c28cb6264a5">showmanyc</a>()</td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a1ded263349d3a3a19f2086a47c42e72c">uflow</a>()</td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a21f5269c6d25ea9b6b8b1f21abb8d371">underflow</a>()</td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html#a8cf6a3d77553c295bab79dc13c4d325b">xsgetn</a>(char *s, std::streamsize n)</td><td class="entry"><a class="el" href="classreflex_1_1_input_1_1dos__streambuf.html">reflex::Input::dos_streambuf</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">protected</span><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
<hr class="footer">
<address class="footer"><small>
Converted on Sun Aug 21 2022 12:04:16 by <a target="_blank" href="http://www.doxygen.org/index.html">Doxygen</a> 1.8.11</small></address>
<br>
<div style="height: 246px; background: #DBDBDB;">
</body>
</html>
| {'content_hash': '47e2f10ef048213296221f58a77fdcfb', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 435, 'avg_line_length': 81.35526315789474, 'alnum_prop': 0.6804140384926411, 'repo_name': 'Genivia/RE-flex', 'id': 'ed807ea569fa027a61bf02a03cb2bd551cd38531', 'size': '6183', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/html/classreflex_1_1_input_1_1dos__streambuf-members.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '591'}, {'name': 'C', 'bytes': '6687'}, {'name': 'C++', 'bytes': '1294081'}, {'name': 'CMake', 'bytes': '5382'}, {'name': 'Lex', 'bytes': '14303'}, {'name': 'M4', 'bytes': '5759'}, {'name': 'Makefile', 'bytes': '158240'}, {'name': 'Shell', 'bytes': '65634'}, {'name': 'Vim Script', 'bytes': '8650'}]} |
/**
* views/notifyView.js
* Display winning dialogue
*
* @return {function} View constructor extended from Bacbone.View
* @author Ben on 22/Jul/2012
*/
define([
'jquery',
'backbone',
'bootstrap-modal',
'bootstrap-transition'
], function($) {
return Backbone.View.extend({
initialize: function() {
this.delegate = this.options.delegate;
this.$el.modal({show: false});
// find each element on the modal
this.$mark = this.$el.find('.mark');
this.$months = this.$el.find('.months');
this.$result = this.$el.find('.result');
this.$firstFive = this.$el.find('.first-five'); // first five digits
this.$lastThree = this.$el.find('.last-three'); // last three digits
this.$description = this.$el.find('.description');
// adjust position
var height = this.$el.height();
this.$el.css('margin-top', - height * 2 / 3);
this.bindEvents();
},
bindEvents: function() {
// bind enter key to continue
var self = this;
$(document).on('keyup', function(event) {
event.which == 13 && self.$el.modal('hide');
});
// focus on input after modal dismissed
this.$el.on('hide', function() {
self.delegate.notifyViewDidDismiss();
});
},
// Display winning message of a record
// @param {object} a given record (Backbone.Model)
displayResult: function(record) {
var result = record.toJSON();
if (result.isMatched) {
var moreThanThreeDigits = (result.matchedNumber.length > 3),
shouldMatchAll = (result.matchType === "matchAll");
this.delegate.notifyViewWillAppear();
this.$mark
.removeClass('check-mark question-mark')
.addClass(shouldMatchAll ? 'question-mark' : 'check-mark');
this.$months.text(result.months);
this.$result.text(result.prizeName);
this.$firstFive.text(moreThanThreeDigits ? result.matchedNumber.substr(0, 5) : "");
this.$lastThree.text(result.num);
this.$description.text(
shouldMatchAll ? "需要8位數字與上列號碼相同" :
moreThanThreeDigits ? "中獎了!請留意末三碼以外的相同數字" :
"中獎了!"
);
this.$el.modal('show');
}
}
});
});
| {'content_hash': '16a63560dd86447fc5746ae2f0e0612f', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 89, 'avg_line_length': 27.92207792207792, 'alnum_prop': 0.6195348837209302, 'repo_name': 'bcylin/receipt-number-checker', 'id': 'b8991c94cd0d382c1805748732dcdff87984553c', 'size': '2216', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/views/notifyView.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23820'}, {'name': 'HTML', 'bytes': '7672'}, {'name': 'JavaScript', 'bytes': '1103819'}, {'name': 'Ruby', 'bytes': '2374'}, {'name': 'Shell', 'bytes': '2010'}]} |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// 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.
#endregion
using System;
using Hotcakes.Payment;
namespace AuthorizeNet.Emulator
{
[Serializable]
public class AuthNetEmulatorSettings : MethodSettings
{
public string MerchantLoginId
{
get { return GetSettingOrEmpty("MerchantLoginId"); }
set { AddOrUpdate("MerchantLoginId", value); }
}
public string TransactionKey
{
get { return GetSettingOrEmpty("TransactionKey"); }
set { AddOrUpdate("TransactionKey", value); }
}
public bool SendEmailToCustomer
{
get { return GetBoolSetting("SendEmailToCustomer"); }
set { SetBoolSetting("SendEmailToCustomer", value); }
}
public bool DeveloperMode
{
get { return GetBoolSetting("DeveloperMode"); }
set { SetBoolSetting("DeveloperMode", value); }
}
public bool TestMode
{
get { return GetBoolSetting("TestMode"); }
set { SetBoolSetting("TestMode", value); }
}
public bool DebugMode
{
get { return GetBoolSetting("DebugMode"); }
set { SetBoolSetting("DebugMode", value); }
}
}
} | {'content_hash': '1c7cb83dde2bb49f5cc8547cca5a6d43', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 101, 'avg_line_length': 35.41428571428571, 'alnum_prop': 0.6446147640177491, 'repo_name': 'HotcakesCommerce/core', 'id': 'dfd4f770cb966c8e3624ae16058914cbdee1f715', 'size': '2481', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DevSamples/AuthorizeNetEmulator/DesktopModules/Hotcakes/Core/Admin/Parts/CreditCardGateways/Authorize.Net Emulator/AuthNetEmulatorSettings.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '2267142'}, {'name': 'Batchfile', 'bytes': '373'}, {'name': 'C#', 'bytes': '11194618'}, {'name': 'CSS', 'bytes': '1952419'}, {'name': 'HTML', 'bytes': '873593'}, {'name': 'JavaScript', 'bytes': '4896110'}, {'name': 'Smalltalk', 'bytes': '2410'}, {'name': 'Visual Basic', 'bytes': '16681'}, {'name': 'XSLT', 'bytes': '10409'}]} |
.class Lcom/google/common/collect/ImmutableSetMultimap$SortedKeyBuilderMultimap;
.super Lcom/google/common/collect/AbstractMultimap;
.source "ImmutableSetMultimap.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/google/common/collect/ImmutableSetMultimap;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0xa
name = "SortedKeyBuilderMultimap"
.end annotation
.annotation system Ldalvik/annotation/Signature;
value = {
"<K:",
"Ljava/lang/Object;",
"V:",
"Ljava/lang/Object;",
">",
"Lcom/google/common/collect/AbstractMultimap",
"<TK;TV;>;"
}
.end annotation
# static fields
.field private static final serialVersionUID:J
# direct methods
.method constructor <init>(Ljava/util/Comparator;Lcom/google/common/collect/Multimap;)V
.locals 1
.annotation system Ldalvik/annotation/Signature;
value = {
"(",
"Ljava/util/Comparator",
"<-TK;>;",
"Lcom/google/common/collect/Multimap",
"<TK;TV;>;)V"
}
.end annotation
.prologue
.line 166
.local p0, "this":Lcom/google/common/collect/ImmutableSetMultimap$SortedKeyBuilderMultimap;, "Lcom/google/common/collect/ImmutableSetMultimap$SortedKeyBuilderMultimap<TK;TV;>;"
.local p1, "keyComparator":Ljava/util/Comparator;, "Ljava/util/Comparator<-TK;>;"
.local p2, "multimap":Lcom/google/common/collect/Multimap;, "Lcom/google/common/collect/Multimap<TK;TV;>;"
new-instance v0, Ljava/util/TreeMap;
invoke-direct {v0, p1}, Ljava/util/TreeMap;-><init>(Ljava/util/Comparator;)V
invoke-direct {p0, v0}, Lcom/google/common/collect/AbstractMultimap;-><init>(Ljava/util/Map;)V
.line 167
invoke-virtual {p0, p2}, Lcom/google/common/collect/ImmutableSetMultimap$SortedKeyBuilderMultimap;->putAll(Lcom/google/common/collect/Multimap;)Z
.line 168
return-void
.end method
# virtual methods
.method createCollection()Ljava/util/Collection;
.locals 1
.annotation system Ldalvik/annotation/Signature;
value = {
"()",
"Ljava/util/Collection",
"<TV;>;"
}
.end annotation
.prologue
.line 170
.local p0, "this":Lcom/google/common/collect/ImmutableSetMultimap$SortedKeyBuilderMultimap;, "Lcom/google/common/collect/ImmutableSetMultimap$SortedKeyBuilderMultimap<TK;TV;>;"
invoke-static {}, Lcom/google/common/collect/Sets;->newLinkedHashSet()Ljava/util/LinkedHashSet;
move-result-object v0
return-object v0
.end method
| {'content_hash': 'fa51ad6c5c1d36946dfc6582b549ad91', 'timestamp': '', 'source': 'github', 'line_count': 84, 'max_line_length': 180, 'avg_line_length': 31.142857142857142, 'alnum_prop': 0.6884556574923547, 'repo_name': 'Zecozhang/click_project', 'id': 'f81fc01dbf3097f37adfc0b72764ce2c410fd939', 'size': '2616', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'APP/Music-master/smali/com/google/common/collect/ImmutableSetMultimap$SortedKeyBuilderMultimap.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '10265'}, {'name': 'HTML', 'bytes': '37165'}, {'name': 'Java', 'bytes': '1183235'}, {'name': 'JavaScript', 'bytes': '5866'}, {'name': 'Smali', 'bytes': '21017973'}]} |
[](https://circleci.com/gh/LatestStable/latest_stable/tree/master)
[](https://codeclimate.com/github/LatestStable/latest_stable)
LatestStable makes it dead simple to stay up to date with the upstream changes of your gem dependencies.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'latest_stable'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install latest_stable
## Usage
When you run latest_stable from the terminal in a git directory.
$ latest_stable
It will do the following things for you:
* checks out master and runs your test suite to ensure that tests
are passing initially
* checks out a new branch 'update_gems_to_latest_stable'
* gets the list of outdated gems and for each of those
* updates the gem
* reruns your test suite
* commits updated gem if tests pass or reverts update if they fail
Afterwards you'll have a branch with all gems that could cleanly be updated.
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. Run `bundle exec latest_stable` to use the gem in this directory, ignoring other installed copies of this gem.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/LatestStable/latest_stable. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
| {'content_hash': 'f315533203934c00ff09dbd5b6d8697f', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 324, 'avg_line_length': 42.075471698113205, 'alnum_prop': 0.7659192825112108, 'repo_name': 'LatestStable/latest_stable', 'id': '17342cb9a6be02b5bf571e9e38b16a27852449f2', 'size': '2246', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Cucumber', 'bytes': '1384'}, {'name': 'Ruby', 'bytes': '11029'}, {'name': 'Shell', 'bytes': '115'}]} |
#pragma once
#include <aws/s3control/S3Control_EXPORTS.h>
#include <aws/s3control/model/EstablishedMultiRegionAccessPointPolicy.h>
#include <aws/s3control/model/ProposedMultiRegionAccessPointPolicy.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace S3Control
{
namespace Model
{
/**
* <p>The Multi-Region Access Point access control policy.</p> <p>When you update
* the policy, the update is first listed as the proposed policy. After the update
* is finished and all Regions have been updated, the proposed policy is listed as
* the established policy. If both policies have the same version number, the
* proposed policy is the established policy.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/s3control-2018-08-20/MultiRegionAccessPointPolicyDocument">AWS
* API Reference</a></p>
*/
class AWS_S3CONTROL_API MultiRegionAccessPointPolicyDocument
{
public:
MultiRegionAccessPointPolicyDocument();
MultiRegionAccessPointPolicyDocument(const Aws::Utils::Xml::XmlNode& xmlNode);
MultiRegionAccessPointPolicyDocument& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;
/**
* <p>The last established policy for the Multi-Region Access Point.</p>
*/
inline const EstablishedMultiRegionAccessPointPolicy& GetEstablished() const{ return m_established; }
/**
* <p>The last established policy for the Multi-Region Access Point.</p>
*/
inline bool EstablishedHasBeenSet() const { return m_establishedHasBeenSet; }
/**
* <p>The last established policy for the Multi-Region Access Point.</p>
*/
inline void SetEstablished(const EstablishedMultiRegionAccessPointPolicy& value) { m_establishedHasBeenSet = true; m_established = value; }
/**
* <p>The last established policy for the Multi-Region Access Point.</p>
*/
inline void SetEstablished(EstablishedMultiRegionAccessPointPolicy&& value) { m_establishedHasBeenSet = true; m_established = std::move(value); }
/**
* <p>The last established policy for the Multi-Region Access Point.</p>
*/
inline MultiRegionAccessPointPolicyDocument& WithEstablished(const EstablishedMultiRegionAccessPointPolicy& value) { SetEstablished(value); return *this;}
/**
* <p>The last established policy for the Multi-Region Access Point.</p>
*/
inline MultiRegionAccessPointPolicyDocument& WithEstablished(EstablishedMultiRegionAccessPointPolicy&& value) { SetEstablished(std::move(value)); return *this;}
/**
* <p>The proposed policy for the Multi-Region Access Point.</p>
*/
inline const ProposedMultiRegionAccessPointPolicy& GetProposed() const{ return m_proposed; }
/**
* <p>The proposed policy for the Multi-Region Access Point.</p>
*/
inline bool ProposedHasBeenSet() const { return m_proposedHasBeenSet; }
/**
* <p>The proposed policy for the Multi-Region Access Point.</p>
*/
inline void SetProposed(const ProposedMultiRegionAccessPointPolicy& value) { m_proposedHasBeenSet = true; m_proposed = value; }
/**
* <p>The proposed policy for the Multi-Region Access Point.</p>
*/
inline void SetProposed(ProposedMultiRegionAccessPointPolicy&& value) { m_proposedHasBeenSet = true; m_proposed = std::move(value); }
/**
* <p>The proposed policy for the Multi-Region Access Point.</p>
*/
inline MultiRegionAccessPointPolicyDocument& WithProposed(const ProposedMultiRegionAccessPointPolicy& value) { SetProposed(value); return *this;}
/**
* <p>The proposed policy for the Multi-Region Access Point.</p>
*/
inline MultiRegionAccessPointPolicyDocument& WithProposed(ProposedMultiRegionAccessPointPolicy&& value) { SetProposed(std::move(value)); return *this;}
private:
EstablishedMultiRegionAccessPointPolicy m_established;
bool m_establishedHasBeenSet = false;
ProposedMultiRegionAccessPointPolicy m_proposed;
bool m_proposedHasBeenSet = false;
};
} // namespace Model
} // namespace S3Control
} // namespace Aws
| {'content_hash': 'bff2e0e33f94e2b7e03a2a84dd4ae7f9', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 164, 'avg_line_length': 36.96491228070175, 'alnum_prop': 0.7237778832463218, 'repo_name': 'aws/aws-sdk-cpp', 'id': '704f4c0df936d7b618ac8bf90a3519f4e8144032', 'size': '4333', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'aws-cpp-sdk-s3control/include/aws/s3control/model/MultiRegionAccessPointPolicyDocument.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '309797'}, {'name': 'C++', 'bytes': '476866144'}, {'name': 'CMake', 'bytes': '1245180'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '8056'}, {'name': 'Java', 'bytes': '413602'}, {'name': 'Python', 'bytes': '79245'}, {'name': 'Shell', 'bytes': '9246'}]} |
<?php
require 'PHPMailerAutoload.php';
/**
* Class die voor mail functionaliteit zorgt.
*
* @package CheckJeStress
*/
class Mailer {
/**
* Constructs the object
*
* @param array $config het deel van het configuratiebestand dat met de SMTP
* server te maken heeft
*/
function __construct($config) {
$this->config = $config;
$this->mail = new PHPMailer;
$this->mail->SMTPDebug = 0; // Enable verbose debug output
}
/**
* De PHPMailer instance van deze class
*/
var $mail;
/**
* De array met gegevens betreffende de SMTP server
*/
private $config;
/**
* Stuurt een mail.
*
* @param array $recipients de e-mailadresse van de personen naar wie de mail
* gestuurd moet worden
* @param string $subject het onderwerp van de e-mail
* @param string $message het bericht zelf
*/
function sendMail($recipients, $subject, $html_message, $non_html_message) {
$this->configure();
foreach ($recipients as $recipient) {
$this->mail->addAddress($recipient);
$this->mail->addReplyTo($recipient);
}
//$mail->addCC('[email protected]');
//$mail->addBCC('[email protected]');
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$this->mail->isHTML(true);
$this->mail->Subject = $subject;
$this->mail->Body = $html_message; /* Body containing HTML */
$this->mail->AltBody = $non_html_message;
if(!$this->mail->send()) {
throw new MailException('Message could not be sent. Mailer Error: ' . $this->mail->ErrorInfo);
}
}
/**
* Haalt waarden uit de configuratie voor gebruik bij het verbinden met de
* mailserver.
*/
private function configure() {
$this->mail->isSMTP();
$this->mail->Host = $config['host'];
$this->mail->Port = $config['port'];
/* Enable TLS encryption, `ssl` also accepted */
$this->mail->SMTPSecure = $config['secure'];
$this->mail->SMTPAuth = $config['auth'];
$this->mail->Username = $config['username'];
$this->mail->Password = $config['password'];
$this->mail->setFrom($config['admin-email'], 'CheckJeStress');
}
}
/**
* Thrown if een mail niet verstuurd kon worden.
*
* @package CheckJeStress
*/
class MailException extends Exception {
}
| {'content_hash': '59fc1af2df742a3e583fc3bea5edf2f5', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 100, 'avg_line_length': 26.382022471910112, 'alnum_prop': 0.6260647359454855, 'repo_name': 'MateyByrd/CheckJeStress', 'id': '6d3fe70c93ba9310c83ed5f6b18c9fb2270d42df', 'size': '2348', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/resources/includes/PHPMailer/mail.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '1221'}, {'name': 'CSS', 'bytes': '74088'}, {'name': 'HTML', 'bytes': '13931'}, {'name': 'JavaScript', 'bytes': '25'}, {'name': 'PHP', 'bytes': '125449'}, {'name': 'Shell', 'bytes': '4733'}]} |
#include <asm/cacheflush.h>
#include <linux/clk.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-ioctl.h>
#include "iss_video.h"
#include "iss.h"
/* -----------------------------------------------------------------------------
* Helper functions
*/
static struct iss_format_info formats[] = {
{ MEDIA_BUS_FMT_Y8_1X8, MEDIA_BUS_FMT_Y8_1X8,
MEDIA_BUS_FMT_Y8_1X8, MEDIA_BUS_FMT_Y8_1X8,
V4L2_PIX_FMT_GREY, 8, "Greyscale 8 bpp", },
{ MEDIA_BUS_FMT_Y10_1X10, MEDIA_BUS_FMT_Y10_1X10,
MEDIA_BUS_FMT_Y10_1X10, MEDIA_BUS_FMT_Y8_1X8,
V4L2_PIX_FMT_Y10, 10, "Greyscale 10 bpp", },
{ MEDIA_BUS_FMT_Y12_1X12, MEDIA_BUS_FMT_Y10_1X10,
MEDIA_BUS_FMT_Y12_1X12, MEDIA_BUS_FMT_Y8_1X8,
V4L2_PIX_FMT_Y12, 12, "Greyscale 12 bpp", },
{ MEDIA_BUS_FMT_SBGGR8_1X8, MEDIA_BUS_FMT_SBGGR8_1X8,
MEDIA_BUS_FMT_SBGGR8_1X8, MEDIA_BUS_FMT_SBGGR8_1X8,
V4L2_PIX_FMT_SBGGR8, 8, "BGGR Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SGBRG8_1X8, MEDIA_BUS_FMT_SGBRG8_1X8,
MEDIA_BUS_FMT_SGBRG8_1X8, MEDIA_BUS_FMT_SGBRG8_1X8,
V4L2_PIX_FMT_SGBRG8, 8, "GBRG Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SGRBG8_1X8, MEDIA_BUS_FMT_SGRBG8_1X8,
MEDIA_BUS_FMT_SGRBG8_1X8, MEDIA_BUS_FMT_SGRBG8_1X8,
V4L2_PIX_FMT_SGRBG8, 8, "GRBG Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SRGGB8_1X8, MEDIA_BUS_FMT_SRGGB8_1X8,
MEDIA_BUS_FMT_SRGGB8_1X8, MEDIA_BUS_FMT_SRGGB8_1X8,
V4L2_PIX_FMT_SRGGB8, 8, "RGGB Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8, MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8,
MEDIA_BUS_FMT_SGRBG10_1X10, 0,
V4L2_PIX_FMT_SGRBG10DPCM8, 8, "GRBG Bayer 10 bpp DPCM8", },
{ MEDIA_BUS_FMT_SBGGR10_1X10, MEDIA_BUS_FMT_SBGGR10_1X10,
MEDIA_BUS_FMT_SBGGR10_1X10, MEDIA_BUS_FMT_SBGGR8_1X8,
V4L2_PIX_FMT_SBGGR10, 10, "BGGR Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SGBRG10_1X10, MEDIA_BUS_FMT_SGBRG10_1X10,
MEDIA_BUS_FMT_SGBRG10_1X10, MEDIA_BUS_FMT_SGBRG8_1X8,
V4L2_PIX_FMT_SGBRG10, 10, "GBRG Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SGRBG10_1X10, MEDIA_BUS_FMT_SGRBG10_1X10,
MEDIA_BUS_FMT_SGRBG10_1X10, MEDIA_BUS_FMT_SGRBG8_1X8,
V4L2_PIX_FMT_SGRBG10, 10, "GRBG Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SRGGB10_1X10, MEDIA_BUS_FMT_SRGGB10_1X10,
MEDIA_BUS_FMT_SRGGB10_1X10, MEDIA_BUS_FMT_SRGGB8_1X8,
V4L2_PIX_FMT_SRGGB10, 10, "RGGB Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SBGGR12_1X12, MEDIA_BUS_FMT_SBGGR10_1X10,
MEDIA_BUS_FMT_SBGGR12_1X12, MEDIA_BUS_FMT_SBGGR8_1X8,
V4L2_PIX_FMT_SBGGR12, 12, "BGGR Bayer 12 bpp", },
{ MEDIA_BUS_FMT_SGBRG12_1X12, MEDIA_BUS_FMT_SGBRG10_1X10,
MEDIA_BUS_FMT_SGBRG12_1X12, MEDIA_BUS_FMT_SGBRG8_1X8,
V4L2_PIX_FMT_SGBRG12, 12, "GBRG Bayer 12 bpp", },
{ MEDIA_BUS_FMT_SGRBG12_1X12, MEDIA_BUS_FMT_SGRBG10_1X10,
MEDIA_BUS_FMT_SGRBG12_1X12, MEDIA_BUS_FMT_SGRBG8_1X8,
V4L2_PIX_FMT_SGRBG12, 12, "GRBG Bayer 12 bpp", },
{ MEDIA_BUS_FMT_SRGGB12_1X12, MEDIA_BUS_FMT_SRGGB10_1X10,
MEDIA_BUS_FMT_SRGGB12_1X12, MEDIA_BUS_FMT_SRGGB8_1X8,
V4L2_PIX_FMT_SRGGB12, 12, "RGGB Bayer 12 bpp", },
{ MEDIA_BUS_FMT_UYVY8_1X16, MEDIA_BUS_FMT_UYVY8_1X16,
MEDIA_BUS_FMT_UYVY8_1X16, 0,
V4L2_PIX_FMT_UYVY, 16, "YUV 4:2:2 (UYVY)", },
{ MEDIA_BUS_FMT_YUYV8_1X16, MEDIA_BUS_FMT_YUYV8_1X16,
MEDIA_BUS_FMT_YUYV8_1X16, 0,
V4L2_PIX_FMT_YUYV, 16, "YUV 4:2:2 (YUYV)", },
{ MEDIA_BUS_FMT_YUYV8_1_5X8, MEDIA_BUS_FMT_YUYV8_1_5X8,
MEDIA_BUS_FMT_YUYV8_1_5X8, 0,
V4L2_PIX_FMT_NV12, 8, "YUV 4:2:0 (NV12)", },
};
const struct iss_format_info *
omap4iss_video_format_info(u32 code)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(formats); ++i) {
if (formats[i].code == code)
return &formats[i];
}
return NULL;
}
/*
* iss_video_mbus_to_pix - Convert v4l2_mbus_framefmt to v4l2_pix_format
* @video: ISS video instance
* @mbus: v4l2_mbus_framefmt format (input)
* @pix: v4l2_pix_format format (output)
*
* Fill the output pix structure with information from the input mbus format.
* The bytesperline and sizeimage fields are computed from the requested bytes
* per line value in the pix format and information from the video instance.
*
* Return the number of padding bytes at end of line.
*/
static unsigned int iss_video_mbus_to_pix(const struct iss_video *video,
const struct v4l2_mbus_framefmt *mbus,
struct v4l2_pix_format *pix)
{
unsigned int bpl = pix->bytesperline;
unsigned int min_bpl;
unsigned int i;
memset(pix, 0, sizeof(*pix));
pix->width = mbus->width;
pix->height = mbus->height;
/* Skip the last format in the loop so that it will be selected if no
* match is found.
*/
for (i = 0; i < ARRAY_SIZE(formats) - 1; ++i) {
if (formats[i].code == mbus->code)
break;
}
min_bpl = pix->width * ALIGN(formats[i].bpp, 8) / 8;
/* Clamp the requested bytes per line value. If the maximum bytes per
* line value is zero, the module doesn't support user configurable line
* sizes. Override the requested value with the minimum in that case.
*/
if (video->bpl_max)
bpl = clamp(bpl, min_bpl, video->bpl_max);
else
bpl = min_bpl;
if (!video->bpl_zero_padding || bpl != min_bpl)
bpl = ALIGN(bpl, video->bpl_alignment);
pix->pixelformat = formats[i].pixelformat;
pix->bytesperline = bpl;
pix->sizeimage = pix->bytesperline * pix->height;
pix->colorspace = mbus->colorspace;
pix->field = mbus->field;
/* FIXME: Special case for NV12! We should make this nicer... */
if (pix->pixelformat == V4L2_PIX_FMT_NV12)
pix->sizeimage += (pix->bytesperline * pix->height) / 2;
return bpl - min_bpl;
}
static void iss_video_pix_to_mbus(const struct v4l2_pix_format *pix,
struct v4l2_mbus_framefmt *mbus)
{
unsigned int i;
memset(mbus, 0, sizeof(*mbus));
mbus->width = pix->width;
mbus->height = pix->height;
/* Skip the last format in the loop so that it will be selected if no
* match is found.
*/
for (i = 0; i < ARRAY_SIZE(formats) - 1; ++i) {
if (formats[i].pixelformat == pix->pixelformat)
break;
}
mbus->code = formats[i].code;
mbus->colorspace = pix->colorspace;
mbus->field = pix->field;
}
static struct v4l2_subdev *
iss_video_remote_subdev(struct iss_video *video, u32 *pad)
{
struct media_pad *remote;
remote = media_entity_remote_pad(&video->pad);
if (!remote || !is_media_entity_v4l2_subdev(remote->entity))
return NULL;
if (pad)
*pad = remote->index;
return media_entity_to_v4l2_subdev(remote->entity);
}
/* Return a pointer to the ISS video instance at the far end of the pipeline. */
static struct iss_video *
iss_video_far_end(struct iss_video *video)
{
struct media_entity_graph graph;
struct media_entity *entity = &video->video.entity;
struct media_device *mdev = entity->graph_obj.mdev;
struct iss_video *far_end = NULL;
mutex_lock(&mdev->graph_mutex);
if (media_entity_graph_walk_init(&graph, mdev)) {
mutex_unlock(&mdev->graph_mutex);
return NULL;
}
media_entity_graph_walk_start(&graph, entity);
while ((entity = media_entity_graph_walk_next(&graph))) {
if (entity == &video->video.entity)
continue;
if (!is_media_entity_v4l2_io(entity))
continue;
far_end = to_iss_video(media_entity_to_video_device(entity));
if (far_end->type != video->type)
break;
far_end = NULL;
}
mutex_unlock(&mdev->graph_mutex);
media_entity_graph_walk_cleanup(&graph);
return far_end;
}
static int
__iss_video_get_format(struct iss_video *video,
struct v4l2_mbus_framefmt *format)
{
struct v4l2_subdev_format fmt;
struct v4l2_subdev *subdev;
u32 pad;
int ret;
subdev = iss_video_remote_subdev(video, &pad);
if (!subdev)
return -EINVAL;
memset(&fmt, 0, sizeof(fmt));
fmt.pad = pad;
fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
mutex_lock(&video->mutex);
ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt);
mutex_unlock(&video->mutex);
if (ret)
return ret;
*format = fmt.format;
return 0;
}
static int
iss_video_check_format(struct iss_video *video, struct iss_video_fh *vfh)
{
struct v4l2_mbus_framefmt format;
struct v4l2_pix_format pixfmt;
int ret;
ret = __iss_video_get_format(video, &format);
if (ret < 0)
return ret;
pixfmt.bytesperline = 0;
ret = iss_video_mbus_to_pix(video, &format, &pixfmt);
if (vfh->format.fmt.pix.pixelformat != pixfmt.pixelformat ||
vfh->format.fmt.pix.height != pixfmt.height ||
vfh->format.fmt.pix.width != pixfmt.width ||
vfh->format.fmt.pix.bytesperline != pixfmt.bytesperline ||
vfh->format.fmt.pix.sizeimage != pixfmt.sizeimage)
return -EINVAL;
return ret;
}
/* -----------------------------------------------------------------------------
* Video queue operations
*/
static int iss_video_queue_setup(struct vb2_queue *vq,
unsigned int *count, unsigned int *num_planes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct iss_video_fh *vfh = vb2_get_drv_priv(vq);
struct iss_video *video = vfh->video;
/* Revisit multi-planar support for NV12 */
*num_planes = 1;
sizes[0] = vfh->format.fmt.pix.sizeimage;
if (sizes[0] == 0)
return -EINVAL;
alloc_ctxs[0] = video->alloc_ctx;
*count = min(*count, video->capture_mem / PAGE_ALIGN(sizes[0]));
return 0;
}
static void iss_video_buf_cleanup(struct vb2_buffer *vb)
{
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct iss_buffer *buffer = container_of(vbuf, struct iss_buffer, vb);
if (buffer->iss_addr)
buffer->iss_addr = 0;
}
static int iss_video_buf_prepare(struct vb2_buffer *vb)
{
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct iss_video_fh *vfh = vb2_get_drv_priv(vb->vb2_queue);
struct iss_buffer *buffer = container_of(vbuf, struct iss_buffer, vb);
struct iss_video *video = vfh->video;
unsigned long size = vfh->format.fmt.pix.sizeimage;
dma_addr_t addr;
if (vb2_plane_size(vb, 0) < size)
return -ENOBUFS;
addr = vb2_dma_contig_plane_dma_addr(vb, 0);
if (!IS_ALIGNED(addr, 32)) {
dev_dbg(video->iss->dev,
"Buffer address must be aligned to 32 bytes boundary.\n");
return -EINVAL;
}
vb2_set_plane_payload(vb, 0, size);
buffer->iss_addr = addr;
return 0;
}
static void iss_video_buf_queue(struct vb2_buffer *vb)
{
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct iss_video_fh *vfh = vb2_get_drv_priv(vb->vb2_queue);
struct iss_video *video = vfh->video;
struct iss_buffer *buffer = container_of(vbuf, struct iss_buffer, vb);
struct iss_pipeline *pipe = to_iss_pipeline(&video->video.entity);
unsigned long flags;
bool empty;
spin_lock_irqsave(&video->qlock, flags);
/* Mark the buffer is faulty and give it back to the queue immediately
* if the video node has registered an error. vb2 will perform the same
* check when preparing the buffer, but that is inherently racy, so we
* need to handle the race condition with an authoritative check here.
*/
if (unlikely(video->error)) {
vb2_buffer_done(vb, VB2_BUF_STATE_ERROR);
spin_unlock_irqrestore(&video->qlock, flags);
return;
}
empty = list_empty(&video->dmaqueue);
list_add_tail(&buffer->list, &video->dmaqueue);
spin_unlock_irqrestore(&video->qlock, flags);
if (empty) {
enum iss_pipeline_state state;
unsigned int start;
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
state = ISS_PIPELINE_QUEUE_OUTPUT;
else
state = ISS_PIPELINE_QUEUE_INPUT;
spin_lock_irqsave(&pipe->lock, flags);
pipe->state |= state;
video->ops->queue(video, buffer);
video->dmaqueue_flags |= ISS_VIDEO_DMAQUEUE_QUEUED;
start = iss_pipeline_ready(pipe);
if (start)
pipe->state |= ISS_PIPELINE_STREAM;
spin_unlock_irqrestore(&pipe->lock, flags);
if (start)
omap4iss_pipeline_set_stream(pipe,
ISS_PIPELINE_STREAM_SINGLESHOT);
}
}
static const struct vb2_ops iss_video_vb2ops = {
.queue_setup = iss_video_queue_setup,
.buf_prepare = iss_video_buf_prepare,
.buf_queue = iss_video_buf_queue,
.buf_cleanup = iss_video_buf_cleanup,
};
/*
* omap4iss_video_buffer_next - Complete the current buffer and return the next
* @video: ISS video object
*
* Remove the current video buffer from the DMA queue and fill its timestamp,
* field count and state fields before waking up its completion handler.
*
* For capture video nodes, the buffer state is set to VB2_BUF_STATE_DONE if no
* error has been flagged in the pipeline, or to VB2_BUF_STATE_ERROR otherwise.
*
* The DMA queue is expected to contain at least one buffer.
*
* Return a pointer to the next buffer in the DMA queue, or NULL if the queue is
* empty.
*/
struct iss_buffer *omap4iss_video_buffer_next(struct iss_video *video)
{
struct iss_pipeline *pipe = to_iss_pipeline(&video->video.entity);
enum iss_pipeline_state state;
struct iss_buffer *buf;
unsigned long flags;
spin_lock_irqsave(&video->qlock, flags);
if (WARN_ON(list_empty(&video->dmaqueue))) {
spin_unlock_irqrestore(&video->qlock, flags);
return NULL;
}
buf = list_first_entry(&video->dmaqueue, struct iss_buffer,
list);
list_del(&buf->list);
spin_unlock_irqrestore(&video->qlock, flags);
buf->vb.vb2_buf.timestamp = ktime_get_ns();
/* Do frame number propagation only if this is the output video node.
* Frame number either comes from the CSI receivers or it gets
* incremented here if H3A is not active.
* Note: There is no guarantee that the output buffer will finish
* first, so the input number might lag behind by 1 in some cases.
*/
if (video == pipe->output && !pipe->do_propagation)
buf->vb.sequence =
atomic_inc_return(&pipe->frame_number);
else
buf->vb.sequence = atomic_read(&pipe->frame_number);
vb2_buffer_done(&buf->vb.vb2_buf, pipe->error ?
VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
pipe->error = false;
spin_lock_irqsave(&video->qlock, flags);
if (list_empty(&video->dmaqueue)) {
spin_unlock_irqrestore(&video->qlock, flags);
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
state = ISS_PIPELINE_QUEUE_OUTPUT
| ISS_PIPELINE_STREAM;
else
state = ISS_PIPELINE_QUEUE_INPUT
| ISS_PIPELINE_STREAM;
spin_lock_irqsave(&pipe->lock, flags);
pipe->state &= ~state;
if (video->pipe.stream_state == ISS_PIPELINE_STREAM_CONTINUOUS)
video->dmaqueue_flags |= ISS_VIDEO_DMAQUEUE_UNDERRUN;
spin_unlock_irqrestore(&pipe->lock, flags);
return NULL;
}
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && pipe->input) {
spin_lock(&pipe->lock);
pipe->state &= ~ISS_PIPELINE_STREAM;
spin_unlock(&pipe->lock);
}
buf = list_first_entry(&video->dmaqueue, struct iss_buffer,
list);
spin_unlock_irqrestore(&video->qlock, flags);
buf->vb.vb2_buf.state = VB2_BUF_STATE_ACTIVE;
return buf;
}
/*
* omap4iss_video_cancel_stream - Cancel stream on a video node
* @video: ISS video object
*
* Cancelling a stream mark all buffers on the video node as erroneous and makes
* sure no new buffer can be queued.
*/
void omap4iss_video_cancel_stream(struct iss_video *video)
{
unsigned long flags;
spin_lock_irqsave(&video->qlock, flags);
while (!list_empty(&video->dmaqueue)) {
struct iss_buffer *buf;
buf = list_first_entry(&video->dmaqueue, struct iss_buffer,
list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
}
vb2_queue_error(video->queue);
video->error = true;
spin_unlock_irqrestore(&video->qlock, flags);
}
/* -----------------------------------------------------------------------------
* V4L2 ioctls
*/
static int
iss_video_querycap(struct file *file, void *fh, struct v4l2_capability *cap)
{
struct iss_video *video = video_drvdata(file);
strlcpy(cap->driver, ISS_VIDEO_DRIVER_NAME, sizeof(cap->driver));
strlcpy(cap->card, video->video.name, sizeof(cap->card));
strlcpy(cap->bus_info, "media", sizeof(cap->bus_info));
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
else
cap->device_caps = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
cap->capabilities = V4L2_CAP_DEVICE_CAPS | V4L2_CAP_STREAMING
| V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT;
return 0;
}
static int
iss_video_enum_format(struct file *file, void *fh, struct v4l2_fmtdesc *f)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_mbus_framefmt format;
unsigned int index = f->index;
unsigned int i;
int ret;
if (f->type != video->type)
return -EINVAL;
ret = __iss_video_get_format(video, &format);
if (ret < 0)
return ret;
for (i = 0; i < ARRAY_SIZE(formats); ++i) {
const struct iss_format_info *info = &formats[i];
if (format.code != info->code)
continue;
if (index == 0) {
f->pixelformat = info->pixelformat;
strlcpy(f->description, info->description,
sizeof(f->description));
return 0;
}
index--;
}
return -EINVAL;
}
static int
iss_video_get_format(struct file *file, void *fh, struct v4l2_format *format)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
if (format->type != video->type)
return -EINVAL;
mutex_lock(&video->mutex);
*format = vfh->format;
mutex_unlock(&video->mutex);
return 0;
}
static int
iss_video_set_format(struct file *file, void *fh, struct v4l2_format *format)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
struct v4l2_mbus_framefmt fmt;
if (format->type != video->type)
return -EINVAL;
mutex_lock(&video->mutex);
/* Fill the bytesperline and sizeimage fields by converting to media bus
* format and back to pixel format.
*/
iss_video_pix_to_mbus(&format->fmt.pix, &fmt);
iss_video_mbus_to_pix(video, &fmt, &format->fmt.pix);
vfh->format = *format;
mutex_unlock(&video->mutex);
return 0;
}
static int
iss_video_try_format(struct file *file, void *fh, struct v4l2_format *format)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_subdev_format fmt;
struct v4l2_subdev *subdev;
u32 pad;
int ret;
if (format->type != video->type)
return -EINVAL;
subdev = iss_video_remote_subdev(video, &pad);
if (!subdev)
return -EINVAL;
iss_video_pix_to_mbus(&format->fmt.pix, &fmt.format);
fmt.pad = pad;
fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt);
if (ret)
return ret;
iss_video_mbus_to_pix(video, &fmt.format, &format->fmt.pix);
return 0;
}
static int
iss_video_get_param(struct file *file, void *fh, struct v4l2_streamparm *a)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
if (video->type != V4L2_BUF_TYPE_VIDEO_OUTPUT ||
video->type != a->type)
return -EINVAL;
memset(a, 0, sizeof(*a));
a->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
a->parm.output.timeperframe = vfh->timeperframe;
return 0;
}
static int
iss_video_set_param(struct file *file, void *fh, struct v4l2_streamparm *a)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
if (video->type != V4L2_BUF_TYPE_VIDEO_OUTPUT ||
video->type != a->type)
return -EINVAL;
if (a->parm.output.timeperframe.denominator == 0)
a->parm.output.timeperframe.denominator = 1;
vfh->timeperframe = a->parm.output.timeperframe;
return 0;
}
static int
iss_video_reqbufs(struct file *file, void *fh, struct v4l2_requestbuffers *rb)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_reqbufs(&vfh->queue, rb);
}
static int
iss_video_querybuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_querybuf(&vfh->queue, b);
}
static int
iss_video_qbuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_qbuf(&vfh->queue, b);
}
static int
iss_video_expbuf(struct file *file, void *fh, struct v4l2_exportbuffer *e)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_expbuf(&vfh->queue, e);
}
static int
iss_video_dqbuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_dqbuf(&vfh->queue, b, file->f_flags & O_NONBLOCK);
}
/*
* Stream management
*
* Every ISS pipeline has a single input and a single output. The input can be
* either a sensor or a video node. The output is always a video node.
*
* As every pipeline has an output video node, the ISS video objects at the
* pipeline output stores the pipeline state. It tracks the streaming state of
* both the input and output, as well as the availability of buffers.
*
* In sensor-to-memory mode, frames are always available at the pipeline input.
* Starting the sensor usually requires I2C transfers and must be done in
* interruptible context. The pipeline is started and stopped synchronously
* to the stream on/off commands. All modules in the pipeline will get their
* subdev set stream handler called. The module at the end of the pipeline must
* delay starting the hardware until buffers are available at its output.
*
* In memory-to-memory mode, starting/stopping the stream requires
* synchronization between the input and output. ISS modules can't be stopped
* in the middle of a frame, and at least some of the modules seem to become
* busy as soon as they're started, even if they don't receive a frame start
* event. For that reason frames need to be processed in single-shot mode. The
* driver needs to wait until a frame is completely processed and written to
* memory before restarting the pipeline for the next frame. Pipelined
* processing might be possible but requires more testing.
*
* Stream start must be delayed until buffers are available at both the input
* and output. The pipeline must be started in the videobuf queue callback with
* the buffers queue spinlock held. The modules subdev set stream operation must
* not sleep.
*/
static int
iss_video_streamon(struct file *file, void *fh, enum v4l2_buf_type type)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
struct media_entity_graph graph;
struct media_entity *entity = &video->video.entity;
enum iss_pipeline_state state;
struct iss_pipeline *pipe;
struct iss_video *far_end;
unsigned long flags;
int ret;
if (type != video->type)
return -EINVAL;
mutex_lock(&video->stream_lock);
/* Start streaming on the pipeline. No link touching an entity in the
* pipeline can be activated or deactivated once streaming is started.
*/
pipe = entity->pipe
? to_iss_pipeline(entity) : &video->pipe;
pipe->external = NULL;
pipe->external_rate = 0;
pipe->external_bpp = 0;
ret = media_entity_enum_init(&pipe->ent_enum, entity->graph_obj.mdev);
if (ret)
goto err_graph_walk_init;
ret = media_entity_graph_walk_init(&graph, entity->graph_obj.mdev);
if (ret)
goto err_graph_walk_init;
if (video->iss->pdata->set_constraints)
video->iss->pdata->set_constraints(video->iss, true);
ret = media_entity_pipeline_start(entity, &pipe->pipe);
if (ret < 0)
goto err_media_entity_pipeline_start;
media_entity_graph_walk_start(&graph, entity);
while ((entity = media_entity_graph_walk_next(&graph)))
media_entity_enum_set(&pipe->ent_enum, entity);
/* Verify that the currently configured format matches the output of
* the connected subdev.
*/
ret = iss_video_check_format(video, vfh);
if (ret < 0)
goto err_iss_video_check_format;
video->bpl_padding = ret;
video->bpl_value = vfh->format.fmt.pix.bytesperline;
/* Find the ISS video node connected at the far end of the pipeline and
* update the pipeline.
*/
far_end = iss_video_far_end(video);
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
state = ISS_PIPELINE_STREAM_OUTPUT | ISS_PIPELINE_IDLE_OUTPUT;
pipe->input = far_end;
pipe->output = video;
} else {
if (!far_end) {
ret = -EPIPE;
goto err_iss_video_check_format;
}
state = ISS_PIPELINE_STREAM_INPUT | ISS_PIPELINE_IDLE_INPUT;
pipe->input = video;
pipe->output = far_end;
}
spin_lock_irqsave(&pipe->lock, flags);
pipe->state &= ~ISS_PIPELINE_STREAM;
pipe->state |= state;
spin_unlock_irqrestore(&pipe->lock, flags);
/* Set the maximum time per frame as the value requested by userspace.
* This is a soft limit that can be overridden if the hardware doesn't
* support the request limit.
*/
if (video->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
pipe->max_timeperframe = vfh->timeperframe;
video->queue = &vfh->queue;
INIT_LIST_HEAD(&video->dmaqueue);
video->error = false;
atomic_set(&pipe->frame_number, -1);
ret = vb2_streamon(&vfh->queue, type);
if (ret < 0)
goto err_iss_video_check_format;
/* In sensor-to-memory mode, the stream can be started synchronously
* to the stream on command. In memory-to-memory mode, it will be
* started when buffers are queued on both the input and output.
*/
if (!pipe->input) {
unsigned long flags;
ret = omap4iss_pipeline_set_stream(pipe,
ISS_PIPELINE_STREAM_CONTINUOUS);
if (ret < 0)
goto err_omap4iss_set_stream;
spin_lock_irqsave(&video->qlock, flags);
if (list_empty(&video->dmaqueue))
video->dmaqueue_flags |= ISS_VIDEO_DMAQUEUE_UNDERRUN;
spin_unlock_irqrestore(&video->qlock, flags);
}
media_entity_graph_walk_cleanup(&graph);
mutex_unlock(&video->stream_lock);
return 0;
err_omap4iss_set_stream:
vb2_streamoff(&vfh->queue, type);
err_iss_video_check_format:
media_entity_pipeline_stop(&video->video.entity);
err_media_entity_pipeline_start:
if (video->iss->pdata->set_constraints)
video->iss->pdata->set_constraints(video->iss, false);
video->queue = NULL;
media_entity_graph_walk_cleanup(&graph);
err_graph_walk_init:
media_entity_enum_cleanup(&pipe->ent_enum);
mutex_unlock(&video->stream_lock);
return ret;
}
static int
iss_video_streamoff(struct file *file, void *fh, enum v4l2_buf_type type)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
struct iss_pipeline *pipe = to_iss_pipeline(&video->video.entity);
enum iss_pipeline_state state;
unsigned long flags;
if (type != video->type)
return -EINVAL;
mutex_lock(&video->stream_lock);
if (!vb2_is_streaming(&vfh->queue))
goto done;
/* Update the pipeline state. */
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
state = ISS_PIPELINE_STREAM_OUTPUT
| ISS_PIPELINE_QUEUE_OUTPUT;
else
state = ISS_PIPELINE_STREAM_INPUT
| ISS_PIPELINE_QUEUE_INPUT;
spin_lock_irqsave(&pipe->lock, flags);
pipe->state &= ~state;
spin_unlock_irqrestore(&pipe->lock, flags);
/* Stop the stream. */
omap4iss_pipeline_set_stream(pipe, ISS_PIPELINE_STREAM_STOPPED);
vb2_streamoff(&vfh->queue, type);
video->queue = NULL;
media_entity_enum_cleanup(&pipe->ent_enum);
if (video->iss->pdata->set_constraints)
video->iss->pdata->set_constraints(video->iss, false);
media_entity_pipeline_stop(&video->video.entity);
done:
mutex_unlock(&video->stream_lock);
return 0;
}
static int
iss_video_enum_input(struct file *file, void *fh, struct v4l2_input *input)
{
if (input->index > 0)
return -EINVAL;
strlcpy(input->name, "camera", sizeof(input->name));
input->type = V4L2_INPUT_TYPE_CAMERA;
return 0;
}
static int
iss_video_g_input(struct file *file, void *fh, unsigned int *input)
{
*input = 0;
return 0;
}
static int
iss_video_s_input(struct file *file, void *fh, unsigned int input)
{
return input == 0 ? 0 : -EINVAL;
}
static const struct v4l2_ioctl_ops iss_video_ioctl_ops = {
.vidioc_querycap = iss_video_querycap,
.vidioc_enum_fmt_vid_cap = iss_video_enum_format,
.vidioc_g_fmt_vid_cap = iss_video_get_format,
.vidioc_s_fmt_vid_cap = iss_video_set_format,
.vidioc_try_fmt_vid_cap = iss_video_try_format,
.vidioc_g_fmt_vid_out = iss_video_get_format,
.vidioc_s_fmt_vid_out = iss_video_set_format,
.vidioc_try_fmt_vid_out = iss_video_try_format,
.vidioc_g_parm = iss_video_get_param,
.vidioc_s_parm = iss_video_set_param,
.vidioc_reqbufs = iss_video_reqbufs,
.vidioc_querybuf = iss_video_querybuf,
.vidioc_qbuf = iss_video_qbuf,
.vidioc_expbuf = iss_video_expbuf,
.vidioc_dqbuf = iss_video_dqbuf,
.vidioc_streamon = iss_video_streamon,
.vidioc_streamoff = iss_video_streamoff,
.vidioc_enum_input = iss_video_enum_input,
.vidioc_g_input = iss_video_g_input,
.vidioc_s_input = iss_video_s_input,
};
/* -----------------------------------------------------------------------------
* V4L2 file operations
*/
static int iss_video_open(struct file *file)
{
struct iss_video *video = video_drvdata(file);
struct iss_video_fh *handle;
struct vb2_queue *q;
int ret = 0;
handle = kzalloc(sizeof(*handle), GFP_KERNEL);
if (!handle)
return -ENOMEM;
v4l2_fh_init(&handle->vfh, &video->video);
v4l2_fh_add(&handle->vfh);
/* If this is the first user, initialise the pipeline. */
if (!omap4iss_get(video->iss)) {
ret = -EBUSY;
goto done;
}
ret = media_entity_graph_walk_init(&handle->graph,
&video->iss->media_dev);
if (ret)
goto done;
ret = omap4iss_pipeline_pm_use(&video->video.entity, 1,
&handle->graph);
if (ret < 0) {
omap4iss_put(video->iss);
goto done;
}
video->alloc_ctx = vb2_dma_contig_init_ctx(video->iss->dev);
if (IS_ERR(video->alloc_ctx)) {
ret = PTR_ERR(video->alloc_ctx);
omap4iss_put(video->iss);
goto done;
}
q = &handle->queue;
q->type = video->type;
q->io_modes = VB2_MMAP | VB2_DMABUF;
q->drv_priv = handle;
q->ops = &iss_video_vb2ops;
q->mem_ops = &vb2_dma_contig_memops;
q->buf_struct_size = sizeof(struct iss_buffer);
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
ret = vb2_queue_init(q);
if (ret) {
omap4iss_put(video->iss);
goto done;
}
memset(&handle->format, 0, sizeof(handle->format));
handle->format.type = video->type;
handle->timeperframe.denominator = 1;
handle->video = video;
file->private_data = &handle->vfh;
done:
if (ret < 0) {
v4l2_fh_del(&handle->vfh);
media_entity_graph_walk_cleanup(&handle->graph);
kfree(handle);
}
return ret;
}
static int iss_video_release(struct file *file)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_fh *vfh = file->private_data;
struct iss_video_fh *handle = to_iss_video_fh(vfh);
/* Disable streaming and free the buffers queue resources. */
iss_video_streamoff(file, vfh, video->type);
omap4iss_pipeline_pm_use(&video->video.entity, 0, &handle->graph);
/* Release the videobuf2 queue */
vb2_queue_release(&handle->queue);
/* Release the file handle. */
media_entity_graph_walk_cleanup(&handle->graph);
v4l2_fh_del(vfh);
kfree(handle);
file->private_data = NULL;
omap4iss_put(video->iss);
return 0;
}
static unsigned int iss_video_poll(struct file *file, poll_table *wait)
{
struct iss_video_fh *vfh = to_iss_video_fh(file->private_data);
return vb2_poll(&vfh->queue, file, wait);
}
static int iss_video_mmap(struct file *file, struct vm_area_struct *vma)
{
struct iss_video_fh *vfh = to_iss_video_fh(file->private_data);
return vb2_mmap(&vfh->queue, vma);
}
static struct v4l2_file_operations iss_video_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
.open = iss_video_open,
.release = iss_video_release,
.poll = iss_video_poll,
.mmap = iss_video_mmap,
};
/* -----------------------------------------------------------------------------
* ISS video core
*/
static const struct iss_video_operations iss_video_dummy_ops = {
};
int omap4iss_video_init(struct iss_video *video, const char *name)
{
const char *direction;
int ret;
switch (video->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
direction = "output";
video->pad.flags = MEDIA_PAD_FL_SINK;
break;
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
direction = "input";
video->pad.flags = MEDIA_PAD_FL_SOURCE;
break;
default:
return -EINVAL;
}
ret = media_entity_pads_init(&video->video.entity, 1, &video->pad);
if (ret < 0)
return ret;
spin_lock_init(&video->qlock);
mutex_init(&video->mutex);
atomic_set(&video->active, 0);
spin_lock_init(&video->pipe.lock);
mutex_init(&video->stream_lock);
/* Initialize the video device. */
if (!video->ops)
video->ops = &iss_video_dummy_ops;
video->video.fops = &iss_video_fops;
snprintf(video->video.name, sizeof(video->video.name),
"OMAP4 ISS %s %s", name, direction);
video->video.vfl_type = VFL_TYPE_GRABBER;
video->video.release = video_device_release_empty;
video->video.ioctl_ops = &iss_video_ioctl_ops;
video->pipe.stream_state = ISS_PIPELINE_STREAM_STOPPED;
video_set_drvdata(&video->video, video);
return 0;
}
void omap4iss_video_cleanup(struct iss_video *video)
{
media_entity_cleanup(&video->video.entity);
mutex_destroy(&video->stream_lock);
mutex_destroy(&video->mutex);
}
int omap4iss_video_register(struct iss_video *video, struct v4l2_device *vdev)
{
int ret;
video->video.v4l2_dev = vdev;
ret = video_register_device(&video->video, VFL_TYPE_GRABBER, -1);
if (ret < 0)
dev_err(video->iss->dev,
"could not register video device (%d)\n", ret);
return ret;
}
void omap4iss_video_unregister(struct iss_video *video)
{
video_unregister_device(&video->video);
}
| {'content_hash': 'd22cc4d575e400c9953e29576c187241', 'timestamp': '', 'source': 'github', 'line_count': 1179, 'max_line_length': 80, 'avg_line_length': 27.953350296861746, 'alnum_prop': 0.6818885214066814, 'repo_name': 'mikedlowis-prototypes/albase', 'id': '058233a9de67427dfecc05aea58a82c6504d3468', 'size': '33374', 'binary': False, 'copies': '46', 'ref': 'refs/heads/master', 'path': 'source/kernel/drivers/staging/media/omap4iss/iss_video.c', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '10263145'}, {'name': 'Awk', 'bytes': '55187'}, {'name': 'Batchfile', 'bytes': '31438'}, {'name': 'C', 'bytes': '551654518'}, {'name': 'C++', 'bytes': '11818066'}, {'name': 'CMake', 'bytes': '122998'}, {'name': 'Clojure', 'bytes': '945'}, {'name': 'DIGITAL Command Language', 'bytes': '232099'}, {'name': 'GDB', 'bytes': '18113'}, {'name': 'Gherkin', 'bytes': '5110'}, {'name': 'HTML', 'bytes': '18291'}, {'name': 'Lex', 'bytes': '58937'}, {'name': 'M4', 'bytes': '561745'}, {'name': 'Makefile', 'bytes': '7082768'}, {'name': 'Objective-C', 'bytes': '634652'}, {'name': 'POV-Ray SDL', 'bytes': '546'}, {'name': 'Perl', 'bytes': '1229221'}, {'name': 'Perl6', 'bytes': '11648'}, {'name': 'Python', 'bytes': '316536'}, {'name': 'Roff', 'bytes': '4201130'}, {'name': 'Shell', 'bytes': '2436879'}, {'name': 'SourcePawn', 'bytes': '2711'}, {'name': 'TeX', 'bytes': '182745'}, {'name': 'UnrealScript', 'bytes': '12824'}, {'name': 'Visual Basic', 'bytes': '11568'}, {'name': 'XS', 'bytes': '1239'}, {'name': 'Yacc', 'bytes': '146537'}]} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="79dp"
android:background="#FFFFFF"
android:paddingLeft="15dp"
android:paddingRight="15dp">
<TextView
android:id="@+id/tv_order_state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="15dp"
android:text=""
android:textStyle="bold"
android:textColor="#2E2E2E"
android:textSize="16sp"
/>
<TextView
android:id="@+id/tv_tip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/tv_order_state"
android:layout_below="@id/tv_order_state"
android:layout_marginTop="7dp"
android:text=""
android:textColor="#999999"
android:textSize="14sp"
/>
<TextView
android:id="@+id/tv_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="19dp"
android:text=""
android:textColor="#999999"
android:textSize="13sp"
/>
<TextView
android:id="@+id/btn_state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/tv_tip"
android:layout_alignParentRight="true"
android:background="@null"
android:drawableRight="@drawable/orderdetail_greenarrow"
android:drawablePadding="2.5dp"
android:text="更多状态"
android:textSize="@dimen/second_title"
android:textColor="#6BB400"/>
</RelativeLayout> | {'content_hash': '475496e9b532c5c51a391fb7fcc5f664', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 74, 'avg_line_length': 34.44642857142857, 'alnum_prop': 0.6101607050285122, 'repo_name': 'ebridfighter/GongXianSheng', 'id': '22ebe250fdaf83f2ab7b56e24656852d9540737d', 'size': '1937', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/item_order_state.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1183024'}]} |
module BackburnerJobsManager
def setup
ActiveJob::Base.queue_adapter = :backburner
Backburner.configure do |config|
config.logger = Rails.logger
end
unless can_run?
puts "Cannot run integration tests for backburner. To be able to run integration tests for backburner you need to install and start beanstalkd.\n"
exit
end
end
def clear_jobs
tube.clear
end
def start_workers
@thread = Thread.new { Backburner.work "integration-tests" } # backburner dasherizes the queue name
end
def stop_workers
@thread.kill
end
def tube
@tube ||= Beaneater::Tube.new(Backburner::Worker.connection, "backburner.worker.queue.integration-tests") # backburner dasherizes the queue name
end
def can_run?
begin
Backburner::Worker.connection.send :connect!
rescue
return false
end
true
end
end
| {'content_hash': '8b7f316af879151da1ac676e59f7c69a', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 152, 'avg_line_length': 23.81081081081081, 'alnum_prop': 0.699205448354143, 'repo_name': 'tijwelch/rails', 'id': '263097c792daeec43c44a4ee64df384faa1cf5fa', 'size': '881', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'activejob/test/support/integration/adapters/backburner.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '33444'}, {'name': 'CoffeeScript', 'bytes': '41914'}, {'name': 'HTML', 'bytes': '195552'}, {'name': 'JavaScript', 'bytes': '86514'}, {'name': 'Ruby', 'bytes': '10496098'}, {'name': 'Yacc', 'bytes': '965'}]} |
/*
* Do not modify this file. This file is generated from the monitoring-2010-08-01.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.CloudWatch.Model
{
///<summary>
/// CloudWatch exception
/// </summary>
public class InvalidParameterValueException : AmazonCloudWatchException
{
/// <summary>
/// Constructs a new InvalidParameterValueException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidParameterValueException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidParameterValueException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidParameterValueException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidParameterValueException
/// </summary>
/// <param name="innerException"></param>
public InvalidParameterValueException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidParameterValueException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidParameterValueException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidParameterValueException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidParameterValueException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
}
} | {'content_hash': '78cde9c8aa8f9f88db3b5a4d55bb189d', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 172, 'avg_line_length': 38.86363636363637, 'alnum_prop': 0.6183235867446394, 'repo_name': 'rafd123/aws-sdk-net', 'id': '9d7a413a705ba1a6640c1f0a5d65ee609226ffe1', 'size': '3152', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sdk/src/Services/CloudWatch/Generated/Model/InvalidParameterValueException.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '85386370'}, {'name': 'CSS', 'bytes': '18119'}, {'name': 'HTML', 'bytes': '24352'}, {'name': 'JavaScript', 'bytes': '6576'}, {'name': 'PowerShell', 'bytes': '12753'}, {'name': 'XSLT', 'bytes': '7010'}]} |
/**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highcharts]]
*/
package com.highcharts.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>plotOptions-vector-states-select-marker</code>
*/
@js.annotation.ScalaJSDefined
class PlotOptionsVectorStatesSelectMarker extends com.highcharts.HighchartsGenericObject {
/**
* <p>The width of the point marker's outline.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-fillcolor/">2px blue marker</a>
* @since 6.0.0
*/
val lineWidth: js.UndefOr[Double] = js.undefined
/**
* <p>The color of the point marker's outline. When <code>undefined</code>, the
* series' or point's color is used.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-fillcolor/">Inherit from series color (undefined)</a>
* @since 6.0.0
*/
val lineColor: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>The threshold for how dense the point markers should be before they
* are hidden, given that <code>enabled</code> is not defined. The number indicates
* the horizontal distance between the two closest points in the series,
* as multiples of the <code>marker.radius</code>. In other words, the default
* value of 2 means points are hidden if overlapping horizontally.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-enabledthreshold">A higher threshold</a>
* @since 6.0.5
*/
val enabledThreshold: js.UndefOr[Double] = js.undefined
/**
* <p>The radius of the point marker.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-radius/">Bigger markers</a>
* @since 6.0.0
*/
val radius: js.UndefOr[Double] = js.undefined
/**
* <p>States for a single point marker.</p>
* @since 6.0.0
*/
val states: js.Any = js.undefined
/**
* <p>The fill color of the point marker. When <code>undefined</code>, the series' or
* point's color is used.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-fillcolor/">White fill</a>
* @since 6.0.0
*/
val fillColor: js.UndefOr[String | js.Object] = js.undefined
/**
* <p>Enable or disable the point marker. If <code>undefined</code>, the markers are
* hidden when the data is dense, and shown for more widespread data
* points.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-enabled/">Disabled markers</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-enabled-false/">Disabled in normal state but enabled on hover</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/stock/plotoptions/series-marker/">Enabled markers</a>
* @since 6.0.0
*/
val enabled: js.UndefOr[Boolean] = js.undefined
/**
* <p>Image markers only. Set the image width explicitly. When using this
* option, a <code>width</code> must also be set.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a>
* @since 4.0.4
*/
val height: js.UndefOr[Double] = js.undefined
/**
* <p>A predefined shape or symbol for the marker. When undefined, the
* symbol is pulled from options.symbols. Other possible values are
* "circle", "square", "diamond", "triangle" and "triangle-down".</p>
* <p>Additionally, the URL to a graphic can be given on this form:
* "url(graphic.png)". Note that for the image to be applied to exported
* charts, its URL needs to be accessible by the export server.</p>
* <p>Custom callbacks for symbol path generation can also be added to
* <code>Highcharts.SVGRenderer.prototype.symbols</code>. The callback is then
* used by its method name, as shown in the demo.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-symbol/">Predefined, graphic and custom markers</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-symbol/">Predefined, graphic and custom markers</a>
* @since 6.0.0
*/
val symbol: js.UndefOr[String] = js.undefined
/**
* <p>Image markers only. Set the image width explicitly. When using this
* option, a <code>height</code> must also be set.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a>
* @since 4.0.4
*/
val width: js.UndefOr[Double] = js.undefined
}
object PlotOptionsVectorStatesSelectMarker {
/**
* @param lineWidth <p>The width of the point marker's outline.</p>
* @param lineColor <p>The color of the point marker's outline. When <code>undefined</code>, the. series' or point's color is used.</p>
* @param enabledThreshold <p>The threshold for how dense the point markers should be before they. are hidden, given that <code>enabled</code> is not defined. The number indicates. the horizontal distance between the two closest points in the series,. as multiples of the <code>marker.radius</code>. In other words, the default. value of 2 means points are hidden if overlapping horizontally.</p>
* @param radius <p>The radius of the point marker.</p>
* @param states <p>States for a single point marker.</p>
* @param fillColor <p>The fill color of the point marker. When <code>undefined</code>, the series' or. point's color is used.</p>
* @param enabled <p>Enable or disable the point marker. If <code>undefined</code>, the markers are. hidden when the data is dense, and shown for more widespread data. points.</p>
* @param height <p>Image markers only. Set the image width explicitly. When using this. option, a <code>width</code> must also be set.</p>
* @param symbol <p>A predefined shape or symbol for the marker. When undefined, the. symbol is pulled from options.symbols. Other possible values are. "circle", "square", "diamond", "triangle" and "triangle-down".</p>. <p>Additionally, the URL to a graphic can be given on this form:. "url(graphic.png)". Note that for the image to be applied to exported. charts, its URL needs to be accessible by the export server.</p>. <p>Custom callbacks for symbol path generation can also be added to. <code>Highcharts.SVGRenderer.prototype.symbols</code>. The callback is then. used by its method name, as shown in the demo.</p>
* @param width <p>Image markers only. Set the image width explicitly. When using this. option, a <code>height</code> must also be set.</p>
*/
def apply(lineWidth: js.UndefOr[Double] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, enabledThreshold: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, states: js.UndefOr[js.Any] = js.undefined, fillColor: js.UndefOr[String | js.Object] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, height: js.UndefOr[Double] = js.undefined, symbol: js.UndefOr[String] = js.undefined, width: js.UndefOr[Double] = js.undefined): PlotOptionsVectorStatesSelectMarker = {
val lineWidthOuter: js.UndefOr[Double] = lineWidth
val lineColorOuter: js.UndefOr[String | js.Object] = lineColor
val enabledThresholdOuter: js.UndefOr[Double] = enabledThreshold
val radiusOuter: js.UndefOr[Double] = radius
val statesOuter: js.Any = states
val fillColorOuter: js.UndefOr[String | js.Object] = fillColor
val enabledOuter: js.UndefOr[Boolean] = enabled
val heightOuter: js.UndefOr[Double] = height
val symbolOuter: js.UndefOr[String] = symbol
val widthOuter: js.UndefOr[Double] = width
com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsVectorStatesSelectMarker {
override val lineWidth: js.UndefOr[Double] = lineWidthOuter
override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter
override val enabledThreshold: js.UndefOr[Double] = enabledThresholdOuter
override val radius: js.UndefOr[Double] = radiusOuter
override val states: js.Any = statesOuter
override val fillColor: js.UndefOr[String | js.Object] = fillColorOuter
override val enabled: js.UndefOr[Boolean] = enabledOuter
override val height: js.UndefOr[Double] = heightOuter
override val symbol: js.UndefOr[String] = symbolOuter
override val width: js.UndefOr[Double] = widthOuter
})
}
}
| {'content_hash': 'af9dee36abd514cd6e261163705f8f02', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 682, 'avg_line_length': 65.58108108108108, 'alnum_prop': 0.7248093962497424, 'repo_name': 'Karasiq/scalajs-highcharts', 'id': 'a8f81214e053ef3a5ccc3f29bb2fbf5fd5e1ea7b', 'size': '9706', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/scala/com/highcharts/config/PlotOptionsVectorStatesSelectMarker.scala', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Scala', 'bytes': '131509301'}]} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_32880_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=8996#src-8996" >testAbaNumberCheck_32880_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:20
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_32880_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=32771#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=32771#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=32771#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | {'content_hash': '4e9f4e133e358b4b3d9307574337a55c', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 359, 'avg_line_length': 46.744680851063826, 'alnum_prop': 0.5302685480200273, 'repo_name': 'dcarda/aba.route.validator', 'id': '92bdd2c5e65996edf3bf8acf0bc5976fbc67a8de', 'size': '10985', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15_testAbaNumberCheck_32880_bad_pab.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '18715254'}]} |
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("CS.Architecture.Tests")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("Package Description")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("CS.Architecture.Tests")]
[assembly: System.Reflection.AssemblyTitleAttribute("CS.Architecture.Tests")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| {'content_hash': '9085cbc7365dbadc56454e24d24fc2c6', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 81, 'avg_line_length': 49.857142857142854, 'alnum_prop': 0.8237822349570201, 'repo_name': 'larsrotgers/computing-system', 'id': '852de815fff5989ff94ffcb15b2bfa4e8ec6ec62', 'size': '1095', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CS.Architecture.Tests/obj/Debug/netcoreapp1.1/CS.Architecture.Tests.AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '460'}, {'name': 'Batchfile', 'bytes': '56'}, {'name': 'C#', 'bytes': '123677'}, {'name': 'Smalltalk', 'bytes': '924'}]} |
function print_help() {
echo "Usage: $0 {start | stop | restart | status}"
exit 1
}
if [ $# != 1 ]
then
print_help
fi
source $(dirname $0)/eagle-env.sh
export CATALINA_HOME=$EAGLE_HOME/lib/tomcat
export CATALINA_BASE=$CATALINA_HOME
export CATALINA_LOGDIR=$EAGLE_HOME/logs
export CATALINA_TMPDIR=$EAGLE_HOME/temp
export CATALINA_OUT=$CATALINA_LOGDIR/eagle-service.out
export CATALINA_PID=$CATALINA_TMPDIR/service.pid
# CLASSPATH
export CLASSPATH=$CLASSPATH:$EAGLE_HOME/conf
#for i in `ls $EAGLE_HOME/lib/*.jar`; do CLASSPATH=$CLASSPATH:$i; done
if [ ! -e $CATALINA_LOGDIR ];then
mkdir -p $CATALINA_LOGDIR
fi
if [ ! -e $CATALINA_TMPDIR ]; then
mkdir -p $CATALINA_TMPDIR
fi
EAGLE_SERVICE_CONF="eagle-service.conf"
# Always copy conf/eagle-service.properties to lib/tomcat/webapps/eagle-service/WEB-INF/classes/application.conf before starting
if [ ! -e ${EAGLE_HOME}/conf/${EAGLE_SERVICE_CONF} ]
then
echo "Failure: cannot find ${EAGLE_HOME}/conf/${EAGLE_SERVICE_CONF}"
exit 1
fi
cp -f $EAGLE_HOME/conf/$EAGLE_SERVICE_CONF ${EAGLE_HOME}/lib/tomcat/webapps/eagle-service/WEB-INF/classes/application.conf
case $1 in
"start")
echo "Starting eagle service ..."
$EAGLE_HOME/lib/tomcat/bin/catalina.sh start
if [ $? != 0 ];then
echo "Error: failed starting"
exit 1
fi
;;
"stop")
echo "Stopping eagle service ..."
$EAGLE_HOME/lib/tomcat/bin/catalina.sh stop
if [ $? != 0 ];then
echo "Error: failed stopping"
exit 1
fi
echo "Stopping is completed"
;;
"restart")
echo "Stopping eagle service ..."
$EAGLE_HOME/lib/tomcat/bin/catalina.sh stop
echo "Restarting eagle service ..."
$EAGLE_HOME/lib/tomcat/bin/catalina.sh start
if [ $? != 0 ];then
echo "Error: failed starting"
exit 1
fi
echo "Restarting is completed "
;;
"status")
#echo "Listing eagle service status ..."
if [ -e $CATALINA_TMPDIR/service.pid ] && ps -p `cat $CATALINA_TMPDIR/service.pid` > /dev/null
then
echo "Eagle service is running `cat $CATALINA_TMPDIR/service.pid`"
exit 0
else
echo "Eagle service is stopped"
exit 1
fi
;;
*)
print_help
;;
esac
if [ $? != 0 ]; then
echo "Error: start failure"
exit 1
fi
exit 0
| {'content_hash': 'a9036f32ed60512fe25699bee7e14cad', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 128, 'avg_line_length': 22.375, 'alnum_prop': 0.6964618249534451, 'repo_name': 'sunlibin/incubator-eagle', 'id': 'cdf097ef0123964fc8df78828abe0f14d480142a', 'size': '2942', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'eagle-assembly/src/main/bin/eagle-service.sh', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '2884'}, {'name': 'CSS', 'bytes': '10117'}, {'name': 'Groff', 'bytes': '3975'}, {'name': 'HTML', 'bytes': '83712'}, {'name': 'Java', 'bytes': '2716144'}, {'name': 'JavaScript', 'bytes': '139245'}, {'name': 'Protocol Buffer', 'bytes': '2229'}, {'name': 'Ruby', 'bytes': '12755'}, {'name': 'Scala', 'bytes': '219968'}, {'name': 'Shell', 'bytes': '152554'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '34a75a38d2cbf9877f664d83ae56f35b', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '3ce5ff6bcfec679512cb541a577140ee442ffcf5', 'size': '202', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Solidago/Solidago speciosa/Solidago speciosa speciosa/ Syn. Solidago rigidiuscula/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
DOUBTFUL
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '60e644679b4f93b95c20b7bc71201bba', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'd56089f6051f3a8a88280498d207b4f6d9382cec', 'size': '199', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Murorum/Murorum murorum/Murorum murorum caprinense/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2014 Google Inc. All Rights Reserved. -->
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="wallet_buy_button_place_holder" msgid="4184147110658930238">"Comprar com o Google"</string>
</resources>
| {'content_hash': '4358e7fe37aaf8e9711a937a709a35d2', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 109, 'avg_line_length': 49.857142857142854, 'alnum_prop': 0.7163323782234957, 'repo_name': 'CalSPEED/CalSPEED-Android', 'id': '43e1c58a5f6a8eb5cc870852906a0f47b6785acf', 'size': '349', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'googleplayservices_lib/src/main/res/values-pt/wallet_strings.xml', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '341905'}]} |
#include "flutter/sky/engine/platform/fonts/opentype/OpenTypeVerticalData.h"
#include "flutter/sky/engine/platform/SharedBuffer.h"
#include "flutter/sky/engine/platform/fonts/SimpleFontData.h"
#include "flutter/sky/engine/platform/fonts/GlyphPage.h"
#include "flutter/sky/engine/platform/fonts/opentype/OpenTypeTypes.h"
#include "flutter/sky/engine/platform/geometry/FloatRect.h"
#include "flutter/sky/engine/wtf/RefPtr.h"
namespace blink {
namespace OpenType {
const uint32_t HheaTag = OT_MAKE_TAG('h', 'h', 'e', 'a');
const uint32_t HmtxTag = OT_MAKE_TAG('h', 'm', 't', 'x');
const uint32_t VheaTag = OT_MAKE_TAG('v', 'h', 'e', 'a');
const uint32_t VmtxTag = OT_MAKE_TAG('v', 'm', 't', 'x');
const uint32_t VORGTag = OT_MAKE_TAG('V', 'O', 'R', 'G');
#pragma pack(1)
struct HheaTable {
OpenType::Fixed version;
OpenType::Int16 ascender;
OpenType::Int16 descender;
OpenType::Int16 lineGap;
OpenType::Int16 advanceWidthMax;
OpenType::Int16 minLeftSideBearing;
OpenType::Int16 minRightSideBearing;
OpenType::Int16 xMaxExtent;
OpenType::Int16 caretSlopeRise;
OpenType::Int16 caretSlopeRun;
OpenType::Int16 caretOffset;
OpenType::Int16 reserved[4];
OpenType::Int16 metricDataFormat;
OpenType::UInt16 numberOfHMetrics;
};
struct VheaTable {
OpenType::Fixed version;
OpenType::Int16 ascent;
OpenType::Int16 descent;
OpenType::Int16 lineGap;
OpenType::Int16 advanceHeightMax;
OpenType::Int16 minTopSideBearing;
OpenType::Int16 minBottomSideBearing;
OpenType::Int16 yMaxExtent;
OpenType::Int16 caretSlopeRise;
OpenType::Int16 caretSlopeRun;
OpenType::Int16 caretOffset;
OpenType::Int16 reserved[4];
OpenType::Int16 metricDataFormat;
OpenType::UInt16 numOfLongVerMetrics;
};
struct HmtxTable {
struct Entry {
OpenType::UInt16 advanceWidth;
OpenType::Int16 lsb;
} entries[1];
};
struct VmtxTable {
struct Entry {
OpenType::UInt16 advanceHeight;
OpenType::Int16 topSideBearing;
} entries[1];
};
struct VORGTable {
OpenType::UInt16 majorVersion;
OpenType::UInt16 minorVersion;
OpenType::Int16 defaultVertOriginY;
OpenType::UInt16 numVertOriginYMetrics;
struct VertOriginYMetrics {
OpenType::UInt16 glyphIndex;
OpenType::Int16 vertOriginY;
} vertOriginYMetrics[1];
size_t requiredSize() const { return sizeof(*this) + sizeof(VertOriginYMetrics) * (numVertOriginYMetrics - 1); }
};
#pragma pack()
} // namespace OpenType
OpenTypeVerticalData::OpenTypeVerticalData(const FontPlatformData& platformData)
: m_defaultVertOriginY(0)
{
loadMetrics(platformData);
}
void OpenTypeVerticalData::loadMetrics(const FontPlatformData& platformData)
{
// Load hhea and hmtx to get x-component of vertical origins.
// If these tables are missing, it's not an OpenType font.
RefPtr<SharedBuffer> buffer = platformData.openTypeTable(OpenType::HheaTag);
const OpenType::HheaTable* hhea = OpenType::validateTable<OpenType::HheaTable>(buffer);
if (!hhea)
return;
uint16_t countHmtxEntries = hhea->numberOfHMetrics;
if (!countHmtxEntries) {
WTF_LOG_ERROR("Invalid numberOfHMetrics");
return;
}
buffer = platformData.openTypeTable(OpenType::HmtxTag);
const OpenType::HmtxTable* hmtx = OpenType::validateTable<OpenType::HmtxTable>(buffer, countHmtxEntries);
if (!hmtx) {
WTF_LOG_ERROR("hhea exists but hmtx does not (or broken)");
return;
}
m_advanceWidths.resize(countHmtxEntries);
for (uint16_t i = 0; i < countHmtxEntries; ++i)
m_advanceWidths[i] = hmtx->entries[i].advanceWidth;
// Load vhea first. This table is required for fonts that support vertical flow.
buffer = platformData.openTypeTable(OpenType::VheaTag);
const OpenType::VheaTable* vhea = OpenType::validateTable<OpenType::VheaTable>(buffer);
if (!vhea)
return;
uint16_t countVmtxEntries = vhea->numOfLongVerMetrics;
if (!countVmtxEntries) {
WTF_LOG_ERROR("Invalid numOfLongVerMetrics");
return;
}
// Load VORG. This table is optional.
buffer = platformData.openTypeTable(OpenType::VORGTag);
const OpenType::VORGTable* vorg = OpenType::validateTable<OpenType::VORGTable>(buffer);
if (vorg && buffer->size() >= vorg->requiredSize()) {
m_defaultVertOriginY = vorg->defaultVertOriginY;
uint16_t countVertOriginYMetrics = vorg->numVertOriginYMetrics;
if (!countVertOriginYMetrics) {
// Add one entry so that hasVORG() becomes true
m_vertOriginY.set(0, m_defaultVertOriginY);
} else {
for (uint16_t i = 0; i < countVertOriginYMetrics; ++i) {
const OpenType::VORGTable::VertOriginYMetrics& metrics = vorg->vertOriginYMetrics[i];
m_vertOriginY.set(metrics.glyphIndex, metrics.vertOriginY);
}
}
}
// Load vmtx then. This table is required for fonts that support vertical flow.
buffer = platformData.openTypeTable(OpenType::VmtxTag);
const OpenType::VmtxTable* vmtx = OpenType::validateTable<OpenType::VmtxTable>(buffer, countVmtxEntries);
if (!vmtx) {
WTF_LOG_ERROR("vhea exists but vmtx does not (or broken)");
return;
}
m_advanceHeights.resize(countVmtxEntries);
for (uint16_t i = 0; i < countVmtxEntries; ++i)
m_advanceHeights[i] = vmtx->entries[i].advanceHeight;
// VORG is preferred way to calculate vertical origin than vmtx,
// so load topSideBearing from vmtx only if VORG is missing.
if (hasVORG())
return;
size_t sizeExtra = buffer->size() - sizeof(OpenType::VmtxTable::Entry) * countVmtxEntries;
if (sizeExtra % sizeof(OpenType::Int16)) {
WTF_LOG_ERROR("vmtx has incorrect tsb count");
return;
}
size_t countTopSideBearings = countVmtxEntries + sizeExtra / sizeof(OpenType::Int16);
m_topSideBearings.resize(countTopSideBearings);
size_t i;
for (i = 0; i < countVmtxEntries; ++i)
m_topSideBearings[i] = vmtx->entries[i].topSideBearing;
if (i < countTopSideBearings) {
const OpenType::Int16* pTopSideBearingsExtra = reinterpret_cast<const OpenType::Int16*>(&vmtx->entries[countVmtxEntries]);
for (; i < countTopSideBearings; ++i, ++pTopSideBearingsExtra)
m_topSideBearings[i] = *pTopSideBearingsExtra;
}
}
float OpenTypeVerticalData::advanceHeight(const SimpleFontData* font, Glyph glyph) const
{
size_t countHeights = m_advanceHeights.size();
if (countHeights) {
uint16_t advanceFUnit = m_advanceHeights[glyph < countHeights ? glyph : countHeights - 1];
float advance = advanceFUnit * font->sizePerUnit();
return advance;
}
// No vertical info in the font file; use height as advance.
return font->fontMetrics().height();
}
void OpenTypeVerticalData::getVerticalTranslationsForGlyphs(const SimpleFontData* font, const Glyph* glyphs, size_t count, float* outXYArray) const
{
size_t countWidths = m_advanceWidths.size();
ASSERT(countWidths > 0);
const FontMetrics& metrics = font->fontMetrics();
float sizePerUnit = font->sizePerUnit();
float ascent = metrics.ascent();
bool useVORG = hasVORG();
size_t countTopSideBearings = m_topSideBearings.size();
float defaultVertOriginY = std::numeric_limits<float>::quiet_NaN();
for (float* end = &(outXYArray[count * 2]); outXYArray != end; ++glyphs, outXYArray += 2) {
Glyph glyph = *glyphs;
uint16_t widthFUnit = m_advanceWidths[glyph < countWidths ? glyph : countWidths - 1];
float width = widthFUnit * sizePerUnit;
outXYArray[0] = -width / 2;
// For Y, try VORG first.
if (useVORG) {
if (glyph) {
int16_t vertOriginYFUnit = m_vertOriginY.get(glyph);
if (vertOriginYFUnit) {
outXYArray[1] = -vertOriginYFUnit * sizePerUnit;
continue;
}
}
if (std::isnan(defaultVertOriginY))
defaultVertOriginY = -m_defaultVertOriginY * sizePerUnit;
outXYArray[1] = defaultVertOriginY;
continue;
}
// If no VORG, try vmtx next.
if (countTopSideBearings) {
int16_t topSideBearingFUnit = m_topSideBearings[glyph < countTopSideBearings ? glyph : countTopSideBearings - 1];
float topSideBearing = topSideBearingFUnit * sizePerUnit;
FloatRect bounds = font->boundsForGlyph(glyph);
outXYArray[1] = bounds.y() - topSideBearing;
continue;
}
// No vertical info in the font file; use ascent as vertical origin.
outXYArray[1] = -ascent;
}
}
} // namespace blink
| {'content_hash': '81c1d20fb8317b5ccb9a34ebc45ce602', 'timestamp': '', 'source': 'github', 'line_count': 237, 'max_line_length': 147, 'avg_line_length': 37.164556962025316, 'alnum_prop': 0.6705267938237965, 'repo_name': 'abarth/sky_engine', 'id': '634efcdc3389641e13ba7a797fd64292bd97e953', 'size': '10164', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'sky/engine/platform/fonts/opentype/OpenTypeVerticalData.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '2785'}, {'name': 'C', 'bytes': '291531'}, {'name': 'C++', 'bytes': '18081798'}, {'name': 'Dart', 'bytes': '267594'}, {'name': 'Groff', 'bytes': '29030'}, {'name': 'Java', 'bytes': '797390'}, {'name': 'JavaScript', 'bytes': '6905'}, {'name': 'Makefile', 'bytes': '402'}, {'name': 'Objective-C', 'bytes': '115874'}, {'name': 'Objective-C++', 'bytes': '437540'}, {'name': 'Python', 'bytes': '2279798'}, {'name': 'Shell', 'bytes': '183100'}, {'name': 'nesC', 'bytes': '18347'}]} |
rails_root = ENV['RAILS_ROOT'] || File.dirname(__FILE__) + '/../..'
rails_env = ENV['RAILS_ENV'] || 'development'
resque_config = YAML.load_file(rails_root + '/config/resque.yaml')
Resque.redis = resque_config[rails_env]
| {'content_hash': 'e5ae5a305d6e5b1ebed8fd8867d9ab88', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 67, 'avg_line_length': 44.4, 'alnum_prop': 0.6576576576576577, 'repo_name': 'rkischuk/StartAtlanta', 'id': '5b623a8ce42d4627eadb253e961f09ece904ce72', 'size': '222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/initializers/resque.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '5998'}, {'name': 'Ruby', 'bytes': '45697'}]} |
package org.apache.geode.management.internal.configuration.messages;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.apache.geode.internal.DataSerializableFixedID;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.lang.StringUtils;
/***
* Request sent by a member to the locator requesting the shared configuration
*
*/
public class ConfigurationRequest implements DataSerializableFixedID {
private static int DEFAULT_NUM_ATTEMPTS = 5;
private Set<String> groups = new HashSet<String>();
private boolean isRequestForEntireConfiguration = false;
private int numAttempts = DEFAULT_NUM_ATTEMPTS;
public ConfigurationRequest() {
super();
}
public ConfigurationRequest(Set<String> groups) {
this.groups = groups;
this.isRequestForEntireConfiguration = false;
}
public ConfigurationRequest(boolean getEntireConfiguration) {
this.isRequestForEntireConfiguration = true;
}
public void addGroups(String group) {
if (!StringUtils.isBlank(group))
this.groups.add(group);
}
@Override
public int getDSFID() {
return DataSerializableFixedID.CONFIGURATION_REQUEST;
}
@Override
public void toData(DataOutput out) throws IOException {
out.writeBoolean(isRequestForEntireConfiguration);
int size = groups.size();
out.writeInt(size);
if (size > 0) {
for (String group : groups) {
out.writeUTF(group);
}
}
out.writeInt(numAttempts);
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
this.isRequestForEntireConfiguration = in.readBoolean();
int size = in.readInt();
Set<String> groups = new HashSet<String>();
if (size > 0) {
for (int i = 0; i < size; i++) {
groups.add(in.readUTF());
}
}
this.groups = groups;
this.numAttempts = in.readInt();
}
public Set<String> getGroups() {
return this.groups;
}
public void setGroups(Set<String> groups) {
this.groups = groups;
}
public boolean isRequestForEntireConfiguration() {
return this.isRequestForEntireConfiguration;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("ConfigurationRequest for groups : ");
sb.append("\n cluster");
sb.append(this.groups);
return sb.toString();
}
// TODO Sourabh, please review for correctness
// Asif: Returning null, as otherwise backward compatibility tests fail
// due to missing pre to & from data functions.
public Version[] getSerializationVersions() {
return null;// new Version[] { Version.CURRENT };
}
public int getNumAttempts() {
return numAttempts;
}
public void setNumAttempts(int numAttempts) {
this.numAttempts = numAttempts;
}
}
| {'content_hash': '258c134043cacf43573d555e2cbb69dd', 'timestamp': '', 'source': 'github', 'line_count': 112, 'max_line_length': 81, 'avg_line_length': 26.0625, 'alnum_prop': 0.7070914696813977, 'repo_name': 'prasi-in/geode', 'id': '837d99e52b914f5fbd01927a68ff6ce39517babf', 'size': '3708', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'geode-core/src/main/java/org/apache/geode/management/internal/configuration/messages/ConfigurationRequest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '106707'}, {'name': 'Groovy', 'bytes': '2928'}, {'name': 'HTML', 'bytes': '3984628'}, {'name': 'Java', 'bytes': '26703981'}, {'name': 'JavaScript', 'bytes': '1781013'}, {'name': 'Ruby', 'bytes': '6751'}, {'name': 'Scala', 'bytes': '236402'}, {'name': 'Shell', 'bytes': '43900'}]} |
import React, { Component } from "react";
import CSSModules from "react-css-modules";
import styles from "../css/FontAwesomeIconBox.css";
class FontAwesomeIconBox extends Component {
render() {
return (
<div className="col-md-3 col-sm-6 col-xs-12">
<div styleName="feature-box">
<div styleName="icon">
<span className={this.props.icon} />
</div>
<h3>{this.props.header}</h3>
<p>{this.props.description}</p>
</div>
</div>
);
}
}
export default CSSModules(FontAwesomeIconBox, styles);
| {'content_hash': '4b488bbfb0df61b2f71885b4500e847d', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 54, 'avg_line_length': 26.73913043478261, 'alnum_prop': 0.5772357723577236, 'repo_name': 'jeffshek/betterself', 'id': '173013d0e6944a72b0b0d020b9b5377ab509d2f6', 'size': '615', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/js/home/components/FontAwesomeIconBox.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '430527'}, {'name': 'HTML', 'bytes': '26382'}, {'name': 'JavaScript', 'bytes': '232349'}, {'name': 'Python', 'bytes': '525014'}, {'name': 'Shell', 'bytes': '6298'}]} |
<?php
$callback = mysql_real_escape_string($_GET['callback']);
$link = mysql_connect("localhost","DB_User","Password") or die($callback."(".json_encode("Cannot connect to the server!").")");
mysql_select_db("DB_Name",$link) or die($callback."(".json_encode("Cannot connect to the database!").")");
$method = mysql_real_escape_string($_GET['method']);
switch ($method)
{
case getFact:
getFact();
break;
case setFact:
setFact();
break;
case getSurveyForEdit:
getSurveyForEdit();
break;
case getSurveyForTest:
getSurveyForTest();
break;
case getSurveyCodes:
getSurveyCodes();
break;
case setSurvey:
setSurvey();
break;
case getAgeList:
getAgeList();
break;
case getCityStateList:
getCityStateList();
break;
case getEthnicityList:
getEthnicityList();
break;
case getGenderList:
getGenderList();
break;
case setUser:
setUser();
break;
case test:
test();
break;
default:
die($callback."(".json_encode("Could not find the specified method!").")");
}
@mysql_close($link);
function getFact()
{
$callback = mysql_real_escape_string($_GET['callback']);
$code = mysql_real_escape_string($_GET['code']);
if($code == "") die($callback."(".json_encode("No code found!").")");
$query = "SELECT s.SURVEY_TITLE, cd.CARD_DESC, ct.CATEGORY_DESC FROM FACT_TABLE f INNER JOIN CARD_TABLE cd ON cd.CARD_ID = f.CARD_ID INNER JOIN CATEGORY_TABLE ct ON ct.CATEGORY_ID = f.CATEGORY_ID INNER JOIN USER_TABLE u ON f.USER_ID = u.USER_ID INNER JOIN SURVEY_TABLE s ON s.SURVEY_ID = f.SURVEY_ID AND s.SURVEY_CODE='".$code."'";
$gender = mysql_real_escape_string($_GET['gender']);
if($gender != "")
{
$query = $query." INNER JOIN GENDER_TABLE g ON g.GENDER_ID = u.GENDER_ID AND g.GENDER_DESC='".$gender."'";
}
$age = mysql_real_escape_string($_GET['age']);
if($age != "")
{
$query = $query." INNER JOIN AGE_TABLE a ON a.AGE_ID = u.AGE_ID AND a.AGE_DESC='".$age."'";
}
$ethnicity = mysql_real_escape_string($_GET['ethnicity']);
if($ethnicity != "")
{
$query = $query." INNER JOIN ETHNICITY_TABLE e ON e.ETHNICITY_ID = u.ETHNICITY_ID AND e.ETHNICITY_DESC='".$ethnicity."'";
}
$city = mysql_real_escape_string($_GET['city']);
$state = mysql_real_escape_string($_GET['state']);
if($city == "" && $state != "")
{
$query = $query." INNER JOIN CITY_STATE_TABLE cs ON cs.CITY_STATE_ID = u.CITY_STATE_ID AND cs.STATE_DESC='".$state."'";
}
else if($city != "" && $state != "")
{
$query = $query." INNER JOIN CITY_STATE_TABLE cs ON cs.CITY_STATE_ID = u.CITY_STATE_ID AND cs.STATE_DESC='".$state."' AND cs.CITY_DESC='".$city."'";
}
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function setFact()
{
$callback = mysql_real_escape_string($_GET['callback']);
$card = mysql_real_escape_string($_GET['card']);
if($card == "") die($callback."(".json_encode("No card found!").")");
$query = "SELECT CARD_ID FROM CARD_TABLE WHERE CARD_DESC='".$card."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$cardId = $row['CARD_ID'];
}
if(is_null($cardId))
{
$query = "INSERT INTO CARD_TABLE (CARD_DESC) VALUES ('".$card."')";
mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$query = "SELECT CARD_ID FROM CARD_TABLE WHERE CARD_DESC='".$card."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$cardId = $row['CARD_ID'];
}
}
$category = mysql_real_escape_string($_GET['category']);
if($category == "") die($callback."(".json_encode("No category found!").")");
$query = "SELECT CATEGORY_ID FROM CATEGORY_TABLE WHERE CATEGORY_DESC='".$category."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$categoryId = $row['CATEGORY_ID'];
}
if($categoryId == "")
{
$query = "INSERT INTO CATEGORY_TABLE (CATEGORY_DESC) VALUES ('".$category."')";
mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$query = "SELECT CATEGORY_ID FROM CATEGORY_TABLE WHERE CATEGORY_DESC='".$category."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$categoryId = $row['CATEGORY_ID'];
}
}
$code = mysql_real_escape_string($_GET['code']);
if($code == "") die($callback."(".json_encode("No code found!").")");
$query = "SELECT SURVEY_ID, EDITABLE_IDEN FROM SURVEY_TABLE WHERE SURVEY_CODE='".$code."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$surveyId = $row['SURVEY_ID'];
$editable = $row['EDITABLE_IDEN'];
}
if($editable == 1)
{
$query = "UPDATE SURVEY_TABLE SET EDITABLE_IDEN=0 WHERE SURVEY_ID=".$surveyId;
mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
}
$userId = mysql_real_escape_string($_GET['userId']);
if($userId == "") $userId = 1;
$query = "INSERT INTO FACT_TABLE (CARD_ID, CATEGORY_ID, SURVEY_ID, USER_ID) VALUES (".$cardId.", ".$categoryId.", ".$surveyId.", ".$userId.")";
mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
echo $callback."(".json_encode("Set fact successful!").")";
}
function getSurveyForEdit()
{
$callback = mysql_real_escape_string($_GET['callback']);
$password = mysql_real_escape_string($_GET['password']);
if($password == "") die($callback."(".json_encode("No password found!").")");
$code = mysql_real_escape_string($_GET['code']);
if($code == "") die($callback."(".json_encode("No code found!").")");
$query = "SELECT DEMOGRAPHICS_IDEN, EDITABLE_IDEN, SURVEY_TITLE, SURVEY_EMAIL, SURVEY_COMMENTS, SURVEY_CARDS, SURVEY_CATEGORIES FROM SURVEY_TABLE WHERE SURVEY_PASS='".$password."' AND SURVEY_CODE='".$code."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function getSurveyForTest()
{
$callback = mysql_real_escape_string($_GET['callback']);
$code = mysql_real_escape_string($_GET['code']);
if($code == "") die($callback."(".json_encode("No code found!").")");
$query = "SELECT DEMOGRAPHICS_IDEN, SURVEY_TITLE, SURVEY_EMAIL, SURVEY_COMMENTS, SURVEY_CARDS, SURVEY_CATEGORIES FROM SURVEY_TABLE WHERE SURVEY_CODE='".$code."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function getSurveyCodes()
{
$callback = mysql_real_escape_string($_GET['callback']);
$query = "SELECT SURVEY_CODE FROM SURVEY_TABLE";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function setSurvey()
{
$callback = mysql_real_escape_string($_GET['callback']);
$demographics = mysql_real_escape_string($_GET['demographics']);
if($demographics == "") $demographics = 1;
$code = mysql_real_escape_string($_GET['code']);
if($code == "") die($callback."(".json_encode("No code found!").")");
$password = mysql_real_escape_string($_GET['password']);
$email = mysql_real_escape_string($_GET['email']);
$title = mysql_real_escape_string($_GET['title']);
$comments = mysql_real_escape_string($_GET['comments']);
$cards = mysql_real_escape_string($_GET['cards']);
$categories = mysql_real_escape_string($_GET['categories']);
$query = "SELECT SURVEY_ID FROM SURVEY_TABLE WHERE SURVEY_CODE='".$code."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$surveyId = $row['SURVEY_ID'];
}
if($surveyId == "")
{
$query = "INSERT INTO SURVEY_TABLE (DEMOGRAPHICS_IDEN, EDITABLE_IDEN, SURVEY_CODE, SURVEY_PASS, SURVEY_EMAIL, SURVEY_TITLE, SURVEY_COMMENTS, SURVEY_CARDS, SURVEY_CATEGORIES) VALUES (".$demographics.", 1, '".$code."', '".$password."', '".$email."', '".$title."', '".$comments."', '".$cards."', '".$categories."')";
}
else
{
$query = "UPDATE SURVEY_TABLE SET DEMOGRAPHICS_IDEN=".$demographics.", SURVEY_PASS='".$password."', SURVEY_EMAIL='".$email."', SURVEY_TITLE='".$title."', SURVEY_COMMENTS='".$comments."', SURVEY_CARDS='".$cards."', SURVEY_CATEGORIES='".$categories."' WHERE SURVEY_ID=".$surveyId;
}
mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
echo $callback."(".json_encode("Set survey successful!").")";
}
function getAgeList()
{
$callback = mysql_real_escape_string($_GET['callback']);
$query = "SELECT AGE_DESC FROM AGE_TABLE";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function getCityStateList()
{
$callback = mysql_real_escape_string($_GET['callback']);
$query = "SELECT CITY_DESC, STATE_DESC FROM CITY_STATE_TABLE";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function getEthnicityList()
{
$callback = mysql_real_escape_string($_GET['callback']);
$query = "SELECT ETHNICITY_DESC FROM ETHNICITY_TABLE";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function getGenderList()
{
$callback = mysql_real_escape_string($_GET['callback']);
$query = "SELECT GENDER_DESC FROM GENDER_TABLE";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$table = array();
while($row = mysql_fetch_assoc($result))
{
$table[] = array("row"=>$row);
}
echo $callback."(".json_encode(array("table"=>$table)).")";
}
function setUser()
{
$callback = mysql_real_escape_string($_GET['callback']);
$gender = mysql_real_escape_string($_GET['gender']);
if($gender == "") $gender = "UNKNOWN";
$query = "SELECT GENDER_ID FROM GENDER_TABLE WHERE GENDER_DESC='".$gender."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$genderId = $row['GENDER_ID'];
}
$age = mysql_real_escape_string($_GET['age']);
if($age == "") $age = "UNKNOWN";
$query = "SELECT AGE_ID FROM AGE_TABLE WHERE AGE_DESC='".$age."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$ageId = $row['AGE_ID'];
}
$ethnicity = mysql_real_escape_string($_GET['ethnicity']);
if($ethnicity == "") $ethnicity = "UNKNOWN";
$query = "SELECT ETHNICITY_ID FROM ETHNICITY_TABLE WHERE ETHNICITY_DESC='".$ethnicity."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$ethnicityId = $row['ETHNICITY_ID'];
}
$city = mysql_real_escape_string($_GET['city']);
if($city == "") $city = "UNKNOWN";
$state = mysql_real_escape_string($_GET['state']);
if($state == "") $state = "UNKNOWN";
$query = "SELECT CITY_STATE_ID FROM CITY_STATE_TABLE WHERE CITY_DESC='".$city."' AND STATE_DESC='".$state."'";
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$cityStateId = $row['CITY_STATE_ID'];
}
$query = "SELECT USER_ID FROM USER_TABLE WHERE GENDER_ID=".$genderId." AND AGE_ID=".$ageId." AND ETHNICITY_ID=".$ethnicityId." AND CITY_STATE_ID=".$cityStateId;
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$userId = $row['USER_ID'];
}
if($userId == "")
{
$query = "INSERT INTO USER_TABLE (GENDER_ID, AGE_ID, ETHNICITY_ID, CITY_STATE_ID) VALUES (".$genderId.", ".$ageId.", ".$ethnicityId.", ".$cityStateId.")";
mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
$query = "SELECT USER_ID FROM USER_TABLE WHERE GENDER_ID=".$genderId." AND AGE_ID=".$ageId." AND ETHNICITY_ID=".$ethnicityId." AND CITY_STATE_ID=".$cityStateId;
$result = mysql_query($query) or die($callback."(".json_encode("Query at database failed! ".$query).")");
while($row = mysql_fetch_array($result))
{
$userId = $row['USER_ID'];
}
}
echo $callback."(".json_encode("Set user successful! USER_ID=".$userId).")";
}
function test()
{
$callback = mysql_real_escape_string($_GET['callback']);
echo $callback."(".json_encode("Test function is successful!").")";
}
?>
| {'content_hash': '4a6dfe681b039e703b176503038f90c3', 'timestamp': '', 'source': 'github', 'line_count': 345, 'max_line_length': 332, 'avg_line_length': 40.0231884057971, 'alnum_prop': 0.640715527230591, 'repo_name': 'albs22/wisc-card-sort', 'id': '7da33fc661fdd15a557586deb7ccfa73bc7dd474', 'size': '13808', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'webservice.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8974'}, {'name': 'JavaScript', 'bytes': '1625247'}, {'name': 'PHP', 'bytes': '13808'}]} |
var args = arguments[0] || {};
var convex_hull = require(WPATH('convex_hull'));
var convexHull = new convex_hull;
var useConvexHull = true;
$.allPoints = $.hullPoints = [];
var mapRegion;
var route;
var drawableWidth;
var drawableHeight;
var topLeftLat;
var topLeftLon;
var widthRatio;
var heightRatio;
var lineColor ='#c60000';
var lineWidth =4;
var throttleTimer=75;
var routeAdded = false;
var handlers = {};
handlers.drawStart = function(r){};
handlers.drawEnd = function(r){};
exports.addEventListener = function(listenerName, listenerFunction){
switch(listenerName){
case 'drawStart' :
handlers.drawStart = listenerFunction;
break;
case 'drawEnd' :
handlers.drawEnd = listenerFunction;
break;
};
};
$.init = function(args){
_args = args || {};
$.TiDrawableMapView.region = typeof(_args.mapRegion) != "undefined"?_args.mapRegion:mapRegion;
if(typeof(_args.lineColor) != "undefined")lineColor = _args.lineColor;
if(typeof(_args.lineWidth) != "undefined")lineWidth = _args.lineWidth;
if(typeof(_args.throttleTimer) != "undefined")throttleTimer = _args.throttleTimer;
};
$.setSizes = function() {
if (OS_ANDROID) {
//if we do not call this info line then we get the wong sizes for width/height
//do no comment out the info
Ti.API.info($.TiDrawableMapDrawingView.toImage().height + ' >> ' + $.TiDrawableMapDrawingView.toImage().width );
drawableWidth = $.TiDrawableMapDrawingView.toImage().width;
drawableHeight = $.TiDrawableMapDrawingView.toImage().height;
}else{
drawableWidth = $.TiDrawableMapDrawingView.size.width;
drawableHeight = $.TiDrawableMapDrawingView.size.height;
}
Ti.API.info('set sizes::: drawableWidth: '+drawableWidth+' drawableHeight: '+drawableHeight);
};
$.clearRoute = function(){
if(routeAdded){$.TiDrawableMapView.removeRoute(route);}
routeAdded = false;
};
$.startDraw = function(args){
var _args = args || {};
if(typeof(_args.useConvexHull) != "undefined"){useConvexHull = _args.useConvexHull;}
if(typeof(_args.lineColor) != "undefined"){lineColor = _args.lineColor;}
if(typeof(_args.lineWidth) != "undefined"){lineWidth = _args.lineWidth;}
if(typeof(_args.throttleTimer) != "undefined"){throttleTimer = _args.throttleTimer;}
$.allPoints.length = $.hullPoints.length = 0;
if(routeAdded){
$.TiDrawableMapView.removeRoute(route);
}
//touchenabled would not work on android se had to fall back to using zindexes
$.TiDrawableMapDrawingView.zIndex = 3;
routeAdded = false;
};
$.TiDrawableMapView.addEventListener('regionchanged',function(e){
mapRegion = e;
topLeftLat = mapRegion.latitude + (mapRegion.latitudeDelta/2);
topLeftLon = mapRegion.longitude - (mapRegion.longitudeDelta/2);
widthRatio = mapRegion.longitudeDelta/drawableWidth;
heightRatio = mapRegion.latitudeDelta/drawableHeight;
Ti.API.info('regionchanged::: topLeftLat: '+topLeftLat+' topLeftLon: '+topLeftLon+' topLeftLon: '+widthRatio+' heightRatio: '+heightRatio);
});
$.TiDrawableMapDrawingView.addEventListener('touchstart',function(e){
handlers.drawStart();
addPoint(e);
});
//Workaround for https://jira.appcelerator.org/browse/TIMOB-14213
if (OS_ANDROID) {
getTime = (Date.now ||
function() {
return new Date().getTime();
});
// Monkey patch throttle and debounce to fix bug in throttle function on
// Titanium (3.2.0.GA) Android.
_.throttle = function(func, wait, options) {
var context, args, result, timeout, previous, later;
timeout = null;
previous = 0;
options = options || {};
later = function() {
previous = options.leading === false ? 0 : getTime();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now, remaining;
now = getTime();
if (!previous && options.leading === false) {
previous = now;
}
remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result, later = function() {
var last = getTime() - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
}
};
return function() {
var callNow = immediate && !timeout;
context = this;
args = arguments;
timestamp = getTime();
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
}
function finalizeDraw(){
if(useConvexHull){
calculateConvexHull();
}
handlers.drawEnd();
}
$.TiDrawableMapDrawingView.addEventListener('touchend',function(e){
//touch enabled would not work on android so had to use zindexes
$.TiDrawableMapDrawingView.zIndex = 1;
setTimeout(finalizeDraw,throttleTimer*1.25);
});
var touchMove = _.throttle(function(e){addPoint(e)},throttleTimer)
$.TiDrawableMapDrawingView.addEventListener('touchmove',touchMove);
function addPoint(e){
Ti.API.info(e.x+','+e.y);
Ti.API.info(topLeftLat+','+topLeftLon);
Ti.API.info(heightRatio+','+widthRatio);
$.allPoints.push({
latitude: (topLeftLat-(e.y*heightRatio)),
longitude: (topLeftLon+(e.x*widthRatio))
});
addDrawing();
}
function addDrawing(drawPoints){
if(routeAdded){
$.TiDrawableMapView.removeRoute(route);
}
route = Alloy.Globals.Map.createRoute({
name: 'TiDrawableMapRoute',
points: typeof(drawPoints) != "undefined"?drawPoints:$.allPoints,
color: lineColor,
width: lineWidth
});
$.TiDrawableMapView.addRoute(route);
routeAdded=true;
}
function calculateConvexHull() {
$.hullPoints = convexHull.convex_hull($.allPoints);
addDrawing($.hullPoints);
Ti.API.info(JSON.stringify($.allPoints));
Ti.API.info(JSON.stringify($.hullPoints));
}
| {'content_hash': 'df700793d3172e53f9ca12f55bc38d5e', 'timestamp': '', 'source': 'github', 'line_count': 229, 'max_line_length': 140, 'avg_line_length': 26.895196506550217, 'alnum_prop': 0.6864750771229096, 'repo_name': 'appcelerator-training/x-platform', 'id': 'e74849f7029b0e18b0f8a81653caaaf7ed2b361d', 'size': '6159', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/widgets/com.n3wc.TiDrawableMap/controllers/widget.js', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '5942'}, {'name': 'Erlang', 'bytes': '878'}, {'name': 'Java', 'bytes': '1230'}, {'name': 'JavaScript', 'bytes': '625007'}, {'name': 'Perl', 'bytes': '8226'}, {'name': 'Python', 'bytes': '24046'}, {'name': 'R', 'bytes': '420'}, {'name': 'Shell', 'bytes': '194'}]} |
package net
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"os"
"reflect"
"runtime"
"strings"
"testing"
"k8s.io/kubernetes/pkg/util/sets"
)
func TestCloneTLSConfig(t *testing.T) {
expected := sets.NewString(
// These fields are copied in CloneTLSConfig
"Rand",
"Time",
"Certificates",
"RootCAs",
"NextProtos",
"ServerName",
"InsecureSkipVerify",
"CipherSuites",
"PreferServerCipherSuites",
"MinVersion",
"MaxVersion",
"CurvePreferences",
"NameToCertificate",
"GetCertificate",
"ClientAuth",
"ClientCAs",
"ClientSessionCache",
// These fields are not copied
"SessionTicketsDisabled",
"SessionTicketKey",
// These fields are unexported
"serverInitOnce",
"mutex",
"sessionTicketKeys",
)
// See #33936.
if strings.HasPrefix(runtime.Version(), "go1.7") {
expected.Insert("DynamicRecordSizingDisabled", "Renegotiation")
}
fields := sets.NewString()
structType := reflect.TypeOf(tls.Config{})
for i := 0; i < structType.NumField(); i++ {
fields.Insert(structType.Field(i).Name)
}
if missing := expected.Difference(fields); len(missing) > 0 {
t.Errorf("Expected fields that were not seen in http.Transport: %v", missing.List())
}
if extra := fields.Difference(expected); len(extra) > 0 {
t.Errorf("New fields seen in http.Transport: %v\nAdd to CopyClientTLSConfig if client-relevant, then add to expected list in TestCopyClientTLSConfig", extra.List())
}
}
func TestGetClientIP(t *testing.T) {
ipString := "10.0.0.1"
ip := net.ParseIP(ipString)
invalidIPString := "invalidIPString"
testCases := []struct {
Request http.Request
ExpectedIP net.IP
}{
{
Request: http.Request{},
},
{
Request: http.Request{
Header: map[string][]string{
"X-Real-Ip": {ipString},
},
},
ExpectedIP: ip,
},
{
Request: http.Request{
Header: map[string][]string{
"X-Real-Ip": {invalidIPString},
},
},
},
{
Request: http.Request{
Header: map[string][]string{
"X-Forwarded-For": {ipString},
},
},
ExpectedIP: ip,
},
{
Request: http.Request{
Header: map[string][]string{
"X-Forwarded-For": {invalidIPString},
},
},
},
{
Request: http.Request{
Header: map[string][]string{
"X-Forwarded-For": {invalidIPString + "," + ipString},
},
},
ExpectedIP: ip,
},
{
Request: http.Request{
// RemoteAddr is in the form host:port
RemoteAddr: ipString + ":1234",
},
ExpectedIP: ip,
},
{
Request: http.Request{
RemoteAddr: invalidIPString,
},
},
{
Request: http.Request{
Header: map[string][]string{
"X-Forwarded-For": {invalidIPString},
},
// RemoteAddr is in the form host:port
RemoteAddr: ipString,
},
ExpectedIP: ip,
},
}
for i, test := range testCases {
if a, e := GetClientIP(&test.Request), test.ExpectedIP; reflect.DeepEqual(e, a) != true {
t.Fatalf("test case %d failed. expected: %v, actual: %v", i, e, a)
}
}
}
func TestProxierWithNoProxyCIDR(t *testing.T) {
testCases := []struct {
name string
noProxy string
url string
expectedDelegated bool
}{
{
name: "no env",
url: "https://192.168.143.1/api",
expectedDelegated: true,
},
{
name: "no cidr",
noProxy: "192.168.63.1",
url: "https://192.168.143.1/api",
expectedDelegated: true,
},
{
name: "hostname",
noProxy: "192.168.63.0/24,192.168.143.0/24",
url: "https://my-hostname/api",
expectedDelegated: true,
},
{
name: "match second cidr",
noProxy: "192.168.63.0/24,192.168.143.0/24",
url: "https://192.168.143.1/api",
expectedDelegated: false,
},
{
name: "match second cidr with host:port",
noProxy: "192.168.63.0/24,192.168.143.0/24",
url: "https://192.168.143.1:8443/api",
expectedDelegated: false,
},
}
for _, test := range testCases {
os.Setenv("NO_PROXY", test.noProxy)
actualDelegated := false
proxyFunc := NewProxierWithNoProxyCIDR(func(req *http.Request) (*url.URL, error) {
actualDelegated = true
return nil, nil
})
req, err := http.NewRequest("GET", test.url, nil)
if err != nil {
t.Errorf("%s: unexpected err: %v", test.name, err)
continue
}
if _, err := proxyFunc(req); err != nil {
t.Errorf("%s: unexpected err: %v", test.name, err)
continue
}
if test.expectedDelegated != actualDelegated {
t.Errorf("%s: expected %v, got %v", test.name, test.expectedDelegated, actualDelegated)
continue
}
}
}
| {'content_hash': '95dc6bf4068c7f35300605f920dd60d5', 'timestamp': '', 'source': 'github', 'line_count': 211, 'max_line_length': 166, 'avg_line_length': 22.04739336492891, 'alnum_prop': 0.6038263112639725, 'repo_name': 'aclisp/kubernetes', 'id': '9709c29129e511a7b1a932f2ae74d50ee141efda', 'size': '5221', 'binary': False, 'copies': '1', 'ref': 'refs/heads/release-1.4', 'path': 'pkg/util/net/http_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '978'}, {'name': 'Go', 'bytes': '43478458'}, {'name': 'HTML', 'bytes': '2249497'}, {'name': 'Makefile', 'bytes': '69888'}, {'name': 'Nginx', 'bytes': '1013'}, {'name': 'Protocol Buffer', 'bytes': '558624'}, {'name': 'Python', 'bytes': '48408'}, {'name': 'SaltStack', 'bytes': '56179'}, {'name': 'Shell', 'bytes': '1551221'}, {'name': 'nesC', 'bytes': '466'}]} |
"""
Read graphs in GML format.
"GML, the G>raph Modelling Language, is our proposal for a portable
file format for graphs. GML's key features are portability, simple
syntax, extensibility and flexibility. A GML file consists of a
hierarchical key-value lists. Graphs can be annotated with arbitrary
data structures. The idea for a common file format was born at the
GD'95; this proposal is the outcome of many discussions. GML is the
standard file format in the Graphlet graph editor system. It has been
overtaken and adapted by several other systems for drawing graphs."
See http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
Format
------
See http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
for format specification.
Example graphs in GML format:
http://www-personal.umich.edu/~mejn/netdata/
"""
__author__ = """Aric Hagberg ([email protected])"""
# Copyright (C) 2008-2010 by
# Aric Hagberg <[email protected]>
# Dan Schult <[email protected]>
# Pieter Swart <[email protected]>
# All rights reserved.
# BSD license.
__all__ = ['read_gml', 'parse_gml', 'generate_gml', 'write_gml']
try:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
except ImportError:
from io import StringIO
from ast import literal_eval
from collections import defaultdict
from lib2to3.pgen2.parse import ParseError
from lib2to3.pgen2.tokenize import TokenError
#from lib2to3.refactor import RefactoringTool
import networkx as nx
from networkx.exception import NetworkXError
from networkx.utils import open_file
import re
try:
import htmlentitydefs
except ImportError:
# Python 3.x
import html.entities as htmlentitydefs
try:
long
except NameError:
long = int
try:
unicode
except NameError:
unicode = str
try:
unichr
except NameError:
unichr = chr
try:
literal_eval(r"u'\u4444'")
except SyntaxError:
# Remove 'u' prefixes in unicode literals in Python 3
rtp_fix_unicode = None
#RefactoringTool(['lib2to3.fixes.fix_unicode'],
# {'print_function': True})
else:
rtp_fix_unicode = None
def escape(text):
"""Escape unprintable or non-ASCII characters, double quotes and ampersands
in a string using XML character references.
"""
def fixup(m):
ch = m.group(0)
return '&#' + str(ord(ch)) + ';'
text = re.sub('[^ -~]|[&"]', fixup, text)
return text if isinstance(text, str) else str(text)
def unescape(text):
"""Replace XML character references in a string with the referenced
characters.
"""
def fixup(m):
text = m.group(0)
if text[1] == '#':
# Character reference
if text[2] == 'x':
code = int(text[3:-1], 16)
else:
code = int(text[2:-1])
else:
# Named entity
try:
code = htmlentitydefs.name2codepoint[text[1:-1]]
except KeyError:
return text # leave unchanged
try:
return chr(code) if code < 256 else unichr(code)
except (ValueError, OverflowError):
return text # leave unchanged
return re.sub("&(?:[0-9A-Za-z]+|#(?:[0-9]+|x[0-9A-Fa-f]+));", fixup, text)
def literal_destringizer(rep):
"""Convert a Python literal to the value it represents.
Parameters
----------
rep : string
A Python literal.
Returns
-------
value : object
The value of the Python literal.
Raises
------
ValueError
If ``rep`` is not a Python literal.
"""
if isinstance(rep, (str, unicode)):
orig_rep = rep
try:
# Python 3.2 does not recognize 'u' prefixes before string literals
if rtp_fix_unicode:
rep = str(rtp_fix_unicode.refactor_string(
rep + '\n', '<string>'))[:-1]
return literal_eval(rep)
except (ParseError, SyntaxError, TokenError):
raise ValueError('%r is not a valid Python literal' % (orig_rep,))
else:
raise ValueError('%r is not a string' % (rep,))
@open_file(0, mode='rb')
def read_gml(path, label='label', destringizer=None):
"""Read graph in GML format from path.
Parameters
----------
path : filename or filehandle
The filename or filehandle to read from.
label : string, optional
If not None, the parsed nodes will be renamed according to node
attributes indicated by ``label``. Default value: ``'label'``.
destringizer : callable, optional
A destringizer that recovers values stored as strings in GML. If it
cannot convert a string to a value, a ``ValueError`` is raised. Default
value : ``None``.
Returns
-------
G : NetworkX graph
The parsed graph.
Raises
------
NetworkXError
If the input cannot be parsed.
See Also
--------
write_gml, parse_gml
Notes
-----
The GML specification says that files should be ASCII encoded, with any
extended ASCII characters (iso8859-1) appearing as HTML character entities.
References
----------
GML specification:
http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_gml(G, 'test.gml')
>>> H = nx.read_gml('test.gml')
"""
def filter_lines(lines):
for line in lines:
try:
line = line.decode('ascii')
except UnicodeDecodeError:
raise NetworkXError('input is not ASCII-encoded')
if not isinstance(line, str):
lines = str(lines)
if line and line[-1] == '\n':
line = line[:-1]
yield line
G = parse_gml_lines(filter_lines(path), label, destringizer)
return G
def parse_gml(lines, label='label', destringizer=None):
"""Parse GML graph from a string or iterable.
Parameters
----------
lines : string or iterable of strings
Data in GML format.
label : string, optional
If not None, the parsed nodes will be renamed according to node
attributes indicated by ``label``. Default value: ``'label'``.
destringizer : callable, optional
A destringizer that recovers values stored as strings in GML. If it
cannot convert a string to a value, a ``ValueError`` is raised. Default
value : ``None``.
Returns
-------
G : NetworkX graph
The parsed graph.
Raises
------
NetworkXError
If the input cannot be parsed.
See Also
--------
write_gml, read_gml
Notes
-----
This stores nested GML attributes as dictionaries in the
NetworkX graph, node, and edge attribute structures.
References
----------
GML specification:
http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html
"""
def decode_line(line):
if isinstance(line, bytes):
try:
line.decode('ascii')
except UnicodeDecodeError:
raise NetworkXError('input is not ASCII-encoded')
if not isinstance(line, str):
line = str(line)
return line
def filter_lines(lines):
if isinstance(lines, (str, unicode)):
lines = decode_line(lines)
lines = lines.splitlines()
for line in lines:
yield line
else:
for line in lines:
line = decode_line(line)
if line and line[-1] == '\n':
line = line[:-1]
if line.find('\n') != -1:
raise NetworkXError('input line contains newline')
yield line
G = parse_gml_lines(filter_lines(lines), label, destringizer)
return G
def parse_gml_lines(lines, label, destringizer):
"""Parse GML into a graph.
"""
def tokenize():
patterns = [
r'[A-Za-z][0-9A-Za-z]*\s+', # keys
r'[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)(?:[Ee][+-]?[0-9]+)?', # reals
r'[+-]?[0-9]+', # ints
r'".*?"', # strings
r'\[', # dict start
r'\]', # dict end
r'#.*$|\s+' # comments and whitespaces
]
tokens = re.compile(
'|'.join('(' + pattern + ')' for pattern in patterns))
lineno = 0
for line in lines:
length = len(line)
pos = 0
while pos < length:
match = tokens.match(line, pos)
if match is not None:
for i in range(len(patterns)):
group = match.group(i + 1)
if group is not None:
if i == 0: # keys
value = group.rstrip()
elif i == 1: # reals
value = float(group)
elif i == 2: # ints
value = int(group)
else:
value = group
if i != 6: # comments and whitespaces
yield (i, value, lineno + 1, pos + 1)
pos += len(group)
break
else:
raise NetworkXError('cannot tokenize %r at (%d, %d)' %
(line[pos:], lineno + 1, pos + 1))
lineno += 1
yield (None, None, lineno + 1, 1) # EOF
def unexpected(curr_token, expected):
type, value, lineno, pos = curr_token
raise NetworkXError(
'expected %s, found %s at (%d, %d)' %
(expected, repr(value) if value is not None else 'EOF', lineno,
pos))
def consume(curr_token, type, expected):
if curr_token[0] == type:
return next(tokens)
unexpected(curr_token, expected)
def parse_kv(curr_token):
dct = defaultdict(list)
while curr_token[0] == 0: # keys
key = curr_token[1]
curr_token = next(tokens)
type = curr_token[0]
if type == 1 or type == 2: # reals or ints
value = curr_token[1]
curr_token = next(tokens)
elif type == 3: # strings
value = unescape(curr_token[1][1:-1])
if destringizer:
try:
value = destringizer(value)
except ValueError:
pass
curr_token = next(tokens)
elif type == 4: # dict start
curr_token, value = parse_dict(curr_token)
else:
unexpected(curr_token, "an int, float, string or '['")
dct[key].append(value)
dct = {key: (value if not isinstance(value, list) or len(value) != 1
else value[0]) for key, value in dct.items()}
return curr_token, dct
def parse_dict(curr_token):
curr_token = consume(curr_token, 4, "'['") # dict start
curr_token, dct = parse_kv(curr_token)
curr_token = consume(curr_token, 5, "']'") # dict end
return curr_token, dct
def parse_graph():
curr_token, dct = parse_kv(next(tokens))
if curr_token[0] is not None: # EOF
unexpected(curr_token, 'EOF')
if 'graph' not in dct:
raise NetworkXError('input contains no graph')
graph = dct['graph']
if isinstance(graph, list):
raise NetworkXError('input contains more than one graph')
return graph
tokens = tokenize()
graph = parse_graph()
directed = graph.pop('directed', False)
multigraph = graph.pop('multigraph', False)
if not multigraph:
G = nx.DiGraph() if directed else nx.Graph()
else:
G = nx.MultiDiGraph() if directed else nx.MultiGraph()
G.graph.update((key, value) for key, value in graph.items()
if key != 'node' and key != 'edge')
def pop_attr(dct, type, attr, i):
try:
return dct.pop(attr)
except KeyError:
raise NetworkXError(
"%s #%d has no '%s' attribute" % (type, i, attr))
nodes = graph.get('node', [])
mapping = {}
labels = set()
for i, node in enumerate(nodes if isinstance(nodes, list) else [nodes]):
id = pop_attr(node, 'node', 'id', i)
if id in G:
raise NetworkXError('node id %r is duplicated' % (id,))
if label != 'id':
label = pop_attr(node, 'node', 'label', i)
if label in labels:
raise NetworkXError('node label %r is duplicated' % (label,))
labels.add(label)
mapping[id] = label
G.add_node(id, node)
edges = graph.get('edge', [])
for i, edge in enumerate(edges if isinstance(edges, list) else [edges]):
source = pop_attr(edge, 'edge', 'source', i)
target = pop_attr(edge, 'edge', 'target', i)
if source not in G:
raise NetworkXError(
'edge #%d has an undefined source %r' % (i, source))
if target not in G:
raise NetworkXError(
'edge #%d has an undefined target %r' % (i, target))
if not multigraph:
if not G.has_edge(source, target):
G.add_edge(source, target, edge)
else:
raise nx.NetworkXError(
'edge #%d (%r%s%r) is duplicated' %
(i, source, '->' if directed else '--', target))
else:
key = edge.pop('key', None)
if key is not None and G.has_edge(source, target, key):
raise nx.NetworkXError(
'edge #%d (%r%s%r, %r) is duplicated' %
(i, source, '->' if directed else '--', target, key))
G.add_edge(source, target, key, edge)
if label != 'id':
G = nx.relabel_nodes(G, mapping)
if 'name' in graph:
G.graph['name'] = graph['name']
else:
del G.graph['name']
return G
def literal_stringizer(value):
"""Convert a value to a Python literal in GML representation.
Parameters
----------
value : object
The value to be converted to GML representation.
Returns
-------
rep : string
A double-quoted Python literal representing value. Unprintable
characters are replaced by XML character references.
Raises
------
ValueError
If ``value`` cannot be converted to GML.
Notes
-----
``literal_stringizer`` is largely the same as ``repr`` in terms of
functionality but attempts prefix ``unicode`` and ``bytes`` literals with
``u`` and ``b`` to provide better interoperability of data generated by
Python 2 and Python 3.
The original value can be recovered using the
``networkx.readwrite.gml.literal_destringizer`` function.
"""
def stringize(value):
if isinstance(value, (int, long, bool)) or value is None:
buf.write(str(value))
elif isinstance(value, unicode):
text = repr(value)
if text[0] != 'u':
try:
value.encode('latin1')
except UnicodeEncodeError:
text = 'u' + text
buf.write(text)
elif isinstance(value, (float, complex, str, bytes)):
buf.write(repr(value))
elif isinstance(value, list):
buf.write('[')
first = True
for item in value:
if not first:
buf.write(',')
else:
first = False
stringize(item)
buf.write(']')
elif isinstance(value, tuple):
if len(value) > 1:
buf.write('(')
first = True
for item in value:
if not first:
buf.write(',')
else:
first = False
stringize(item)
buf.write(')')
elif value:
buf.write('(')
stringize(value[0])
buf.write(',)')
else:
buf.write('()')
elif isinstance(value, dict):
buf.write('{')
first = True
for key, value in value.items():
if not first:
buf.write(',')
else:
first = False
stringize(key)
buf.write(':')
stringize(value)
buf.write('}')
elif isinstance(value, set):
buf.write('{')
first = True
for item in value:
if not first:
buf.write(',')
else:
first = False
stringize(item)
buf.write('}')
else:
raise ValueError(
'%r cannot be converted into a Python literal' % (value,))
buf = StringIO()
stringize(value)
return buf.getvalue()
def generate_gml(G, stringizer=None):
"""Generate a single entry of the graph G in GML format.
Parameters
----------
G : NetworkX graph
The graph to be converted to GML.
stringizer : callable, optional
A stringizer which converts non-int/float/dict values into strings. If
it cannot convert a value into a string, it should raise a
``ValueError`` raised to indicate that. Default value: ``None``.
Returns
-------
lines: generator of strings
Lines of GML data. Newlines are not appended.
Raises
------
NetworkXError
If ``stringizer`` cannot convert a value into a string, or the value to
convert is not a string while ``stringizer`` is ``None``.
Notes
-----
Graph attributes named ``'directed'``, ``'multigraph'``, ``'node'`` or
``'edge'``,node attributes named ``'id'`` or ``'label'``, edge attributes
named ``'source'`` or ``'target'`` (or ``'key'`` if ``G`` is a multigraph)
are ignored because these attribute names are used to encode the graph
structure.
"""
valid_keys = re.compile('^[A-Za-z][0-9A-Za-z]*$')
def stringize(key, value, ignored_keys, indent, in_list=False):
if not isinstance(key, (str, unicode)):
raise NetworkXError('%r is not a string' % (key,))
if not valid_keys.match(key):
raise NetworkXError('%r is not a valid key' % (key,))
if not isinstance(key, str):
key = str(key)
if key not in ignored_keys:
if isinstance(value, (int, long)):
yield indent + key + ' ' + str(value)
elif isinstance(value, float):
text = repr(value).upper()
# GML requires that a real literal contain a decimal point, but
# repr may not output a decimal point when the mantissa is
# integral and hence needs fixing.
epos = text.rfind('E')
if epos != -1 and text.find('.', 0, epos) == -1:
text = text[:epos] + '.' + text[epos:]
yield indent + key + ' ' + text
elif isinstance(value, dict):
yield indent + key + ' ['
next_indent = indent + ' '
for key, value in value.items():
for line in stringize(key, value, (), next_indent):
yield line
yield indent + ']'
elif isinstance(value, list) and value and not in_list:
next_indent = indent + ' '
for value in value:
for line in stringize(key, value, (), next_indent, True):
yield line
else:
if stringizer:
try:
value = stringizer(value)
except ValueError:
raise NetworkXError(
'%r cannot be converted into a string' % (value,))
if not isinstance(value, (str, unicode)):
raise NetworkXError('%r is not a string' % (value,))
yield indent + key + ' "' + escape(value) + '"'
multigraph = G.is_multigraph()
yield 'graph ['
# Output graph attributes
if G.is_directed():
yield ' directed 1'
if multigraph:
yield ' multigraph 1'
ignored_keys = {'directed', 'multigraph', 'node', 'edge'}
for attr, value in G.graph.items():
for line in stringize(attr, value, ignored_keys, ' '):
yield line
# Output node data
node_id = dict(zip(G, range(len(G))))
ignored_keys = {'id', 'label'}
for node, attrs in G.node.items():
yield ' node ['
yield ' id ' + str(node_id[node])
for line in stringize('label', node, (), ' '):
yield line
for attr, value in attrs.items():
for line in stringize(attr, value, ignored_keys, ' '):
yield line
yield ' ]'
# Output edge data
ignored_keys = {'source', 'target'}
kwargs = {'data': True}
if multigraph:
ignored_keys.add('key')
kwargs['keys'] = True
for e in G.edges_iter(**kwargs):
yield ' edge ['
yield ' source ' + str(node_id[e[0]])
yield ' target ' + str(node_id[e[1]])
if multigraph:
for line in stringize('key', e[2], (), ' '):
yield line
for attr, value in e[-1].items():
for line in stringize(attr, value, ignored_keys, ' '):
yield line
yield ' ]'
yield ']'
@open_file(1, mode='wb')
def write_gml(G, path, stringizer=None):
"""Write a graph ``G`` in GML format to the file or file handle ``path``.
Parameters
----------
G : NetworkX graph
The graph to be converted to GML.
path : filename or filehandle
The filename or filehandle to write. Files whose names end with .gz or
.bz2 will be compressed.
stringizer : callable, optional
A stringizer which converts non-int/non-float/non-dict values into
strings. If it cannot convert a value into a string, it should raise a
``ValueError`` to indicate that. Default value: ``None``.
Raises
------
NetworkXError
If ``stringizer`` cannot convert a value into a string, or the value to
convert is not a string while ``stringizer`` is ``None``.
See Also
--------
read_gml, generate_gml
Notes
-----
Graph attributes named ``'directed'``, ``'multigraph'``, ``'node'`` or
``'edge'``,node attributes named ``'id'`` or ``'label'``, edge attributes
named ``'source'`` or ``'target'`` (or ``'key'`` if ``G`` is a multigraph)
are ignored because these attribute names are used to encode the graph
structure.
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_gml(G, "test.gml")
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_gml(G, "test.gml.gz")
"""
for line in generate_gml(G, stringizer):
path.write((line + '\n').encode('ascii'))
# fixture for nose
def teardown_module(module):
import os
for fname in ['test.gml', 'test.gml.gz']:
if os.path.isfile(fname):
os.unlink(fname)
| {'content_hash': 'b11ef8d086a94d67a81eea89f43d9d73', 'timestamp': '', 'source': 'github', 'line_count': 726, 'max_line_length': 83, 'avg_line_length': 32.72038567493113, 'alnum_prop': 0.5277204798989686, 'repo_name': 'LumPenPacK/NetworkExtractionFromImages', 'id': '597364ef1bba509cd4b293452a71246e9f550e5a', 'size': '23773', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/readwrite/gml.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '1577'}, {'name': 'C', 'bytes': '3035840'}, {'name': 'C++', 'bytes': '147394619'}, {'name': 'CMake', 'bytes': '603'}, {'name': 'CSS', 'bytes': '4298'}, {'name': 'FORTRAN', 'bytes': '14321'}, {'name': 'HTML', 'bytes': '41126'}, {'name': 'Lex', 'bytes': '20920'}, {'name': 'Makefile', 'bytes': '350419'}, {'name': 'Python', 'bytes': '25507066'}, {'name': 'QMake', 'bytes': '22941'}, {'name': 'Shell', 'bytes': '19080'}, {'name': 'Yacc', 'bytes': '248826'}]} |
.cm-tab-panel {
background: #fff;
width: 306px;
position: absolute;
top: 5px;
right: 5px;
height: auto;
max-height: 98%;
overflow-y: hidden;
z-index: 1;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
-moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
-webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
}
.cm-embedded .cm-tab-panel {
float: none;
width: 100%;
z-index: 1;
border: none;
}
.cm-tabbed .cm-map-wrapper {
margin-left: 0 !important;
}
.cm-tabbed.cm-panel-left .cm-searchbox {
margin-left: 320px; /* Move the searchbox over to avoid the panel. */
}
.cm-tab-bar-container {
background: #444;
/* @alternate */ background-image:-webkit-linear-gradient(top, #555, #333);
/* @alternate */ background-image:linear-gradient(top, #555, #333);
color: #ddd;
position: relative;
z-index: 1;
white-space: nowrap;
overflow: hidden;
}
.cm-tab-bar-container * {
/* Prevent entire tab bar from becoming selected on mobile devices */
-webkit-tap-highlight-color: transparent;
-moz-user-select: none;
-webkit-user-select: none;
}
.cm-footer-shadow .cm-tab-panel {
box-shadow: 0 0 6px rgba(0,0,0,0.4);
}
.cm-footer-shadow .cm-tab-bar-container {
border-top: none;
}
.cm-tab-bar-buttons {
display: inline-block;
float: right;
height: 35px;
}
.cm-tab-panel-below .cm-tab-bar-buttons, .cm-touch .cm-tab-bar-buttons {
height: 42px;
}
.cm-tab-content {
overflow-x: visible;
overflow-y: auto;
-webkit-overflow-scrolling:touch;
}
.cm-panel-links a {
display: inline-block;
}
.cm-tab-content input[type=checkbox] {
margin-bottom: -2px;
}
.cm-tab-content::-webkit-scrollbar {
-webkit-appearance: none;
}
.cm-tab-content::-webkit-scrollbar:vertical {
width: 12px;
}
.cm-tab-content::-webkit-scrollbar-thumb {
border-radius: 6px;
border: 2px solid #fff;
background-color: #777;
}
.cm-feature-info-content {
margin: 12px;
font-family: arial !important; /* override Roboto specified by Maps API */
}
.cm-chevron-up:hover {
background-color: #121212;
/* @alternate */ background:url('chevron_up.png') center center no-repeat, -webkit-linear-gradient(top, #383838, #121212);
/* @alternate */ background:url('chevron_up.png') center center no-repeat, linear-gradient(top, #383838, #121212);
}
.cm-chevron-down:hover {
background-color: #121212;
/* @alternate */ background:url('chevron_down.png') center center no-repeat, -webkit-linear-gradient(top, #383838, #121212);
/* @alternate */ background:url('chevron_down.png') center center no-repeat, linear-gradient(top, #383838, #121212);
}
.cm-chevron-up, .cm-chevron-down {
width: 35px;
height: 35px;
padding: 0px;
margin: 0px;
cursor: pointer;
display: inline-block;
-moz-user-select: none;
-webkit-user-select: none;
}
.cm-chevron-up {
background:url('chevron_up.png') center center no-repeat;
}
.cm-chevron-down {
background: url('chevron_down.png') center center no-repeat;
}
.cm-tab-panel-below .cm-chevron-up, .cm-tab-panel-below .cm-chevron-down,
.cm-touch .cm-chevron-up, .cm-touch .cm-chevron-down {
width: 42px;
height: 42px;
}
.cm-tab-panel-below {
top: inherit !important;
width: inherit !important;
right: inherit !important;
left: inherit !important;
box-shadow: none;
position: relative;
max-height: none;
}
.cm-tab-panel-below .cm-tab-container {
border-bottom: none;
width: 100% !important;
}
.cm-tabbed.cm-panel-right .cm-my-location-button {
margin-right: 317px;
}
.cm-tabbed.cm-embedded .cm-my-location-button,
.cm-tabbed.cm-panel-below .cm-my-location-button {
margin-right: 5px !important;
}
.cm-panel-left .cm-tab-panel {
float: left;
left: 5px;
}
.cm-tab-content .cm-map-picker-button {
right: auto;
margin-left: 6px;
top: 0px;
position: relative;
}
.cm-tabbed-legend-box {
border-top: 1px solid #f0f0f0;
margin: 12px 0;
padding: 12px 12px 0 12px;
overflow: hidden; /* fully enclose any floating children */
}
.cm-tabbed-legend-box.cm-first-tabbed-legend-box {
border-top: 0px;
padding: 0 12px 0 12px;
}
.cm-tabbed-legend-content {
font-size: 11px;
color: #222;
margin: 6px 0 0;
}
.cm-tab-content .cm-legend-item {
font-size: 12px;
}
.cm-tab-panel .cm-panel-header {
margin: 12px 0px 6px 0px;
padding: 0px 12px;
}
.cm-tab-content .cm-legend-graphic {
margin: 2px 4px 4px 2px;
}
/*
* TODO(romano,rew): Basic rules copied from
* https://code.google.com/p/closure-library/source/browse/closure/goog/css/tab.css
* to be replaced with our own rules and merged into main.css.
*/
.goog-tab {
cursor: pointer;
padding: 12px 9px 11px;
font-size: 12px;
line-height: 1.0;
/* Transparent borders on every tab: makes room for border when selected */
border-left: 1px solid transparent;
border-right: 1px solid transparent;
}
.cm-tab-panel-below .goog-tab, .cm-touch .goog-tab {
padding: 14px;
font-size: 14px;
}
.goog-tab-bar {
outline: none;
display: block;
margin-right: 35px; /* makes room for chevron button */
border-right: 1px solid #606060;
white-space: normal;
}
.cm-tab-panel-below .goog-tab-bar, .cm-touch .goog-tab-bar {
margin-right: 42px;
}
.goog-tab-bar-top .goog-tab {
display: inline-block;
outline: none;
}
.goog-tab-bar-top:after,
.goog-tab-bar-bottom:after {
}
.goog-tab-bar-bottom .goog-tab {
margin: 0 16px 1px 0;
border-top: 0;
outline: none;
}
.goog-tab-bar-start .goog-tab {
margin: 0 0 4px 1px;
border-right: 0;
}
.goog-tab-bar-end .goog-tab {
margin: 0 1px 4px 0;
border-left: 0;
}
.goog-tab-hover, .goog-tab-selected {
background: #121212;
/* @alternate */ background-image:-webkit-linear-gradient(top, #383838, #121212);
/* @alternate */ background-image:linear-gradient(top, #383838, #121212);
}
/* State: Disabled */
.goog-tab-disabled {
color: #666;
}
/* State: Selected */
.goog-tab-selected {
text-decoration: none;
color: #ddd;
border-left: 1px solid #606060;
border-right: 1px solid #606060;
}
.goog-tab-selected:first-child {
/* No left-border on first selected tab. */
border-left: 1px solid transparent;
}
.goog-tab-bar-top {
}
/*
* Shift selected tabs 1px towards the contents (and compensate via margin and
* padding) to visually merge the borders of the tab with the borders of the
* content area.
*/
.goog-tab-bar-top .goog-tab-selected {
margin-top: 0;
}
.goog-tab-bar-bottom .goog-tab-selected {
margin-bottom: 0;
padding-top: 5px;
}
.goog-tab-bar-start .goog-tab-selected {
left: 1px;
margin-left: 0;
padding-right: 9px;
}
.goog-tab-bar-end .goog-tab-selected {
left: -1px;
margin-right: 0;
padding-left: 9px;
}
/* Crowd reports */
.cm-crowd {
margin-top: 12px;
border-top: 1px solid #c0c0c0;
background: #f0f0f0;
overflow: hidden;
}
.cm-crowd .cm-notice {
font-size: 11px;
margin: 12px 0;
color: #777;
}
.cm-crowd-report-form .cm-notice {
margin: 6px 0;
}
/* Report collection area */
.cm-report-collection {
padding: 0 12px;
}
.cm-crowd h2 {
font-size: 12px;
padding-top: 12px;
margin: 0;
color: #888;
letter-spacing: -0.2px;
}
.cm-crowd-bubble {
background: #ddd;
padding: 6px 9px;
margin: 12px 0 18px;
border-radius: 4px 4px 4px 0;
position: relative;
}
.cm-crowd-bubble.cm-collapsed .cm-close-button {
display: none;
}
.cm-crowd-more {
border-color: transparent transparent transparent #666;
border-width: 4px 0 4px 5px;
border-style: solid;
position: absolute;
right: 9px;
top: 49%;
margin-top: -4px;
}
.cm-crowd-bubble:hover .cm-crowd-more {
border-color: transparent transparent transparent #000;
}
.cm-crowd-bubble.cm-collapsed:hover {
cursor: pointer;
background: #ccc;
}
.cm-crowd-bubble-tail {
position: absolute;
left: 0;
bottom: -6px;
border-width: 3px;
border-color: #ddd transparent transparent #ddd;
border-style: solid;
}
.cm-crowd-bubble.cm-collapsed:hover .cm-crowd-bubble-tail {
border-color: #ccc transparent transparent #ccc;
}
.cm-crowd-bubble.cm-expanded .cm-crowd-report-prompt {
display: none;
}
.cm-crowd-bubble.cm-collapsed .cm-crowd-report-form {
display: none;
}
.cm-question {
margin: 6px 0 12px;
}
.cm-question:first-child {
margin-top: 0;
}
.cm-question h3 {
margin: 6px 0;
font-weight: 700;
font-size: 13px;
}
.cm-answers {
margin: 6px 0 12px;
}
.cm-answer input[type="text"],
.cm-report-text input[type="text"] {
width: 100%;
}
.cm-crowd-report-form .cm-report-text {
margin-top: 18px;
}
.cm-crowd .cm-button-area {
margin: 12px 0 6px;
}
/* Report display area */
.cm-reports {
margin: 12px 0;
padding: 0 12px;
}
.cm-reports p { /* Loading... message */
margin: 12px 6px;
color: #666;
font-size: 11px;
font-style: italic;
}
.cm-report {
margin: 12px 0 3px;
min-height: 16px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.cm-report-answers {
padding: 9px 9px;
}
.cm-reports .cm-report-text {
padding: 9px 9px;
border-top: 1px solid #eee;
}
.cm-report .cm-answer {
text-transform: uppercase;
font-size: 11px;
padding: 1px 3px;
margin-right: 4px;
display: inline-block;
color: #000;
background: #fff;
}
.cm-report .cm-time {
font-size: 11px;
float: right;
color: #999;
padding: 2px 0 0 6px;
}
.cm-report-vote {
padding: 0 9px 9px 9px;
font-size: 11px;
color: #999;
cursor: default;
}
.cm-report-vote .cm-vote-count {
display: inline-block;
min-width: 1em;
}
.cm-report-vote .cm-vote {
display: inline-block;
margin-left: 3px;
width: 10px;
height: 13px;
border: 2px solid transparent;
border-width: 2px 4px;
margin: -2px 0 -5px -4px;
opacity: 0.4;
}
.cm-report-vote .cm-upvote {
background: url('thumb_up.png') no-repeat;
margin-left: 6px;
}
.cm-report-vote .cm-downvote {
background: url('thumb_down.png') no-repeat;
margin-left: 0;
}
.cm-report-vote .cm-vote:hover {
opacity: 0.6;
}
.cm-report-vote .cm-vote.cm-selected {
opacity: 0.8;
}
.cm-report-vote .cm-vote.cm-selected:hover {
opacity: 1;
}
.cm-report-vote .cm-report-abuse:link {
float: right;
color: #999;
width: 14px;
height: 14px;
margin-top: -1px;
background: url('spam.png') no-repeat;
opacity: 0.4;
}
.cm-report-vote .cm-report-abuse:hover {
opacity: 0.6;
}
| {'content_hash': '6129214387afc3d346429dc7cec4721d', 'timestamp': '', 'source': 'github', 'line_count': 536, 'max_line_length': 126, 'avg_line_length': 19.26679104477612, 'alnum_prop': 0.6642781059358962, 'repo_name': 'pnakka/googlecrisismap', 'id': 'ed719f1c0f6ffd91bcd1ac211f8ffa6c598cb617', 'size': '10902', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'resource/tab_panel.css', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '64220'}, {'name': 'HTML', 'bytes': '166696'}, {'name': 'JavaScript', 'bytes': '1690524'}, {'name': 'Makefile', 'bytes': '8362'}, {'name': 'Python', 'bytes': '707243'}]} |
package com.google.javascript.jscomp;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNull;
import com.google.common.io.BaseEncoding;
import junit.framework.TestCase;
public final class SourceMapResolverTest extends TestCase {
public void testResolveBase64Inline() throws Exception {
String sourceMap = "{map: 'asdfasdf'}";
String encoded = BaseEncoding.base64().encode(sourceMap.getBytes("UTF-8"));
String url = "data:application/json;base64," + encoded;
String code = "console.log('asdf')\n//# sourceMappingURL=" + url;
SourceFile s =
SourceMapResolver.extractSourceMap(
SourceFile.fromCode("somePath/hello.js", code), url, true);
assertEquals(sourceMap, s.getCode());
assertEquals("somePath/hello.js.inline.map", s.getName());
// --parse_inline_source_maps=false
SourceFile noInline =
SourceMapResolver.extractSourceMap(
SourceFile.fromCode("somePath/hello.js", code), url, false);
assertNull(noInline);
}
public void testAbsolute() {
SourceFile jsFile = SourceFile.fromCode("somePath/hello.js", "console.log(1)");
// We cannot reslove absolute urls.
assertNull(SourceMapResolver.extractSourceMap(jsFile, "/asdf/asdf.js", true));
assertNull(SourceMapResolver.extractSourceMap(jsFile, "/asdf/.././asdf.js", true));
assertNull(SourceMapResolver.extractSourceMap(jsFile, "http://google.com/asdf/asdf.js", true));
assertNull(SourceMapResolver.extractSourceMap(jsFile, "https://google.com/asdf/asdf.js", true));
// We can resolve relative urls
assertNotNull(SourceMapResolver.extractSourceMap(jsFile, "asdf.js", true));
assertNotNull(SourceMapResolver.extractSourceMap(jsFile, "asdf/asdf.js", true));
assertNotNull(SourceMapResolver.extractSourceMap(jsFile, "asdf/.././asdf.js", true));
assertNotNull(SourceMapResolver.extractSourceMap(jsFile, "not/.././a/js/file.txt", true));
}
public void testRelativePaths() {
assertEquals(
"basefile.js.map",
SourceMapResolver.getRelativePath("basefile.js", "basefile.js.map").getOriginalPath());
assertEquals(
"path/relative/path/basefile.js.map",
SourceMapResolver.getRelativePath("path/basefile.js", "relative/path/basefile.js.map")
.getOriginalPath());
assertEquals(
"some/longer/sourcemap.js.map",
SourceMapResolver.getRelativePath("some/longer/path/basefile.js", "../sourcemap.js.map")
.toString());
assertEquals(
"some/sourcemap.js.map",
SourceMapResolver.getRelativePath(
"some/longer/path/basefile.js", ".././../sourcemap.js.map")
.getOriginalPath());
assertEquals(
"../basefile.js.map",
SourceMapResolver.getRelativePath("basefile.js", "../basefile.js.map").getOriginalPath());
assertEquals(
"baz/foo/bar.js",
SourceMapResolver.getRelativePath("baz/bam/qux.js", "../foo/bar.js").getOriginalPath());
}
public void testIntegration() {
String url = "relative/path/to/sourcemap/hello.js.map";
SourceFile s =
SourceMapResolver.extractSourceMap(
SourceFile.fromCode("somePath/hello.js", ""), url, false);
assertEquals("somePath/relative/path/to/sourcemap/hello.js.map", s.getName());
}
}
| {'content_hash': 'd39b247d80e6a55b5629a89f39c6637e', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 100, 'avg_line_length': 43.27272727272727, 'alnum_prop': 0.6917767106842737, 'repo_name': 'MatrixFrog/closure-compiler', 'id': 'c6f58bc2d72896bb3eab9e8bb5d02b141f2c3f23', 'size': '3944', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/com/google/javascript/jscomp/SourceMapResolverTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1765'}, {'name': 'Java', 'bytes': '15578871'}, {'name': 'JavaScript', 'bytes': '6493323'}, {'name': 'Protocol Buffer', 'bytes': '8652'}, {'name': 'Shell', 'bytes': '703'}]} |
//
// GTLYouTubeContentRating.h
//
// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
// YouTube Data API (youtube/v3)
// Description:
// Programmatic access to YouTube features.
// Documentation:
// https://developers.google.com/youtube/v3
// Classes:
// GTLYouTubeContentRating (0 custom class methods, 19 custom properties)
#if GTL_BUILT_AS_FRAMEWORK
#import "GTL/GTLObject.h"
#else
#import "GTLObject.h"
#endif
// ----------------------------------------------------------------------------
//
// GTLYouTubeContentRating
//
// Ratings schemes. The country-specific ratings are mostly for movies and
// shows.
@interface GTLYouTubeContentRating : GTLObject
// Rating system in Australia - Australian Classification Board
@property (copy) NSString *acbRating;
// British Board of Film Classification
@property (copy) NSString *bbfcRating;
// Rating system for French Canadian TV - Regie du cinema
@property (copy) NSString *catvfrRating;
// Rating system for Canadian TV - Canadian TV Classification System
@property (copy) NSString *catvRating;
// Rating system in India - Central Board of Film Certification
@property (copy) NSString *cbfcRating;
// Canadian Home Video Rating System
@property (copy) NSString *chvrsRating;
// Rating system in Brazil - Department of Justice, Rating, Titles and
// Qualification
@property (copy) NSString *djctqRating;
// Rating system in Japan - Eiga Rinri Kanri Iinkai
@property (copy) NSString *eirinRating;
// Rating system in France - French Minister of Culture
@property (copy) NSString *fmocRating;
// Rating system in Germany - Voluntary Self Regulation of the Movie Industry
@property (copy) NSString *fskRating;
// Rating system in Spain - Instituto de Cinematografia y de las Artes
// Audiovisuales
@property (copy) NSString *icaaRating;
// Rating system in South Korea - Korea Media Rating Board
@property (copy) NSString *kmrbRating;
// Rating system in Italy - Ministero dei Beni e delle Attivita Culturali e del
// Turismo
@property (copy) NSString *mibacRating;
// Motion Picture Association of America rating for the content.
@property (copy) NSString *mpaaRating;
// Rating system in New Zealand - Office of Film and Literature Classification
@property (copy) NSString *oflcRating;
// Rating system in Mexico - General Directorate of Radio, Television and
// Cinematography
@property (copy) NSString *rtcRating;
// Rating system in Russia
@property (copy) NSString *russiaRating;
// TV Parental Guidelines rating of the content.
@property (copy) NSString *tvpgRating;
// Internal YouTube rating.
@property (copy) NSString *ytRating;
@end
| {'content_hash': '322a9a951862715bcde16a92e83e3c0c', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 79, 'avg_line_length': 28.88421052631579, 'alnum_prop': 0.7131924198250729, 'repo_name': 'latemic/autocultura.ios', 'id': '154ebed2fda4b1d261269f10e7146b1f1ab362f6', 'size': '3339', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'google-api-objectivec-client-read-only/Source/Services/YouTube/Generated/GTLYouTubeContentRating.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Objective-C', 'bytes': '59835'}]} |
package com.davidbracewell.json;
import com.davidbracewell.EnumValue;
import com.davidbracewell.collection.Collect;
import com.davidbracewell.collection.counter.Counter;
import com.davidbracewell.conversion.Cast;
import com.davidbracewell.conversion.Convert;
import com.davidbracewell.io.resource.Resource;
import com.davidbracewell.string.StringUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.Multimap;
import lombok.NonNull;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
/**
* The type JSON writer.
*
* @author David B. Bracewell
*/
public final class JsonWriter implements AutoCloseable, Closeable {
private final com.google.gson.stream.JsonWriter writer;
private final Stack<JsonTokenType> writeStack = new Stack<>();
private boolean isArray;
/**
* Instantiates a new JSON writer.
*
* @param resource the resource
* @throws IOException the structured iO exception
*/
public JsonWriter(@NonNull Resource resource) throws IOException {
this.writer = new com.google.gson.stream.JsonWriter(resource.writer());
// this.writer.setHtmlSafe(true);
// this.writer.setLenient(true);
}
/**
* Begins a new array
*
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter beginArray() throws IOException {
writer.beginArray();
writeStack.add(JsonTokenType.BEGIN_ARRAY);
return this;
}
/**
* Begins a new array with given name
*
* @param arrayName the name
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter beginArray(String arrayName) throws IOException {
writeName(arrayName);
writer.beginArray();
writeStack.add(JsonTokenType.BEGIN_ARRAY);
return this;
}
/**
* Begin document as an object structure
*
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter beginDocument() throws IOException {
return beginDocument(false);
}
/**
* Begin document
*
* @param isArray True the document is an array structure, false is an object structure
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter beginDocument(boolean isArray) throws IOException {
this.isArray = isArray;
if (isArray) {
writer.beginArray();
} else {
writer.beginObject();
}
writeStack.add(JsonTokenType.BEGIN_DOCUMENT);
return this;
}
/**
* Begins a new object
*
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter beginObject() throws IOException {
writer.beginObject();
writeStack.add(JsonTokenType.BEGIN_OBJECT);
return this;
}
/**
* Begins a new object with a given name
*
* @param objectName the name
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter beginObject(String objectName) throws IOException {
writeName(objectName);
writer.beginObject();
writeStack.add(JsonTokenType.BEGIN_OBJECT);
return this;
}
private void checkAndPop(JsonTokenType required) throws IOException {
if (writeStack.peek() != required) {
throw new IOException("Ill-formed JSON: " + required + " is required, but have the following unclosed: " + writeStack);
}
writeStack.pop();
}
@Override
public void close() throws IOException {
writer.close();
}
/**
* Ends the current array
*
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter endArray() throws IOException {
checkAndPop(JsonTokenType.BEGIN_ARRAY);
popIf(JsonTokenType.NAME);
writer.endArray();
return this;
}
/**
* End document.
*
* @throws IOException Something went wrong writing
*/
public void endDocument() throws IOException {
checkAndPop(JsonTokenType.BEGIN_DOCUMENT);
if (isArray) {
writer.endArray();
} else {
writer.endObject();
}
}
/**
* Ends the current object
*
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter endObject() throws IOException {
checkAndPop(JsonTokenType.BEGIN_OBJECT);
popIf(JsonTokenType.NAME);
writer.endObject();
return this;
}
/**
* Flushes the writer.
*
* @throws IOException Something went wrong writing
*/
public void flush() throws IOException {
writer.flush();
}
/**
* Determines if the writer is currently in an array
*
* @return True if in an array, False if not
*/
public boolean inArray() {
return writeStack.peek() == JsonTokenType.BEGIN_ARRAY || (writeStack.peek() == JsonTokenType.BEGIN_DOCUMENT && isArray);
}
/**
* Determines if the writer is currently in an object
*
* @return True if in an object, False if not
*/
public boolean inObject() {
return writeStack.peek() == JsonTokenType.BEGIN_OBJECT || (writeStack.peek() == JsonTokenType.BEGIN_DOCUMENT && !isArray);
}
/**
* Writes a null value
*
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter nullValue() throws IOException {
Preconditions.checkArgument(inArray() || writeStack.peek() == JsonTokenType.NAME,
"Expecting an array or a name, but found " + writeStack.peek());
popIf(JsonTokenType.NAME);
writer.nullValue();
return this;
}
private void popIf(JsonTokenType type) {
if (writeStack.peek() == type) {
writeStack.pop();
}
}
/**
* Writes an array with the given key name
*
* @param key the key name for the array
* @param array the array to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
protected JsonWriter property(String key, Object[] array) throws IOException {
return property(key, Arrays.asList(array));
}
/**
* Writes an iterable with the given key name
*
* @param key the key name for the collection
* @param iterable the iterable to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
protected JsonWriter property(String key, Iterable<?> iterable) throws IOException {
Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array.");
beginArray(key);
for (Object o : iterable) {
value(o);
}
endArray();
return this;
}
/**
* Writes an iterator with the given key name
*
* @param key the key name for the collection
* @param iterator the iterator to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
protected JsonWriter property(String key, Iterator<?> iterator) throws IOException {
return property(key, Collect.asIterable(iterator));
}
/**
* Writes a key value pair
*
* @param key the key
* @param value the value
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter property(String key, Object value) throws IOException {
Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array.");
writeName(key);
value(value);
return this;
}
/**
* Writes a map with the given key name
*
* @param key the key name for the map
* @param map the map to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter property(String key, Map<String, ?> map) throws IOException {
Preconditions.checkArgument(!inArray(), "Cannot write a property inside an array.");
writeName(key);
value(map);
return this;
}
/**
* Sets the output to indented by some number of spaces
*
* @param numberOfSpaces The number of spaces to indent by
* @return This JSONWriter
*/
public JsonWriter spaceIndent(int numberOfSpaces) {
if (numberOfSpaces >= 0) {
writer.setIndent(StringUtils.repeat(' ', numberOfSpaces));
}
return this;
}
/**
* Sets the output to be indented by a tab
*
* @return This JSONWriter
*/
public JsonWriter tabIndent() {
writer.setIndent("\t");
return this;
}
/**
* Writes an array
*
* @param array the array to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
protected JsonWriter value(@NonNull Object[] array) throws IOException {
return value(Arrays.asList(array));
}
/**
* Writes a boolean.
*
* @param value the value
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter value(boolean value) throws IOException {
Preconditions.checkArgument(inArray() || writeStack.peek() == JsonTokenType.NAME,
"Expecting an array or a name, but found " + writeStack.peek());
popIf(JsonTokenType.NAME);
writer.value(value);
return this;
}
/**
* Writes an iterable
*
* @param value the iterable to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter value(@NonNull Iterable<?> value) throws IOException {
Preconditions.checkArgument(inArray() || writeStack.peek() == JsonTokenType.NAME,
"Expecting an array or a name, but found " + writeStack.peek());
popIf(JsonTokenType.NAME);
beginArray();
for (Object o : value) {
value(o);
}
endArray();
return this;
}
/**
* Writes an Iterator
*
* @param value the Iterator to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter value(@NonNull Iterator<?> value) throws IOException {
Preconditions.checkArgument(inArray() || writeStack.peek() == JsonTokenType.NAME,
"Expecting an array or a name, but found " + writeStack.peek());
popIf(JsonTokenType.NAME);
return value(Collect.asIterable(value));
}
/**
* Writes a map
*
* @param map the map to be written
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter value(Map<String, ?> map) throws IOException {
if (map == null) {
nullValue();
} else {
boolean inObject = inObject();
if (!inObject) beginObject();
for (Map.Entry<String, ?> entry : map.entrySet()) {
property(entry.getKey(), entry.getValue());
}
if (!inObject) endObject();
}
popIf(JsonTokenType.NAME);
return this;
}
/**
* Writes a number
*
* @param number the number
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter value(Number number) throws IOException {
Preconditions.checkArgument(inArray() || writeStack.peek() == JsonTokenType.NAME,
"Expecting an array or a name, but found " + writeStack.peek());
popIf(JsonTokenType.NAME);
writer.value(number);
return this;
}
/**
* Writes a string
*
* @param string the string
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter value(String string) throws IOException {
writer.value(string);
return this;
}
/**
* Writes an array value
*
* @param value the value
* @return This structured writer
* @throws IOException Something went wrong writing
*/
public JsonWriter value(Object value) throws IOException {
Preconditions.checkArgument(inArray() || writeStack.peek() == JsonTokenType.NAME,
"Expecting an array or a name, but found " + writeStack.peek());
writeObject(value);
popIf(JsonTokenType.NAME);
return this;
}
private void writeName(String name) throws IOException {
if (writeStack.peek() == JsonTokenType.NAME) {
throw new IOException("Cannot write two consecutive names.");
}
writer.name(name);
writeStack.push(JsonTokenType.NAME);
}
/**
* Serializes an object
*
* @param object the object to serialize
* @return This structured writer
* @throws IOException Something went wrong writing
*/
protected JsonWriter writeObject(Object object) throws IOException {
if (object == null) {
nullValue();
} else if (object instanceof JsonSerializable) {
JsonSerializable structuredSerializable = Cast.as(object);
if (object instanceof JsonArraySerializable) {
beginArray();
} else {
beginObject();
}
structuredSerializable.toJson(this);
if (object instanceof JsonArraySerializable) {
endArray();
} else {
endObject();
}
} else if (object instanceof Number) {
value(Cast.<Number>as(object));
} else if (object instanceof String) {
value(Cast.<String>as(object));
} else if (object instanceof Boolean) {
value(Cast.<Boolean>as(object).toString());
} else if (object instanceof Enum) {
value(Cast.<Enum>as(object).name());
} else if (object instanceof EnumValue) {
value(Cast.<EnumValue>as(object).name());
} else if (object instanceof Map) {
value(Cast.<Map<String, ?>>as(object));
} else if (object.getClass().isArray()) {
value(Cast.<Object[]>as(object));
} else if (object instanceof Multimap) {
value(Cast.<Multimap<String, ?>>as(object).asMap());
} else if (object instanceof Counter) {
value(Cast.<Counter<String>>as(object).asMap());
} else if (object instanceof Iterable) {
value(Cast.<Iterable>as(object));
} else if (object instanceof Iterator) {
value(Cast.<Iterator>as(object));
} else {
value(Convert.convert(object, String.class));
}
return this;
}
}//END OF JSONWriter | {'content_hash': 'f0842d29bb30f73112bcc14475071189', 'timestamp': '', 'source': 'github', 'line_count': 499, 'max_line_length': 128, 'avg_line_length': 29.857715430861724, 'alnum_prop': 0.6346063494194242, 'repo_name': 'dbracewell/mango', 'id': '6b7c6608c6fa4e7965fdd719098bd5d00395cc22', 'size': '15740', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/davidbracewell/json/JsonWriter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1720396'}, {'name': 'JavaScript', 'bytes': '29'}, {'name': 'Lex', 'bytes': '4744'}]} |
clean:
rm -ri data_analysis/*
cleanall:
rm -r data_analysis/*
| {'content_hash': 'aa8308239370b90901c4a1b729a4f74d', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 23, 'avg_line_length': 16.0, 'alnum_prop': 0.6875, 'repo_name': 'StanczakDominik/PythonPIC', 'id': '6e4bb82fadc7176eecddf21a6b6ecaff8fdf469f', 'size': '64', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Makefile', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Makefile', 'bytes': '64'}, {'name': 'Python', 'bytes': '226256'}]} |
Cards.module('Entities', function(Entities, App, Backbone){
Entities.Badge = Backbone.Model.extend({
urlRoot: "/badge",
idAttribute: "username"
});
Entities.BadgeCollection = Backbone.Collection.extend({
model: Entities.Score,
url: function() {
return "/badge/" + this.username;
},
constructor: function(models, options){
this.username = options.username;
Backbone.Collection.apply(this, arguments);
}
});
}); | {'content_hash': '3b2aa295cf9062061b1d1f71a0f9fed9', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 59, 'avg_line_length': 24.333333333333332, 'alnum_prop': 0.6917808219178082, 'repo_name': 'thmcards/thmcards', 'id': 'a078fe9bef7d12e2c54957669dbb5f08dd630899', 'size': '438', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'public/javascripts/entities/Badge.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15886'}, {'name': 'JavaScript', 'bytes': '184197'}, {'name': 'Python', 'bytes': '2775'}]} |
Input::
//// [/user/username/projects/noEmitOnError/shared/types/db.ts]
export interface A {
name: string;
}
//// [/user/username/projects/noEmitOnError/src/main.ts]
import { A } from "../shared/types/db";
const a = {
lastName: 'sdsd'
;
//// [/user/username/projects/noEmitOnError/src/other.ts]
console.log("hi");
export { }
//// [/user/username/projects/noEmitOnError/tsconfig.json]
{"compilerOptions":{"outDir":"./dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true}}
//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }
interface ReadonlyArray<T> {}
declare const console: { log(msg: any): void; };
/a/lib/tsc.js --w
Output::
>> Screen clear
[[90m12:00:31 AM[0m] Starting compilation in watch mode...
[96msrc/main.ts[0m:[93m4[0m:[93m1[0m - [91merror[0m[90m TS1005: [0m',' expected.
[7m4[0m ;
[7m [0m [91m~[0m
[96msrc/main.ts[0m:[93m2[0m:[93m11[0m
[7m2[0m const a = {
[7m [0m [96m ~[0m
The parser expected to find a '}' to match the '{' token here.
[[90m12:00:32 AM[0m] Found 1 error. Watching for file changes.
Program root files: ["/user/username/projects/noEmitOnError/shared/types/db.ts","/user/username/projects/noEmitOnError/src/main.ts","/user/username/projects/noEmitOnError/src/other.ts"]
Program options: {"outDir":"/user/username/projects/noEmitOnError/dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true,"watch":true,"configFilePath":"/user/username/projects/noEmitOnError/tsconfig.json"}
Program structureReused: Not
Program files::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Semantic diagnostics in builder refreshed for::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Shape signatures in builder refreshed for::
/a/lib/lib.d.ts (used version)
/user/username/projects/noemitonerror/shared/types/db.ts (used version)
/user/username/projects/noemitonerror/src/main.ts (used version)
/user/username/projects/noemitonerror/src/other.ts (used version)
WatchedFiles::
/user/username/projects/noemitonerror/tsconfig.json:
{"fileName":"/user/username/projects/noEmitOnError/tsconfig.json","pollingInterval":250}
/user/username/projects/noemitonerror/shared/types/db.ts:
{"fileName":"/user/username/projects/noEmitOnError/shared/types/db.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/main.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/main.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/other.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/other.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/noemitonerror/node_modules/@types:
{"directoryName":"/user/username/projects/noEmitOnError/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/user/username/projects/noemitonerror:
{"directoryName":"/user/username/projects/noemitonerror","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
Change:: No change
Input::
//// [/user/username/projects/noEmitOnError/src/main.ts] file written with same contents
Output::
>> Screen clear
[[90m12:00:36 AM[0m] File change detected. Starting incremental compilation...
[96msrc/main.ts[0m:[93m4[0m:[93m1[0m - [91merror[0m[90m TS1005: [0m',' expected.
[7m4[0m ;
[7m [0m [91m~[0m
[96msrc/main.ts[0m:[93m2[0m:[93m11[0m
[7m2[0m const a = {
[7m [0m [96m ~[0m
The parser expected to find a '}' to match the '{' token here.
[[90m12:00:37 AM[0m] Found 1 error. Watching for file changes.
Program root files: ["/user/username/projects/noEmitOnError/shared/types/db.ts","/user/username/projects/noEmitOnError/src/main.ts","/user/username/projects/noEmitOnError/src/other.ts"]
Program options: {"outDir":"/user/username/projects/noEmitOnError/dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true,"watch":true,"configFilePath":"/user/username/projects/noEmitOnError/tsconfig.json"}
Program structureReused: Completely
Program files::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Semantic diagnostics in builder refreshed for::
No shapes updated in the builder::
WatchedFiles::
/user/username/projects/noemitonerror/tsconfig.json:
{"fileName":"/user/username/projects/noEmitOnError/tsconfig.json","pollingInterval":250}
/user/username/projects/noemitonerror/shared/types/db.ts:
{"fileName":"/user/username/projects/noEmitOnError/shared/types/db.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/main.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/main.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/other.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/other.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/noemitonerror/node_modules/@types:
{"directoryName":"/user/username/projects/noEmitOnError/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/user/username/projects/noemitonerror:
{"directoryName":"/user/username/projects/noemitonerror","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
Change:: Fix Syntax error
Input::
//// [/user/username/projects/noEmitOnError/src/main.ts]
import { A } from "../shared/types/db";
const a = {
lastName: 'sdsd'
};
Output::
>> Screen clear
[[90m12:00:41 AM[0m] File change detected. Starting incremental compilation...
[[90m12:01:04 AM[0m] Found 0 errors. Watching for file changes.
Program root files: ["/user/username/projects/noEmitOnError/shared/types/db.ts","/user/username/projects/noEmitOnError/src/main.ts","/user/username/projects/noEmitOnError/src/other.ts"]
Program options: {"outDir":"/user/username/projects/noEmitOnError/dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true,"watch":true,"configFilePath":"/user/username/projects/noEmitOnError/tsconfig.json"}
Program structureReused: Completely
Program files::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Semantic diagnostics in builder refreshed for::
/user/username/projects/noEmitOnError/src/main.ts
Shape signatures in builder refreshed for::
/user/username/projects/noemitonerror/src/main.ts (computed .d.ts)
WatchedFiles::
/user/username/projects/noemitonerror/tsconfig.json:
{"fileName":"/user/username/projects/noEmitOnError/tsconfig.json","pollingInterval":250}
/user/username/projects/noemitonerror/shared/types/db.ts:
{"fileName":"/user/username/projects/noEmitOnError/shared/types/db.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/main.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/main.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/other.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/other.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/noemitonerror/node_modules/@types:
{"directoryName":"/user/username/projects/noEmitOnError/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/user/username/projects/noemitonerror:
{"directoryName":"/user/username/projects/noemitonerror","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
//// [/user/username/projects/noEmitOnError/dev-build/shared/types/db.js]
"use strict";
exports.__esModule = true;
//// [/user/username/projects/noEmitOnError/dev-build/shared/types/db.d.ts]
export interface A {
name: string;
}
//// [/user/username/projects/noEmitOnError/dev-build/src/main.js]
"use strict";
exports.__esModule = true;
var a = {
lastName: 'sdsd'
};
//// [/user/username/projects/noEmitOnError/dev-build/src/main.d.ts]
export {};
//// [/user/username/projects/noEmitOnError/dev-build/src/other.js]
"use strict";
exports.__esModule = true;
console.log("hi");
//// [/user/username/projects/noEmitOnError/dev-build/src/other.d.ts]
export {};
Change:: Semantic Error
Input::
//// [/user/username/projects/noEmitOnError/src/main.ts]
import { A } from "../shared/types/db";
const a: string = 10;
Output::
>> Screen clear
[[90m12:01:08 AM[0m] File change detected. Starting incremental compilation...
[96msrc/main.ts[0m:[93m2[0m:[93m7[0m - [91merror[0m[90m TS2322: [0mType 'number' is not assignable to type 'string'.
[7m2[0m const a: string = 10;
[7m [0m [91m ~[0m
[[90m12:01:09 AM[0m] Found 1 error. Watching for file changes.
Program root files: ["/user/username/projects/noEmitOnError/shared/types/db.ts","/user/username/projects/noEmitOnError/src/main.ts","/user/username/projects/noEmitOnError/src/other.ts"]
Program options: {"outDir":"/user/username/projects/noEmitOnError/dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true,"watch":true,"configFilePath":"/user/username/projects/noEmitOnError/tsconfig.json"}
Program structureReused: Completely
Program files::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Semantic diagnostics in builder refreshed for::
/user/username/projects/noEmitOnError/src/main.ts
Shape signatures in builder refreshed for::
/user/username/projects/noemitonerror/src/main.ts (computed .d.ts)
WatchedFiles::
/user/username/projects/noemitonerror/tsconfig.json:
{"fileName":"/user/username/projects/noEmitOnError/tsconfig.json","pollingInterval":250}
/user/username/projects/noemitonerror/shared/types/db.ts:
{"fileName":"/user/username/projects/noEmitOnError/shared/types/db.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/main.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/main.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/other.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/other.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/noemitonerror/node_modules/@types:
{"directoryName":"/user/username/projects/noEmitOnError/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/user/username/projects/noemitonerror:
{"directoryName":"/user/username/projects/noemitonerror","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
Change:: No change
Input::
//// [/user/username/projects/noEmitOnError/src/main.ts] file written with same contents
Output::
>> Screen clear
[[90m12:01:13 AM[0m] File change detected. Starting incremental compilation...
[96msrc/main.ts[0m:[93m2[0m:[93m7[0m - [91merror[0m[90m TS2322: [0mType 'number' is not assignable to type 'string'.
[7m2[0m const a: string = 10;
[7m [0m [91m ~[0m
[[90m12:01:14 AM[0m] Found 1 error. Watching for file changes.
Program root files: ["/user/username/projects/noEmitOnError/shared/types/db.ts","/user/username/projects/noEmitOnError/src/main.ts","/user/username/projects/noEmitOnError/src/other.ts"]
Program options: {"outDir":"/user/username/projects/noEmitOnError/dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true,"watch":true,"configFilePath":"/user/username/projects/noEmitOnError/tsconfig.json"}
Program structureReused: Completely
Program files::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Semantic diagnostics in builder refreshed for::
No shapes updated in the builder::
WatchedFiles::
/user/username/projects/noemitonerror/tsconfig.json:
{"fileName":"/user/username/projects/noEmitOnError/tsconfig.json","pollingInterval":250}
/user/username/projects/noemitonerror/shared/types/db.ts:
{"fileName":"/user/username/projects/noEmitOnError/shared/types/db.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/main.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/main.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/other.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/other.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/noemitonerror/node_modules/@types:
{"directoryName":"/user/username/projects/noEmitOnError/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/user/username/projects/noemitonerror:
{"directoryName":"/user/username/projects/noemitonerror","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
Change:: Fix Semantic Error
Input::
//// [/user/username/projects/noEmitOnError/src/main.ts]
import { A } from "../shared/types/db";
const a: string = "hello";
Output::
>> Screen clear
[[90m12:01:18 AM[0m] File change detected. Starting incremental compilation...
[[90m12:01:25 AM[0m] Found 0 errors. Watching for file changes.
Program root files: ["/user/username/projects/noEmitOnError/shared/types/db.ts","/user/username/projects/noEmitOnError/src/main.ts","/user/username/projects/noEmitOnError/src/other.ts"]
Program options: {"outDir":"/user/username/projects/noEmitOnError/dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true,"watch":true,"configFilePath":"/user/username/projects/noEmitOnError/tsconfig.json"}
Program structureReused: Completely
Program files::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Semantic diagnostics in builder refreshed for::
/user/username/projects/noEmitOnError/src/main.ts
Shape signatures in builder refreshed for::
/user/username/projects/noemitonerror/src/main.ts (computed .d.ts)
WatchedFiles::
/user/username/projects/noemitonerror/tsconfig.json:
{"fileName":"/user/username/projects/noEmitOnError/tsconfig.json","pollingInterval":250}
/user/username/projects/noemitonerror/shared/types/db.ts:
{"fileName":"/user/username/projects/noEmitOnError/shared/types/db.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/main.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/main.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/other.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/other.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/noemitonerror/node_modules/@types:
{"directoryName":"/user/username/projects/noEmitOnError/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/user/username/projects/noemitonerror:
{"directoryName":"/user/username/projects/noemitonerror","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
//// [/user/username/projects/noEmitOnError/dev-build/src/main.js]
"use strict";
exports.__esModule = true;
var a = "hello";
//// [/user/username/projects/noEmitOnError/dev-build/src/main.d.ts] file written with same contents
Change:: No change
Input::
//// [/user/username/projects/noEmitOnError/src/main.ts] file written with same contents
Output::
>> Screen clear
[[90m12:01:29 AM[0m] File change detected. Starting incremental compilation...
[[90m12:01:30 AM[0m] Found 0 errors. Watching for file changes.
Program root files: ["/user/username/projects/noEmitOnError/shared/types/db.ts","/user/username/projects/noEmitOnError/src/main.ts","/user/username/projects/noEmitOnError/src/other.ts"]
Program options: {"outDir":"/user/username/projects/noEmitOnError/dev-build","noEmitOnError":true,"isolatedModules":true,"declaration":true,"watch":true,"configFilePath":"/user/username/projects/noEmitOnError/tsconfig.json"}
Program structureReused: Completely
Program files::
/a/lib/lib.d.ts
/user/username/projects/noEmitOnError/shared/types/db.ts
/user/username/projects/noEmitOnError/src/main.ts
/user/username/projects/noEmitOnError/src/other.ts
Semantic diagnostics in builder refreshed for::
No shapes updated in the builder::
WatchedFiles::
/user/username/projects/noemitonerror/tsconfig.json:
{"fileName":"/user/username/projects/noEmitOnError/tsconfig.json","pollingInterval":250}
/user/username/projects/noemitonerror/shared/types/db.ts:
{"fileName":"/user/username/projects/noEmitOnError/shared/types/db.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/main.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/main.ts","pollingInterval":250}
/user/username/projects/noemitonerror/src/other.ts:
{"fileName":"/user/username/projects/noEmitOnError/src/other.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/noemitonerror/node_modules/@types:
{"directoryName":"/user/username/projects/noEmitOnError/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/user/username/projects/noemitonerror:
{"directoryName":"/user/username/projects/noemitonerror","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
| {'content_hash': '0f18049f6f6ff6a1480b59bef70cfabf', 'timestamp': '', 'source': 'github', 'line_count': 468, 'max_line_length': 224, 'avg_line_length': 40.96367521367522, 'alnum_prop': 0.7493088519117417, 'repo_name': 'SaschaNaz/TypeScript', 'id': '183aa9d1b4e970387ec24de330c86fc900f8f1bd', 'size': '19171', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'tests/baselines/reference/tscWatch/emitAndErrorUpdates/isolatedModulesAndD/with-noEmitOnError.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '945'}, {'name': 'Groovy', 'bytes': '721'}, {'name': 'HTML', 'bytes': '4005'}, {'name': 'JavaScript', 'bytes': '175'}, {'name': 'PowerShell', 'bytes': '2855'}, {'name': 'Shell', 'bytes': '264'}, {'name': 'TypeScript', 'bytes': '45808106'}]} |
define(
//begin v1.x content
({
"pasteFromWord": "Coller depuis Word",
"paste": "Coller",
"cancel": "Annuler",
"instructions": "Collez le contenu Word dans la zone de texte ci-dessous. Quand le contenu à insérer vous convient, appuyez sur le bouton Coller. Pour annuler l'insertion du texte, utilisez le bouton Annuler."
})
//end v1.x content
);
| {'content_hash': 'db593f4422614ad3545cd5d6275580d7', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 210, 'avg_line_length': 31.90909090909091, 'alnum_prop': 0.7207977207977208, 'repo_name': 'LighthouseHPC/lighthouse', 'id': 'd8fb150cce76f38aa58891cfe0fb3f3371664e67', 'size': '363', 'binary': False, 'copies': '44', 'ref': 'refs/heads/master', 'path': 'src/Dlighthouse/dojango/dojo-media/src/1.7.1/dojox/editor/plugins/nls/fr/PasteFromWord.js', 'mode': '33188', 'license': 'mit', 'language': []} |
// Copyright [2011] [PagSeguro Internet Ltda.]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace Uol.PagSeguro.Domain
{
/// <summary>
/// Represents a PagSeguro web service error
/// </summary>
[Serializable]
public sealed class ServiceError : ISerializable
{
private const string CodeField = "Code";
private const string MessageField = "Message";
/// <summary>
/// Initializes a new instance of the PagSeguroServiceError class
/// </summary>
/// <param name="code"></param>
/// <param name="message"></param>
public ServiceError(string code, string message)
{
this.Code = code;
this.Message = message;
}
private ServiceError(SerializationInfo info, StreamingContext context)
{
this.Code = info.GetString(ServiceError.CodeField);
this.Message = info.GetString(ServiceError.MessageField);
}
/// <summary>
/// Populates a SerializationInfo with the data needed to serialize the target object
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(ServiceError.CodeField, this.Code);
info.AddValue(ServiceError.MessageField, this.Message);
}
/// <summary>
/// Error code
/// </summary>
public string Code
{
get;
private set;
}
/// <summary>
/// Error description
/// </summary>
public string Message
{
get;
private set;
}
/// <summary>
/// Returns a textual representation of this object
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder builder = new StringBuilder(this.Code);
builder.Append("=");
builder.Append(this.Message);
return builder.ToString();
}
}
}
| {'content_hash': 'd16fe00ce3e31c4dc8fc22e87465ea48', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 110, 'avg_line_length': 32.144444444444446, 'alnum_prop': 0.6042170756999654, 'repo_name': 'pagseguro/dotnet', 'id': '723e2f464e6aad9822976490d5c98ee7cb27ce13', 'size': '2895', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'source/Uol.PagSeguro/Domain/ServiceError.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '559267'}]} |
package storage::netapp::santricity::restapi::mode::hardware;
use base qw(centreon::plugins::templates::hardware);
use strict;
use warnings;
sub set_system {
my ($self, %options) = @_;
$self->{regexp_threshold_numeric_check_section_option} = '^(?:drive.temperature)$';
$self->{cb_hook2} = 'execute_custom';
$self->{thresholds} = {
battery => [
['optimal', 'OK'],
['fullCharging', 'OK'],
['nearExpiration', 'WARNING'],
['failed', 'CRITICAL'],
['removed', 'OK'],
['unknown', 'UNKNOWN'],
['notInConfig', 'WARNING'],
['configMismatch', 'WARNING'],
['learning', 'OK'],
['overtemp', ''],
['expired', 'WARNING'],
['maintenanceCharging', 'OK'],
['replacementRequired', 'CRITICAL']
],
board => [
['unknown', 'UNKNOWN'],
['optimal', 'OK'],
['needsAttention', 'WARNING'],
['notPresent', 'OK'],
['degraded', 'WARNING'],
['failed', 'CRITICAL'],
['diagInProgress', 'OK']
],
cbd => [
['unknown', 'UNKNOWN'],
['optimal', 'OK'],
['failed', 'CRITICAL'],
['removed', 'OK'],
['writeProtected', 'OK'],
['incompatible', 'CRITICAL']
],
cmd => [
['unknown', 'UNKNOWN'],
['optimal', 'OK'],
['failed', 'CRITICAL'],
['empty', 'OK']
],
ctrl => [
['unknown', 'UNKNOWN'],
['optimal', 'OK'],
['failed', 'CRITICAL'],
['removed', 'OK'],
['rpaParErr', 'WARNING'],
['serviceMode', 'OK'],
['suspended', 'OK'],
['degraded', 'WARNING']
],
drive => [
['optimal', 'OK'],
['failed', 'CRITICAL'],
['replaced', 'OK'],
['bypassed', 'OK'],
['unresponsive', 'WARNING'],
['removed', 'OK'],
['incompatible', 'WARNING'],
['dataRelocation', 'OK'],
['preFailCopy', 'WARNING'],
['preFailCopyPending', 'WARNING']
],
fan => [
['optimal', 'OK'],
['removed', 'OK'],
['failed', 'CRITICAL'],
['unknown', 'UNKNOWN']
],
psu => [
['optimal', 'OK'],
['removed', 'OK'],
['failed', 'CRITICAL'],
['unknown', 'UNKNOWN'],
['noinput', 'WARNING']
],
storage => [
['neverContacted', 'UNKNOWN'],
['offline', 'OK'],
['optimal', 'OK'],
['needsAttn', 'WARNING'],
['newDevice', 'OK'],
['lockDown', 'WARNING']
],
thsensor => [
['optimal', 'OK'],
['nominalTempExceed', 'WARNING'],
['maxTempExceed', 'CRITICAL'],
['unknown', 'UNKNOWN'],
['removed', 'OK']
]
};
$self->{components_exec_load} = 0;
$self->{components_path} = 'storage::netapp::santricity::restapi::mode::components';
$self->{components_module} = [
'storage', 'ctrl', 'battery', 'board', 'cbd', 'cmd', 'drive', 'psu', 'fan',
'thsensor'
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, no_absent => 1, force_new_perfdata => 1);
bless $self, $class;
$options{options}->add_options(arguments => {});
return $self;
}
sub execute_custom {
my ($self, %options) = @_;
$self->{json_results} = $options{custom}->execute_storages_request(
endpoints => [ { endpoint => '/hardware-inventory' } ]
);
}
1;
=head1 MODE
Check hardware.
=over 8
=item B<--component>
Which component to check (Default: '.*').
Can be: 'storage', 'ctrl', 'battery', 'board', 'cbd', 'cmd', 'drive', 'psu', 'fan', 'thsensor'.
=item B<--filter>
Exclude some parts (comma seperated list)
Can also exclude specific instance: --filter='drive,010000005000C500C244251B0000000000000000'
=item B<--no-component>
Return an error if no compenents are checked.
If total (with skipped) is 0. (Default: 'critical' returns).
=item B<--threshold-overload>
Set to overload default threshold values (syntax: section,[instance,]status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='drive,OK,preFailCopy'
=item B<--warning>
Set warning threshold for 'temperature' (syntax: type,regexp,threshold)
Example: --warning='drive.temperature,.*,40'
=item B<--critical>
Set critical threshold for 'drive.temperature' (syntax: type,regexp,threshold)
Example: --critical='drive.temperature,.*,50'
=back
=cut
| {'content_hash': '9e2d0b8704d4c4a7cdff91297f2a87d8', 'timestamp': '', 'source': 'github', 'line_count': 174, 'max_line_length': 109, 'avg_line_length': 27.70689655172414, 'alnum_prop': 0.4907695498859158, 'repo_name': 'Tpo76/centreon-plugins', 'id': '248043c68d7b4c999fb374b2a74414a72d8013a6', 'size': '5581', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'storage/netapp/santricity/restapi/mode/hardware.pm', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '719'}, {'name': 'Perl', 'bytes': '19128067'}]} |
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
class Types extends Admin_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$data = array();
$data['breadcrumb'] = set_crumbs(array(current_url() => 'Content Types'));
$this->load->model('content_types_model');
$data['Types'] = $this->content_types_model
->order_by(($this->input->get('sort')) ? $this->input->get('sort') : 'title', ($this->input->get('order')) ? $this->input->get('order') : 'asc')
->get();
$this->template->view('admin/types/types', $data);
}
function edit()
{
// Init
$data = array();
$data['breadcrumb'] = set_crumbs(array('content/types' => 'Content Types', current_url() => 'Content Type Edit'));
$data['revision_id'] = $revision_id = $this->uri->segment(6);
$this->load->model('content_types_model');
$this->load->model('content_types_admin_groups_model');
$this->load->model('users/groups_model');
$this->load->model('category_groups_model');
// Load codemirror
$this->template->add_package(array('codemirror', 'zclip'));
$content_type_id = $this->uri->segment(5);
$data['Content_type'] = $Content_type = $this->content_types_model->get_by_id($content_type_id);
$data['theme_layouts'] = $this->template->get_theme_layouts($this->settings->theme, TRUE);
$data['Admin_groups'] = $Admin_groups = $this->groups_model->where('type', ADMINISTRATOR)->order_by('name')->get();
// Get all groups except super admin for group access
$Groups = new Groups_model();
$data['Groups'] = $Groups->where('type !=', SUPER_ADMIN)->order_by('name')->get();
// Get all category groups for dropdown
$data['category_groups'] = option_array_value($this->category_groups_model->order_by('title')->get(), 'id', 'title', array('' => ''));
// Check if layout exists
if ( ! $data['Content_type']->exists())
{
return show_404();
}
// Get selected restrict to groups for repopulation
$data['restrict_to'] = @unserialize($data['Content_type']->restrict_to);
if ( ! is_array($data['restrict_to']))
{
$data['restrict_to'] = (array) $data['restrict_to'];
}
// Load a revision if a revision id was provided in the URL
if ( ! empty($revision_id))
{
$this->load->model('revisions_model');
$Revision = new Revisions_model();
$Revision->get_by_id($revision_id);
if ($Revision->exists())
{
$revision_data = @unserialize($Revision->revision_data);
$Content_type->from_array($revision_data);
}
else
{
return show_404();
}
}
// Get admin groups currently assigned to this conten type
$data['current_admin_groups'] = option_array_value($Content_type->admin_groups->get(), 'id', 'group_id');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('short_name', 'Short Name', 'trim|required|alpha_dash|max_length[50]|is_unique[content_types.short_name.id.' . $content_type_id . ']');
$this->form_validation->set_rules('enable_dynamic_routing', 'Enable Dynamic Routing', 'trim');
$this->form_validation->set_rules('enable_versioning', 'Enable Versioning', 'trim|required');
$this->form_validation->set_rules('max_revisions', 'Max Revisions', 'trim|required|integer|less_than[26]');
$this->form_validation->set_rules('category_group_id', 'Category Group', 'trim');
$this->form_validation->set_rules('restrict_admin_access', 'Restrict Admin Access', 'trim|required');
$this->form_validation->set_rules('selected_admin_groups[]', 'Administrative Access', 'trim');
$this->form_validation->set_rules('access', 'Access', 'trim|required');
$this->form_validation->set_rules('restrict_to[]', 'Group Access', 'trim');
$this->form_validation->set_rules('entries_allowed', 'Number of Entries Allowed', 'trim|integer');
$this->form_validation->set_rules('layout', 'layout', '');
// Add dynamic route validation if enable dynamic routing checkbox selected
if ($this->input->post('enable_dynamic_routing') == 1)
{
$this->form_validation->set_rules('dynamic_route', 'Dynamic Route', 'trim|required|max_length[255]|callback_unique_dynamic_route['. $Content_type->dynamic_route . ']');
}
// Form validation
if ($this->form_validation->run() == TRUE)
{
// Detect if the category group changed.
// If it has changed delete entry category relations
// of the content type
if ($Content_type->category_group_id != $this->input->post('category_group_id'))
{
$Content_type->entries->get();
foreach ($Content_type->entries as $Entry)
{
$Entry->categories->get();
$Entry->delete($Entry->categories->all, 'categories');
}
}
$Content_type->from_array($this->input->post());
$Content_type->id = $content_type_id;
$Content_type->dynamic_route = ($this->input->post('dynamic_route') != '' && $this->input->post('enable_dynamic_routing')) ? $this->input->post('dynamic_route') : NULL;
$Content_type->restrict_to = ($this->input->post('access') == 2) ? serialize($this->input->post('restrict_to')) : NULL;
$Content_type->category_group_id = ($this->input->post('category_group_id') != '') ? $this->input->post('category_group_id') : NULL;
$Content_type->layout = (trim($this->input->post('layout')) != '') ? $this->input->post('layout') : NULL;
$Content_type->page_head = (trim($this->input->post('page_head')) != '') ? $this->input->post('page_head') : NULL;
$Content_type->theme_layout = ($this->input->post('theme_layout') != '') ? $this->input->post('theme_layout') : NULL;
$Content_type->entries_allowed = ($this->input->post('entries_allowed') != '') ? $this->input->post('entries_allowed') : NULL;
$Content_type->save();
$Content_type->add_revision();
// Assign admin groups to this content type
// if restrict admin access is enabled
if ($this->content_types_model->restrict_admin_access && is_array($this->input->post('selected_admin_groups')))
{
$selected_admin_groups = $this->input->post('selected_admin_groups');
foreach ($Admin_groups as $Admin_group)
{
$Content_types_admin_groups = new Content_types_admin_groups_model();
$Content_types_admin_groups->where('content_type_id', $Content_type->id)
->where('group_id', $Admin_group->id)
->get();
if (in_array($Admin_group->id, $selected_admin_groups))
{
// Admin group was selected so Update or Insert to database
$Content_types_admin_groups->content_type_id = $Content_type->id;
$Content_types_admin_groups->group_id = $Admin_group->id;
$Content_types_admin_groups->save();
}
else
{
// Admin group was NOT selected so delete it
$Content_types_admin_groups->delete_all();
}
}
}
else
{
// Restrict admin access was disabled so remove any assigned groups from database
$Content_types_admin_groups = new Content_types_admin_groups_model();
$Content_types_admin_groups->where('content_type_id', $this->content_types_model->id)
->get();
$Content_types_admin_groups->delete_all();
}
// Clear cache
$this->load->library('cache');
$this->cache->delete_all('entries');
$this->cache->delete_all('content_types');
$this->session->set_flashdata('message', '<p class="success">Content Type Saved.</p>');
if ($this->input->post('save_exit'))
{
redirect(ADMIN_PATH . '/content/types/');
}
else
{
redirect(ADMIN_PATH . '/content/types/edit/'.$this->content_types_model->id);
}
}
$data['Fields'] = $this->content_types_model->content_fields->order_by('sort')->get();
$this->template->view('admin/types/edit', $data);
}
function delete()
{
$this->load->helper('file');
$this->load->model('content_types_model');
$this->load->model('content_types_admin_groups_model');
$this->load->model('entries_model');
if ($this->input->post('selected'))
{
$selected = $this->input->post('selected');
}
else
{
$selected = (array) $this->uri->segment(5);
}
$Content_types = new Content_types_model();
$Content_types->where_in('id', $selected)->get();
if ($Content_types->exists())
{
$message = '';
$content_types_deleted = FALSE;
$this->load->model('content_fields_model');
foreach($Content_types as $Content_type)
{
if ($Content_type->required)
{
$message .= '<p class="error">Content type ' . $Content_type->title . ' (' . $Content_type->short_name . ') is required by the system and cannot be deleted.</p>';
}
else if($Content_type->entries->limit(1)->get()->exists())
{
$message .= '<p class="error">Content type ' . $Content_type->title .' ('. $Content_type->short_name . ') is associated to one or more entries and cannot be deleted.</p>';
}
else
{
// Delete content type fields and entries data coloumns
$Content_fields = new Content_fields_model();
$Content_fields->where('content_type_id', $Content_type->id)->get();
foreach ($Content_fields as $Content_field)
{
$Content_fields->drop_entries_column();
$Content_fields->delete();
}
// Delete content type admin groups
$Content_types_admin_groups = new Content_types_admin_groups_model();
$Content_types_admin_groups->where('content_type_id', $Content_type->id)->get();
$Content_types_admin_groups->delete_all();
// Delete content type revisions
$Content_type->delete_revisions();
// Delete content type
$Content_type->delete();
$content_types_deleted = TRUE;
}
}
if ($content_types_deleted)
{
// Clear cache
$this->load->library('cache');
$this->cache->delete_all('entries');
$message = '<p class="success">The selected items were successfully deleted.</p>' . $message;
}
$this->session->set_flashdata('message', $message);
}
redirect(ADMIN_PATH . '/content/types');
}
function add()
{
// Init
$data = array();
$data['breadcrumb'] = set_crumbs(array('content/types' => 'Content Types', current_url() => 'Add Content Type'));
$this->load->model('content_types_model');
$this->load->model('content_types_admin_groups_model');
$this->load->model('content_fields_model');
$this->load->model('users/groups_model');
$this->load->model('category_groups_model');
// Get theme layouts for theme layout dropdown
$data['theme_layouts'] = $this->template->get_theme_layouts($this->settings->theme, TRUE);
// Get all admin groups for admin group access
$data['Admin_groups'] = $this->groups_model->where('type', ADMINISTRATOR)->order_by('name')->get();
// Get all user groups except super admin for group access
$Groups = new Groups_model();
$data['Groups'] = $Groups->where('type !=', SUPER_ADMIN)->order_by('name')->get();
// Get all category groups for dropdown
$data['category_groups'] = option_array_value($this->category_groups_model->order_by('title')->get(), 'id', 'title', array('' => ''));
// Form Validation
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('short_name', 'Short Name', 'trim|required|alpha_dash|max_length[50]|is_unique[content_types.short_name]');
$this->form_validation->set_rules('enable_dynamic_routing', 'Enable Dynamic Routing', 'trim');
$this->form_validation->set_rules('enable_versioning', 'Enable Versioning', 'trim|required');
$this->form_validation->set_rules('max_revisions', 'Max Revisions', 'trim|required|integer|less_than[26]');
$this->form_validation->set_rules('category_group_id', 'Category Group', 'trim');
$this->form_validation->set_rules('restrict_admin_access', 'Restrict Admin Access', 'trim|required');
$this->form_validation->set_rules('selected_admin_groups[]', 'Administrative Access', 'trim');
$this->form_validation->set_rules('access', 'Access', 'trim|required');
$this->form_validation->set_rules('restrict_to[]', 'Group Access', 'trim');
$this->form_validation->set_rules('entries_allowed', 'Number of Entries Allowed', 'trim|integer');
// Add dynamic route validation if enable dynamic routing checkbox selected
if ($this->input->post('enable_dynamic_routing') == 1)
{
$this->form_validation->set_rules('dynamic_route', 'Dynamic Route', 'trim|required|max_length[255]|callback_unique_dynamic_route');
}
if ($this->form_validation->run() == TRUE)
{
// Save new content type
$Content_type = new Content_types_model();
$Content_type->from_array($this->input->post());
$Content_type->dynamic_route = ($this->input->post('dynamic_route') != '' && $this->input->post('enable_dynamic_routing')) ? $this->input->post('dynamic_route') : NULL;
$Content_type->restrict_to = ($this->input->post('access') == 2) ? serialize($this->input->post('restrict_to')) : NULL;
$Content_type->category_group_id = ($this->input->post('category_group_id') != '') ? $this->input->post('category_group_id') : NULL;
$Content_type->theme_layout = ($this->input->post('theme_layout') != '') ? $this->input->post('theme_layout') : NULL;
$Content_type->entries_allowed = ($this->input->post('entries_allowed') != '') ? $this->input->post('entries_allowed') : NULL;
$Content_type->save();
$Content_type->add_revision();
// Assign admin groups to this content type
// if restrict admin access is enabled
if ($Content_type->restrict_admin_access && is_array($this->input->post('selected_admin_groups')))
{
$selected_admin_groups = $this->input->post('selected_admin_groups');
foreach ($selected_admin_groups as $admin_group)
{
$Content_types_admin_groups = new Content_types_admin_groups_model();
$Content_types_admin_groups->content_type_id = $Content_type->id;
$Content_types_admin_groups->group_id = $admin_group;
$Content_types_admin_groups->save();
}
}
// Clear cache
$this->load->library('cache');
$this->cache->delete_all('entries');
$this->cache->delete_all('content_types');
redirect(ADMIN_PATH . "/content/types/edit/$Content_type->id");
}
$this->template->view('admin/types/add', $data);
}
function unique_dynamic_route($route, $current_route = '')
{
$route = trim($route, '/');
$regex = "(\/?([a-zA-Z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-zA-Z+&\$_.-][a-zA-Z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-zA-Z_.-][a-zA-Z0-9+\$_.-]*)?"; // Anchor
if (preg_match("/^$regex$/", $route))
{
$Content_types = new Content_types_model();
$Content_types->get_by_dynamic_route($route);
if ($Content_types->exists() && $route != stripslashes($current_route))
{
$this->form_validation->set_message('unique_dynamic_route', 'This %s provided is already in use.');
return FALSE;
}
else
{
return $route;
}
}
else
{
$this->form_validation->set_message('unique_dynamic_route', 'The %s provided is not valid.');
return FALSE;
}
}
}
| {'content_hash': 'e3f8bd553f790da66b8b5c28f4b066c1', 'timestamp': '', 'source': 'github', 'line_count': 386, 'max_line_length': 191, 'avg_line_length': 45.65025906735751, 'alnum_prop': 0.5396969524998582, 'repo_name': 'zurcxer/canvas_goodfood', 'id': '4752e9bbdf89709735026d590ebee0a5363325e6', 'size': '17621', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'application/modules/content/controllers/admin/types.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '213399'}, {'name': 'JavaScript', 'bytes': '744565'}, {'name': 'PHP', 'bytes': '2734422'}]} |
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace KarateIsere.DataAccess {
public partial class Role {
private RoleStore<IdentityRole> roleStore;
private UserStore<ApplicationUser> userStore;
private RoleManager<IdentityRole> roleManager;
private UserManager<ApplicationUser> userManager;
protected KarateIsereContext context = new KarateIsereContext();
private RoleStore<IdentityRole> RoleStore {
get {
if (roleStore == null) {
roleStore = new RoleStore<IdentityRole>(context);
}
return roleStore;
}
}
private RoleManager<IdentityRole> RoleManager {
get {
if (roleManager == null) {
roleManager = new RoleManager<IdentityRole>(RoleStore);
}
return roleManager;
}
}
private UserStore<ApplicationUser> UserStore {
get {
if (userStore == null) {
userStore = new UserStore<ApplicationUser>(context);
}
return userStore;
}
}
private UserManager<ApplicationUser> UserManager {
get {
if (userManager == null) {
userManager = new UserManager<ApplicationUser>(UserStore);
}
return userManager;
}
}
/// <summary>
/// Gets the list of roles
/// </summary>
/// <returns>the IdentityRole list</returns>
public List<IdentityRole> Get() {
return RoleManager.Roles.ToList();
}
/// <summary>
/// Gets the list of user having a role
/// </summary>
/// <param name="roleName">Role name</param>
/// <returns>List of user having a role</returns>
public List<ApplicationUser> GetUsers() {
Contract.Requires(!string.IsNullOrWhiteSpace(Name));
IdentityRole r = RoleManager.FindByName(Name);
List<IdentityUserRole> usersRoles = r.Users.ToList();
List<string> userIds = usersRoles.Select(d => d.UserId).ToList();
return UserManager.Users.Where(d => userIds.Contains(d.Id)).ToList();
}
/// <summary>
/// Create a new role
/// </summary>
public void Create() {
Contract.Requires(!string.IsNullOrWhiteSpace(Name));
var res = RoleManager.Roles.Where(d => d.Name.ToUpper() == Name.ToUpper()).SingleOrDefault();
if (res == null) {
IdentityRole ir = new IdentityRole(Name);
RoleManager.Create(ir);
context.SaveChanges();
}
}
/// <summary>
/// Delete a new role
/// </summary>
/// <param name="name">Role name</param>
public void Delete() {
Contract.Requires(!string.IsNullOrWhiteSpace(Name));
if (RoleManager.RoleExists(Name)) {
var res = RoleManager.FindByName(Name);
RoleManager.Delete(res);
context.SaveChanges();
}
}
/// <summary>
/// Grant a role to a user by its name
/// </summary>
/// <param name="role"></param>
/// <param name="user"></param>
public void Grant(string userId) {
Contract.Requires(!string.IsNullOrWhiteSpace(Name));
Contract.Requires(!string.IsNullOrWhiteSpace(userId));
UserManager.AddToRole(userId, Name);
}
public void UnGrant(string userId) {
Contract.Requires(!string.IsNullOrWhiteSpace(Name));
Contract.Requires(!string.IsNullOrWhiteSpace(userId));
UserManager.RemoveFromRole(userId, Name);
}
}
}
| {'content_hash': '9b395870cfb8c9d76b30e403149cd422', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 105, 'avg_line_length': 30.721804511278197, 'alnum_prop': 0.5499265785609398, 'repo_name': 'angegar/CDI-WebApplication', 'id': '9cdd703c29743284a7cf8af48547a2262a13dcbc', 'size': '4088', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'KarateIsere.DataAccess/Dao/DaoRole.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '102'}, {'name': 'C#', 'bytes': '332837'}, {'name': 'CSS', 'bytes': '210795'}, {'name': 'HTML', 'bytes': '6249'}, {'name': 'JavaScript', 'bytes': '192793'}, {'name': 'PowerShell', 'bytes': '101111'}]} |
package git
import (
"fmt"
"github.com/root-gg/plik/client/Godeps/_workspace/src/github.com/docopt/docopt-go"
)
func main() {
usage := `usage: git remote [-v | --verbose]
git remote add [-t <branch>] [-m <master>] [-f] [--mirror] <name> <url>
git remote rename <old> <new>
git remote rm <name>
git remote set-head <name> (-a | -d | <branch>)
git remote [-v | --verbose] show [-n] <name>
git remote prune [-n | --dry-run] <name>
git remote [-v | --verbose] update [-p | --prune] [(<group> | <remote>)...]
git remote set-branches <name> [--add] <branch>...
git remote set-url <name> <newurl> [<oldurl>]
git remote set-url --add <name> <newurl>
git remote set-url --delete <name> <url>
options:
-v, --verbose be verbose; must be placed before a subcommand
`
args, _ := docopt.Parse(usage, nil, true, "", false)
fmt.Println(args)
}
| {'content_hash': 'e3de7b3583c3bfcc0627d369b0f99bd0', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 83, 'avg_line_length': 33.07142857142857, 'alnum_prop': 0.5766738660907127, 'repo_name': 'bodji/test4', 'id': '0e12e59f33a973149aca8d3f62e33e478790b625', 'size': '926', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/Godeps/_workspace/src/github.com/docopt/docopt-go/examples/git/remote/git_remote.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '973'}, {'name': 'Go', 'bytes': '160172'}, {'name': 'HTML', 'bytes': '27038'}, {'name': 'JavaScript', 'bytes': '19576'}, {'name': 'Makefile', 'bytes': '1266'}, {'name': 'Shell', 'bytes': '7125'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.