text stringlengths 2 1.04M | meta dict |
|---|---|
name: Feature request
about: Suggest an idea for this project
title: 'FEATURE REQUEST: '
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
| {
"content_hash": "c5e76a72d00004a56d12756e279a54bb",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 92,
"avg_line_length": 32.473684210526315,
"alnum_prop": 0.7714748784440842,
"repo_name": "Nordstrom/serverless-artillery",
"id": "8ce70512e1028889d0871b8a0e70c8b8ec001295",
"size": "621",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".github/ISSUE_TEMPLATE/feature_request.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "170"
},
{
"name": "JavaScript",
"bytes": "998269"
},
{
"name": "Shell",
"bytes": "1329"
}
],
"symlink_target": ""
} |
'use strict';
module.exports.definition = {
set: function (v) {
this.setProperty('table-layout', v);
},
get: function () {
return this.getPropertyValue('table-layout');
},
enumerable: true,
configurable: true
};
| {
"content_hash": "161ba2025d20e4c4616925dafaa5ddc9",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 53,
"avg_line_length": 22.083333333333332,
"alnum_prop": 0.5622641509433962,
"repo_name": "mathewgrabau/shmotg",
"id": "6bec88ffe1325115ee9113319c4106b7c0eaed82",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/d3/node_modules/jsdom/node_modules/cssstyle/lib/properties/tableLayout.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11753"
},
{
"name": "HTML",
"bytes": "34774"
},
{
"name": "JavaScript",
"bytes": "292750"
}
],
"symlink_target": ""
} |
package com.google.cloud.apigeeregistry.v1.samples;
// [START apigeeregistry_v1_generated_Registry_UpdateApiVersion_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.apigeeregistry.v1.ApiVersion;
import com.google.cloud.apigeeregistry.v1.RegistryClient;
import com.google.cloud.apigeeregistry.v1.UpdateApiVersionRequest;
import com.google.protobuf.FieldMask;
public class AsyncUpdateApiVersion {
public static void main(String[] args) throws Exception {
asyncUpdateApiVersion();
}
public static void asyncUpdateApiVersion() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (RegistryClient registryClient = RegistryClient.create()) {
UpdateApiVersionRequest request =
UpdateApiVersionRequest.newBuilder()
.setApiVersion(ApiVersion.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.setAllowMissing(true)
.build();
ApiFuture<ApiVersion> future = registryClient.updateApiVersionCallable().futureCall(request);
// Do something.
ApiVersion response = future.get();
}
}
}
// [END apigeeregistry_v1_generated_Registry_UpdateApiVersion_async]
| {
"content_hash": "790719e278aed0661e72e0389eaceff5",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 100,
"avg_line_length": 42.5945945945946,
"alnum_prop": 0.7423857868020305,
"repo_name": "googleapis/java-apigee-registry",
"id": "ee15fb3cbe8bc0823834b1af199413f82a8ff4d2",
"size": "2171",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "samples/snippets/generated/com/google/cloud/apigeeregistry/v1/registry/updateapiversion/AsyncUpdateApiVersion.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "3644993"
},
{
"name": "Python",
"bytes": "787"
},
{
"name": "Shell",
"bytes": "20468"
}
],
"symlink_target": ""
} |
package gorillas.collection.immutable
import gorillas.collection.generic.KeyTransformation
import collection.immutable.{ SortedSet, Seq }
import collection.SortedMap
private[immutable] final class NavigableMultiMap0[K, +V](implicit val ordering: Ordering[K],
protected[this] val key2int: KeyTransformation[K],
protected[this] val keyManifest: ClassManifest[K],
protected[this] val valueManifest: ClassManifest[V])
extends NavigableMultiMap[K, V] {
override def size = 0
def get(key: K) = None
def flat: (Iterator[K], Iterator[V]) = (Iterator.empty -> Iterator.empty)
def flatEntries: Iterator[(K, V)] = Iterator.empty
def totalSize: Int = 0
def floorKey(key: K) = None
def higherKey(key: K) = None
def ceilingKey(key: K) = None
def lowerKey(key: K) = None
override def keySet = SortedSet.empty[K]
override def isEmpty = true
override def keysIterator: Iterator[K] = Iterator.empty
override def contains(key: K) = false
override def empty = this
override def valuesIterator = Iterator.empty
override def toIterator = Iterator.empty
def contains[V1 >: V](k: K, v: V1): Boolean = false
def iterator = Iterator.empty
def -(key: K) = this
def +[V1 >: Seq[V]](kv: (K, V1)): SortedMap[K, V1] = SortedMap(kv)
def rangeImpl(from: Option[K], until: Option[K]) = this
override def toString() = "NavigableMultiMap()"
}
| {
"content_hash": "689126df238d40ce9a8b306b25a4cc70",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 92,
"avg_line_length": 24.696428571428573,
"alnum_prop": 0.707881417208966,
"repo_name": "rmleon/GorillasCollection",
"id": "9ebd483abd2c32500d76134a3938e14c1e9e1cb8",
"size": "1383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "maps/src/main/scala/gorillas/collection/immutable/NavigableMultiMap0.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Scala",
"bytes": "100185"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.vertext</groupId>
<artifactId>vertext</artifactId>
<version>0.1</version>
<packaging>jar</packaging>
<name>vertext</name>
<description>Framework for distributed NLP applications.</description>
<url>http://github.com/peterbednar/vertext</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>dk.brics.automaton</groupId>
<artifactId>automaton</artifactId>
<version>1.11-8</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>4.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgs>
<arg>-Xlint</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.15</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId>
<version>4.5</version>
<executions>
<execution>
<id>antlr</id>
<goals>
<goal>antlr4</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "17858fd6df6d0edfc05bcf6fec75c6e7",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 105,
"avg_line_length": 35.880434782608695,
"alnum_prop": 0.49409269918206605,
"repo_name": "peterbednar/vertext",
"id": "199b3a23d7bd106e42cdebe61946d223375bd2ec",
"size": "3301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "3210"
},
{
"name": "Java",
"bytes": "219508"
}
],
"symlink_target": ""
} |
function makeDefaultQueryInfo() {
return {
seen: false,
observable: null
};
}
var RenderPromises = (function () {
function RenderPromises() {
this.queryPromises = new Map();
this.queryInfoTrie = new Map();
this.stopped = false;
}
RenderPromises.prototype.stop = function () {
if (!this.stopped) {
this.queryPromises.clear();
this.queryInfoTrie.clear();
this.stopped = true;
}
};
RenderPromises.prototype.registerSSRObservable = function (observable) {
if (this.stopped)
return;
this.lookupQueryInfo(observable.options).observable = observable;
};
RenderPromises.prototype.getSSRObservable = function (props) {
return this.lookupQueryInfo(props).observable;
};
RenderPromises.prototype.addQueryPromise = function (queryInstance, finish) {
if (!this.stopped) {
var info = this.lookupQueryInfo(queryInstance.getOptions());
if (!info.seen) {
this.queryPromises.set(queryInstance.getOptions(), new Promise(function (resolve) {
resolve(queryInstance.fetchData());
}));
return null;
}
}
return finish ? finish() : null;
};
RenderPromises.prototype.addObservableQueryPromise = function (obsQuery) {
return this.addQueryPromise({
getOptions: function () { return obsQuery.options; },
fetchData: function () { return new Promise(function (resolve) {
var sub = obsQuery.subscribe({
next: function (result) {
if (!result.loading) {
resolve();
sub.unsubscribe();
}
},
error: function () {
resolve();
sub.unsubscribe();
},
complete: function () {
resolve();
},
});
}); },
});
};
RenderPromises.prototype.hasPromises = function () {
return this.queryPromises.size > 0;
};
RenderPromises.prototype.consumeAndAwaitPromises = function () {
var _this = this;
var promises = [];
this.queryPromises.forEach(function (promise, queryInstance) {
_this.lookupQueryInfo(queryInstance).seen = true;
promises.push(promise);
});
this.queryPromises.clear();
return Promise.all(promises);
};
RenderPromises.prototype.lookupQueryInfo = function (props) {
var queryInfoTrie = this.queryInfoTrie;
var query = props.query, variables = props.variables;
var varMap = queryInfoTrie.get(query) || new Map();
if (!queryInfoTrie.has(query))
queryInfoTrie.set(query, varMap);
var variablesString = JSON.stringify(variables);
var info = varMap.get(variablesString) || makeDefaultQueryInfo();
if (!varMap.has(variablesString))
varMap.set(variablesString, info);
return info;
};
return RenderPromises;
}());
export { RenderPromises };
//# sourceMappingURL=RenderPromises.js.map | {
"content_hash": "a5e13ba581511411cb33b9e31af06eae",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 99,
"avg_line_length": 36.888888888888886,
"alnum_prop": 0.5487951807228916,
"repo_name": "BigBoss424/portfolio",
"id": "0eb1275e9f3fd4738bff7faa975d81927cf694fa",
"size": "3320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v8/development/node_modules/@apollo/client/react/ssr/RenderPromises.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.tests.product.hive;
import io.airlift.units.Duration;
import io.trino.tempto.ProductTest;
import io.trino.tempto.assertions.QueryAssert.Row;
import io.trino.tests.product.hive.util.CachingTestUtils.CacheStats;
import org.testng.annotations.Test;
import java.util.Collections;
import java.util.Random;
import static io.airlift.testing.Assertions.assertGreaterThan;
import static io.airlift.testing.Assertions.assertGreaterThanOrEqual;
import static io.trino.tempto.assertions.QueryAssert.Row.row;
import static io.trino.tempto.assertions.QueryAssert.assertThat;
import static io.trino.tempto.query.QueryExecutor.query;
import static io.trino.tests.product.TestGroups.HIVE_CACHING;
import static io.trino.tests.product.TestGroups.PROFILE_SPECIFIC_TESTS;
import static io.trino.tests.product.hive.util.CachingTestUtils.getCacheStats;
import static io.trino.tests.product.utils.QueryAssertions.assertEventually;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.Assert.assertEquals;
public class TestHiveCaching
extends ProductTest
{
private static final int NUMBER_OF_FILES = 5;
@Test(groups = {HIVE_CACHING, PROFILE_SPECIFIC_TESTS})
public void testReadFromCache()
{
testReadFromTable("table1");
testReadFromTable("table2");
}
private void testReadFromTable(String tableNameSuffix)
{
String cachedTableName = "hive.default.test_cache_read" + tableNameSuffix;
String nonCachedTableName = "hivenoncached.default.test_cache_read" + tableNameSuffix;
Row[] tableData = createTestTable(nonCachedTableName);
CacheStats beforeCacheStats = getCacheStats();
long initialRemoteReads = beforeCacheStats.getRemoteReads();
long initialCachedReads = beforeCacheStats.getCachedReads();
long initialNonLocalReads = beforeCacheStats.getNonLocalReads();
long initialAsyncDownloadedMb = beforeCacheStats.getAsyncDownloadedMb();
assertThat(query("SELECT * FROM " + cachedTableName))
.containsExactlyInOrder(tableData);
assertEventually(
new Duration(20, SECONDS),
() -> {
// first query via caching catalog should fetch remote data
CacheStats afterQueryCacheStats = getCacheStats();
assertGreaterThanOrEqual(afterQueryCacheStats.getAsyncDownloadedMb(), initialAsyncDownloadedMb + 5);
assertGreaterThan(afterQueryCacheStats.getRemoteReads(), initialRemoteReads);
assertEquals(afterQueryCacheStats.getCachedReads(), initialCachedReads);
assertEquals(afterQueryCacheStats.getNonLocalReads(), initialNonLocalReads);
});
assertEventually(
new Duration(10, SECONDS),
() -> {
CacheStats beforeQueryCacheStats = getCacheStats();
long beforeQueryCachedReads = beforeQueryCacheStats.getCachedReads();
long beforeQueryRemoteReads = beforeQueryCacheStats.getRemoteReads();
long beforeQueryNonLocalReads = beforeQueryCacheStats.getNonLocalReads();
assertThat(query("SELECT * FROM " + cachedTableName))
.containsExactlyInOrder(tableData);
// query via caching catalog should read exclusively from cache
CacheStats afterQueryCacheStats = getCacheStats();
assertGreaterThan(afterQueryCacheStats.getCachedReads(), beforeQueryCachedReads);
assertEquals(afterQueryCacheStats.getRemoteReads(), beforeQueryRemoteReads);
// all reads should be local as Presto would schedule splits on nodes with cached data
assertEquals(afterQueryCacheStats.getNonLocalReads(), beforeQueryNonLocalReads);
});
query("DROP TABLE " + nonCachedTableName);
}
/**
* Creates table with 5 text files that are larger than 1MB
*/
private Row[] createTestTable(String tableName)
{
StringBuilder randomDataBuilder = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 500_000; ++i) {
randomDataBuilder.append(random.nextInt(10));
}
String randomData = randomDataBuilder.toString();
query("DROP TABLE IF EXISTS " + tableName);
query("CREATE TABLE " + tableName + " (col varchar) WITH (format='TEXTFILE')");
for (int i = 0; i < NUMBER_OF_FILES; ++i) {
// use `format` to overcome SQL query length limit
query("INSERT INTO " + tableName + " SELECT format('%1$s%1$s%1$s%1$s%1$s', '" + randomData + "')");
}
Row row = row(randomData.repeat(5));
return Collections.nCopies(NUMBER_OF_FILES, row).toArray(new Row[0]);
}
}
| {
"content_hash": "4a5ff3906c8977ee3388b615fde025a9",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 120,
"avg_line_length": 45.18181818181818,
"alnum_prop": 0.6826413023596122,
"repo_name": "Praveen2112/presto",
"id": "b1d756ee380f00d295b2ef866e1466b0ca707b2d",
"size": "5467",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "testing/trino-product-tests/src/main/java/io/trino/tests/product/hive/TestHiveCaching.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "29911"
},
{
"name": "CSS",
"bytes": "13435"
},
{
"name": "Dockerfile",
"bytes": "1312"
},
{
"name": "HTML",
"bytes": "24211"
},
{
"name": "Java",
"bytes": "36960430"
},
{
"name": "JavaScript",
"bytes": "219155"
},
{
"name": "Makefile",
"bytes": "6908"
},
{
"name": "PLSQL",
"bytes": "2990"
},
{
"name": "Python",
"bytes": "10747"
},
{
"name": "SQLPL",
"bytes": "926"
},
{
"name": "Shell",
"bytes": "39389"
},
{
"name": "TSQL",
"bytes": "162084"
},
{
"name": "Thrift",
"bytes": "12631"
}
],
"symlink_target": ""
} |
"""Contains tests for oweb.views.basic.home"""
# Python imports
from unittest import skip
# Django imports
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from django.contrib.auth.models import User
# app imports
from oweb.tests import OWebViewTests
from oweb.models.account import Account
@override_settings(AUTH_USER_MODEL='auth.User')
class OWebViewsHomeTests(OWebViewTests):
def test_login_required(self):
"""Unauthenticated users should be redirected to oweb:app_login"""
r = self.client.get(reverse('oweb:home'))
self.assertRedirects(r,
reverse('oweb:app_login'),
status_code=302,
target_status_code=200)
def test_account_listing(self):
"""Does the home view list the correct accounts?"""
u = User.objects.get(username='test01')
accs = Account.objects.filter(owner=u)
self.client.login(username='test01', password='foo')
r = self.client.get(reverse('oweb:home'))
self.assertEqual(r.status_code, 200)
self.assertTemplateUsed(r, 'oweb/home.html')
self.assertTrue('accounts' in r.context)
self.assertEqual([acc.pk for acc in r.context['accounts']], [acc.pk for acc in accs])
| {
"content_hash": "9294f7d50e3e85686e223caf8496952f",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 93,
"avg_line_length": 39.93939393939394,
"alnum_prop": 0.6608497723823976,
"repo_name": "Mischback/django-oweb",
"id": "2798ef9da63ccbd6cce38817f60b5cd407e69587",
"size": "1318",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "oweb/tests/views/home.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6779"
},
{
"name": "Python",
"bytes": "170213"
},
{
"name": "Shell",
"bytes": "6706"
}
],
"symlink_target": ""
} |
<?php
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Type;
use umi\orm\metadata\ICollectionDataSource;
return function (ICollectionDataSource $dataSource) {
$masterServer = $dataSource->getMasterServer();
$schemaManager = $masterServer
->getConnection()
->getSchemaManager();
$tableScheme = new Table($dataSource->getSourceName());
$tableScheme->addOption('engine', 'InnoDB');
$tableScheme
->addColumn('id', Type::INTEGER)
->setAutoincrement(true);
$tableScheme
->addColumn('guid', Type::GUID)
->setNotnull(false);
$tableScheme
->addColumn('type', Type::STRING)
->setNotnull(false);
$tableScheme
->addColumn('version', Type::INTEGER)
->setUnsigned(true)
->setDefault(1);
$tableScheme
->addColumn('user_id', Type::INTEGER)
->setNotnull(false);
$tableScheme
->addColumn('blog_id', Type::INTEGER)
->setNotnull(false);
$tableScheme->setPrimaryKey(['id']);
$tableScheme->addUniqueIndex(['guid'], 'blog_subscriber_guid');
$tableScheme->addIndex(['blog_id'], 'subscriber_blog_id');
$tableScheme->addIndex(['user_id'], 'subscriber_user_id');
$tableScheme->addIndex(['type'], 'subscribers_type');
/** @noinspection PhpParamsInspection */
$tableScheme->addForeignKeyConstraint(
'umi_mock_users',
['user_id'],
['id'],
['onUpdate' => 'CASCADE', 'onDelete' => 'CASCADE'],
'FK_user'
);
/** @noinspection PhpParamsInspection */
$tableScheme->addForeignKeyConstraint(
'umi_mock_blogs',
['blog_id'],
['id'],
['onUpdate' => 'CASCADE', 'onDelete' => 'CASCADE'],
'FK_blog'
);
return $schemaManager->getDatabasePlatform()->getCreateTableSQL(
$tableScheme,
AbstractPlatform::CREATE_INDEXES | AbstractPlatform::CREATE_FOREIGNKEYS
);
};
| {
"content_hash": "51ad3463085b88940508b5e627edca86",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 79,
"avg_line_length": 28.81159420289855,
"alnum_prop": 0.614185110663984,
"repo_name": "Umisoft/umi.framework-dev",
"id": "fc312917c76d60dab4750e278cfa1ba3e11b279b",
"size": "2266",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/utest/orm/mock/collections/setup/blogs_blog_subscribers.setup.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "520"
},
{
"name": "CSS",
"bytes": "80"
},
{
"name": "HTML",
"bytes": "12133"
},
{
"name": "PHP",
"bytes": "2630107"
},
{
"name": "Shell",
"bytes": "2405"
},
{
"name": "XML",
"bytes": "896"
}
],
"symlink_target": ""
} |
package org.apache.solr.request;
import static org.apache.solr.common.params.CommonParams.SORT;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.Semaphore;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.lucene.index.ExitableDirectoryReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.MultiPostingsEnum;
import org.apache.lucene.index.MultiTerms;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.FilterCollector;
import org.apache.lucene.search.LeafCollector;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.grouping.AllGroupHeadsCollector;
import org.apache.lucene.search.grouping.AllGroupsCollector;
import org.apache.lucene.search.grouping.TermGroupFacetCollector;
import org.apache.lucene.search.grouping.TermGroupSelector;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.params.GroupParams;
import org.apache.solr.common.params.RequiredSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.util.StrUtils;
import org.apache.solr.handler.component.ResponseBuilder;
import org.apache.solr.handler.component.SpatialHeatmapFacets;
import org.apache.solr.request.IntervalFacets.FacetInterval;
import org.apache.solr.schema.BoolField;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.schema.TrieField;
import org.apache.solr.search.BitDocSet;
import org.apache.solr.search.DocSet;
import org.apache.solr.search.Grouping;
import org.apache.solr.search.NumericHidingLeafReader;
import org.apache.solr.search.QParser;
import org.apache.solr.search.QueryParsing;
import org.apache.solr.search.QueryUtils;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.SyntaxError;
import org.apache.solr.search.facet.FacetDebugInfo;
import org.apache.solr.search.facet.FacetRequest;
import org.apache.solr.search.grouping.GroupingSpecification;
import org.apache.solr.util.BoundedTreeSet;
import org.apache.solr.util.RTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A class that generates simple Facet information for a request.
*
* <p>More advanced facet implementations may compose or subclass this class to leverage any of its
* functionality.
*/
public class SimpleFacets {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
/** The main set of documents all facet counts should be relative to */
protected DocSet docsOrig;
/** Configuration params behavior should be driven by */
protected final SolrParams global;
/** Searcher to use for all calculations */
protected final SolrIndexSearcher searcher;
protected final SolrQueryRequest req;
protected final ResponseBuilder rb;
protected FacetDebugInfo fdebugParent;
protected FacetDebugInfo fdebug;
// per-facet values
protected static final class ParsedParams {
public final SolrParams localParams; // localParams on this particular facet command
public final SolrParams params; // local+original
public final SolrParams required; // required version of params
public final String facetValue; // the field to or query to facet on (minus local params)
public final DocSet docs; // the base docset for this particular facet
public final String key; // what name should the results be stored under
public final List<String> tags; // the tags applied to this facet value
public final int threads;
public ParsedParams(
final SolrParams localParams, // localParams on this particular facet command
final SolrParams params, // local+original
final SolrParams required, // required version of params
final String facetValue, // the field to or query to facet on (minus local params)
final DocSet docs, // the base docset for this particular facet
final String key, // what name should the results be stored under
final List<String> tags,
final int threads) {
this.localParams = localParams;
this.params = params;
this.required = required;
this.facetValue = facetValue;
this.docs = docs;
this.key = key;
this.tags = tags;
this.threads = threads;
}
public ParsedParams withDocs(final DocSet docs) {
return new ParsedParams(localParams, params, required, facetValue, docs, key, tags, threads);
}
}
public SimpleFacets(SolrQueryRequest req, DocSet docs, SolrParams params) {
this(req, docs, params, null);
}
public SimpleFacets(SolrQueryRequest req, DocSet docs, SolrParams params, ResponseBuilder rb) {
this.req = req;
this.searcher = req.getSearcher();
this.docsOrig = docs;
this.global = params;
this.rb = rb;
this.facetExecutor = req.getCoreContainer().getUpdateShardHandler().getUpdateExecutor();
}
public void setFacetDebugInfo(FacetDebugInfo fdebugParent) {
this.fdebugParent = fdebugParent;
}
protected ParsedParams parseParams(String type, String param) throws SyntaxError, IOException {
SolrParams localParams = QueryParsing.getLocalParams(param, req.getParams());
DocSet docs = docsOrig;
String facetValue = param;
String key = param;
List<String> tags = Collections.emptyList();
int threads = -1;
if (localParams == null) {
SolrParams params = global;
SolrParams required = new RequiredSolrParams(params);
return new ParsedParams(localParams, params, required, facetValue, docs, key, tags, threads);
}
SolrParams params = SolrParams.wrapDefaults(localParams, global);
SolrParams required = new RequiredSolrParams(params);
// remove local params unless it's a query
if (!Objects.equals(type, FacetParams.FACET_QUERY)) { // TODO Cut over to an Enum here
facetValue = localParams.get(CommonParams.VALUE);
}
// reset set the default key now that localParams have been removed
key = facetValue;
// allow explicit set of the key
key = localParams.get(CommonParams.OUTPUT_KEY, key);
String tagStr = localParams.get(CommonParams.TAG);
tags = tagStr == null ? Collections.<String>emptyList() : StrUtils.splitSmart(tagStr, ',');
String threadStr = localParams.get(CommonParams.THREADS);
if (threadStr != null) {
threads = Integer.parseInt(threadStr);
}
// figure out if we need a new base DocSet
String excludeStr = localParams.get(CommonParams.EXCLUDE);
if (excludeStr == null)
return new ParsedParams(localParams, params, required, facetValue, docs, key, tags, threads);
List<String> excludeTagList = StrUtils.splitSmart(excludeStr, ',');
docs = computeDocSet(docs, excludeTagList);
return new ParsedParams(localParams, params, required, facetValue, docs, key, tags, threads);
}
protected DocSet computeDocSet(DocSet baseDocSet, List<String> excludeTagList)
throws SyntaxError, IOException {
Map<?, ?> tagMap = (Map<?, ?>) req.getContext().get("tags");
// rb can be null if facets are being calculated from a RequestHandler e.g. MoreLikeThisHandler
if (tagMap == null || rb == null) {
return baseDocSet;
}
IdentityHashMap<Query, Boolean> excludeSet = new IdentityHashMap<>();
for (String excludeTag : excludeTagList) {
Object olst = tagMap.get(excludeTag);
// tagMap has entries of List<String,List<QParser>>, but subject to change in the future
if (!(olst instanceof Collection)) continue;
for (Object o : (Collection<?>) olst) {
if (!(o instanceof QParser)) continue;
QParser qp = (QParser) o;
excludeSet.put(qp.getQuery(), Boolean.TRUE);
}
}
if (excludeSet.size() == 0) return baseDocSet;
List<Query> qlist = new ArrayList<>();
// add the base query
if (!excludeSet.containsKey(rb.getQuery())) {
qlist.add(rb.getQuery());
}
// add the filters
if (rb.getFilters() != null) {
for (Query q : rb.getFilters()) {
if (!excludeSet.containsKey(q)) {
qlist.add(q);
}
}
}
// get the new base docset for this facet
DocSet base = searcher.getDocSet(qlist);
if (rb.grouping() && rb.getGroupingSpec().isTruncateGroups()) {
Grouping grouping = new Grouping(searcher, null, rb.createQueryCommand(), false, 0, false);
grouping.setWithinGroupSort(rb.getGroupingSpec().getWithinGroupSortSpec().getSort());
if (rb.getGroupingSpec().getFields().length > 0) {
grouping.addFieldCommand(rb.getGroupingSpec().getFields()[0], req);
} else if (rb.getGroupingSpec().getFunctions().length > 0) {
grouping.addFunctionCommand(rb.getGroupingSpec().getFunctions()[0], req);
} else {
return base;
}
AllGroupHeadsCollector<?> allGroupHeadsCollector =
grouping.getCommands().get(0).createAllGroupCollector();
searcher.search(base.makeQuery(), allGroupHeadsCollector);
return new BitDocSet(allGroupHeadsCollector.retrieveGroupHeads(searcher.maxDoc()));
} else {
return base;
}
}
/**
* Returns a list of facet counts for each of the facet queries specified in the params
*
* @see FacetParams#FACET_QUERY
*/
public NamedList<Integer> getFacetQueryCounts() throws IOException, SyntaxError {
NamedList<Integer> res = new SimpleOrderedMap<>();
/* Ignore CommonParams.DF - could have init param facet.query assuming
* the schema default with query param DF intented to only affect Q.
* If user doesn't want schema default for facet.query, they should be
* explicit.
*/
// SolrQueryParser qp = searcher.getSchema().getSolrQueryParser(null);
String[] facetQs = global.getParams(FacetParams.FACET_QUERY);
if (null != facetQs && 0 != facetQs.length) {
for (String q : facetQs) {
final ParsedParams parsed = parseParams(FacetParams.FACET_QUERY, q);
getFacetQueryCount(parsed, res);
}
}
return res;
}
public void getFacetQueryCount(ParsedParams parsed, NamedList<Integer> res)
throws SyntaxError, IOException {
// TODO: slight optimization would prevent double-parsing of any localParams
// TODO: SOLR-7753
Query qobj = QParser.getParser(parsed.facetValue, req).getQuery();
if (qobj == null) {
res.add(parsed.key, 0);
} else if (parsed.params.getBool(GroupParams.GROUP_FACET, false)) {
res.add(parsed.key, getGroupedFacetQueryCount(qobj, parsed.docs));
} else {
res.add(parsed.key, searcher.numDocs(qobj, parsed.docs));
}
}
/**
* Returns a grouped facet count for the facet query
*
* @see FacetParams#FACET_QUERY
*/
public int getGroupedFacetQueryCount(Query facetQuery, DocSet docSet) throws IOException {
// It is okay to retrieve group.field from global because it is never a local param
String groupField = global.get(GroupParams.GROUP_FIELD);
if (groupField == null) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
"Specify the group.field as parameter or local parameter");
}
AllGroupsCollector<?> collector = new AllGroupsCollector<>(new TermGroupSelector(groupField));
searcher.search(QueryUtils.combineQueryAndFilter(facetQuery, docSet.makeQuery()), collector);
return collector.getGroupCount();
}
enum FacetMethod {
ENUM,
FC,
FCS,
UIF;
}
/**
* Create a new bytes ref filter for excluding facet terms.
*
* <p>This method by default uses the {@link FacetParams#FACET_EXCLUDETERMS} parameter but custom
* SimpleFacets classes could use a different implementation.
*
* @param field the field to check for facet term filters
* @param params the request parameter object
* @return A predicate for filtering terms or null if no filters are applicable.
*/
protected Predicate<BytesRef> newExcludeBytesRefFilter(String field, SolrParams params) {
final String exclude = params.getFieldParam(field, FacetParams.FACET_EXCLUDETERMS);
if (exclude == null) {
return null;
}
final Set<String> excludeTerms = new HashSet<>(StrUtils.splitSmart(exclude, ",", true));
return new Predicate<BytesRef>() {
@Override
public boolean test(BytesRef bytesRef) {
return !excludeTerms.contains(bytesRef.utf8ToString());
}
};
}
/**
* Create a new bytes ref filter for filtering facet terms. If more than one filter is applicable
* the applicable filters will be returned as an {@link Predicate#and(Predicate)} of all such
* filters.
*
* @param field the field to check for facet term filters
* @param params the request parameter object
* @return A predicate for filtering terms or null if no filters are applicable.
*/
protected Predicate<BytesRef> newBytesRefFilter(String field, SolrParams params) {
final String contains = params.getFieldParam(field, FacetParams.FACET_CONTAINS);
Predicate<BytesRef> finalFilter = null;
if (contains != null) {
final boolean containsIgnoreCase =
params.getFieldBool(field, FacetParams.FACET_CONTAINS_IGNORE_CASE, false);
finalFilter = new SubstringBytesRefFilter(contains, containsIgnoreCase);
}
final String regex = params.getFieldParam(field, FacetParams.FACET_MATCHES);
if (regex != null) {
final RegexBytesRefFilter regexBytesRefFilter = new RegexBytesRefFilter(regex);
finalFilter =
(finalFilter == null) ? regexBytesRefFilter : finalFilter.and(regexBytesRefFilter);
}
final Predicate<BytesRef> excludeFilter = newExcludeBytesRefFilter(field, params);
if (excludeFilter != null) {
finalFilter = (finalFilter == null) ? excludeFilter : finalFilter.and(excludeFilter);
}
return finalFilter;
}
/**
* Term counts for use in pivot faceting that resepcts the appropriate mincount
*
* @see FacetParams#FACET_PIVOT_MINCOUNT
*/
public NamedList<Integer> getTermCountsForPivots(String field, ParsedParams parsed)
throws IOException {
Integer mincount = parsed.params.getFieldInt(field, FacetParams.FACET_PIVOT_MINCOUNT, 1);
return getTermCounts(field, mincount, parsed);
}
/**
* Term counts for use in field faceting that resepects the appropriate mincount
*
* @see FacetParams#FACET_MINCOUNT
*/
public NamedList<Integer> getTermCounts(String field, ParsedParams parsed) throws IOException {
Integer mincount = parsed.params.getFieldInt(field, FacetParams.FACET_MINCOUNT);
return getTermCounts(field, mincount, parsed);
}
/**
* Term counts for use in field faceting that resepcts the specified mincount - if mincount is
* null, the "zeros" param is consulted for the appropriate backcompat default
*
* @see FacetParams#FACET_ZEROS
*/
private NamedList<Integer> getTermCounts(String field, Integer mincount, ParsedParams parsed)
throws IOException {
final SolrParams params = parsed.params;
final DocSet docs = parsed.docs;
final int threads = parsed.threads;
int offset = params.getFieldInt(field, FacetParams.FACET_OFFSET, 0);
int limit = params.getFieldInt(field, FacetParams.FACET_LIMIT, 100);
boolean missing = params.getFieldBool(field, FacetParams.FACET_MISSING, false);
// when limit=0 and missing=false then return empty list
if (limit == 0 && !missing) return new NamedList<>();
if (mincount == null) {
Boolean zeros = params.getFieldBool(field, FacetParams.FACET_ZEROS);
// mincount = (zeros!=null && zeros) ? 0 : 1;
mincount = (zeros != null && !zeros) ? 1 : 0;
// current default is to include zeros.
}
// default to sorting if there is a limit.
String sort =
params.getFieldParam(
field,
FacetParams.FACET_SORT,
limit > 0 ? FacetParams.FACET_SORT_COUNT : FacetParams.FACET_SORT_INDEX);
String prefix = params.getFieldParam(field, FacetParams.FACET_PREFIX);
final Predicate<BytesRef> termFilter = newBytesRefFilter(field, params);
boolean exists = params.getFieldBool(field, FacetParams.FACET_EXISTS, false);
NamedList<Integer> counts;
SchemaField sf = searcher.getSchema().getField(field);
if (sf.getType().isPointField() && !sf.hasDocValues()) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST, "Can't facet on a PointField without docValues");
}
FieldType ft = sf.getType();
// determine what type of faceting method to use
final String methodStr = params.getFieldParam(field, FacetParams.FACET_METHOD);
final FacetMethod requestedMethod;
if (FacetParams.FACET_METHOD_enum.equals(methodStr)) {
requestedMethod = FacetMethod.ENUM;
} else if (FacetParams.FACET_METHOD_fcs.equals(methodStr)) {
requestedMethod = FacetMethod.FCS;
} else if (FacetParams.FACET_METHOD_fc.equals(methodStr)) {
requestedMethod = FacetMethod.FC;
} else if (FacetParams.FACET_METHOD_uif.equals(methodStr)) {
requestedMethod = FacetMethod.UIF;
} else {
requestedMethod = null;
}
final boolean multiToken = sf.multiValued() || ft.multiValuedFieldCache();
FacetMethod appliedFacetMethod =
selectFacetMethod(field, sf, requestedMethod, mincount, exists);
RTimer timer = null;
if (fdebug != null) {
fdebug.putInfoItem(
"requestedMethod", requestedMethod == null ? "not specified" : requestedMethod.name());
fdebug.putInfoItem("appliedMethod", appliedFacetMethod.name());
fdebug.putInfoItem("inputDocSetSize", docs.size());
fdebug.putInfoItem("field", field);
timer = new RTimer();
}
if (params.getFieldBool(field, GroupParams.GROUP_FACET, false)) {
counts =
getGroupedCounts(
searcher,
docs,
field,
multiToken,
offset,
limit,
mincount,
missing,
sort,
prefix,
termFilter);
} else {
assert appliedFacetMethod != null;
switch (appliedFacetMethod) {
case ENUM:
assert TrieField.getMainValuePrefix(ft) == null;
counts =
getFacetTermEnumCounts(
searcher,
docs,
field,
offset,
limit,
mincount,
missing,
sort,
prefix,
termFilter,
exists);
break;
case FCS:
assert ft.isPointField() || !multiToken;
if (ft.isPointField() || (ft.getNumberType() != null && !sf.multiValued())) {
if (prefix != null) {
throw new SolrException(
ErrorCode.BAD_REQUEST,
FacetParams.FACET_PREFIX + " is not supported on numeric types");
}
if (termFilter != null) {
throw new SolrException(
ErrorCode.BAD_REQUEST,
"BytesRef term filters ("
+ FacetParams.FACET_MATCHES
+ ", "
+ FacetParams.FACET_CONTAINS
+ ", "
+ FacetParams.FACET_EXCLUDETERMS
+ ") are not supported on numeric types");
}
if (ft.isPointField()
&& mincount <= 0) { // default is mincount=0. See SOLR-10033 & SOLR-11174.
String warningMessage =
"Raising facet.mincount from "
+ mincount
+ " to 1, because field "
+ field
+ " is Points-based.";
log.warn(warningMessage);
@SuppressWarnings({"unchecked"})
List<String> warnings = (List<String>) rb.rsp.getResponseHeader().get("warnings");
if (null == warnings) {
warnings = new ArrayList<>();
rb.rsp.getResponseHeader().add("warnings", warnings);
}
warnings.add(warningMessage);
mincount = 1;
}
counts =
NumericFacets.getCounts(
searcher, docs, field, offset, limit, mincount, missing, sort);
} else {
PerSegmentSingleValuedFaceting ps =
new PerSegmentSingleValuedFaceting(
searcher,
docs,
field,
offset,
limit,
mincount,
missing,
sort,
prefix,
termFilter);
Executor executor = threads == 0 ? directExecutor : facetExecutor;
ps.setNumThreads(threads);
counts = ps.getFacetCounts(executor);
}
break;
case UIF:
// Emulate the JSON Faceting structure so we can use the same parsing classes
Map<String, Object> jsonFacet = new HashMap<>(13);
jsonFacet.put("type", "terms");
jsonFacet.put("field", field);
jsonFacet.put("offset", offset);
jsonFacet.put("limit", limit);
jsonFacet.put("mincount", mincount);
jsonFacet.put("missing", missing);
jsonFacet.put("prefix", prefix);
jsonFacet.put("numBuckets", params.getFieldBool(field, "numBuckets", false));
jsonFacet.put("allBuckets", params.getFieldBool(field, "allBuckets", false));
jsonFacet.put("method", "uif");
jsonFacet.put("cacheDf", 0);
jsonFacet.put("perSeg", false);
final String sortVal;
switch (sort) {
case FacetParams.FACET_SORT_COUNT_LEGACY:
sortVal = FacetParams.FACET_SORT_COUNT;
break;
case FacetParams.FACET_SORT_INDEX_LEGACY:
sortVal = FacetParams.FACET_SORT_INDEX;
break;
default:
sortVal = sort;
}
jsonFacet.put(SORT, sortVal);
// TODO do we handle debug? Should probably already be handled by the legacy code
Object resObj = FacetRequest.parseOneFacetReq(req, jsonFacet).process(req, docs);
// Go through the response to build the expected output for SimpleFacets
counts = new NamedList<>();
if (resObj != null) {
@SuppressWarnings({"unchecked"})
NamedList<Object> res = (NamedList<Object>) resObj;
@SuppressWarnings({"unchecked"})
List<NamedList<Object>> buckets = (List<NamedList<Object>>) res.get("buckets");
for (NamedList<Object> b : buckets) {
counts.add(b.get("val").toString(), ((Number) b.get("count")).intValue());
}
if (missing) {
@SuppressWarnings({"unchecked"})
NamedList<Object> missingCounts = (NamedList<Object>) res.get("missing");
counts.add(null, ((Number) missingCounts.get("count")).intValue());
}
}
break;
case FC:
counts =
DocValuesFacets.getCounts(
searcher,
docs,
field,
offset,
limit,
mincount,
missing,
sort,
prefix,
termFilter,
fdebug);
break;
default:
throw new AssertionError();
}
}
if (fdebug != null) {
long timeElapsed = (long) timer.getTime();
fdebug.setElapse(timeElapsed);
}
return counts;
}
/**
* @param existsRequested facet.exists=true is passed for the given field
*/
static FacetMethod selectFacetMethod(
String fieldName,
SchemaField field,
FacetMethod method,
Integer mincount,
boolean existsRequested) {
if (existsRequested) {
checkMincountOnExists(fieldName, mincount);
if (method == null) {
method = FacetMethod.ENUM;
}
}
final FacetMethod facetMethod = selectFacetMethod(field, method, mincount);
if (existsRequested && facetMethod != FacetMethod.ENUM) {
throw new SolrException(
ErrorCode.BAD_REQUEST,
FacetParams.FACET_EXISTS
+ "=true is requested, but "
+ FacetParams.FACET_METHOD
+ "="
+ FacetParams.FACET_METHOD_enum
+ " can't be used with "
+ fieldName);
}
return facetMethod;
}
/**
* This method will force the appropriate facet method even if the user provided a different one
* as a request parameter
*
* <p>N.B. this method could overwrite what you passed as request parameter. Be Extra careful
*
* @param field field we are faceting
* @param method the facet method passed as a request parameter
* @param mincount the minimum value a facet should have to be returned
* @return the FacetMethod to use
*/
static FacetMethod selectFacetMethod(SchemaField field, FacetMethod method, Integer mincount) {
FieldType type = field.getType();
if (type.isPointField()) {
// Only FCS is supported for PointFields for now
return FacetMethod.FCS;
}
/*The user did not specify any preference*/
if (method == null) {
/* Always use filters for booleans if not DocValues only... we know the number of values is very small. */
if (type instanceof BoolField && (field.indexed() == true || field.hasDocValues() == false)) {
method = FacetMethod.ENUM;
} else if (type.getNumberType() != null && !field.multiValued()) {
/* the per-segment approach is optimal for numeric field types since there
are no global ords to merge and no need to create an expensive
top-level reader */
method = FacetMethod.FCS;
} else {
// TODO: default to per-segment or not?
method = FacetMethod.FC;
}
}
/* FC without docValues does not support single valued numeric facets */
if (method == FacetMethod.FC && type.getNumberType() != null && !field.multiValued()) {
method = FacetMethod.FCS;
}
/* UIF without DocValues can't deal with mincount=0, the reason is because
we create the buckets based on the values present in the result set.
So we are not going to see facet values which are not in the result set */
if (method == FacetMethod.UIF && !field.hasDocValues() && mincount == 0) {
method = field.multiValued() ? FacetMethod.FC : FacetMethod.FCS;
}
/* Unless isUninvertible() is true, we prohibit any use of UIF...
Here we just force FC(S) instead, and trust that the DocValues faceting logic will
do the right thing either way (with or w/o docvalues) */
if (FacetMethod.UIF == method && !field.isUninvertible()) {
method = field.multiValued() ? FacetMethod.FC : FacetMethod.FCS;
}
/* ENUM can't deal with trie fields that index several terms per value */
if (method == FacetMethod.ENUM && TrieField.getMainValuePrefix(type) != null) {
method = field.multiValued() ? FacetMethod.FC : FacetMethod.FCS;
}
/* FCS can't deal with multi token fields */
final boolean multiToken = field.multiValued() || type.multiValuedFieldCache();
if (method == FacetMethod.FCS && multiToken) {
method = FacetMethod.FC;
}
return method;
}
public NamedList<Integer> getGroupedCounts(
SolrIndexSearcher searcher,
DocSet base,
String field,
boolean multiToken,
int offset,
int limit,
int mincount,
boolean missing,
String sort,
String prefix,
Predicate<BytesRef> termFilter)
throws IOException {
GroupingSpecification groupingSpecification = rb.getGroupingSpec();
String[] groupFields = groupingSpecification != null ? groupingSpecification.getFields() : null;
final String groupField = ArrayUtils.isNotEmpty(groupFields) ? groupFields[0] : null;
if (groupField == null) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
"Specify the group.field as parameter or local parameter");
}
BytesRef prefixBytesRef = prefix != null ? new BytesRef(prefix) : null;
final TermGroupFacetCollector collector =
TermGroupFacetCollector.createTermGroupFacetCollector(
groupField, field, multiToken, prefixBytesRef, 128);
Collector groupWrapper = getNumericHidingWrapper(groupField, collector);
Collector fieldWrapper = getNumericHidingWrapper(field, groupWrapper);
// When GroupFacetCollector can handle numerics we can remove the wrapped collectors
searcher.search(base.makeQuery(), fieldWrapper);
boolean orderByCount =
sort.equals(FacetParams.FACET_SORT_COUNT)
|| sort.equals(FacetParams.FACET_SORT_COUNT_LEGACY);
TermGroupFacetCollector.GroupedFacetResult result =
collector.mergeSegmentResults(
limit < 0 ? Integer.MAX_VALUE : (offset + limit), mincount, orderByCount);
CharsRefBuilder charsRef = new CharsRefBuilder();
FieldType facetFieldType = searcher.getSchema().getFieldType(field);
NamedList<Integer> facetCounts = new NamedList<>();
List<TermGroupFacetCollector.FacetEntry> scopedEntries =
result.getFacetEntries(offset, limit < 0 ? Integer.MAX_VALUE : limit);
for (TermGroupFacetCollector.FacetEntry facetEntry : scopedEntries) {
// :TODO:can we filter earlier than this to make it more efficient?
if (termFilter != null && !termFilter.test(facetEntry.getValue())) {
continue;
}
facetFieldType.indexedToReadable(facetEntry.getValue(), charsRef);
facetCounts.add(charsRef.toString(), facetEntry.getCount());
}
if (missing) {
facetCounts.add(null, result.getTotalMissingCount());
}
return facetCounts;
}
private Collector getNumericHidingWrapper(final String field, Collector collector) {
SchemaField sf = searcher.getSchema().getFieldOrNull(field);
if (sf != null
&& !sf.hasDocValues()
&& !sf.multiValued()
&& sf.getType().getNumberType() != null) {
// it's a single-valued numeric field: we must hide the numeric because
// there isn't a GroupFacetCollector that works on numerics right now...
return new FilterCollector(collector) {
@Override
public LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {
LeafReader leafReader = NumericHidingLeafReader.wrap(context.reader(), field);
return in.getLeafCollector(leafReader.getContext());
}
};
} else {
return collector;
}
}
static final Executor directExecutor =
new Executor() {
@Override
public void execute(Runnable r) {
r.run();
}
};
private final Executor facetExecutor;
/**
* Returns a list of value constraints and the associated facet counts for each facet field
* specified in the params.
*
* @see FacetParams#FACET_FIELD
* @see #getFieldMissingCount
* @see #getFacetTermEnumCounts
*/
public NamedList<Object> getFacetFieldCounts() throws IOException, SyntaxError {
NamedList<Object> res = new SimpleOrderedMap<>();
String[] facetFs = global.getParams(FacetParams.FACET_FIELD);
if (null == facetFs) {
return res;
}
// Passing a negative number for FACET_THREADS implies an unlimited number of threads is
// acceptable. Also, a subtlety of directExecutor is that no matter how many times you "submit"
// a job, it's really just a method call in that it's run by the calling thread.
int maxThreads = req.getParams().getInt(FacetParams.FACET_THREADS, 0);
Executor executor = maxThreads == 0 ? directExecutor : facetExecutor;
final Semaphore semaphore = new Semaphore((maxThreads <= 0) ? Integer.MAX_VALUE : maxThreads);
List<Future<NamedList<?>>> futures = new ArrayList<>(facetFs.length);
if (fdebugParent != null) {
fdebugParent.putInfoItem("maxThreads", maxThreads);
}
try {
// Loop over fields; submit to executor, keeping the future
for (String f : facetFs) {
if (fdebugParent != null) {
fdebug = new FacetDebugInfo();
fdebugParent.addChild(fdebug);
}
final ParsedParams parsed = parseParams(FacetParams.FACET_FIELD, f);
final SolrParams localParams = parsed.localParams;
final String termList = localParams == null ? null : localParams.get(CommonParams.TERMS);
final String key = parsed.key;
final String facetValue = parsed.facetValue;
Callable<NamedList<?>> callable =
() -> {
try {
NamedList<Object> result = new SimpleOrderedMap<>();
if (termList != null) {
List<String> terms = StrUtils.splitSmart(termList, ",", true);
result.add(key, getListedTermCounts(facetValue, parsed, terms));
} else {
result.add(key, getTermCounts(facetValue, parsed));
}
return result;
} catch (SolrException se) {
throw se;
} catch (ExitableDirectoryReader.ExitingReaderException timeout) {
throw timeout;
} catch (Exception e) {
throw new SolrException(
ErrorCode.SERVER_ERROR, "Exception during facet.field: " + facetValue, e);
} finally {
semaphore.release();
}
};
RunnableFuture<NamedList<?>> runnableFuture = new FutureTask<>(callable);
semaphore.acquire(); // may block and/or interrupt
executor.execute(runnableFuture); // releases semaphore when done
futures.add(runnableFuture);
} // facetFs loop
// Loop over futures to get the values. The order is the same as facetFs but shouldn't matter.
for (Future<NamedList<?>> future : futures) {
res.addAll(future.get());
}
assert semaphore.availablePermits() >= maxThreads;
} catch (InterruptedException e) {
throw new SolrException(
SolrException.ErrorCode.SERVER_ERROR,
"Error while processing facet fields: InterruptedException",
e);
} catch (ExecutionException ee) {
Throwable e = ee.getCause(); // unwrap
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new SolrException(
SolrException.ErrorCode.SERVER_ERROR,
"Error while processing facet fields: " + e.toString(),
e);
}
return res;
}
/**
* Computes the term->count counts for the specified term values relative to the
*
* @param field the name of the field to compute term counts against
* @param parsed contains the docset to compute term counts relative to
* @param terms a list of term values (in the specified field) to compute the counts for
*/
protected NamedList<Integer> getListedTermCounts(
String field, final ParsedParams parsed, List<String> terms) throws IOException {
final String sort = parsed.params.getFieldParam(field, FacetParams.FACET_SORT, "empty");
final SchemaField sf = searcher.getSchema().getField(field);
final FieldType ft = sf.getType();
final DocSet baseDocset = parsed.docs;
final NamedList<Integer> res = new NamedList<>();
Stream<String> inputStream = terms.stream();
if (sort.equals(FacetParams.FACET_SORT_INDEX)) { // it might always make sense
inputStream = inputStream.sorted();
}
Stream<SimpleImmutableEntry<String, Integer>> termCountEntries =
inputStream.map(
(term) -> new SimpleImmutableEntry<>(term, numDocs(term, sf, ft, baseDocset)));
if (sort.equals(FacetParams.FACET_SORT_COUNT)) {
termCountEntries =
termCountEntries.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
}
termCountEntries.forEach(e -> res.add(e.getKey(), e.getValue()));
return res;
}
private int numDocs(
String term, final SchemaField sf, final FieldType ft, final DocSet baseDocset) {
try {
return searcher.numDocs(ft.getFieldTermQuery(null, sf, term), baseDocset);
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
/**
* Returns a count of the documents in the set which do not have any terms for for the specified
* field.
*
* @see FacetParams#FACET_MISSING
*/
public static int getFieldMissingCount(SolrIndexSearcher searcher, DocSet docs, String fieldName)
throws IOException {
SchemaField sf = searcher.getSchema().getField(fieldName);
DocSet hasVal =
searcher.getDocSet(sf.getType().getRangeQuery(null, sf, null, null, false, false));
return docs.andNotSize(hasVal);
}
/**
* Works like {@link #getFacetTermEnumCounts(SolrIndexSearcher, DocSet, String, int, int, int,
* boolean, String, String, Predicate, boolean)} but takes a substring directly for the contains
* check rather than a {@link Predicate} instance.
*/
public NamedList<Integer> getFacetTermEnumCounts(
SolrIndexSearcher searcher,
DocSet docs,
String field,
int offset,
int limit,
int mincount,
boolean missing,
String sort,
String prefix,
String contains,
boolean ignoreCase,
boolean intersectsCheck)
throws IOException {
final Predicate<BytesRef> termFilter = new SubstringBytesRefFilter(contains, ignoreCase);
return getFacetTermEnumCounts(
searcher,
docs,
field,
offset,
limit,
mincount,
missing,
sort,
prefix,
termFilter,
intersectsCheck);
}
/**
* Returns a list of terms in the specified field along with the corresponding count of documents
* in the set that match that constraint. This method uses the FilterCache to get the intersection
* count between <code>docs</code> and the DocSet for each term in the filter.
*
* @see FacetParams#FACET_LIMIT
* @see FacetParams#FACET_ZEROS
* @see FacetParams#FACET_MISSING
*/
public NamedList<Integer> getFacetTermEnumCounts(
SolrIndexSearcher searcher,
DocSet docs,
String field,
int offset,
int limit,
int mincount,
boolean missing,
String sort,
String prefix,
Predicate<BytesRef> termFilter,
boolean intersectsCheck)
throws IOException {
/* :TODO: potential optimization...
* cache the Terms with the highest docFreq and try them first
* don't enum if we get our max from them
*/
final NamedList<Integer> res = new NamedList<>();
if (limit == 0) {
return finalize(res, searcher, docs, field, missing);
}
// Minimum term docFreq in order to use the filterCache for that term.
int minDfFilterCache = global.getFieldInt(field, FacetParams.FACET_ENUM_CACHE_MINDF, 0);
// make sure we have a set that is fast for random access, if we will use it for that
Bits fastForRandomSet;
if (minDfFilterCache <= 0) {
fastForRandomSet = null;
} else {
fastForRandomSet = docs.getBits();
}
IndexSchema schema = searcher.getSchema();
FieldType ft = schema.getFieldType(field);
assert !ft.isPointField() : "Point Fields don't support enum method";
boolean sortByCount = sort.equals("count") || sort.equals("true");
final int maxsize = limit >= 0 ? offset + limit : Integer.MAX_VALUE - 1;
final BoundedTreeSet<CountPair<BytesRef, Integer>> queue =
sortByCount ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(maxsize) : null;
int min = mincount - 1; // the smallest value in the top 'N' values
int off = offset;
int lim = limit >= 0 ? limit : Integer.MAX_VALUE;
BytesRef prefixTermBytes = null;
if (prefix != null) {
String indexedPrefix = ft.toInternal(prefix);
prefixTermBytes = new BytesRef(indexedPrefix);
}
Terms terms = MultiTerms.getTerms(searcher.getIndexReader(), field);
TermsEnum termsEnum = null;
SolrIndexSearcher.DocsEnumState deState = null;
BytesRef term = null;
if (terms != null) {
termsEnum = terms.iterator();
// TODO: OPT: if seek(ord) is supported for this termsEnum, then we could use it for
// facet.offset when sorting by index order.
if (prefixTermBytes != null) {
if (termsEnum.seekCeil(prefixTermBytes) == TermsEnum.SeekStatus.END) {
termsEnum = null;
} else {
term = termsEnum.term();
}
} else {
// position termsEnum on first term
term = termsEnum.next();
}
}
PostingsEnum postingsEnum = null;
CharsRefBuilder charsRef = new CharsRefBuilder();
if (docs.size() >= mincount) {
while (term != null) {
if (prefixTermBytes != null && !StringHelper.startsWith(term, prefixTermBytes)) break;
if (termFilter == null || termFilter.test(term)) {
int df = termsEnum.docFreq();
// If we are sorting, we can use df>min (rather than >=) since we
// are going in index order. For certain term distributions this can
// make a large difference (for example, many terms with df=1).
if (df > 0 && df > min) {
int c;
if (df >= minDfFilterCache) {
// use the filter cache
if (deState == null) {
deState = new SolrIndexSearcher.DocsEnumState();
deState.fieldName = field;
deState.liveDocs = searcher.getLiveDocsBits();
deState.termsEnum = termsEnum;
deState.postingsEnum = postingsEnum;
}
if (intersectsCheck) {
c = searcher.intersects(docs, deState) ? 1 : 0;
} else {
c = searcher.numDocs(docs, deState);
}
postingsEnum = deState.postingsEnum;
} else {
// iterate over TermDocs to calculate the intersection
// TODO: specialize when base docset is a bitset or hash set (skipDocs)? or does it
// matter for this?
// TODO: do this per-segment for better efficiency (MultiDocsEnum just uses base class
// impl)
// TODO: would passing deleted docs lead to better efficiency over checking the
// fastForRandomSet?
postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.NONE);
c = 0;
if (postingsEnum instanceof MultiPostingsEnum) {
MultiPostingsEnum.EnumWithSlice[] subs =
((MultiPostingsEnum) postingsEnum).getSubs();
int numSubs = ((MultiPostingsEnum) postingsEnum).getNumSubs();
SEGMENTS_LOOP:
for (int subindex = 0; subindex < numSubs; subindex++) {
MultiPostingsEnum.EnumWithSlice sub = subs[subindex];
if (sub.postingsEnum == null) continue;
int base = sub.slice.start;
int docid;
while ((docid = sub.postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
if (fastForRandomSet.get(docid + base)) {
c++;
if (intersectsCheck) {
assert c == 1;
break SEGMENTS_LOOP;
}
}
}
}
} else {
int docid;
while ((docid = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
if (fastForRandomSet.get(docid)) {
c++;
if (intersectsCheck) {
assert c == 1;
break;
}
}
}
}
}
if (sortByCount) {
if (c > min) {
BytesRef termCopy = BytesRef.deepCopyOf(term);
queue.add(new CountPair<>(termCopy, c));
if (queue.size() >= maxsize) min = queue.last().val;
}
} else {
if (c >= mincount && --off < 0) {
if (--lim < 0) break;
ft.indexedToReadable(term, charsRef);
res.add(charsRef.toString(), c);
}
}
}
}
term = termsEnum.next();
}
}
if (sortByCount) {
for (CountPair<BytesRef, Integer> p : queue) {
if (--off >= 0) continue;
if (--lim < 0) break;
ft.indexedToReadable(p.key, charsRef);
res.add(charsRef.toString(), p.val);
}
}
return finalize(res, searcher, docs, field, missing);
}
private static NamedList<Integer> finalize(
NamedList<Integer> res,
SolrIndexSearcher searcher,
DocSet docs,
String field,
boolean missing)
throws IOException {
if (missing) {
res.add(null, getFieldMissingCount(searcher, docs, field));
}
return res;
}
public static void checkMincountOnExists(String fieldName, int mincount) {
if (mincount > 1) {
throw new SolrException(
ErrorCode.BAD_REQUEST,
FacetParams.FACET_MINCOUNT
+ "="
+ mincount
+ " exceed 1 that's not supported with "
+ FacetParams.FACET_EXISTS
+ "=true for "
+ fieldName);
}
}
/**
* A simple key=>val pair whose natural order is such that <b>higher</b> vals come before lower
* vals. In case of tie vals, then <b>lower</b> keys come before higher keys.
*/
public static class CountPair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<CountPair<K, V>> {
public CountPair(K k, V v) {
key = k;
val = v;
}
public K key;
public V val;
@Override
public int hashCode() {
return key.hashCode() ^ val.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof CountPair)) return false;
CountPair<?, ?> that = (CountPair<?, ?>) o;
return (this.key.equals(that.key) && this.val.equals(that.val));
}
@Override
public int compareTo(CountPair<K, V> o) {
int vc = o.val.compareTo(val);
return (0 != vc ? vc : key.compareTo(o.key));
}
}
/**
* Returns a <code>NamedList</code> with each entry having the "key" of the interval as name and
* the count of docs in that interval as value. All intervals added in the request are included in
* the returned <code>NamedList</code> (included those with 0 count), and it's required that the
* order of the intervals is deterministic and equals in all shards of a distributed request,
* otherwise the collation of results will fail.
*/
public NamedList<Object> getFacetIntervalCounts() throws IOException, SyntaxError {
NamedList<Object> res = new SimpleOrderedMap<Object>();
String[] fields = global.getParams(FacetParams.FACET_INTERVAL);
if (fields == null || fields.length == 0) return res;
for (String field : fields) {
final ParsedParams parsed = parseParams(FacetParams.FACET_INTERVAL, field);
String[] intervalStrs =
parsed.required.getFieldParams(parsed.facetValue, FacetParams.FACET_INTERVAL_SET);
SchemaField schemaField = searcher.getCore().getLatestSchema().getField(parsed.facetValue);
if (parsed.params.getBool(GroupParams.GROUP_FACET, false)) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
"Interval Faceting can't be used with " + GroupParams.GROUP_FACET);
}
if (schemaField.getType().isPointField() && !schemaField.hasDocValues()) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
"Can't use interval faceting on a PointField without docValues");
}
SimpleOrderedMap<Integer> fieldResults = new SimpleOrderedMap<Integer>();
res.add(parsed.key, fieldResults);
IntervalFacets intervalFacets =
new IntervalFacets(schemaField, searcher, parsed.docs, intervalStrs, parsed.params);
for (FacetInterval interval : intervalFacets) {
fieldResults.add(interval.getKey(), interval.getCount());
}
}
return res;
}
public NamedList<Object> getHeatmapCounts() throws IOException, SyntaxError {
final NamedList<Object> resOuter = new SimpleOrderedMap<>();
String[] unparsedFields = rb.req.getParams().getParams(FacetParams.FACET_HEATMAP);
if (unparsedFields == null || unparsedFields.length == 0) {
return resOuter;
}
if (global.getBool(GroupParams.GROUP_FACET, false)) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
"Heatmaps can't be used with " + GroupParams.GROUP_FACET);
}
for (String unparsedField : unparsedFields) {
final ParsedParams parsed =
parseParams(
FacetParams.FACET_HEATMAP, unparsedField); // populates facetValue, rb, params, docs
resOuter.add(
parsed.key,
SpatialHeatmapFacets.getHeatmapForField(
parsed.key, parsed.facetValue, rb, parsed.params, parsed.docs));
}
return resOuter;
}
public SolrParams getGlobalParams() {
return global;
}
public DocSet getDocsOrig() {
return docsOrig;
}
public SolrQueryRequest getRequest() {
return req;
}
public ResponseBuilder getResponseBuilder() {
return rb;
}
}
| {
"content_hash": "2755e7e035e1c6ee24ccae57079f45c4",
"timestamp": "",
"source": "github",
"line_count": 1367,
"max_line_length": 112,
"avg_line_length": 37.51426481346013,
"alnum_prop": 0.6428571428571429,
"repo_name": "apache/solr",
"id": "7a1ce68a87220b560fb9dfa486ea5c96d3ac627f",
"size": "52083",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "solr/core/src/java/org/apache/solr/request/SimpleFacets.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "509"
},
{
"name": "Batchfile",
"bytes": "91853"
},
{
"name": "CSS",
"bytes": "234034"
},
{
"name": "Emacs Lisp",
"bytes": "73"
},
{
"name": "HTML",
"bytes": "326277"
},
{
"name": "Handlebars",
"bytes": "7549"
},
{
"name": "Java",
"bytes": "35849436"
},
{
"name": "JavaScript",
"bytes": "17639"
},
{
"name": "Python",
"bytes": "219385"
},
{
"name": "Shell",
"bytes": "279599"
},
{
"name": "XSLT",
"bytes": "35107"
}
],
"symlink_target": ""
} |
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
define('BASE_PATH', realpath(dirname(__FILE__).'/../'));
define('APPLICATION_ENV', 'testing');
define('APPLICATION_PATH', BASE_PATH.'/core');
define('LIBRARY_PATH', BASE_PATH.'/library');
define('TESTS_PATH', BASE_PATH.'/tests');
require_once BASE_PATH.'/vendor/autoload.php';
require_once BASE_PATH.'/core/include.php';
date_default_timezone_set('UTC');
Zend_Session::$_unitTestEnabled = true;
Zend_Session::start();
$configCore = new Zend_Config_Ini(CORE_CONFIG, 'global', true);
Zend_Registry::set('configCore', $configCore);
require_once 'ControllerTestCase.php';
require_once 'DatabaseTestCase.php';
Zend_Registry::set('logger', null);
$configGlobal = new Zend_Config_Ini(APPLICATION_CONFIG, 'global', true);
$configGlobal->environment = 'testing';
Zend_Registry::set('configGlobal', $configGlobal);
$config = new Zend_Config_Ini(APPLICATION_CONFIG, 'testing');
Zend_Registry::set('config', $config);
$databaseIni = getenv('MIDAS_DATABASE_INI');
if (!file_exists($databaseIni)) {
if (file_exists(BASE_PATH.'/tests/configs/lock.mysql.ini')) {
$databaseIni = BASE_PATH.'/tests/configs/lock.mysql.ini';
} elseif (file_exists(BASE_PATH.'/tests/configs/lock.pgsql.ini')) {
$databaseIni = BASE_PATH.'/tests/configs/lock.pgsql.ini';
} elseif (file_exists(BASE_PATH.'/tests/configs/lock.sqlite.ini')) {
$databaseIni = BASE_PATH.'/tests/configs/lock.sqlite.ini';
} else {
echo 'Error: database ini file not found.';
exit(1);
}
}
$configDatabase = new Zend_Config_Ini($databaseIni, 'testing');
if (empty($configDatabase->database->params->driver_options)) {
$driverOptions = array();
} else {
$driverOptions = $configDatabase->database->params->driver_options->toArray();
}
$params = array(
'dbname' => $configDatabase->database->params->dbname,
'username' => $configDatabase->database->params->username,
'password' => $configDatabase->database->params->password,
'driver_options' => $driverOptions,
);
if (empty($configDatabase->database->params->unix_socket)) {
$params['host'] = $configDatabase->database->params->host;
$params['port'] = $configDatabase->database->params->port;
} else {
$params['unix_socket'] = $configDatabase->database->params->unix_socket;
}
$db = Zend_Db::factory($configDatabase->database->adapter, $params);
Zend_Db_Table::setDefaultAdapter($db);
Zend_Registry::set('dbAdapter', $db);
Zend_Registry::set('configDatabase', $configDatabase);
Zend_Registry::set('models', array());
require_once BASE_PATH.'/core/controllers/components/UpgradeComponent.php';
$upgradeComponent = new UpgradeComponent();
$db = Zend_Registry::get('dbAdapter');
$dbtype = Zend_Registry::get('configDatabase')->database->adapter;
$upgradeComponent->initUpgrade('core', $db, $dbtype);
require_once BASE_PATH.'/core/controllers/components/UtilityComponent.php';
$version = UtilityComponent::getLatestModuleVersion('core');
if ($version === false) {
if (Zend_Registry::get('configDatabase')->database->adapter === 'PDO_MYSQL'
) {
$type = 'mysql';
} elseif (Zend_Registry::get('configDatabase')->database->adapter === 'PDO_PGSQL'
) {
$type = 'pgsql';
} elseif (Zend_Registry::get('configDatabase')->database->adapter === 'PDO_SQLITE'
) {
$type = 'sqlite';
} else {
echo 'Error';
exit;
}
$MyDirectory = opendir(BASE_PATH.'/core/database/'.$type);
while ($Entry = @readdir($MyDirectory)) {
if (strpos($Entry, '.sql') != false) {
$sqlFile = BASE_PATH.'/core/database/'.$type.'/'.$Entry;
}
}
$version = str_replace('.sql', '', basename($sqlFile));
}
$upgradeComponent->upgrade($version, true);
$logger = Zend_Log::factory(
array(
array(
'writerName' => 'Stream',
'writerParams' => array('stream' => LOGS_PATH.'/testing.log'),
'filterName' => 'Priority',
'filterParams' => array('priority' => Zend_Log::INFO),
),
)
);
Zend_Registry::set('logger', $logger);
if (file_exists(BASE_PATH.'/tests/configs/lock.mysql.ini')) {
rename(BASE_PATH.'/tests/configs/lock.mysql.ini', BASE_PATH.'/tests/configs/mysql.ini');
}
if (file_exists(BASE_PATH.'/tests/configs/lock.pgsql.ini')) {
rename(BASE_PATH.'/tests/configs/lock.pgsql.ini', BASE_PATH.'/tests/configs/pgsql.ini');
}
if (file_exists(BASE_PATH.'/tests/configs/lock.sqlite.ini')) {
rename(BASE_PATH.'/tests/configs/lock.sqlite.ini', BASE_PATH.'/tests/configs/sqlite.ini');
}
| {
"content_hash": "ab3c7bbc91b6d4ebb4e7c0eb09c4decd",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 94,
"avg_line_length": 35.36641221374046,
"alnum_prop": 0.6602633282969997,
"repo_name": "jcfr/Midas",
"id": "7a59606d0b0c2e91ae8fa59f0db866ce9d378df2",
"size": "5489",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/TestsBootstrap.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "4461"
},
{
"name": "CMake",
"bytes": "105576"
},
{
"name": "CSS",
"bytes": "237418"
},
{
"name": "HTML",
"bytes": "523713"
},
{
"name": "Java",
"bytes": "502251"
},
{
"name": "JavaScript",
"bytes": "2381487"
},
{
"name": "PHP",
"bytes": "3876121"
},
{
"name": "Python",
"bytes": "109105"
},
{
"name": "Shell",
"bytes": "798"
}
],
"symlink_target": ""
} |
package org.jivesoftware.util;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;
/**
* Represents a system property - also accessible via {@link JiveGlobals}. The only way to create a SystemProperty object
* is to use a {@link Builder}.
*
* @param <T> The type of system property.
*/
public final class SystemProperty<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(SystemProperty.class);
private static final Map<String, SystemProperty> PROPERTIES = new ConcurrentHashMap<>();
private static final Map<ChronoUnit, Function<Duration, Long>> DURATION_TO_LONG = new HashMap<>();
private static final Map<ChronoUnit, Function<Long, Duration>> LONG_TO_DURATION = new HashMap<>();
private static final Map<Class, BiFunction<String, SystemProperty, Object>> FROM_STRING = new HashMap<>();
private static final Map<Class, BiFunction<Object, SystemProperty, String>> TO_STRING = new HashMap<>();
private static final Map<Class, BiFunction<Object, SystemProperty, String>> TO_DISPLAY_STRING = new HashMap<>();
private static final Set<Class> NULLABLE_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(String.class, Class.class, Duration.class, Instant.class, JID.class)));
static {
// Populate the map that turns a Duration to a Long based on the ChronoUnit a property should be saved in
DURATION_TO_LONG.put(ChronoUnit.MILLIS, Duration::toMillis);
DURATION_TO_LONG.put(ChronoUnit.SECONDS, Duration::getSeconds);
DURATION_TO_LONG.put(ChronoUnit.MINUTES, Duration::toMinutes);
DURATION_TO_LONG.put(ChronoUnit.HOURS, Duration::toHours);
DURATION_TO_LONG.put(ChronoUnit.DAYS, Duration::toDays);
}
static {
// Populate the map that turns a Long to a Duration based on the ChronoUnit a property should be saved in
LONG_TO_DURATION.put(ChronoUnit.MILLIS, Duration::ofMillis);
LONG_TO_DURATION.put(ChronoUnit.SECONDS, Duration::ofSeconds);
LONG_TO_DURATION.put(ChronoUnit.MINUTES, Duration::ofMinutes);
LONG_TO_DURATION.put(ChronoUnit.HOURS, Duration::ofHours);
LONG_TO_DURATION.put(ChronoUnit.DAYS, Duration::ofDays);
}
static {
// Given a String value and a system property, converts the String to the object of appropriate type or null
FROM_STRING.put(String.class, (value, systemProperty) -> value);
FROM_STRING.put(Integer.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseInteger(value).orElse(null));
FROM_STRING.put(Long.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).orElse(null));
FROM_STRING.put(Double.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseDouble(value).orElse(null));
FROM_STRING.put(Boolean.class, (value, systemProperty) -> value == null ? null : Boolean.valueOf(value));
FROM_STRING.put(Duration.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).map(longValue -> LONG_TO_DURATION.get(systemProperty.chronoUnit).apply(longValue)).orElse(null));
FROM_STRING.put(Instant.class, (value, systemProperty) -> org.jivesoftware.util.StringUtils.parseLong(value).map(Instant::ofEpochMilli).orElse(null));
FROM_STRING.put(JID.class, (value, systemProperty) -> {
if(value == null) {
return null;
}
try {
return new JID(value);
} catch(final Exception e) {
LOGGER.warn("Configured property {} is not a valid JID", value);
return null;
}
});
FROM_STRING.put(Enum.class, (value, systemProperty) -> {
if (StringUtils.isBlank(value)) {
return null;
}
for (final Object constant : systemProperty.defaultValue.getClass().getEnumConstants()) {
if (((Enum) constant).name().equals(value)) {
return constant;
}
}
return null;
});
FROM_STRING.put(Class.class, (value, systemProperty) -> {
if(StringUtils.isBlank(value)) {
return null;
}
try {
final Class clazz = ClassUtils.forName(value);
//noinspection unchecked
if (systemProperty.baseClass.isAssignableFrom(clazz)) {
return clazz;
} else {
LOGGER.warn("Configured property {} is not an instance of {}", value, systemProperty.baseClass.getName());
return null;
}
} catch (final ClassNotFoundException e) {
LOGGER.warn("Class {} was not found", value, e);
return null;
}
});
FROM_STRING.put(List.class, (value, systemProperty) -> getObjectStream(value, systemProperty).collect(Collectors.toList()));
FROM_STRING.put(Set.class, (value, systemProperty) -> getObjectStream(value, systemProperty).collect(Collectors.toCollection(LinkedHashSet::new)));
}
private static Stream<Object> getObjectStream(final String value, final SystemProperty systemProperty) {
if (StringUtils.isEmpty(value)) {
return Stream.empty();
}
final List<String> strings = Arrays.asList(value.trim().split("[\\s,]+"));
Stream<Object> stream = strings.stream()
.map(singleValue -> FROM_STRING.get(systemProperty.collectionType).apply(singleValue, systemProperty))
.filter(Objects::nonNull);
if (systemProperty.sorted) {
stream = stream.sorted();
}
return stream;
}
static {
// Given a value and a system property, converts the value to a String with the appropriate value or null
TO_STRING.put(String.class, (value, systemProperty) -> (String)value);
TO_STRING.put(Integer.class, (value, systemProperty) -> value.toString());
TO_STRING.put(Long.class, (value, systemProperty) -> value.toString());
TO_STRING.put(Double.class, (value, systemProperty) -> value.toString());
TO_STRING.put(Boolean.class, (value, systemProperty) -> value.toString());
TO_STRING.put(Duration.class, (value, systemProperty) -> value == null ? null : DURATION_TO_LONG.get(systemProperty.chronoUnit).apply((Duration) value).toString());
TO_STRING.put(Instant.class, (value, systemProperty) -> value == null ? null : String.valueOf(((Instant)value).toEpochMilli()));
TO_STRING.put(JID.class, (value, systemProperty) -> value == null ? null : value.toString());
TO_STRING.put(Enum.class, (value, systemProperty) -> value == null ? null : ((Enum)value).name());
TO_STRING.put(Class.class, (value, systemProperty) -> value == null ? null : ((Class)value).getName());
TO_STRING.put(List.class, (value, systemProperty) -> {
final Collection collection = (Collection) value;
if (collection == null || collection.isEmpty()) {
return null;
}
// noinspection unchecked
Stream<String> stream = collection.stream()
.map(singleValue -> TO_STRING.get(systemProperty.collectionType).apply(singleValue, systemProperty))
.filter(Objects::nonNull);
if(systemProperty.sorted) {
stream = stream.sorted();
}
return stream.collect(Collectors.joining(","));
});
TO_STRING.put(Set.class, TO_STRING.get(List.class));
}
static {
// Given a value and a system property, converts the value to a display String of the appropriate value or null
TO_DISPLAY_STRING.put(String.class, (value, systemProperty) -> (String) value);
TO_DISPLAY_STRING.put(Integer.class, (value, systemProperty) -> value.toString());
TO_DISPLAY_STRING.put(Long.class, (value, systemProperty) -> value.toString());
TO_DISPLAY_STRING.put(Double.class, (value, systemProperty) -> value.toString());
TO_DISPLAY_STRING.put(Boolean.class, (value, systemProperty) -> value.toString());
TO_DISPLAY_STRING.put(Duration.class, (value, systemProperty) -> value == null ? null : org.jivesoftware.util.StringUtils.getFullElapsedTime((Duration)value));
TO_DISPLAY_STRING.put(Instant.class, (value, systemProperty) -> value == null ? null : Date.from((Instant) value).toString());
TO_DISPLAY_STRING.put(JID.class, (value, systemProperty) -> value == null ? null : value.toString());
TO_DISPLAY_STRING.put(Enum.class, (value, systemProperty) -> value == null ? null : ((Enum)value).name());
TO_DISPLAY_STRING.put(Class.class, (value, systemProperty) -> value == null ? null : ((Class)value).getName());
TO_DISPLAY_STRING.put(List.class, (value, systemProperty) -> {
final Collection collection = (Collection) value;
if (collection == null || collection.isEmpty()) {
return null;
}
// noinspection unchecked
Stream<String> stream = collection.stream()
.map(singleValue -> TO_DISPLAY_STRING.get(systemProperty.collectionType).apply(singleValue, systemProperty))
.filter(Objects::nonNull);
if(systemProperty.sorted) {
stream = stream.sorted();
}
return stream.collect(Collectors.joining(","));
});
TO_DISPLAY_STRING.put(Set.class, TO_DISPLAY_STRING.get(List.class));
}
static {
// Add a (single) listener that will call the listeners of each given property
PropertyEventDispatcher.addListener(new PropertyEventListener() {
@SuppressWarnings("unchecked")
@Override
public void propertySet(final String property, final Map<String, Object> params) {
final SystemProperty systemProperty = PROPERTIES.get(property);
if (systemProperty != null) {
final Object newValue = systemProperty.getValue();
systemProperty.listeners.forEach(consumer -> ((Consumer) consumer).accept(newValue));
}
}
@Override
public void propertyDeleted(final String property, final Map<String, Object> params) {
propertySet(property, params);
}
@Override
public void xmlPropertySet(final String property, final Map<String, Object> params) {
// Ignored - we're only covering database properties
}
@Override
public void xmlPropertyDeleted(final String property, final Map<String, Object> params) {
// Ignored - we're only covering database properties
}
});
}
private final Class<T> clazz;
private final String key;
private final String description;
private final String plugin;
private final T defaultValue;
private final T minValue;
private final T maxValue;
private final boolean dynamic;
private final Set<Consumer<T>> listeners = ConcurrentHashMap.newKeySet();
private T initialValue;
private final boolean encrypted;
private final ChronoUnit chronoUnit;
private final Class baseClass;
private final Class collectionType;
private final boolean sorted;
private SystemProperty(final Builder<T> builder) {
// Before we do anything, convert XML based provider setup to Database based
JiveGlobals.migrateProperty(builder.key);
this.clazz = builder.clazz;
this.key = builder.key;
this.plugin = builder.plugin;
this.description = LocaleUtils.getLocalizedPluginString(plugin, "system_property." + key);
this.defaultValue = builder.defaultValue;
this.minValue = builder.minValue;
this.maxValue = builder.maxValue;
this.dynamic = builder.dynamic;
this.encrypted = builder.encrypted;
if (encrypted) {
// Ensure a pre-existing JiveGlobal is encrypted - a null-operation if it doesn't exist/is already encrypted
JiveGlobals.setPropertyEncrypted(key, true);
}
this.chronoUnit = builder.chronoUnit;
this.baseClass = builder.baseClass;
this.collectionType = builder.collectionType;
this.sorted = builder.sorted;
this.listeners.addAll(builder.listeners);
this.initialValue = getValue();
}
/**
* @return an unmodifiable collection of all the current SystemProperties
*/
public static Collection<SystemProperty> getProperties() {
return Collections.unmodifiableCollection(PROPERTIES.values());
}
/**
* Removes all the properties for a specific plugin. This should be called by a plugin when it is unloaded to
* allow it to be added again without a server restart
* @param plugin The plugin for which properties should be removed
*/
@SuppressWarnings("WeakerAccess")
public static void removePropertiesForPlugin(final String plugin) {
getProperties().stream()
.filter(systemProperty -> systemProperty.plugin.equals(plugin))
.map(systemProperty -> systemProperty.key)
.forEach(PROPERTIES::remove);
}
/**
* Returns the SystemProperty for the specified key
*
* @param key the key for the property to fetch
* @return The SystemProperty for that key, if any
*/
public static Optional<SystemProperty> getProperty(final String key) {
return Optional.ofNullable(PROPERTIES.get(key));
}
// Enums are a special case
private Class getConverterClass() {
if(Enum.class.isAssignableFrom(clazz)) {
return Enum.class;
} else {
return clazz;
}
}
/**
* @return the current value of the SystemProperty, or the default value if it is not currently set to within the
* configured constraints. {@code null} if the property has not been set and there is no default value.
*/
@SuppressWarnings("unchecked")
public T getValue() {
final T value = (T) FROM_STRING.get(getConverterClass()).apply(JiveGlobals.getProperty(key), this);
if (value == null || (Collection.class.isAssignableFrom(value.getClass()) && ((Collection) value).isEmpty())) {
return defaultValue;
}
if (minValue != null && ((Comparable) minValue).compareTo(value) > 0) {
LOGGER.warn("Configured value of {} is less than the minimum value of {} for the SystemProperty {} - will use default value of {} instead",
value, minValue, key, defaultValue);
return defaultValue;
}
if (maxValue != null && ((Comparable) maxValue).compareTo(value) < 0) {
LOGGER.warn("Configured value of {} is more than the maximum value of {} for the SystemProperty {} - will use default value of {} instead",
value, maxValue, key, defaultValue);
return defaultValue;
}
return value;
}
/**
* @return the value of this property as saved in the ofProperty table. {@code null} if there is no current value and the default is not set.
*/
public String getValueAsSaved() {
return TO_STRING.get(getConverterClass()).apply(getValue(), this);
}
/**
* @return the value a human readable value of this property. {@code null} if there is no current value and the default is not set.
*/
public String getDisplayValue() {
return TO_DISPLAY_STRING.get(getConverterClass()).apply(getValue(), this);
}
/**
* @return {@code false} if the property has been changed from it's default value, otherwise {@code true}
*/
public boolean hasValueChanged() {
return !Objects.equals(getValue(), defaultValue);
}
/**
* @return the value a human readable value of this property. {@code null} if the default value is not configured.
*/
public String getDefaultDisplayValue() {
return TO_DISPLAY_STRING.get(getConverterClass()).apply(defaultValue, this);
}
/**
* Sets the value of the SystemProperty. Note that the new value can be outside any minimum/maximum for the property,
* and will be saved to the database as such, however subsequent attempts to retrieve it's value will return the default.
*
* @param value the new value for the SystemProperty
*/
public void setValue(final T value) {
JiveGlobals.setProperty(key, TO_STRING.get(getConverterClass()).apply(value, this), isEncrypted());
}
/**
* @return the plugin that created this property - or simply {@code "Openfire"}
*/
public String getPlugin() {
return plugin;
}
/**
* @return {@code false} if Openfire or the plugin needs to be restarted for changes to this property to take effect, otherwise {@code true}
*/
public boolean isDynamic() {
return dynamic;
}
/**
* @return {@code true} if the property was initially setup to be encrypted, or was encrypted subsequently, otherwise {@code false}
*/
public boolean isEncrypted() {
return encrypted || JiveGlobals.isPropertyEncrypted(key);
}
/**
* @return {@code true} if this property has changed and an Openfire or plugin restart is required, otherwise {@code false}
*/
public boolean isRestartRequired() {
return !(dynamic || Objects.equals(getValue(), initialValue));
}
/***
* @param listener a listener to add to the property, that will be called whenever the property value changes
*/
public void addListener(final Consumer<T> listener) {
this.listeners.add(listener);
}
/***
* @param listener the listener that is no longer required
*/
public void removeListener(final Consumer<T> listener) {
this.listeners.remove(listener);
}
/**
* @return the {@link JiveGlobals} key for this property.
*/
public String getKey() {
return key;
}
/**
* @return the description of this property. This is set in the resource bundle for the current locale, using the
* key {@code system_property.}<b><i>property-key</i></b>.
*/
public String getDescription() {
return description;
}
/**
* @return the default value of this property. {@code null} if there is no default value configured.
*/
public T getDefaultValue() {
return defaultValue;
}
/**
* Resets the initial value of the property (used to detect if a restart is required). It should
* be safe to assume that if a property has been migrated from XML to the database, no restart is
* required so this is called post-migration.
*
* For internal use only.
*/
void migrationComplete() {
this.initialValue = getValue();
}
/**
* Used to build a {@link SystemProperty}
*
* @param <T> the type of system property to build
*/
public static final class Builder<T> {
private final Class<T> clazz;
private final Set<Consumer<T>> listeners = new HashSet<>();
private String key;
private String plugin = LocaleUtils.OPENFIRE_PLUGIN_NAME;
private T defaultValue;
private T minValue;
private T maxValue;
private ChronoUnit chronoUnit;
private Boolean dynamic;
private boolean encrypted = false;
private Class<?> baseClass;
private Class collectionType;
private boolean sorted;
private Builder(final Class<T> clazz) {
this.clazz = clazz;
}
/**
* Start a new SystemProperty builder. The following types of SystemProperty are supported:
* <ul>
* <li>{@link String}</li>
* <li>{@link Integer} - for which a default value must be supplied using {@link #setDefaultValue(Object)}</li>
* <li>{@link Long} - for which a default value must be supplied</li>
* <li>{@link Double} - for which a default value must be supplied</li>
* <li>{@link Boolean} - for which a default value must be supplied</li>
* <li>{@link Duration} - for which a {@link ChronoUnit} must be specified, to indicate how the value will be saved, using {@link #setChronoUnit(ChronoUnit)}</li>
* <li>{@link Instant}</li>
* <li>{@link JID}</li>
* <li>{@link Class} - for which a base class must be specified from which values must inherit, using {@link #setBaseClass(Class)}</li>
* <li>any {@link Enum} - for which a default value must be supplied</li>
* <li>{@link List} - for which a collection type must be specified, using {@link #buildList(Class)}</li>
* <li>{@link Set} - for which a collection type must be specified, using {@link #buildSet(Class)}</li>
* </ul>
*
* @param <T> the type of SystemProperty
* @param clazz The class of property being built
* @return A SystemProperty builder
*/
public static <T> Builder<T> ofType(final Class<T> clazz) {
if (!Enum.class.isAssignableFrom(clazz)
&& (!FROM_STRING.containsKey(clazz) || !TO_STRING.containsKey(clazz) || !TO_DISPLAY_STRING.containsKey(clazz))) {
throw new IllegalArgumentException("Cannot create a SystemProperty of type " + clazz.getName());
}
return new Builder<>(clazz);
}
/**
* Sets the key for the SystemProperty. Must be unique
*
* @param key the property key
* @return The current SystemProperty builder
*/
public Builder<T> setKey(final String key) {
this.key = key;
return this;
}
/**
* Sets the default value for the SystemProperty. This value will be used if the property is not set, or
* falls outside the minimum/maximum values configured.
*
* @param defaultValue the default value for the property
* @return The current SystemProperty builder
* @see #setMinValue(Object)
* @see #setMaxValue(Object)
*/
@SuppressWarnings("unchecked")
public Builder<T> setDefaultValue(final T defaultValue) {
if( defaultValue instanceof Instant) {
this.defaultValue = (T) ((Instant) defaultValue).truncatedTo(ChronoUnit.MILLIS);
} else {
this.defaultValue = defaultValue;
}
return this;
}
/**
* This indicates which class configured values must inherit from. It must be set (and can only be set) if the default
* value is a class.
*
* @param baseClass - the base class from which all configured values must inherit
* @return The current SystemProperty builder
*/
public Builder<T> setBaseClass(final Class<?> baseClass) {
if(clazz != Class.class) {
throw new IllegalArgumentException("Only properties of type Class can have a base class set");
}
this.baseClass = baseClass;
return this;
}
/**
* Sets the minimum value for the SystemProperty. If the configured value is less than minimum value, the
* default value will be used instead.
* <p><strong>Important:</strong> If a minimum value is configured, the type of property being built must
* implement {@link Comparable}.</p>
*
* @param minValue the minimum value for the property
* @return The current SystemProperty builder
*/
public Builder<T> setMinValue(final T minValue) {
this.minValue = minValue;
return this;
}
/**
* Sets the maximum value for the SystemProperty. If the configured value is more than maximum value, the
* default value will be used instead.
* <p><strong>Important:</strong> If a maximum value is configured, the type of property being built must
* implement {@link Comparable}.</p>
*
* @param maxValue the maximum value for the property
* @return The current SystemProperty builder
*/
public Builder<T> setMaxValue(final T maxValue) {
this.maxValue = maxValue;
return this;
}
/**
* If the type of the property is a {@link Duration} this is used to indicate how the value is saved in the
* database. For an example a Duration of one hour will be saved as "60" if the ChronoUnit is {@link ChronoUnit#MINUTES}, or
* saved as "3600" if the ChronoUnit is {@link ChronoUnit#SECONDS}.
* <p><strong>Important:</strong> The ChronoUnit is required, and must be set, if the type of property is a Duration.
*
* @param chronoUnit the unit of time the Duration is saved to the database in
* @return The current SystemProperty builder
*/
public Builder<T> setChronoUnit(final ChronoUnit chronoUnit) {
this.chronoUnit = chronoUnit;
return this;
}
/**
* @param listener the listener that will be called when the value of the property changes
* @return The current SystemProperty builder
*/
public Builder<T> addListener(final Consumer<T> listener) {
this.listeners.add(listener);
return this;
}
/**
* @param dynamic {@code true} if changes to this property take effect immediately, {@code false} if a restart
* is required.
* @return The current SystemProperty builder
*/
public Builder<T> setDynamic(final boolean dynamic) {
this.dynamic = dynamic;
return this;
}
/**
* @param encrypted {@code true} if this property should be encrypted, {@code false} if can be stored in
* plain text. Defaults to plain text if not otherwise specified.
* @return The current SystemProperty builder
*/
public Builder<T> setEncrypted(final boolean encrypted) {
this.encrypted = encrypted;
return this;
}
/**
* @param sorted {@code true} if this property is a list and should be sorted, {@code false} otherwise.
* @return The current SystemProperty builder
*/
public Builder<T> setSorted(final boolean sorted) {
this.sorted = sorted;
return this;
}
/**
* Sets the name of the plugin that is associated with this property. This is used on the Openfire System
* Properties admin interface to provide filtering capabilities. This will default to Openfire if not set.
*
* @param plugin the name of the plugin creating this property.
* @return The current SystemProperty builder
*/
public Builder<T> setPlugin(final String plugin) {
this.plugin = plugin;
return this;
}
/**
* Validates the details of the SystemProperty, and generates one if it's valid.
*
* @return A SystemProperty object
* @throws IllegalArgumentException if incorrect arguments have been supplied to the builder
*/
public SystemProperty<T> build() throws IllegalArgumentException {
checkNotNull(key, "The property key has not been set");
if (PROPERTIES.containsKey(key)) {
throw new IllegalArgumentException("A SystemProperty already exists with a key of " + key);
}
if (!NULLABLE_TYPES.contains(clazz)) {
checkNotNull(defaultValue, "The properties default value has not been set");
}
final Class classToCheck;
if (Collection.class.isAssignableFrom(clazz)) {
checkNotNull(collectionType, "A collection type must be built using buildList() or buildSet()");
classToCheck = collectionType;
} else {
classToCheck = clazz;
}
if (sorted) {
if (!Collection.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException("Only Collection properties can be sorted");
}
if (!Comparable.class.isAssignableFrom(classToCheck)) {
throw new IllegalArgumentException("Only Collection properties containing Comparable elements can be sorted");
}
}
checkNotNull(plugin, "The property plugin has not been set");
checkNotNull(dynamic, "The property dynamism has not been set");
if (classToCheck == Duration.class) {
checkNotNull(chronoUnit, "The ChronoUnit for the Duration property has not been set");
if (!DURATION_TO_LONG.containsKey(chronoUnit) || !LONG_TO_DURATION.containsKey(chronoUnit)) {
throw new IllegalArgumentException("A Duration property cannot be saved with a ChronoUnit of " + chronoUnit);
}
} else if (chronoUnit != null) {
throw new IllegalArgumentException("Only properties of type Duration can have a ChronoUnit set");
}
if (minValue != null) {
if (!Comparable.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException("A minimum value can only be applied to properties that implement Comparable");
}
//noinspection unchecked
if (defaultValue != null && ((Comparable<T>) minValue).compareTo(defaultValue) > 0) {
throw new IllegalArgumentException("The minimum value cannot be more than the default value");
}
}
if (maxValue != null) {
if (!Comparable.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException("A maximum value can only be applied to properties that implement Comparable");
}
//noinspection unchecked
if (defaultValue != null && ((Comparable<T>) maxValue).compareTo(defaultValue) < 0) {
throw new IllegalArgumentException("The maximum value cannot be less than the default value");
}
}
if (classToCheck == Class.class) {
checkNotNull(baseClass, "The base class must be set for properties of type class");
}
final SystemProperty<T> property = new SystemProperty<>(this);
PROPERTIES.put(key, property);
return property;
}
@SuppressWarnings("unchecked")
public <C> SystemProperty<List<C>> buildList(final Class<C> listType) {
if (clazz != List.class) {
throw new IllegalArgumentException("Only list types can be built with buildList");
}
checkCollectionType(listType);
this.collectionType = listType;
return (SystemProperty<List<C>>) build();
}
@SuppressWarnings("unchecked")
public <C> SystemProperty<Set<C>> buildSet(final Class<C> listType) {
if (clazz != Set.class) {
throw new IllegalArgumentException("Only set types can be built with buildSet");
}
checkCollectionType(listType);
this.collectionType = listType;
return (SystemProperty<Set<C>>) build();
}
private void checkCollectionType(final Class collectionType) {
if (!FROM_STRING.containsKey(collectionType) || !TO_STRING.containsKey(collectionType) || !TO_DISPLAY_STRING.containsKey(collectionType)) {
throw new IllegalArgumentException("Cannot create a SystemProperty containing a collection of type " + collectionType.getName());
}
if (Collections.class.isAssignableFrom(collectionType)) {
throw new IllegalArgumentException("A collection cannot contain a collection");
}
}
private void checkNotNull(final Object value, final String s) {
if (value == null) {
throw new IllegalArgumentException(s);
}
}
}
}
| {
"content_hash": "49f15dda3f5009ba8bac35e353271d58",
"timestamp": "",
"source": "github",
"line_count": 729,
"max_line_length": 215,
"avg_line_length": 45.62688614540466,
"alnum_prop": 0.6240755216162588,
"repo_name": "igniterealtime/Openfire",
"id": "139dd9176039c3a16e56e085e278cfdb47b6c53e",
"size": "33262",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "xmppserver/src/main/java/org/jivesoftware/util/SystemProperty.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1395"
},
{
"name": "C",
"bytes": "3814"
},
{
"name": "CSS",
"bytes": "53010"
},
{
"name": "Dockerfile",
"bytes": "1014"
},
{
"name": "HTML",
"bytes": "364831"
},
{
"name": "Java",
"bytes": "9275728"
},
{
"name": "JavaScript",
"bytes": "10952"
},
{
"name": "Makefile",
"bytes": "1266"
},
{
"name": "Objective-C",
"bytes": "6879"
},
{
"name": "Shell",
"bytes": "68235"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>
| {
"content_hash": "09b790c9b34adfbdec91fe208328c8f6",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 111,
"avg_line_length": 28.92,
"alnum_prop": 0.5643153526970954,
"repo_name": "philiplourandos/panda-1",
"id": "f0c45691dd02179135f675a06ab4f52c13de04cb",
"size": "723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/misc.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Groovy",
"bytes": "7800"
},
{
"name": "Shell",
"bytes": "540"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Sphaerella sentina f. sentina
### Remarks
null | {
"content_hash": "7c655d39664183bfe364c2e056fe34c1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 29,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.7089552238805971,
"repo_name": "mdoering/backbone",
"id": "900a7b7a44c44818230b17222f75362a5dfc7a63",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Mycosphaerella/Mycosphaerella pyri/Sphaerella sentina sentina/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#import <AppKit/NSPopUpView.h>
#import <AppKit/NSStringDrawer.h>
#import <AppKit/NSGraphicsStyle.h>
#import <AppKit/NSMenuItem.h>
#import <AppKit/NSGraphicsStyle.h>
enum {
KEYBOARD_INACTIVE,
KEYBOARD_ACTIVE,
KEYBOARD_OK,
KEYBOARD_CANCEL
};
#define ITEM_MARGIN 2
@implementation NSPopUpView
// Note: moved these above init to avoid compiler warnings
-(NSDictionary *)itemAttributes {
return [NSDictionary dictionaryWithObjectsAndKeys:
_font,NSFontAttributeName,
nil];
}
-(NSDictionary *)selectedItemAttributes {
return [NSDictionary dictionaryWithObjectsAndKeys:
_font,NSFontAttributeName,
[NSColor selectedTextColor],NSForegroundColorAttributeName,
nil];
}
-(NSDictionary *)disabledItemAttributes {
return [NSDictionary dictionaryWithObjectsAndKeys:
_font,NSFontAttributeName,
[NSColor grayColor],NSForegroundColorAttributeName,
nil];
}
-initWithFrame:(NSRect)frame {
[super initWithFrame:frame];
_cellSize=frame.size;
_font=[[NSFont messageFontOfSize:12] retain];
_selectedIndex=-1;
_pullsDown=NO;
NSSize sz = [@"ABCxyzgjX" sizeWithAttributes: [self itemAttributes] ];
_cellSize.height = sz.height + ITEM_MARGIN + ITEM_MARGIN;
return self;
}
-(void)dealloc {
[_cachedOffsets release];
[_font release];
[super dealloc];
}
-(BOOL)isFlipped {
return YES;
}
-(void)setFont:(NSFont *)font {
[_font autorelease];
_font=[font retain];
}
-(BOOL)pullsDown {
return _pullsDown;
}
-(void)setPullsDown:(BOOL)pullsDown {
_pullsDown=pullsDown;
}
-(void)selectItemAtIndex:(int)index {
_selectedIndex=index;
}
-(NSSize)sizeForContents {
NSArray *items=[_menu itemArray];
int i, count=[items count];
NSSize result=NSMakeSize([self bounds].size.width,4);
NSDictionary *attributes = [self itemAttributes];
for( i = 0; i < count; i++ )
{
NSMenuItem * item = [items objectAtIndex: i];
if( ![item isHidden ] )
{
NSAttributedString* aTitle = [item attributedTitle];
if (aTitle != nil && [aTitle length] > 0) {
// The user is using an attributed title - so respect that when calc-ing the height and width
NSSize size = [aTitle size];
result.height += MAX(_cellSize.height, size.height);
size.width += [item indentationLevel] * 5;
result.width = MAX(result.width, size.width);
} else {
result.height += _cellSize.height;
NSSize titleSize = [[item title] sizeWithAttributes: attributes ];
titleSize.width += [item indentationLevel] * 5;
if( result.width < titleSize.width )
result.width = titleSize.width;
}
}
}
return result;
}
- (void)_buildCachedOffsets
{
NSRect result=NSMakeRect(2,2,[self bounds].size.width,_cellSize.height);
NSArray * items=[_menu itemArray];
int i, count = [items count];
_cachedOffsets = [[NSMutableArray arrayWithCapacity: count] retain];
CGFloat yOffset = 0;
// First offset is 0 of course
[_cachedOffsets addObject: [NSNumber numberWithFloat: 0]];
// Stop one before the end because we're just figuring how far down each one is based on the preceding
// entries.
for( i = 0; i < count - 1; i++ )
{
NSMenuItem* item = [items objectAtIndex: i];
if( [item isHidden ] ) {
continue;
}
NSAttributedString* aTitle = [item attributedTitle];
if (aTitle != nil && [aTitle length] > 0) {
NSSize size = [aTitle size];
yOffset += MAX(_cellSize.height, size.height);
} else {
yOffset += _cellSize.height;
}
[_cachedOffsets addObject: [NSNumber numberWithFloat: yOffset]];
}
}
// For attributed strings - precalcing the the offsets makes performance much faster.
- (NSArray*)_cachedOffsets
{
if (_cachedOffsets == nil) {
[self _buildCachedOffsets];
}
return _cachedOffsets;
}
-(NSRect)rectForItemAtIndex:(NSInteger)index {
NSRect result=NSMakeRect(2,2,[self bounds].size.width,_cellSize.height);
result.size.width-=4;
result.origin.y = [[[self _cachedOffsets] objectAtIndex: index] floatValue];
NSArray * items=[_menu itemArray];
NSMenuItem* item = [items objectAtIndex: index];
NSAttributedString* aTitle = [item attributedTitle];
// Fix up the cell height if needed
if (aTitle != nil && [aTitle length] > 0) {
NSSize size = [aTitle size];
result.size.height = MAX(_cellSize.height, size.height);
}
return result;
}
-(NSRect)rectForSelectedItem {
if(_pullsDown)
return [self rectForItemAtIndex:0];
else if(_selectedIndex==-1)
return [self rectForItemAtIndex:0];
else
return [self rectForItemAtIndex:_selectedIndex];
}
-(void)drawItemAtIndex:(NSInteger)index {
NSMenuItem *item=[_menu itemAtIndex:index];
NSDictionary *attributes;
NSRect itemRect=[self rectForItemAtIndex:index];
if( [item isHidden] )
return;
[[NSColor controlBackgroundColor] setFill];
NSRectFill(itemRect);
if([item isSeparatorItem]){
NSRect r = itemRect;
r.origin.y += r.size.height / 2 - 1;
r.size.height = 2;
[[self graphicsStyle] drawMenuSeparatorInRect:r];
}
else {
if(index==_selectedIndex && [item isEnabled]){
[[NSColor selectedTextBackgroundColor] setFill];
NSRectFill(itemRect);
}
// Accommodate indentation level
itemRect = NSOffsetRect(itemRect, [item indentationLevel] * 5, 0);
// Check for an Attributed title first
NSAttributedString* aTitle = [item attributedTitle];
if (aTitle != nil && [aTitle length] > 0) {
itemRect=NSInsetRect(itemRect,2,2);
[aTitle _clipAndDrawInRect: itemRect];
} else {
if(index==_selectedIndex && [item isEnabled]) {
attributes=[self selectedItemAttributes];
} else if ([item isEnabled] == NO) {
attributes = [self disabledItemAttributes];
} else {
attributes=[self itemAttributes];
}
NSString *string=[item title];
NSSize size=[string sizeWithAttributes:attributes];
itemRect=NSInsetRect(itemRect,2,2);
itemRect.origin.y+=floor((_cellSize.height-size.height)/2);
itemRect.size.height=size.height;
[string _clipAndDrawInRect:itemRect withAttributes:attributes];
}
}
}
/*
* Returns NSNotFound if the point is outside of the menu
* Returns -1 if the point is inside the menu but on a disabled or separator item
* Returns a usable index if the point is on a selectable item
*/
-(NSInteger)itemIndexForPoint:(NSPoint)point {
NSInteger result;
NSArray * items=[_menu itemArray];
int i, count = [items count];
point.y-=2;
if( point.y < 0 ) {
return NSNotFound;
}
for( i = 0; i < count; i++ )
{
if( [[items objectAtIndex: i] isHidden ] )
continue;
NSRect itemRect = [self rectForItemAtIndex: i];
if (NSPointInRect( point, itemRect)) {
if (([[items objectAtIndex: i] isEnabled] == NO) ||
([[items objectAtIndex: i] isSeparatorItem])) {
return -1;
}
return i;
}
}
return NSNotFound;
}
-(void)drawRect:(NSRect)rect {
NSArray *items=[_menu itemArray];
int i,count=[items count];
[[self graphicsStyle] drawPopUpButtonWindowBackgroundInRect: rect];
for(i=0;i<count;i++){
NSRect itemRect = [self rectForItemAtIndex: i];
if (NSIntersectsRect(rect, itemRect)) {
[self drawItemAtIndex:i];
}
}
}
-(void)rightMouseDown:(NSEvent *)event {
// do nothing
}
/*
* This method may return NSNotFound when the view positioned outside the initial tracking area due to preferredEdge settings and the user clicks the mouse.
* The NSPopUpButtonCell code deals with it. It might make sense for this to return the previous value.
*/
-(int)runTrackingWithEvent:(NSEvent *)event {
enum {
STATE_FIRSTMOUSEDOWN,
STATE_MOUSEDOWN,
STATE_MOUSEUP,
STATE_EXIT
} state=STATE_FIRSTMOUSEDOWN;
NSPoint firstLocation,point=[event locationInWindow];
NSInteger initialSelectedIndex = _selectedIndex;
// Make sure we get mouse moved events, too, so we can respond apporpiately to
// click-click actions as well as of click-and-drag
BOOL oldAcceptsMouseMovedEvents = [[self window] acceptsMouseMovedEvents];
[[self window] setAcceptsMouseMovedEvents:YES];
// point comes in on controls window
point=[[event window] convertBaseToScreen:point];
point=[[self window] convertScreenToBase:point];
point=[self convertPoint:point fromView:nil];
firstLocation=point;
// Make sure we know if the user clicks away from the app in the middle of this
BOOL cancelled = NO;
do {
NSInteger index=[self itemIndexForPoint:point];
NSRect screenVisible;
/*
If the popup is activated programmatically with performClick: index may be NSNotFound because the mouse starts out
outside the view. We don't change _selectedIndex in this case.
*/
if(index!= NSNotFound && _keyboardUIState == KEYBOARD_INACTIVE){
if(_selectedIndex!=index){
NSInteger previous=_selectedIndex;
if (previous != -1) {
NSRect itemRect = [self rectForItemAtIndex: previous];
[self setNeedsDisplayInRect: itemRect];
}
_selectedIndex=index;
if (_selectedIndex != -1) {
NSRect itemRect = [self rectForItemAtIndex: _selectedIndex];
[self setNeedsDisplayInRect: itemRect];
}
}
}
[[self window] flushWindow];
event=[[self window] nextEventMatchingMask:NSLeftMouseUpMask|NSMouseMovedMask|NSLeftMouseDraggedMask|NSKeyDownMask|NSAppKitDefinedMask];
if ([event type] == NSKeyDown) {
[self interpretKeyEvents:[NSArray arrayWithObject:event]];
switch (_keyboardUIState) {
case KEYBOARD_INACTIVE:
_keyboardUIState = KEYBOARD_ACTIVE;
continue;
case KEYBOARD_ACTIVE:
break;
case KEYBOARD_CANCEL:
_selectedIndex = initialSelectedIndex;
case KEYBOARD_OK:
state=STATE_EXIT;
break;
}
}
else
_keyboardUIState = KEYBOARD_INACTIVE;
if ([event type] == NSAppKitDefined) {
if ([event subtype] == NSApplicationDeactivated) {
cancelled = YES;
}
}
point=[event locationInWindow];
point=[[event window] convertBaseToScreen:point];
screenVisible=NSInsetRect([[[self window] screen] visibleFrame],4,4);
if(NSPointInRect(point,[[self window] frame]) && !NSPointInRect(point,screenVisible)){
NSPoint origin=[[self window] frame].origin;
BOOL change=NO;
if(point.y<NSMinY(screenVisible)){
origin.y+=_cellSize.height;
change=YES;
}
if(point.y>NSMaxY(screenVisible)){
origin.y-=_cellSize.height;
change=YES;
}
if(change)
[[self window] setFrameOrigin:origin];
} else {
_selectedIndex == -1;
}
point=[self convertPoint:[event locationInWindow] fromView:nil];
switch(state){
case STATE_FIRSTMOUSEDOWN:
if(NSEqualPoints(firstLocation,point)){
if([event type]==NSLeftMouseUp)
state=STATE_MOUSEUP;
}
else
state=STATE_MOUSEDOWN;
break;
default:
if([event type]==NSLeftMouseUp) {
// If the user clicked outside of the window - then they want
// to dismiss it without changing anything
NSPoint winPoint=[event locationInWindow];
winPoint=[[event window] convertBaseToScreen:winPoint];
if (NSPointInRect(winPoint,[[self window] frame]) == NO) {
_selectedIndex = -1;
}
state=STATE_EXIT;
}
break;
}
}while(cancelled == NO && state!=STATE_EXIT);
[[self window] setAcceptsMouseMovedEvents: oldAcceptsMouseMovedEvents];
_keyboardUIState = KEYBOARD_INACTIVE;
return (_selectedIndex == -1) ? NSNotFound : _selectedIndex;
}
- (void)keyDown:(NSEvent *)event {
[self interpretKeyEvents:[NSArray arrayWithObject:event]];
}
- (void)moveUp:(id)sender {
NSInteger previous = _selectedIndex;
// Find the previous visible item
NSArray *items = [_menu itemArray];
if( _selectedIndex == -1 )
_selectedIndex = [items count];
do
{
_selectedIndex--;
} while( (int)_selectedIndex >= 0 && ( [[items objectAtIndex: _selectedIndex] isHidden] ||
[[items objectAtIndex: _selectedIndex] isSeparatorItem] ) );
if ((int)_selectedIndex < 0)
_selectedIndex = previous;
[self setNeedsDisplay:YES];
}
- (void)moveDown:(id)sender {
NSInteger previous = _selectedIndex;
// Find the next visible item
NSArray *items = [_menu itemArray];
NSInteger searchIndex = _selectedIndex;
do
{
searchIndex++;
} while( searchIndex < [items count] && ( [[items objectAtIndex: searchIndex] isHidden] ||
[[items objectAtIndex: searchIndex] isSeparatorItem] ) );
if (searchIndex >= [items count]) {
_selectedIndex = previous;
} else {
_selectedIndex = searchIndex;
}
[self setNeedsDisplay:YES];
}
- (void)cancel:(id)sender {
_keyboardUIState = KEYBOARD_CANCEL;
}
- (void)insertNewline:(id)sender {
_keyboardUIState = KEYBOARD_OK;
}
- (void)insertText:(id)aString {
// We're intercepting insertText: so we can do menu navigation by letter
unichar ch = [aString characterAtIndex: 0];
NSString *letterString = [[NSString stringWithCharacters: &ch length: 1] uppercaseString];
NSInteger oldIndex = _selectedIndex;
NSArray *items = [_menu itemArray];
NSInteger newIndex = _selectedIndex;
// Set to the next item in the array or the start if we're at the end or there's no selection
if (oldIndex == NSNotFound || oldIndex == [items count] - 1) {
newIndex = 0;
} else {
newIndex = oldIndex + 1;
}
// Find the next visible item that has a title with an uppercase letter matching what the user
// entered (who knows what this means in Japan...)
BOOL found = NO;
while (!found && newIndex != oldIndex) {
// Make sure we stop eventually
if (oldIndex == NSNotFound) {
oldIndex = 0;
}
// Try and find a new item to select
NSMenuItem *item = [items objectAtIndex: newIndex];
if ([item isEnabled] == YES && [item isSeparatorItem] == NO) {
NSRange range = [[item title] rangeOfString: letterString];
if (range.location != NSNotFound) {
_selectedIndex = newIndex;
found = YES;
}
}
if (!found) {
if (newIndex == [items count] - 1) {
newIndex = 0;
} else {
newIndex++;
}
}
}
if (newIndex != oldIndex) {
[self setNeedsDisplay:YES];
}
}
@end
| {
"content_hash": "c4764d7905b8e7493f162827b886a63d",
"timestamp": "",
"source": "github",
"line_count": 530,
"max_line_length": 156,
"avg_line_length": 27.043396226415094,
"alnum_prop": 0.666503872183074,
"repo_name": "liruqi/cocotron",
"id": "96b527e34351ff3bcf2a43bf460272ba17b659be",
"size": "15426",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "AppKit/NSPopUpView.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "13460"
},
{
"name": "C",
"bytes": "550278"
},
{
"name": "C++",
"bytes": "171875"
},
{
"name": "M",
"bytes": "172915"
},
{
"name": "Makefile",
"bytes": "1912"
},
{
"name": "Mathematica",
"bytes": "112278"
},
{
"name": "Matlab",
"bytes": "35364"
},
{
"name": "Objective-C",
"bytes": "7804878"
},
{
"name": "Objective-C++",
"bytes": "112924"
},
{
"name": "Shell",
"bytes": "30866"
}
],
"symlink_target": ""
} |
<?php
/**
* Report event type resource model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace Magento\Reports\Model\ResourceModel\Event;
class Type extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Main table initialization
*
* @return void
*/
protected function _construct()
{
$this->_init('report_event_types', 'event_type_id');
}
}
| {
"content_hash": "fc5e69ed58c9fc37c59951ba5c8c65a5",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 71,
"avg_line_length": 19.59090909090909,
"alnum_prop": 0.6403712296983759,
"repo_name": "j-froehlich/magento2_wk",
"id": "c50299c9affaa9814c560bb4e6e47af8dee9a256",
"size": "539",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/magento/module-reports/Model/ResourceModel/Event/Type.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"
}
],
"symlink_target": ""
} |
<?php
/**
* @file
* Rate widget theme
*/
print theme('item_list', array(
'items' => $buttons,
//'title' => $display_options['title'],
));
if ($info) {
print '<div class="rate-info">' . $info . '</div>';
}
if ($display_options['description']) {
print '<div class="rate-description">' . $display_options['description'] . '</div>';
}
| {
"content_hash": "7798c545da6d61fc21fc8bd9f0f43c93",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 86,
"avg_line_length": 18.31578947368421,
"alnum_prop": 0.5689655172413793,
"repo_name": "AlannaBurke/endocommoms",
"id": "774cd7f0ab92f9188ce448301615b2b5b745ca27",
"size": "348",
"binary": false,
"copies": "149",
"ref": "refs/heads/master",
"path": "profiles/commons/modules/contrib/rate/templates/emotion/rate-template-emotion.tpl.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "9299"
},
{
"name": "CSS",
"bytes": "1536944"
},
{
"name": "CoffeeScript",
"bytes": "872"
},
{
"name": "HTML",
"bytes": "1383085"
},
{
"name": "JavaScript",
"bytes": "2110135"
},
{
"name": "PHP",
"bytes": "5280096"
},
{
"name": "Perl",
"bytes": "792"
},
{
"name": "Ruby",
"bytes": "9286"
},
{
"name": "Shell",
"bytes": "41807"
}
],
"symlink_target": ""
} |
'use strict';
import type {NormalizationRootNode} from '../../util/NormalizationNode';
import type {
HandleFieldPayload,
RecordSourceProxy,
} from 'relay-runtime/store/RelayStoreTypes';
import type {RequestParameters} from 'relay-runtime/util/RelayConcreteNode';
import type {
CacheConfig,
Variables,
} from 'relay-runtime/util/RelayRuntimeTypes';
const RelayNetwork = require('../../network/RelayNetwork');
const RelayObservable = require('../../network/RelayObservable');
const {graphql} = require('../../query/GraphQLTag');
const RelayModernEnvironment = require('../RelayModernEnvironment');
const {
createOperationDescriptor,
} = require('../RelayModernOperationDescriptor');
const {getSingularSelector} = require('../RelayModernSelector');
const RelayModernStore = require('../RelayModernStore');
const RelayRecordSource = require('../RelayRecordSource');
const nullthrows = require('nullthrows');
const {disallowWarnings} = require('relay-test-utils-internal');
disallowWarnings();
describe('execute() a query with plural @match', () => {
let callbacks;
let complete;
let dataSource;
let environment;
let error;
let fetch;
let markdownRendererFragment;
let markdownRendererNormalizationFragment;
let next;
let operation;
let operationCallback;
let operationLoader: {
get: (reference: mixed) => ?NormalizationRootNode,
load: JestMockFn<$ReadOnlyArray<mixed>, Promise<?NormalizationRootNode>>,
};
let query;
let resolveFragment;
let source;
let store;
let variables;
beforeEach(() => {
jest.resetModules();
query = graphql`
query RelayModernEnvironmentExecuteWithPluralMatchTestUserQuery(
$id: ID!
) {
node(id: $id) {
... on User {
nameRenderers @match {
...RelayModernEnvironmentExecuteWithPluralMatchTestPlainUserNameRenderer_name
@module(name: "PlainUserNameRenderer.react")
...RelayModernEnvironmentExecuteWithPluralMatchTestMarkdownUserNameRenderer_name
@module(name: "MarkdownUserNameRenderer.react")
}
}
}
}
`;
graphql`
fragment RelayModernEnvironmentExecuteWithPluralMatchTestPlainUserNameRenderer_name on PlainUserNameRenderer {
plaintext
data {
text
}
}
`;
markdownRendererNormalizationFragment = require('./__generated__/RelayModernEnvironmentExecuteWithPluralMatchTestMarkdownUserNameRenderer_name$normalization.graphql');
markdownRendererFragment = graphql`
fragment RelayModernEnvironmentExecuteWithPluralMatchTestMarkdownUserNameRenderer_name on MarkdownUserNameRenderer {
__typename
markdown
data {
markup @__clientField(handle: "markup_handler")
}
}
`;
variables = {id: '1'};
operation = createOperationDescriptor(query, variables);
const MarkupHandler = {
update(storeProxy: RecordSourceProxy, payload: HandleFieldPayload) {
const record = storeProxy.get(payload.dataID);
if (record != null) {
const markup = record.getValue(payload.fieldKey);
record.setValue(
typeof markup === 'string' ? markup.toUpperCase() : null,
payload.handleKey,
);
}
},
};
complete = jest.fn();
error = jest.fn();
next = jest.fn();
callbacks = {complete, error, next};
fetch = (
_query: RequestParameters,
_variables: Variables,
_cacheConfig: CacheConfig,
) => {
return RelayObservable.create(sink => {
dataSource = sink;
});
};
operationLoader = {
load: jest.fn(moduleName => {
return new Promise(resolve => {
resolveFragment = resolve;
});
}),
get: jest.fn(),
};
source = RelayRecordSource.create();
store = new RelayModernStore(source);
environment = new RelayModernEnvironment({
network: RelayNetwork.create(fetch),
store,
operationLoader,
handlerProvider: name => {
switch (name) {
case 'markup_handler':
return MarkupHandler;
}
},
});
const operationSnapshot = environment.lookup(operation.fragment);
operationCallback = jest.fn();
environment.subscribe(operationSnapshot, operationCallback);
});
it('calls next() and publishes the initial payload to the store', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRenderers: [
{
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithPluralMatchTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithPluralMatchTestUserQuery:
'RelayModernEnvironmentExecuteWithPluralMatchTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>',
},
},
],
},
},
};
dataSource.next(payload);
jest.runAllTimers();
expect(operationLoader.load).toBeCalledTimes(1);
expect(operationLoader.load.mock.calls[0][0]).toEqual(
'RelayModernEnvironmentExecuteWithPluralMatchTestMarkdownUserNameRenderer_name$normalization.graphql',
);
expect(next.mock.calls.length).toBe(1);
expect(complete).not.toBeCalled();
expect(error).not.toBeCalled();
expect(operationCallback).toBeCalledTimes(1);
const operationSnapshot = operationCallback.mock.calls[0][0];
expect(operationSnapshot.isMissingData).toBe(false);
expect(operationSnapshot.data).toEqual({
node: {
nameRenderers: [
{
__id: 'client:1:nameRenderers(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"]):0',
__fragmentPropName: 'name',
__fragments: {
RelayModernEnvironmentExecuteWithPluralMatchTestMarkdownUserNameRenderer_name:
{},
},
__fragmentOwner: operation.request,
__isWithinUnmatchedTypeRefinement: false,
__module_component: 'MarkdownUserNameRenderer.react',
},
],
},
});
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRenderers[0],
),
);
const matchSnapshot = environment.lookup(matchSelector);
// ref exists but match field data hasn't been processed yet
expect(matchSnapshot.isMissingData).toBe(true);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: undefined,
markdown: undefined,
});
});
it('loads the @match fragment and normalizes/publishes the field payload', () => {
environment.execute({operation}).subscribe(callbacks);
const payload = {
data: {
node: {
id: '1',
__typename: 'User',
nameRenderers: [
{
__typename: 'MarkdownUserNameRenderer',
__module_component_RelayModernEnvironmentExecuteWithPluralMatchTestUserQuery:
'MarkdownUserNameRenderer.react',
__module_operation_RelayModernEnvironmentExecuteWithPluralMatchTestUserQuery:
'RelayModernEnvironmentExecuteWithPluralMatchTestMarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
id: 'data-1',
// NOTE: should be uppercased when normalized (by MarkupHandler)
markup: '<markup/>',
},
},
],
},
},
};
dataSource.next(payload);
jest.runAllTimers();
next.mockClear();
expect(operationCallback).toBeCalledTimes(1); // initial results tested above
const operationSnapshot = operationCallback.mock.calls[0][0];
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data?.node: any)?.nameRenderers[0],
),
);
// initial results tested above
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(true);
const matchCallback = jest.fn();
environment.subscribe(initialMatchSnapshot, matchCallback);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
// next() should not be called when @match resolves, no new GraphQLResponse
// was received for this case
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
expect(matchCallback).toBeCalledTimes(1);
const matchSnapshot = matchCallback.mock.calls[0][0];
expect(matchSnapshot.isMissingData).toBe(false);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: {
// NOTE: should be uppercased by the MarkupHandler
markup: '<MARKUP/>',
},
markdown: 'markdown payload',
});
});
});
| {
"content_hash": "db10ee1a95e4d67ca4d7cdc82849ffc8",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 171,
"avg_line_length": 32.90492957746479,
"alnum_prop": 0.6454788657035848,
"repo_name": "xuorig/relay",
"id": "2348f12a49f7a8f47ff497a2bfa49025e924eae7",
"size": "9575",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "packages/relay-runtime/store/__tests__/RelayModernEnvironment-ExecuteWithPluralMatch-test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "41275"
},
{
"name": "HTML",
"bytes": "103086"
},
{
"name": "JavaScript",
"bytes": "3487738"
},
{
"name": "Python",
"bytes": "1730"
},
{
"name": "Rust",
"bytes": "3847046"
},
{
"name": "Shell",
"bytes": "1535"
},
{
"name": "TypeScript",
"bytes": "26834"
}
],
"symlink_target": ""
} |
<?php
if (!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Zend_Paginator_AllTests::main');
}
require_once 'Zend/PaginatorTest.php';
require_once 'Zend/Paginator/Adapter/ArrayTest.php';
require_once 'Zend/Paginator/Adapter/DbSelectTest.php';
require_once 'Zend/Paginator/Adapter/DbSelect/OracleTest.php';
require_once 'Zend/Paginator/Adapter/DbTableSelectTest.php';
require_once 'Zend/Paginator/Adapter/DbTableSelect/OracleTest.php';
require_once 'Zend/Paginator/Adapter/IteratorTest.php';
require_once 'Zend/Paginator/Adapter/NullTest.php';
require_once 'Zend/Paginator/ScrollingStyle/AllTest.php';
require_once 'Zend/Paginator/ScrollingStyle/ElasticTest.php';
require_once 'Zend/Paginator/ScrollingStyle/JumpingTest.php';
require_once 'Zend/Paginator/ScrollingStyle/SlidingTest.php';
require_once 'Zend/View/Helper/PaginationControlTest.php';
/**
* @category Zend
* @package Zend_Paginator
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Paginator
*/
class Zend_Paginator_AllTests
{
public static function main()
{
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('Zend Framework - Zend_Paginator');
$suite->addTestSuite('Zend_PaginatorTest');
$suite->addTestSuite('Zend_Paginator_Adapter_ArrayTest');
$suite->addTestSuite('Zend_Paginator_Adapter_DbSelectTest');
$suite->addTestSuite('Zend_Paginator_Adapter_DbTableSelectTest');
$suite->addTestSuite('Zend_Paginator_Adapter_IteratorTest');
$suite->addTestSuite('Zend_Paginator_Adapter_NullTest');
if (TESTS_ZEND_DB_ADAPTER_ORACLE_ENABLED) {
$suite->addTestSuite('Zend_Paginator_Adapter_DbSelect_OracleTest');
$suite->addTestSuite('Zend_Paginator_Adapter_DbTableSelect_OracleTest');
}
$suite->addTestSuite('Zend_Paginator_ScrollingStyle_AllTest');
$suite->addTestSuite('Zend_Paginator_ScrollingStyle_ElasticTest');
$suite->addTestSuite('Zend_Paginator_ScrollingStyle_JumpingTest');
$suite->addTestSuite('Zend_Paginator_ScrollingStyle_SlidingTest');
$suite->addTestSuite('Zend_View_Helper_PaginationControlTest');
return $suite;
}
}
if (PHPUnit_MAIN_METHOD == 'Zend_Paginator_AllTests::main') {
Zend_Paginator_AllTests::main();
}
| {
"content_hash": "6f7f78c46f8cfa2898adad9cd22bf4c6",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 87,
"avg_line_length": 36.79710144927536,
"alnum_prop": 0.7187869239858212,
"repo_name": "bluelovers/ZendFramework-1.x",
"id": "38a58347f14744191bd4d32ce0213280b94acede",
"size": "3259",
"binary": false,
"copies": "6",
"ref": "refs/heads/svn/master",
"path": "tests/Zend/Paginator/AllTests.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "30072"
},
{
"name": "PHP",
"bytes": "30100372"
},
{
"name": "Shell",
"bytes": "5283"
}
],
"symlink_target": ""
} |
/* eslint max-len: 0 */
import * as util from "util";
/**
* Mapping of messages to be used in Babel.
* Messages can include $0-style placeholders.
*/
export const MESSAGES = {
tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence",
classesIllegalBareSuper: "Illegal use of bare super",
classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead",
scopeDuplicateDeclaration: "Duplicate declaration $1",
settersNoRest: "Setters aren't allowed to have a rest",
noAssignmentsInForHead: "No assignments allowed in for-in/of head",
expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier",
invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue",
readOnly: "$1 is read-only",
unknownForHead: "Unknown node type $1 in ForStatement",
didYouMean: "Did you mean $1?",
codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",
missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",
unsupportedOutputType: "Unsupported output type $1",
illegalMethodName: "Illegal method name $1",
lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated",
modulesIllegalExportName: "Illegal export $1",
modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes",
undeclaredVariable: "Reference to undeclared variable $1",
undeclaredVariableType: "Referencing a type alias outside of a type annotation",
undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?",
traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.",
traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?",
traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2",
traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type",
pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3",
pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3",
pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4",
pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3"
};
/**
* Get a message with $0 placeholders replaced by arguments.
*/
export function get(key: string, ...args: Array<any>): string {
let msg = MESSAGES[key];
if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`);
// stringify args
args = parseArgs(args);
// replace $0 placeholders with args
return msg.replace(/\$(\d+)/g, function (str, i) {
return args[i - 1];
});
}
/**
* Stingify arguments to be used inside messages.
*/
export function parseArgs(args: Array<any>): Array<string> {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();
} else {
try {
return JSON.stringify(val) || val + "";
} catch (e) {
return util.inspect(val);
}
}
});
}
| {
"content_hash": "c1bcd887cf1d18dbb146103d6326e492",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 182,
"avg_line_length": 46.265822784810126,
"alnum_prop": 0.7302325581395349,
"repo_name": "zertosh/babel",
"id": "3fce2e2cf277f5179b10f340a295db381f0235a9",
"size": "3655",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "packages/babel-messages/src/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1425230"
},
{
"name": "Makefile",
"bytes": "1726"
},
{
"name": "Shell",
"bytes": "1573"
}
],
"symlink_target": ""
} |
apetools.parsers.iperfparser.IperfParser.reset
==============================================
.. currentmodule:: apetools.parsers.iperfparser
.. automethod:: IperfParser.reset | {
"content_hash": "dc78c9be413e75fc036e096c6b4d5d6b",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 47,
"avg_line_length": 29.5,
"alnum_prop": 0.6045197740112994,
"repo_name": "rsnakamura/oldape",
"id": "d00b32739f03821f1652e6d1ea61730911a04661",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apetools/parsers/api/apetools.parsers.iperfparser.IperfParser.reset.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "5832"
},
{
"name": "Python",
"bytes": "1076570"
},
{
"name": "Shell",
"bytes": "47671"
}
],
"symlink_target": ""
} |
-- This gives a frequency count of how many calls each customer makes. Useful for filtering additional queries.
-- I added some additional rows from materialized view optourism.foreigners_counts, but materialized views can't be
-- updated and other materialized views now depend on it so I can't just regenerate it.
-- Hence, I am making a table.
-- drop table if exists optourism.foreigners_counts2;
create table optourism.foreigners_counts2 as (
select cust_id,
country,
count(*) as calls,
sum(case when in_florence then 1 else 0 end) as calls_in_florence,
sum(case when in_florence_comune then 1 else 0 end) as calls_in_florence_comune,
count(distinct to_char(lat,'99.999') || to_char(lon,'99.999')) as towers,
count(distinct (case when in_florence=true then to_char(lat,'99.999') || to_char(lon,'99.999') end)) as towers_in_florence,
count(distinct (case when in_florence_comune=true then to_char(lat,'99.999') || to_char(lon,'99.999') end)) as towers_in_florence_comune,
count(distinct date_trunc('day', date_time_m)) as days_active,
count(distinct (case when in_florence=true then date_trunc('day', date_time_m) end)) as days_active_in_florence,
count(distinct (case when in_florence_comune=true then date_trunc('day', date_time_m) end)) as days_active_in_florence_comune
from optourism.cdr_foreigners
where cust_id!=25304 /*this customer is an outlier with 490K records, 10x larger than the next-highest*/
group by cust_id, country
order by calls desc
);
-- Confirmed in a separate query that no custs_id have more than 1 country
select count(*) from optourism.foreigners_counts where calls_in_florence > 0; --confirm: 1,189,353
| {
"content_hash": "880788301b68f0c4ee2feabe504dc299",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 138,
"avg_line_length": 66,
"alnum_prop": 0.7521212121212121,
"repo_name": "DSSG2017/florence",
"id": "a3f538c3507efe1b8431d6b9276aaa65f18ff0dc",
"size": "1650",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/sql/foreigners_counts2.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "95882"
},
{
"name": "HTML",
"bytes": "2664888"
},
{
"name": "JavaScript",
"bytes": "88363"
},
{
"name": "Jupyter Notebook",
"bytes": "33347362"
},
{
"name": "PLSQL",
"bytes": "10885"
},
{
"name": "PLpgSQL",
"bytes": "1276"
},
{
"name": "Python",
"bytes": "112585"
},
{
"name": "SQLPL",
"bytes": "8077"
},
{
"name": "Shell",
"bytes": "8947"
}
],
"symlink_target": ""
} |
#include "OgreStableHeaders.h"
#include "OgreManualObject.h"
#include "OgreException.h"
#include "OgreMaterialManager.h"
#include "OgreRoot.h"
#include "OgreRenderSystem.h"
#include "OgreHardwareBufferManager.h"
#include "OgreEdgeListBuilder.h"
#include "OgreMeshManager.h"
#include "OgreMesh.h"
#include "OgreSubMesh.h"
#include "OgreLogManager.h"
#include "OgreTechnique.h"
namespace Ogre {
#define TEMP_INITIAL_SIZE 50
#define TEMP_VERTEXSIZE_GUESS sizeof(float) * 12
#define TEMP_INITIAL_VERTEX_SIZE TEMP_VERTEXSIZE_GUESS * TEMP_INITIAL_SIZE
#define TEMP_INITIAL_INDEX_SIZE sizeof(uint32) * TEMP_INITIAL_SIZE
//-----------------------------------------------------------------------------
ManualObject::ManualObject(const String& name)
: MovableObject(name),
mDynamic(false), mCurrentSection(0), mCurrentUpdating(false), mFirstVertex(true),
mTempVertexPending(false),
mTempVertexBuffer(0), mTempVertexSize(TEMP_INITIAL_VERTEX_SIZE),
mTempIndexBuffer(0), mTempIndexSize(TEMP_INITIAL_INDEX_SIZE),
mDeclSize(0), mEstVertexCount(0), mEstIndexCount(0), mTexCoordIndex(0),
mRadius(0), mAnyIndexed(false), mEdgeList(0),
mUseIdentityProjection(false), mUseIdentityView(false), mKeepDeclarationOrder(false)
{
}
//-----------------------------------------------------------------------------
ManualObject::~ManualObject()
{
clear();
}
//-----------------------------------------------------------------------------
void ManualObject::clear(void)
{
resetTempAreas();
for (SectionList::iterator i = mSectionList.begin(); i != mSectionList.end(); ++i)
{
OGRE_DELETE *i;
}
mSectionList.clear();
mRadius = 0;
mAABB.setNull();
OGRE_DELETE mEdgeList;
mEdgeList = 0;
mAnyIndexed = false;
for (ShadowRenderableList::iterator s = mShadowRenderables.begin();
s != mShadowRenderables.end(); ++s)
{
OGRE_DELETE *s;
}
mShadowRenderables.clear();
}
//-----------------------------------------------------------------------------
void ManualObject::resetTempAreas(void)
{
OGRE_FREE(mTempVertexBuffer, MEMCATEGORY_GEOMETRY);
OGRE_FREE(mTempIndexBuffer, MEMCATEGORY_GEOMETRY);
mTempVertexBuffer = 0;
mTempIndexBuffer = 0;
mTempVertexSize = TEMP_INITIAL_VERTEX_SIZE;
mTempIndexSize = TEMP_INITIAL_INDEX_SIZE;
}
//-----------------------------------------------------------------------------
void ManualObject::resizeTempVertexBufferIfNeeded(size_t numVerts)
{
// Calculate byte size
// Use decl if we know it by now, otherwise default size to pos/norm/texcoord*2
size_t newSize;
if (!mFirstVertex)
{
newSize = mDeclSize * numVerts;
}
else
{
// estimate - size checks will deal for subsequent verts
newSize = TEMP_VERTEXSIZE_GUESS * numVerts;
}
if (newSize > mTempVertexSize || !mTempVertexBuffer)
{
if (!mTempVertexBuffer)
{
// init
newSize = mTempVertexSize;
}
else
{
// increase to at least double current
newSize = std::max(newSize, mTempVertexSize*2);
}
// copy old data
char* tmp = mTempVertexBuffer;
mTempVertexBuffer = OGRE_ALLOC_T(char, newSize, MEMCATEGORY_GEOMETRY);
if (tmp)
{
memcpy(mTempVertexBuffer, tmp, mTempVertexSize);
// delete old buffer
OGRE_FREE(tmp, MEMCATEGORY_GEOMETRY);
}
mTempVertexSize = newSize;
}
}
//-----------------------------------------------------------------------------
void ManualObject::resizeTempIndexBufferIfNeeded(size_t numInds)
{
size_t newSize = numInds * sizeof(uint32);
if (newSize > mTempIndexSize || !mTempIndexBuffer)
{
if (!mTempIndexBuffer)
{
// init
newSize = mTempIndexSize;
}
else
{
// increase to at least double current
newSize = std::max(newSize, mTempIndexSize*2);
}
numInds = newSize / sizeof(uint32);
uint32* tmp = mTempIndexBuffer;
mTempIndexBuffer = OGRE_ALLOC_T(uint32, numInds, MEMCATEGORY_GEOMETRY);
if (tmp)
{
memcpy(mTempIndexBuffer, tmp, mTempIndexSize);
OGRE_FREE(tmp, MEMCATEGORY_GEOMETRY);
}
mTempIndexSize = newSize;
}
}
//-----------------------------------------------------------------------------
void ManualObject::estimateVertexCount(size_t vcount)
{
resizeTempVertexBufferIfNeeded(vcount);
mEstVertexCount = vcount;
}
//-----------------------------------------------------------------------------
void ManualObject::estimateIndexCount(size_t icount)
{
resizeTempIndexBufferIfNeeded(icount);
mEstIndexCount = icount;
}
//-----------------------------------------------------------------------------
void ManualObject::begin(const String& materialName,
RenderOperation::OperationType opType, const String & groupName)
{
if (mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You cannot call begin() again until after you call end()",
"ManualObject::begin");
}
// Check that a valid material was provided
MaterialPtr material = MaterialManager::getSingleton().getByName(materialName, groupName);
if( material.isNull() )
{
LogManager::getSingleton().logMessage("Can't assign material " + materialName +
" to the ManualObject " + mName + " because this "
"Material does not exist. Have you forgotten to define it in a "
".material script?", LML_CRITICAL);
material = MaterialManager::getSingleton().getByName("BaseWhite");
if (material.isNull())
{
OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Can't assign default material "
"to the ManualObject " + mName + ". Did "
"you forget to call MaterialManager::initialise()?",
"ManualObject::begin");
}
}
mCurrentSection = OGRE_NEW ManualObjectSection(this, materialName, opType, groupName);
mCurrentUpdating = false;
mCurrentSection->setUseIdentityProjection(mUseIdentityProjection);
mCurrentSection->setUseIdentityView(mUseIdentityView);
mSectionList.push_back(mCurrentSection);
mFirstVertex = true;
mDeclSize = 0;
mTexCoordIndex = 0;
}
//-----------------------------------------------------------------------------
void ManualObject::beginUpdate(size_t sectionIndex)
{
if (mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You cannot call begin() again until after you call end()",
"ManualObject::beginUpdate");
}
if (sectionIndex >= mSectionList.size())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Invalid section index - out of range.",
"ManualObject::beginUpdate");
}
mCurrentSection = mSectionList[sectionIndex];
mCurrentUpdating = true;
mFirstVertex = true;
mTexCoordIndex = 0;
// reset vertex & index count
RenderOperation* rop = mCurrentSection->getRenderOperation();
rop->vertexData->vertexCount = 0;
if (rop->indexData)
rop->indexData->indexCount = 0;
rop->useIndexes = false;
mDeclSize = rop->vertexData->vertexDeclaration->getVertexSize(0);
}
//-----------------------------------------------------------------------------
void ManualObject::position(const Vector3& pos)
{
position(pos.x, pos.y, pos.z);
}
//-----------------------------------------------------------------------------
void ManualObject::position(Real x, Real y, Real z)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::position");
}
if (mTempVertexPending)
{
// bake current vertex
copyTempVertexToBuffer();
mFirstVertex = false;
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_FLOAT3, VES_POSITION);
mDeclSize += VertexElement::getTypeSize(VET_FLOAT3);
}
mTempVertex.position.x = x;
mTempVertex.position.y = y;
mTempVertex.position.z = z;
// update bounds
mAABB.merge(mTempVertex.position);
mRadius = std::max(mRadius, mTempVertex.position.length());
// reset current texture coord
mTexCoordIndex = 0;
mTempVertexPending = true;
}
//-----------------------------------------------------------------------------
void ManualObject::normal(const Vector3& norm)
{
normal(norm.x, norm.y, norm.z);
}
//-----------------------------------------------------------------------------
void ManualObject::normal(Real x, Real y, Real z)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::normal");
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_FLOAT3, VES_NORMAL);
mDeclSize += VertexElement::getTypeSize(VET_FLOAT3);
}
mTempVertex.normal.x = x;
mTempVertex.normal.y = y;
mTempVertex.normal.z = z;
}
//-----------------------------------------------------------------------------
void ManualObject::tangent(const Vector3& tan)
{
tangent(tan.x, tan.y, tan.z);
}
//-----------------------------------------------------------------------------
void ManualObject::tangent(Real x, Real y, Real z)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::tangent");
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_FLOAT3, VES_TANGENT);
mDeclSize += VertexElement::getTypeSize(VET_FLOAT3);
}
mTempVertex.tangent.x = x;
mTempVertex.tangent.y = y;
mTempVertex.tangent.z = z;
}
//-----------------------------------------------------------------------------
void ManualObject::textureCoord(Real u)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::textureCoord");
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_FLOAT1, VES_TEXTURE_COORDINATES, mTexCoordIndex);
mDeclSize += VertexElement::getTypeSize(VET_FLOAT1);
}
mTempVertex.texCoordDims[mTexCoordIndex] = 1;
mTempVertex.texCoord[mTexCoordIndex].x = u;
++mTexCoordIndex;
}
//-----------------------------------------------------------------------------
void ManualObject::textureCoord(Real u, Real v)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::textureCoord");
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_FLOAT2, VES_TEXTURE_COORDINATES, mTexCoordIndex);
mDeclSize += VertexElement::getTypeSize(VET_FLOAT2);
}
mTempVertex.texCoordDims[mTexCoordIndex] = 2;
mTempVertex.texCoord[mTexCoordIndex].x = u;
mTempVertex.texCoord[mTexCoordIndex].y = v;
++mTexCoordIndex;
}
//-----------------------------------------------------------------------------
void ManualObject::textureCoord(Real u, Real v, Real w)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::textureCoord");
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_FLOAT3, VES_TEXTURE_COORDINATES, mTexCoordIndex);
mDeclSize += VertexElement::getTypeSize(VET_FLOAT3);
}
mTempVertex.texCoordDims[mTexCoordIndex] = 3;
mTempVertex.texCoord[mTexCoordIndex].x = u;
mTempVertex.texCoord[mTexCoordIndex].y = v;
mTempVertex.texCoord[mTexCoordIndex].z = w;
++mTexCoordIndex;
}
//-----------------------------------------------------------------------------
void ManualObject::textureCoord(Real x, Real y, Real z, Real w)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::textureCoord");
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_FLOAT4, VES_TEXTURE_COORDINATES, mTexCoordIndex);
mDeclSize += VertexElement::getTypeSize(VET_FLOAT4);
}
mTempVertex.texCoordDims[mTexCoordIndex] = 4;
mTempVertex.texCoord[mTexCoordIndex].x = x;
mTempVertex.texCoord[mTexCoordIndex].y = y;
mTempVertex.texCoord[mTexCoordIndex].z = z;
mTempVertex.texCoord[mTexCoordIndex].w = w;
++mTexCoordIndex;
}
//-----------------------------------------------------------------------------
void ManualObject::textureCoord(const Vector2& uv)
{
textureCoord(uv.x, uv.y);
}
//-----------------------------------------------------------------------------
void ManualObject::textureCoord(const Vector3& uvw)
{
textureCoord(uvw.x, uvw.y, uvw.z);
}
//---------------------------------------------------------------------
void ManualObject::textureCoord(const Vector4& xyzw)
{
textureCoord(xyzw.x, xyzw.y, xyzw.z, xyzw.w);
}
//-----------------------------------------------------------------------------
void ManualObject::colour(const ColourValue& col)
{
colour(col.r, col.g, col.b, col.a);
}
//-----------------------------------------------------------------------------
void ManualObject::colour(Real r, Real g, Real b, Real a)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::colour");
}
if (mFirstVertex && !mCurrentUpdating)
{
// defining declaration
mCurrentSection->getRenderOperation()->vertexData->vertexDeclaration
->addElement(0, mDeclSize, VET_COLOUR, VES_DIFFUSE);
mDeclSize += VertexElement::getTypeSize(VET_COLOUR);
}
mTempVertex.colour.r = r;
mTempVertex.colour.g = g;
mTempVertex.colour.b = b;
mTempVertex.colour.a = a;
}
//-----------------------------------------------------------------------------
void ManualObject::index(uint32 idx)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::index");
}
mAnyIndexed = true;
if (idx >= 65536)
mCurrentSection->set32BitIndices(true);
// make sure we have index data
RenderOperation* rop = mCurrentSection->getRenderOperation();
if (!rop->indexData)
{
rop->indexData = OGRE_NEW IndexData();
rop->indexData->indexCount = 0;
}
rop->useIndexes = true;
resizeTempIndexBufferIfNeeded(++rop->indexData->indexCount);
mTempIndexBuffer[rop->indexData->indexCount - 1] = idx;
}
//-----------------------------------------------------------------------------
void ManualObject::triangle(uint32 i1, uint32 i2, uint32 i3)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You must call begin() before this method",
"ManualObject::index");
}
if (mCurrentSection->getRenderOperation()->operationType !=
RenderOperation::OT_TRIANGLE_LIST)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"This method is only valid on triangle lists",
"ManualObject::index");
}
index(i1);
index(i2);
index(i3);
}
//-----------------------------------------------------------------------------
void ManualObject::quad(uint32 i1, uint32 i2, uint32 i3, uint32 i4)
{
// first tri
triangle(i1, i2, i3);
// second tri
triangle(i3, i4, i1);
}
//-----------------------------------------------------------------------------
size_t ManualObject::getCurrentVertexCount() const
{
if (!mCurrentSection)
return 0;
RenderOperation* rop = mCurrentSection->getRenderOperation();
// There's an unfinished vertex being defined, so include it in count
if (mTempVertexPending)
return rop->vertexData->vertexCount + 1;
else
return rop->vertexData->vertexCount;
}
//-----------------------------------------------------------------------------
size_t ManualObject::getCurrentIndexCount() const
{
if (!mCurrentSection)
return 0;
RenderOperation* rop = mCurrentSection->getRenderOperation();
if (rop->indexData)
return rop->indexData->indexCount;
else
return 0;
}
//-----------------------------------------------------------------------------
void ManualObject::copyTempVertexToBuffer(void)
{
mTempVertexPending = false;
RenderOperation* rop = mCurrentSection->getRenderOperation();
if (rop->vertexData->vertexCount == 0 && !mCurrentUpdating)
{
// first vertex, autoorganise decl
VertexDeclaration* oldDcl = rop->vertexData->vertexDeclaration;
rop->vertexData->vertexDeclaration =
oldDcl->getAutoOrganisedDeclaration(false, false, false);
HardwareBufferManager::getSingleton().destroyVertexDeclaration(oldDcl);
}
resizeTempVertexBufferIfNeeded(++rop->vertexData->vertexCount);
// get base pointer
char* pBase = mTempVertexBuffer + (mDeclSize * (rop->vertexData->vertexCount-1));
const VertexDeclaration::VertexElementList& elemList =
rop->vertexData->vertexDeclaration->getElements();
for (VertexDeclaration::VertexElementList::const_iterator i = elemList.begin();
i != elemList.end(); ++i)
{
float* pFloat = 0;
RGBA* pRGBA = 0;
const VertexElement& elem = *i;
switch(elem.getType())
{
case VET_FLOAT1:
case VET_FLOAT2:
case VET_FLOAT3:
case VET_FLOAT4:
elem.baseVertexPointerToElement(pBase, &pFloat);
break;
case VET_COLOUR:
case VET_COLOUR_ABGR:
case VET_COLOUR_ARGB:
elem.baseVertexPointerToElement(pBase, &pRGBA);
break;
default:
// nop ?
break;
};
RenderSystem* rs;
unsigned short dims;
switch(elem.getSemantic())
{
case VES_POSITION:
*pFloat++ = mTempVertex.position.x;
*pFloat++ = mTempVertex.position.y;
*pFloat++ = mTempVertex.position.z;
break;
case VES_NORMAL:
*pFloat++ = mTempVertex.normal.x;
*pFloat++ = mTempVertex.normal.y;
*pFloat++ = mTempVertex.normal.z;
break;
case VES_TANGENT:
*pFloat++ = mTempVertex.tangent.x;
*pFloat++ = mTempVertex.tangent.y;
*pFloat++ = mTempVertex.tangent.z;
break;
case VES_TEXTURE_COORDINATES:
dims = VertexElement::getTypeCount(elem.getType());
for (ushort t = 0; t < dims; ++t)
*pFloat++ = mTempVertex.texCoord[elem.getIndex()][t];
break;
case VES_DIFFUSE:
rs = Root::getSingleton().getRenderSystem();
if (rs)
{
rs->convertColourValue(mTempVertex.colour, pRGBA++);
}
else
{
switch(elem.getType())
{
case VET_COLOUR_ABGR:
*pRGBA++ = mTempVertex.colour.getAsABGR();
break;
case VET_COLOUR_ARGB:
*pRGBA++ = mTempVertex.colour.getAsARGB();
break;
default:
*pRGBA++ = mTempVertex.colour.getAsRGBA();
}
}
break;
default:
// nop ?
break;
};
}
}
//-----------------------------------------------------------------------------
ManualObject::ManualObjectSection* ManualObject::end(void)
{
if (!mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You cannot call end() until after you call begin()",
"ManualObject::end");
}
if (mTempVertexPending)
{
// bake current vertex
copyTempVertexToBuffer();
}
// pointer that will be returned
ManualObjectSection* result = NULL;
RenderOperation* rop = mCurrentSection->getRenderOperation();
// Check for empty content
if (rop->vertexData->vertexCount == 0 ||
(rop->useIndexes && rop->indexData->indexCount == 0))
{
// You're wasting my time sonny
if (mCurrentUpdating)
{
// Can't just undo / remove since may be in the middle
// Just allow counts to be 0, will not be issued to renderer
// return the finished section (though it has zero vertices)
result = mCurrentSection;
}
else
{
// First creation, can really undo
// Has already been added to section list end, so remove
mSectionList.pop_back();
OGRE_DELETE mCurrentSection;
}
}
else // not an empty section
{
// Bake the real buffers
HardwareVertexBufferSharedPtr vbuf;
// Check buffer sizes
bool vbufNeedsCreating = true;
bool ibufNeedsCreating = rop->useIndexes;
// Work out if we require 16 or 32-bit index buffers
HardwareIndexBuffer::IndexType indexType = mCurrentSection->get32BitIndices()?
HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT;
if (mCurrentUpdating)
{
// May be able to reuse buffers, check sizes
vbuf = rop->vertexData->vertexBufferBinding->getBuffer(0);
if (vbuf->getNumVertices() >= rop->vertexData->vertexCount)
vbufNeedsCreating = false;
if (rop->useIndexes)
{
if ((rop->indexData->indexBuffer->getNumIndexes() >= rop->indexData->indexCount) &&
(indexType == rop->indexData->indexBuffer->getType()))
ibufNeedsCreating = false;
}
}
if (vbufNeedsCreating)
{
// Make the vertex buffer larger if estimated vertex count higher
// to allow for user-configured growth area
size_t vertexCount = std::max(rop->vertexData->vertexCount,
mEstVertexCount);
vbuf =
HardwareBufferManager::getSingleton().createVertexBuffer(
mDeclSize,
vertexCount,
mDynamic? HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY :
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
rop->vertexData->vertexBufferBinding->setBinding(0, vbuf);
}
if (ibufNeedsCreating)
{
// Make the index buffer larger if estimated index count higher
// to allow for user-configured growth area
size_t indexCount = std::max(rop->indexData->indexCount,
mEstIndexCount);
rop->indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
indexType,
indexCount,
mDynamic? HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY :
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
}
// Write vertex data
vbuf->writeData(
0, rop->vertexData->vertexCount * vbuf->getVertexSize(),
mTempVertexBuffer, true);
// Write index data
if(rop->useIndexes)
{
if (HardwareIndexBuffer::IT_32BIT == indexType)
{
// direct copy from the mTempIndexBuffer
rop->indexData->indexBuffer->writeData(
0,
rop->indexData->indexCount
* rop->indexData->indexBuffer->getIndexSize(),
mTempIndexBuffer, true);
}
else //(HardwareIndexBuffer::IT_16BIT == indexType)
{
uint16* pIdx = static_cast<uint16*>(rop->indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD));
uint32* pSrc = mTempIndexBuffer;
for (size_t i = 0; i < rop->indexData->indexCount; i++)
{
*pIdx++ = static_cast<uint16>(*pSrc++);
}
rop->indexData->indexBuffer->unlock();
}
}
// return the finished section
result = mCurrentSection;
} // empty section check
mCurrentSection = 0;
resetTempAreas();
// Tell parent if present
if (mParentNode)
{
mParentNode->needUpdate();
}
// will return the finished section or NULL if
// the section was empty (i.e. zero vertices/indices)
return result;
}
//-----------------------------------------------------------------------------
void ManualObject::setMaterialName(size_t idx, const String& name, const String& group)
{
if (idx >= mSectionList.size())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Index out of bounds!",
"ManualObject::setMaterialName");
}
mSectionList[idx]->setMaterialName(name, group);
}
//-----------------------------------------------------------------------------
MeshPtr ManualObject::convertToMesh(const String& meshName, const String& groupName)
{
if (mCurrentSection)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"You cannot call convertToMesh() whilst you are in the middle of "
"defining the object; call end() first.",
"ManualObject::convertToMesh");
}
if (mSectionList.empty())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"No data defined to convert to a mesh.",
"ManualObject::convertToMesh");
}
MeshPtr m = MeshManager::getSingleton().createManual(meshName, groupName);
for (SectionList::iterator i = mSectionList.begin(); i != mSectionList.end(); ++i)
{
ManualObjectSection* sec = *i;
RenderOperation* rop = sec->getRenderOperation();
SubMesh* sm = m->createSubMesh();
sm->useSharedVertices = false;
sm->operationType = rop->operationType;
sm->setMaterialName(sec->getMaterialName(), groupName);
// Copy vertex data; replicate buffers too
sm->vertexData = rop->vertexData->clone(true);
// Copy index data; replicate buffers too; delete the default, old one to avoid memory leaks
// check if index data is present
if (rop->indexData)
{
// Copy index data; replicate buffers too; delete the default, old one to avoid memory leaks
OGRE_DELETE sm->indexData;
sm->indexData = rop->indexData->clone(true);
}
}
// update bounds
m->_setBounds(mAABB);
m->_setBoundingSphereRadius(mRadius);
m->load();
return m;
}
//-----------------------------------------------------------------------------
void ManualObject::setUseIdentityProjection(bool useIdentityProjection)
{
// Set existing
for (SectionList::iterator i = mSectionList.begin(); i != mSectionList.end(); ++i)
{
(*i)->setUseIdentityProjection(useIdentityProjection);
}
// Save setting for future sections
mUseIdentityProjection = useIdentityProjection;
}
//-----------------------------------------------------------------------------
void ManualObject::setUseIdentityView(bool useIdentityView)
{
// Set existing
for (SectionList::iterator i = mSectionList.begin(); i != mSectionList.end(); ++i)
{
(*i)->setUseIdentityView(useIdentityView);
}
// Save setting for future sections
mUseIdentityView = useIdentityView;
}
//-----------------------------------------------------------------------
ManualObject::ManualObjectSection* ManualObject::getSection(unsigned int inIndex) const
{
if (inIndex >= mSectionList.size())
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Index out of bounds.",
"ManualObject::getSection");
return mSectionList[inIndex];
}
//-----------------------------------------------------------------------
unsigned int ManualObject::getNumSections(void) const
{
return static_cast< unsigned int >( mSectionList.size() );
}
//-----------------------------------------------------------------------------
const String& ManualObject::getMovableType(void) const
{
return ManualObjectFactory::FACTORY_TYPE_NAME;
}
//-----------------------------------------------------------------------------
const AxisAlignedBox& ManualObject::getBoundingBox(void) const
{
return mAABB;
}
//-----------------------------------------------------------------------------
Real ManualObject::getBoundingRadius(void) const
{
return mRadius;
}
//-----------------------------------------------------------------------------
void ManualObject::_updateRenderQueue(RenderQueue* queue)
{
// To be used when order of creation must be kept while rendering
unsigned short priority = queue->getDefaultRenderablePriority();
for (SectionList::iterator i = mSectionList.begin(); i != mSectionList.end(); ++i)
{
// Skip empty sections (only happens if non-empty first, then updated)
RenderOperation* rop = (*i)->getRenderOperation();
if (rop->vertexData->vertexCount == 0 ||
(rop->useIndexes && rop->indexData->indexCount == 0))
continue;
if (mRenderQueuePrioritySet)
{
assert(mRenderQueueIDSet == true);
queue->addRenderable(*i, mRenderQueueID, mRenderQueuePriority);
}
else if (mRenderQueueIDSet)
queue->addRenderable(*i, mRenderQueueID, mKeepDeclarationOrder ? priority++ : queue->getDefaultRenderablePriority());
else
queue->addRenderable(*i, queue->getDefaultQueueGroup(), mKeepDeclarationOrder ? priority++ : queue->getDefaultRenderablePriority());
}
}
//-----------------------------------------------------------------------------
void ManualObject::visitRenderables(Renderable::Visitor* visitor,
bool debugRenderables)
{
for (SectionList::iterator i = mSectionList.begin(); i != mSectionList.end(); ++i)
{
visitor->visit(*i, 0, false);
}
}
//-----------------------------------------------------------------------------
EdgeData* ManualObject::getEdgeList(void)
{
// Build on demand
if (!mEdgeList && mAnyIndexed)
{
EdgeListBuilder eb;
size_t vertexSet = 0;
bool anyBuilt = false;
for (SectionList::iterator i = mSectionList.begin(); i != mSectionList.end(); ++i)
{
RenderOperation* rop = (*i)->getRenderOperation();
// Only indexed triangle geometry supported for stencil shadows
if (rop->useIndexes && rop->indexData->indexCount != 0 &&
(rop->operationType == RenderOperation::OT_TRIANGLE_FAN ||
rop->operationType == RenderOperation::OT_TRIANGLE_LIST ||
rop->operationType == RenderOperation::OT_TRIANGLE_STRIP))
{
eb.addVertexData(rop->vertexData);
eb.addIndexData(rop->indexData, vertexSet++);
anyBuilt = true;
}
}
if (anyBuilt)
mEdgeList = eb.build();
}
return mEdgeList;
}
//---------------------------------------------------------------------
bool ManualObject::hasEdgeList()
{
return getEdgeList() != 0;
}
//-----------------------------------------------------------------------------
ShadowCaster::ShadowRenderableListIterator
ManualObject::getShadowVolumeRenderableIterator(
ShadowTechnique shadowTechnique, const Light* light,
HardwareIndexBufferSharedPtr* indexBuffer, size_t* indexBufferUsedSize,
bool extrude, Real extrusionDistance, unsigned long flags)
{
assert(indexBuffer && "Only external index buffers are supported right now");
EdgeData* edgeList = getEdgeList();
if (!edgeList)
{
return ShadowRenderableListIterator(
mShadowRenderables.begin(), mShadowRenderables.end());
}
// Calculate the object space light details
Vector4 lightPos = light->getAs4DVector();
Matrix4 world2Obj = mParentNode->_getFullTransform().inverseAffine();
lightPos = world2Obj.transformAffine(lightPos);
Matrix3 world2Obj3x3;
world2Obj.extract3x3Matrix(world2Obj3x3);
extrusionDistance *= Math::Sqrt(std::min(std::min(world2Obj3x3.GetColumn(0).squaredLength(), world2Obj3x3.GetColumn(1).squaredLength()), world2Obj3x3.GetColumn(2).squaredLength()));
// Init shadow renderable list if required (only allow indexed)
bool init = mShadowRenderables.empty() && mAnyIndexed;
EdgeData::EdgeGroupList::iterator egi;
ShadowRenderableList::iterator si, siend;
ManualObjectSectionShadowRenderable* esr = 0;
SectionList::iterator seci;
if (init)
mShadowRenderables.resize(edgeList->edgeGroups.size());
siend = mShadowRenderables.end();
egi = edgeList->edgeGroups.begin();
seci = mSectionList.begin();
for (si = mShadowRenderables.begin(); si != siend; ++seci)
{
// Skip non-indexed geometry
if (!(*seci)->getRenderOperation()->useIndexes)
{
continue;
}
if (init)
{
// Create a new renderable, create a separate light cap if
// we're using a vertex program (either for this model, or
// for extruding the shadow volume) since otherwise we can
// get depth-fighting on the light cap
MaterialPtr mat = (*seci)->getMaterial();
mat->load();
bool vertexProgram = false;
Technique* t = mat->getBestTechnique(0, *seci);
for (unsigned short p = 0; p < t->getNumPasses(); ++p)
{
Pass* pass = t->getPass(p);
if (pass->hasVertexProgram())
{
vertexProgram = true;
break;
}
}
*si = OGRE_NEW ManualObjectSectionShadowRenderable(this, indexBuffer,
egi->vertexData, vertexProgram || !extrude);
}
// Get shadow renderable
esr = static_cast<ManualObjectSectionShadowRenderable*>(*si);
HardwareVertexBufferSharedPtr esrPositionBuffer = esr->getPositionBuffer();
// Extrude vertices in software if required
if (extrude)
{
extrudeVertices(esrPositionBuffer,
egi->vertexData->vertexCount,
lightPos, extrusionDistance);
}
++si;
++egi;
}
// Calc triangle light facing
updateEdgeListLightFacing(edgeList, lightPos);
// Generate indexes and update renderables
generateShadowVolume(edgeList, *indexBuffer, *indexBufferUsedSize,
light, mShadowRenderables, flags);
return ShadowRenderableListIterator(
mShadowRenderables.begin(), mShadowRenderables.end());
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
ManualObject::ManualObjectSection::ManualObjectSection(ManualObject* parent,
const String& materialName, RenderOperation::OperationType opType, const String & groupName)
: mParent(parent), mMaterialName(materialName), mGroupName(groupName), m32BitIndices(false)
{
mRenderOperation.operationType = opType;
// default to no indexes unless we're told
mRenderOperation.useIndexes = false;
mRenderOperation.useGlobalInstancingVertexBufferIsAvailable = false;
mRenderOperation.vertexData = OGRE_NEW VertexData();
mRenderOperation.vertexData->vertexCount = 0;
}
//-----------------------------------------------------------------------------
ManualObject::ManualObjectSection::~ManualObjectSection()
{
OGRE_DELETE mRenderOperation.vertexData;
OGRE_DELETE mRenderOperation.indexData; // ok to delete 0
}
//-----------------------------------------------------------------------------
RenderOperation* ManualObject::ManualObjectSection::getRenderOperation(void)
{
return &mRenderOperation;
}
//-----------------------------------------------------------------------------
const MaterialPtr& ManualObject::ManualObjectSection::getMaterial(void) const
{
if (mMaterial.isNull())
{
// Load from default group. If user wants to use alternate groups,
// they can define it and preload
mMaterial = MaterialManager::getSingleton().load(mMaterialName, mGroupName).staticCast<Material>();
}
return mMaterial;
}
//-----------------------------------------------------------------------------
void ManualObject::ManualObjectSection::setMaterialName( const String& name, const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */)
{
if (mMaterialName != name || mGroupName != groupName)
{
mMaterialName = name;
mGroupName = groupName;
mMaterial.setNull();
}
}
//-----------------------------------------------------------------------------
void ManualObject::ManualObjectSection::getRenderOperation(RenderOperation& op)
{
// direct copy
op = mRenderOperation;
}
//-----------------------------------------------------------------------------
void ManualObject::ManualObjectSection::getWorldTransforms(Matrix4* xform) const
{
xform[0] = mParent->_getParentNodeFullTransform();
}
//-----------------------------------------------------------------------------
Real ManualObject::ManualObjectSection::getSquaredViewDepth(const Ogre::Camera *cam) const
{
Node* n = mParent->getParentNode();
assert(n);
return n->getSquaredViewDepth(cam);
}
//-----------------------------------------------------------------------------
const LightList& ManualObject::ManualObjectSection::getLights(void) const
{
return mParent->queryLights();
}
//-----------------------------------------------------------------------------
//--------------------------------------------------------------------------
ManualObject::ManualObjectSectionShadowRenderable::ManualObjectSectionShadowRenderable(
ManualObject* parent, HardwareIndexBufferSharedPtr* indexBuffer,
const VertexData* vertexData, bool createSeparateLightCap,
bool isLightCap)
: mParent(parent)
{
// Initialise render op
mRenderOp.indexData = OGRE_NEW IndexData();
mRenderOp.indexData->indexBuffer = *indexBuffer;
mRenderOp.indexData->indexStart = 0;
// index start and count are sorted out later
// Create vertex data which just references position component (and 2 component)
mRenderOp.vertexData = OGRE_NEW VertexData();
// Map in position data
mRenderOp.vertexData->vertexDeclaration->addElement(0,0,VET_FLOAT3, VES_POSITION);
ushort origPosBind =
vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION)->getSource();
mPositionBuffer = vertexData->vertexBufferBinding->getBuffer(origPosBind);
mRenderOp.vertexData->vertexBufferBinding->setBinding(0, mPositionBuffer);
// Map in w-coord buffer (if present)
if(!vertexData->hardwareShadowVolWBuffer.isNull())
{
mRenderOp.vertexData->vertexDeclaration->addElement(1,0,VET_FLOAT1, VES_TEXTURE_COORDINATES, 0);
mWBuffer = vertexData->hardwareShadowVolWBuffer;
mRenderOp.vertexData->vertexBufferBinding->setBinding(1, mWBuffer);
}
// Use same vertex start as input
mRenderOp.vertexData->vertexStart = vertexData->vertexStart;
if (isLightCap)
{
// Use original vertex count, no extrusion
mRenderOp.vertexData->vertexCount = vertexData->vertexCount;
}
else
{
// Vertex count must take into account the doubling of the buffer,
// because second half of the buffer is the extruded copy
mRenderOp.vertexData->vertexCount =
vertexData->vertexCount * 2;
if (createSeparateLightCap)
{
// Create child light cap
mLightCap = OGRE_NEW ManualObjectSectionShadowRenderable(parent,
indexBuffer, vertexData, false, true);
}
}
}
//--------------------------------------------------------------------------
ManualObject::ManualObjectSectionShadowRenderable::~ManualObjectSectionShadowRenderable()
{
OGRE_DELETE mRenderOp.indexData;
OGRE_DELETE mRenderOp.vertexData;
}
//--------------------------------------------------------------------------
void ManualObject::ManualObjectSectionShadowRenderable::getWorldTransforms(
Matrix4* xform) const
{
// pretransformed
*xform = mParent->_getParentNodeFullTransform();
}
//-----------------------------------------------------------------------
void ManualObject::ManualObjectSectionShadowRenderable::rebindIndexBuffer(const HardwareIndexBufferSharedPtr& indexBuffer)
{
mRenderOp.indexData->indexBuffer = indexBuffer;
if (mLightCap) mLightCap->rebindIndexBuffer(indexBuffer);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
String ManualObjectFactory::FACTORY_TYPE_NAME = "ManualObject";
//-----------------------------------------------------------------------------
const String& ManualObjectFactory::getType(void) const
{
return FACTORY_TYPE_NAME;
}
//-----------------------------------------------------------------------------
MovableObject* ManualObjectFactory::createInstanceImpl(
const String& name, const NameValuePairList* params)
{
return OGRE_NEW ManualObject(name);
}
//-----------------------------------------------------------------------------
void ManualObjectFactory::destroyInstance( MovableObject* obj)
{
OGRE_DELETE obj;
}
}
| {
"content_hash": "623251b1c53b9a3491498afe9f2e12f5",
"timestamp": "",
"source": "github",
"line_count": 1207,
"max_line_length": 189,
"avg_line_length": 39.454018227009115,
"alnum_prop": 0.503748346317801,
"repo_name": "redheli/ogre",
"id": "f0699efbc84ab1a5431e6d4c0851a61f193351cd",
"size": "48984",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OgreMain/src/OgreManualObject.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "281"
},
{
"name": "Batchfile",
"bytes": "8997"
},
{
"name": "C",
"bytes": "3516438"
},
{
"name": "C++",
"bytes": "25507917"
},
{
"name": "CMake",
"bytes": "392563"
},
{
"name": "CSS",
"bytes": "8682"
},
{
"name": "GLSL",
"bytes": "1038"
},
{
"name": "Groff",
"bytes": "68243"
},
{
"name": "HTML",
"bytes": "145744"
},
{
"name": "Java",
"bytes": "6289"
},
{
"name": "Lex",
"bytes": "83193"
},
{
"name": "Makefile",
"bytes": "413"
},
{
"name": "Objective-C",
"bytes": "60249"
},
{
"name": "Objective-C++",
"bytes": "279639"
},
{
"name": "Python",
"bytes": "479342"
},
{
"name": "Shell",
"bytes": "10305"
},
{
"name": "TeX",
"bytes": "43359"
},
{
"name": "Visual Basic",
"bytes": "1095"
},
{
"name": "Yacc",
"bytes": "40113"
}
],
"symlink_target": ""
} |
@interface User : NSObject
@property(readonly,nonatomic,strong) NSString* userid;
@property(readonly,nonatomic,strong) NSString* password;
+(instancetype)userWithId:(NSString*)userid AndPassword:(NSString*)password;
-(instancetype)initWithId:(NSString*)userid AndPassword:(NSString*)password;
@end
| {
"content_hash": "560b3375793d62ee501b20a6f4f277b2",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 76,
"avg_line_length": 42.714285714285715,
"alnum_prop": 0.8093645484949833,
"repo_name": "pydio/pydio-sdk-objc",
"id": "a715c19d318ee031a617e98090c9b47c28dd438c",
"size": "449",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "PydioSDK/PydioSDK/Classes/Public/Data/User.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "218258"
},
{
"name": "Shell",
"bytes": "1068"
}
],
"symlink_target": ""
} |
package com.google.cloud.notebooks.v1.samples;
// [START notebooks_v1_generated_notebookserviceclient_getinstancehealth_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.notebooks.v1.GetInstanceHealthRequest;
import com.google.cloud.notebooks.v1.GetInstanceHealthResponse;
import com.google.cloud.notebooks.v1.InstanceName;
import com.google.cloud.notebooks.v1.NotebookServiceClient;
public class AsyncGetInstanceHealth {
public static void main(String[] args) throws Exception {
asyncGetInstanceHealth();
}
public static void asyncGetInstanceHealth() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (NotebookServiceClient notebookServiceClient = NotebookServiceClient.create()) {
GetInstanceHealthRequest request =
GetInstanceHealthRequest.newBuilder()
.setName(InstanceName.of("[PROJECT]", "[INSTANCE]").toString())
.build();
ApiFuture<GetInstanceHealthResponse> future =
notebookServiceClient.getInstanceHealthCallable().futureCall(request);
// Do something.
GetInstanceHealthResponse response = future.get();
}
}
}
// [END notebooks_v1_generated_notebookserviceclient_getinstancehealth_async]
| {
"content_hash": "16b5178696211cc6d9724ced0b3b6ebe",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 100,
"avg_line_length": 44.5,
"alnum_prop": 0.7590511860174781,
"repo_name": "googleapis/java-notebooks",
"id": "f85dced78f8a6f0598f27f5d665f56b0a31eedd6",
"size": "2197",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "samples/snippets/generated/com/google/cloud/notebooks/v1/notebookserviceclient/getinstancehealth/AsyncGetInstanceHealth.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "801"
},
{
"name": "Java",
"bytes": "6627024"
},
{
"name": "Python",
"bytes": "788"
},
{
"name": "Shell",
"bytes": "20450"
}
],
"symlink_target": ""
} |
#http://www.techdiction.com/2016/02/12/create-a-custom-script-extension-for-an-azure-resource-manager-vm-using-powershell/
$rgname = "rg_vm"
$VMName = "vm4"
$file = "C:\Data\dev\posh\Azure\Utilities\ConfigureWinRM_HTTPS.ps1"
$containerName = "script-container"
# Get the VM we need to configure
$vm = Get-AzureRmVM -ResourceGroupName $rgname -Name $VMName
# Get storage account name
$storageaccountname = $vm.StorageProfile.OsDisk.Vhd.Uri.Split('.')[0].Replace('https://','')
# get storage account key
$key = (Get-AzureRmStorageAccountKey -Name $storageaccountname -ResourceGroupName $rgname).Key1
# create storage context
$storagecontext = New-AzureStorageContext -StorageAccountName $storageaccountname -StorageAccountKey $key
# create a container called scripts
New-AzureStorageContainer -Name "scripts" -Context $storagecontext
#upload the file
Set-AzureStorageBlobContent -Container "scripts" -File "$file" -Context $storagecontext -Blob "ConfigureWinRM_HTTPS.ps1" -BlobType Page
# Create custom script extension from uploaded file
#Set-AzureRmVMCustomScriptExtension -ResourceGroupName $rgname -VMName $vmname -Name "EnableWinRM_HTTPS" -Location $vm.Location -StorageAccountName $storageaccountname -StorageAccountKey $key -FileName "ConfigureWinRM_HTTPS.ps1" -ContainerName "scripts"
| {
"content_hash": "043af7e329ebffb230c0f156e4a8eea6",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 253,
"avg_line_length": 43.63333333333333,
"alnum_prop": 0.7853323147440795,
"repo_name": "alexverboon/posh",
"id": "8a75cfe09718784531168fa50867b574c8c88f27",
"size": "1311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Azure/Utilities/wip/Scriptsfolder.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "6104"
},
{
"name": "PowerShell",
"bytes": "831754"
},
{
"name": "Ruby",
"bytes": "3334"
},
{
"name": "Shell",
"bytes": "1938"
}
],
"symlink_target": ""
} |
require File.expand_path('../../../../spec_helper', __FILE__)
require 'stringio'
require 'zlib'
describe "Zlib::GzipWriter#mtime=" do
before :each do
@io = StringIO.new
end
it "sets mtime using Integer" do
Zlib::GzipWriter.wrap @io do |gzio|
gzio.mtime = 1
gzio.mtime.should == Time.at(1)
end
@io.string[4, 4].should == "\001\0\0\0"
end
it "sets mtime using Time" do
Zlib::GzipWriter.wrap @io do |gzio|
gzio.mtime = Time.at 1
gzio.mtime.should == Time.at(1)
end
@io.string[4, 4].should == "\001\0\0\0"
end
it "raises if the header was written" do
Zlib::GzipWriter.wrap @io do |gzio|
gzio.write ''
lambda { gzio.mtime = nil }.should \
raise_error(Zlib::GzipFile::Error, 'header is already written')
end
end
end
| {
"content_hash": "65d3c126da63763144d80979117e8c8f",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 71,
"avg_line_length": 20.615384615384617,
"alnum_prop": 0.6106965174129353,
"repo_name": "yous/rubyspec",
"id": "8113ad289029ab350f706e1198da469c3c0bcf3d",
"size": "804",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "library/zlib/gzipwriter/mtime_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "184707"
},
{
"name": "Ruby",
"bytes": "5184300"
}
],
"symlink_target": ""
} |
package org.springframework.boot.autoconfigure.graphql.reactive;
import java.util.Collections;
import java.util.stream.Collectors;
import graphql.GraphQL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.graphql.GraphQlAutoConfiguration;
import org.springframework.boot.autoconfigure.graphql.GraphQlCorsProperties;
import org.springframework.boot.autoconfigure.graphql.GraphQlProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.log.LogMessage;
import org.springframework.graphql.ExecutionGraphQlService;
import org.springframework.graphql.execution.GraphQlSource;
import org.springframework.graphql.server.WebGraphQlHandler;
import org.springframework.graphql.server.WebGraphQlInterceptor;
import org.springframework.graphql.server.webflux.GraphQlHttpHandler;
import org.springframework.graphql.server.webflux.GraphQlWebSocketHandler;
import org.springframework.graphql.server.webflux.GraphiQlHandler;
import org.springframework.graphql.server.webflux.SchemaHandler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.config.CorsRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.function.server.RequestPredicate;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.server.support.WebSocketUpgradeHandlerPredicate;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RequestPredicates.contentType;
/**
* {@link EnableAutoConfiguration Auto-configuration} for enabling Spring GraphQL over
* WebFlux.
*
* @author Brian Clozel
* @since 2.7.0
*/
@AutoConfiguration(after = GraphQlAutoConfiguration.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass({ GraphQL.class, GraphQlHttpHandler.class })
@ConditionalOnBean(ExecutionGraphQlService.class)
@EnableConfigurationProperties(GraphQlCorsProperties.class)
public class GraphQlWebFluxAutoConfiguration {
private static final RequestPredicate SUPPORTS_MEDIATYPES = accept(MediaType.APPLICATION_GRAPHQL,
MediaType.APPLICATION_JSON).and(contentType(MediaType.APPLICATION_GRAPHQL, MediaType.APPLICATION_JSON));
private static final Log logger = LogFactory.getLog(GraphQlWebFluxAutoConfiguration.class);
@Bean
@ConditionalOnMissingBean
public GraphQlHttpHandler graphQlHttpHandler(WebGraphQlHandler webGraphQlHandler) {
return new GraphQlHttpHandler(webGraphQlHandler);
}
@Bean
@ConditionalOnMissingBean
public WebGraphQlHandler webGraphQlHandler(ExecutionGraphQlService service,
ObjectProvider<WebGraphQlInterceptor> interceptorsProvider) {
return WebGraphQlHandler.builder(service)
.interceptors(interceptorsProvider.orderedStream().collect(Collectors.toList())).build();
}
@Bean
@Order(0)
public RouterFunction<ServerResponse> graphQlRouterFunction(GraphQlHttpHandler httpHandler,
GraphQlSource graphQlSource, GraphQlProperties properties) {
String path = properties.getPath();
logger.info(LogMessage.format("GraphQL endpoint HTTP POST %s", path));
RouterFunctions.Builder builder = RouterFunctions.route();
builder = builder.GET(path, this::onlyAllowPost);
builder = builder.POST(path, SUPPORTS_MEDIATYPES, httpHandler::handleRequest);
if (properties.getGraphiql().isEnabled()) {
GraphiQlHandler graphQlHandler = new GraphiQlHandler(path, properties.getWebsocket().getPath());
builder = builder.GET(properties.getGraphiql().getPath(), graphQlHandler::handleRequest);
}
if (properties.getSchema().getPrinter().isEnabled()) {
SchemaHandler schemaHandler = new SchemaHandler(graphQlSource);
builder = builder.GET(path + "/schema", schemaHandler::handleRequest);
}
return builder.build();
}
private Mono<ServerResponse> onlyAllowPost(ServerRequest request) {
return ServerResponse.status(HttpStatus.METHOD_NOT_ALLOWED).headers(this::onlyAllowPost).build();
}
private void onlyAllowPost(HttpHeaders headers) {
headers.setAllow(Collections.singleton(HttpMethod.POST));
}
@Configuration(proxyBeanMethods = false)
public static class GraphQlEndpointCorsConfiguration implements WebFluxConfigurer {
final GraphQlProperties graphQlProperties;
final GraphQlCorsProperties corsProperties;
public GraphQlEndpointCorsConfiguration(GraphQlProperties graphQlProps, GraphQlCorsProperties corsProps) {
this.graphQlProperties = graphQlProps;
this.corsProperties = corsProps;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
CorsConfiguration configuration = this.corsProperties.toCorsConfiguration();
if (configuration != null) {
registry.addMapping(this.graphQlProperties.getPath()).combine(configuration);
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.graphql.websocket", name = "path")
public static class WebSocketConfiguration {
@Bean
@ConditionalOnMissingBean
public GraphQlWebSocketHandler graphQlWebSocketHandler(WebGraphQlHandler webGraphQlHandler,
GraphQlProperties properties, ServerCodecConfigurer configurer) {
return new GraphQlWebSocketHandler(webGraphQlHandler, configurer,
properties.getWebsocket().getConnectionInitTimeout());
}
@Bean
public HandlerMapping graphQlWebSocketEndpoint(GraphQlWebSocketHandler graphQlWebSocketHandler,
GraphQlProperties properties) {
String path = properties.getWebsocket().getPath();
logger.info(LogMessage.format("GraphQL endpoint WebSocket %s", path));
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setHandlerPredicate(new WebSocketUpgradeHandlerPredicate());
mapping.setUrlMap(Collections.singletonMap(path, graphQlWebSocketHandler));
mapping.setOrder(-2); // Ahead of HTTP endpoint ("routerFunctionMapping" bean)
return mapping;
}
}
}
| {
"content_hash": "ed56289b7a989645ca495edaf5868fb6",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 108,
"avg_line_length": 44.84939759036145,
"alnum_prop": 0.8333109469442579,
"repo_name": "chrylis/spring-boot",
"id": "70178c80163478782a350adb3efb3e4b49536593",
"size": "8066",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/graphql/reactive/GraphQlWebFluxAutoConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2138"
},
{
"name": "CSS",
"bytes": "117"
},
{
"name": "Dockerfile",
"bytes": "2309"
},
{
"name": "Groovy",
"bytes": "29009"
},
{
"name": "HTML",
"bytes": "58426"
},
{
"name": "Java",
"bytes": "21597949"
},
{
"name": "JavaScript",
"bytes": "33592"
},
{
"name": "Kotlin",
"bytes": "434872"
},
{
"name": "Mustache",
"bytes": "449"
},
{
"name": "Ruby",
"bytes": "7867"
},
{
"name": "Shell",
"bytes": "45438"
},
{
"name": "Smarty",
"bytes": "2882"
},
{
"name": "Vim Snippet",
"bytes": "135"
}
],
"symlink_target": ""
} |
/**
*
*/
package com.hcr.bdr.crm.dao;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* @author seraph
*
*/
public class DataBaseManager {
private static DataSource dataSource;
private static String jdbcDriver;
private static String jdbcUrl;
private static String jdbcUser;
private static String jdbcPass;
private static String filePath = "jdbc.properties";
private static Properties properties;
static {
initParams();
dataSource = setupDataSource();
}
public static void initParams() {
properties = new Properties();
try {
ClassLoader classLoader = DataBaseManager.class.getClassLoader();
properties.load(classLoader.getResourceAsStream(filePath));
} catch (IOException e) {
e.printStackTrace();
}
jdbcDriver = properties.getProperty("jdbc.driver");
jdbcUrl = properties.getProperty("jdbc.url");
jdbcUser = properties.getProperty("jdbc.user");
jdbcPass = properties.getProperty("jdbc.pass");
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
private static DataSource setupDataSource() {
ComboPooledDataSource cpds = new ComboPooledDataSource();
try {
cpds.setDriverClass(jdbcDriver);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
cpds.setJdbcUrl(jdbcUrl);
cpds.setUser(jdbcUser);
cpds.setPassword(jdbcPass);
cpds.setMinPoolSize(10);
cpds.setAcquireIncrement(10);
cpds.setMaxPoolSize(20);
return cpds;
}
}
| {
"content_hash": "54576269faaaef42c5aec4ab90102bf4",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 68,
"avg_line_length": 22.43243243243243,
"alnum_prop": 0.7463855421686747,
"repo_name": "seraph115/crm4j",
"id": "2bdffe03902a8d0a5b92135f1a26b52d51eb6840",
"size": "1660",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/hcr/bdr/crm/dao/DataBaseManager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "12621"
}
],
"symlink_target": ""
} |
#ifndef _ACTIVEMQ_TEST_OPENWIRE_OPENWIREVIRTUALTOPICTEST_H_
#define _ACTIVEMQ_TEST_OPENWIRE_OPENWIREVIRTUALTOPICTEST_H_
#include <activemq/test/VirtualTopicTest.h>
namespace activemq {
namespace test {
namespace openwire {
class OpenwireVirtualTopicTest : public VirtualTopicTest {
private:
CPPUNIT_TEST_SUITE( OpenwireVirtualTopicTest );
CPPUNIT_TEST( testVirtualTopicSyncReceiveAutoAck );
CPPUNIT_TEST( testVirtualTopicSyncReceiveClinetAck );
CPPUNIT_TEST( testVirtualTopicSyncReceiveTransacted );
CPPUNIT_TEST_SUITE_END();
public:
OpenwireVirtualTopicTest();
virtual ~OpenwireVirtualTopicTest();
virtual std::string getBrokerURL() const {
return activemq::util::IntegrationCommon::getInstance().getOpenwireURL();
}
};
}}}
#endif /* _ACTIVEMQ_TEST_OPENWIRE_OPENWIREVIRTUALTOPICTEST_H_ */
| {
"content_hash": "5e56bad08ca1c176780badd8fc3c6fe6",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 85,
"avg_line_length": 26.529411764705884,
"alnum_prop": 0.7161862527716186,
"repo_name": "apache/activemq-cpp",
"id": "ed0276c9b542731d2b005714aebe7a80d57e425c",
"size": "1700",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "activemq-cpp/src/test-integration/activemq/test/openwire/OpenwireVirtualTopicTest.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "447207"
},
{
"name": "C++",
"bytes": "12024283"
},
{
"name": "Java",
"bytes": "251150"
},
{
"name": "M4",
"bytes": "72135"
},
{
"name": "Makefile",
"bytes": "114773"
},
{
"name": "Objective-C",
"bytes": "14815"
},
{
"name": "Shell",
"bytes": "7934"
}
],
"symlink_target": ""
} |
'use strict';
import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
import requireNativeComponent from '../../ReactNative/requireNativeComponent';
import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
import type {Int32} from '../../Types/CodegenTypes';
import type {TextInputNativeCommands} from './TextInputNativeCommands';
import * as React from 'react';
type NativeType = HostComponent<mixed>;
type NativeCommands = TextInputNativeCommands<NativeType>;
export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
supportedCommands: ['focus', 'blur', 'setTextAndSelection'],
});
const SinglelineTextInputNativeComponent: HostComponent<mixed> = requireNativeComponent<mixed>(
'RCTMultilineTextInputView',
);
export default SinglelineTextInputNativeComponent;
| {
"content_hash": "9df62a24e8bb3f64d1c689e307694648",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 95,
"avg_line_length": 34.75,
"alnum_prop": 0.7925659472422062,
"repo_name": "exponent/react-native",
"id": "a0dd8841123f6d6c8b743fd391b8eeda4ba30b8e",
"size": "1058",
"binary": false,
"copies": "3",
"ref": "refs/heads/exp-latest",
"path": "Libraries/Components/TextInput/RCTMultilineTextInputNativeComponent.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "15612"
},
{
"name": "Awk",
"bytes": "121"
},
{
"name": "Batchfile",
"bytes": "683"
},
{
"name": "C",
"bytes": "182631"
},
{
"name": "C++",
"bytes": "738469"
},
{
"name": "CSS",
"bytes": "31486"
},
{
"name": "HTML",
"bytes": "34338"
},
{
"name": "IDL",
"bytes": "897"
},
{
"name": "Java",
"bytes": "2734102"
},
{
"name": "JavaScript",
"bytes": "3521229"
},
{
"name": "Makefile",
"bytes": "8493"
},
{
"name": "Objective-C",
"bytes": "1405671"
},
{
"name": "Objective-C++",
"bytes": "204752"
},
{
"name": "Prolog",
"bytes": "287"
},
{
"name": "Python",
"bytes": "123976"
},
{
"name": "Ruby",
"bytes": "7013"
},
{
"name": "Shell",
"bytes": "29715"
}
],
"symlink_target": ""
} |
layout: post
title: Implementation-defined Behavior in C
tags: C semantics
published: true
---
I've become interested recently in how we should think about C programs that perform implementation-defined operations, in particular, conversions between nonnull pointers and integers.
Mostly, this is just idle curiosity on my part.
On the other hand, there are some interesting issues surrounding implementation-defined behavior, portability, and formal models of compiler correctness. I don't go deep into these issues here---this post is mostly just a high-level overview, with some unanswered questions.
First, definitions:
### Implementation-defined Behavior
The C11 standard defines "implementation-defined behavior" as
> unspecified behavior where each implementation documents how the choice is made.
> (3.4.1, [C11 draft standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf))
Here are some examples:
* pointer-to-integer (and integer-to-pointer) conversions, whenever the pointer/integer is nonnull/nonzero
* representation of signed integers (two's complement, one's complement, etc.)
* the extent to which the compiler respects the inline function specifier
* ... and many more (J.3)
### Unspecified Behavior
"Unspecified behavior" (3.4.4), in turn, is behavior that either has two or more possible outcomes, or involves the use of an "unspecified value," which is any valid value of the relevant type (int, float, etc.).
All of the following are unspecified:
* the order in which subexpressions are evaluated (and the order in which any resulting side-effects occur) in function calls, evaluation of `&&`, `||`, `?:`, and comma operators
* the order in which `#` and `##` operations are evaluated during preprocessing
* ... and many more (J.1)
### Integer-Pointer Conversion
The most interesting kind of implementation-defined behavior, from my perspective, is conversion between (void, nonnull) pointers and integers. These kinds of conversions can be legitimately useful in some situations (consider tagged pointers in GCs). On the other hand, they can also quickly degenerate.
To illustrate how things can get messy, consider the following C program. I believe this program is well-defined according to the C standard, but please correct me if I'm wrong!
{% raw %}
<pre>
int g(int* x) { return ((uintptr_t)(void*)x <= 0xbffff980); }
static int f(void) {
int a = 0;
return g(&a);
}
int main(void) { return f(); }
</pre>
{% endraw %}
What integer does this program return?
If we do a mental trace, we pretty quickly get to the key bit:
{% raw %}
<pre>
return ((uintptr_t)(void*)x <= 0xbffff980);
</pre>
{% endraw %}
The first cast to `void*` is always well-defined.
The conversion `(uintptr_t)x`, on the other hand, is only implementation defined, i.e., "[...] has unspecified behavior, where each implementation documents how the choice is made."
(`uintptr_t` is an unsigned integer type guaranteed not to screw up the integer-pointer conversion.)
Let's assume for a moment that we're trying to determine the result without reference to any particular compiler (C verification and bugfinding tools do this all the time).
The result of the conversion must just be unspecified, right? We don't have an implementation to "document how the choice is made."
Which means that `(uintptr_t)x` is an "unspecified value" of unsigned integer type (that is, any unsigned integer representable as a `uintptr_t`). All we can say, then, about the less-than-or-equal-to comparison is that it is either 0 or 1, but we don't know which. The program is nondeterministic.
Another way to think about this is: If we want to treat the code as truly portable, and, e.g., verify its result once and for all for __all__ implementations, we need to consider all possible implementations of implementation-defined operations such as pointer-to-integer casts.
### gcc
Things get a bit weirder if we start thinking about the behavior of the program above with reference to a particular C implementation, e.g., gcc, clang, or CompCert.
gcc, for example, documents pointer-to-integer casts as follows:
> A cast from pointer to integer discards most-significant bits if the pointer representation is larger than the integer type, sign-extends(2) if the pointer representation is smaller than the integer type, otherwise the bits are unchanged.
If we assume gcc, we should assume that pointer-integer casts have this behavior, which should at least resolve the nondeterminism we saw earlier, right? (Because we're fixing a particular implementation.)
We can experiment by compiling the program, running it, and checking its exit code.
When compiled without optimizations, I get exit code 1 on my machine.
```
> gcc -O0 f.c
> ./a.out
> echo $?
> 1
```
When compiled with optimizations turned on, I get exit code 0.
```
> gcc -O3 f.c
> ./a.out
> echo $?
> 0
```
What's going on?
In the second compilation, gcc inlines function `f` at `f`'s callsite in `main`. Inlining, in turn, changes the absolute position on the stack at which local variable `a` is allocated, which causes the less-than-or-equal comparison to switch from `1` to `0`.
(To see this behavior on your own platform, you'll probably have to choose the integer `0xbffff980` a bit craftily, and turn address-space randomization off.)
Here we've uncovered a second source of unspecified, or nondeterministic, behavior in the program above. Although the cast is now guaranteed to produce a well-defined result, there's no reason we should assume that `a` is allocated at any particular location in memory. The C standard guarantees that the address of an object remains constant only during the _lifetime_ of the object, not across program executions (6.2.4, footnote 33).
### CompCert
While I was at it, I thought I'd compile the program above with [CompCert](http://compcert.inria.fr), just to see what happens.
CompCert, if you haven't seen it before, is a verified compiler for a large subset of C, written and proved correct in the Coq theorem prover. The CompCert distribution includes both the compiler (with correctness proof) and an executable C interpreter.
Compiling the program above with CompCert results in the same behavior (different return values, depending on whether `f` is inlined or not). To get CompCert to inline `f`, I had to explicitly add the `inline` function specifier. To get different return values, I also had to pick a slightly different integer constant.
More interesting is what happens when you "run" the program above using CompCert's C interpreter `ccomp -interp`:
```
Stuck state: in function g, expression <ptr> <= -1073743488
Stuck subexpression: <ptr> <= -1073743488
ERROR: Undefined behavior
```
The `ERROR: Undefined behavior` indicates that the CompCert C semantics got stuck when attempting to execute the pointer-integer cast `(uintptr_t)x` in `g`.
If you read the CompCert C semantics, you see that the cast to `uintptr_t` leaves the pointer a pointer (it's classified as a "neutral" cast by CompCert). The comparison, between the pointer and integer, then gets stuck.
The question I'm left with: Is getting stuck at this point a valid "unspecified behavior"?
| {
"content_hash": "39ac053297598c6853adb2472c64e0fa",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 436,
"avg_line_length": 53.11764705882353,
"alnum_prop": 0.7631506090808416,
"repo_name": "gstew5/gstew5.github.io",
"id": "ec3684cbd76709fa79329b293e80be26d2033f6b",
"size": "7228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2014-07-21-implementation-defined-behavior-in-c.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10343"
}
],
"symlink_target": ""
} |
calculate_concurrency() {
MEMORY_AVAILABLE=${MEMORY_AVAILABLE-$(detect_memory 512)}
WEB_MEMORY=${WEB_MEMORY-512}
WEB_CONCURRENCY=${WEB_CONCURRENCY-$((MEMORY_AVAILABLE/WEB_MEMORY))}
if (( WEB_CONCURRENCY < 1 )); then
WEB_CONCURRENCY=1
fi
WEB_CONCURRENCY=$WEB_CONCURRENCY
}
log_concurrency() {
echo "Detected $MEMORY_AVAILABLE MB available memory, $WEB_MEMORY MB limit per process (WEB_MEMORY)"
echo "Recommending WEB_CONCURRENCY=$WEB_CONCURRENCY"
}
detect_memory() {
local default=$1
local limit=$(ulimit -u)
case $limit in
256) echo "512";; # Standard-1X
512) echo "1024";; # Standard-2X
16384) echo "2560";; # Performance-M
32768) echo "14336";; # Performance-L
*) echo "$default";;
esac
}
export PATH="$HOME/.heroku/node/bin:$PATH:$HOME/bin:$HOME/node_modules/.bin"
export NODE_HOME="$HOME/.heroku/node"
export NODE_ENV=${NODE_ENV:-production}
export LD_LIBRARY_PATH=$HOME/.heroku/oracle/instantclient:${LD_LIBRARY_PATH:-}
export OCI_LIB_DIR=$HOME/.heroku/oracle/instantclient
export OCI_INC_DIR=$HOME/.heroku/oracle/instantclient/sdk/include
calculate_concurrency
export MEMORY_AVAILABLE=$MEMORY_AVAILABLE
export WEB_MEMORY=$WEB_MEMORY
export WEB_CONCURRENCY=$WEB_CONCURRENCY
if [ "$LOG_CONCURRENCY" = "true" ]; then
log_concurrency
fi
| {
"content_hash": "07690c0158acb7da927735cc43081735",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 102,
"avg_line_length": 29.08888888888889,
"alnum_prop": 0.7089381207028266,
"repo_name": "NSWIDER/nodejs-oracle-buildpack",
"id": "f038da227aaa0bb877a85c77ac44cd6da8643280",
"size": "1309",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "profile/nodejs.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6201"
},
{
"name": "Ruby",
"bytes": "15105"
},
{
"name": "Shell",
"bytes": "21789"
}
],
"symlink_target": ""
} |
include(ExternalProject)
set(ROCKSDB_PREFIX_DIR ${THIRD_PARTY_PATH}/rocksdb)
set(ROCKSDB_INSTALL_DIR ${THIRD_PARTY_PATH}/install/rocksdb)
set(ROCKSDB_INCLUDE_DIR
"${ROCKSDB_INSTALL_DIR}/include"
CACHE PATH "rocksdb include directory." FORCE)
set(ROCKSDB_LIBRARIES
"${ROCKSDB_INSTALL_DIR}/lib/librocksdb.a"
CACHE FILEPATH "rocksdb library." FORCE)
set(ROCKSDB_CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
include_directories(${ROCKSDB_INCLUDE_DIR})
ExternalProject_Add(
extern_rocksdb
${EXTERNAL_PROJECT_LOG_ARGS}
PREFIX ${ROCKSDB_PREFIX_DIR}
GIT_REPOSITORY "https://github.com/facebook/rocksdb"
GIT_TAG v6.10.1
UPDATE_COMMAND ""
CMAKE_ARGS -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
-DWITH_BZ2=OFF
-DPORTABLE=1
-DWITH_GFLAGS=OFF
-DCMAKE_CXX_FLAGS=${ROCKSDB_CMAKE_CXX_FLAGS}
-DCMAKE_C_FLAGS=${CMAKE_C_FLAGS}
# BUILD_BYPRODUCTS ${ROCKSDB_PREFIX_DIR}/src/extern_rocksdb/librocksdb.a
INSTALL_COMMAND
mkdir -p ${ROCKSDB_INSTALL_DIR}/lib/ && cp
${ROCKSDB_PREFIX_DIR}/src/extern_rocksdb/librocksdb.a ${ROCKSDB_LIBRARIES}
&& cp -r ${ROCKSDB_PREFIX_DIR}/src/extern_rocksdb/include
${ROCKSDB_INSTALL_DIR}/
BUILD_IN_SOURCE 1
BYPRODUCTS ${ROCKSDB_LIBRARIES})
add_dependencies(extern_rocksdb snappy)
add_library(rocksdb STATIC IMPORTED GLOBAL)
set_property(TARGET rocksdb PROPERTY IMPORTED_LOCATION ${ROCKSDB_LIBRARIES})
add_dependencies(rocksdb extern_rocksdb)
list(APPEND external_project_dependencies rocksdb)
| {
"content_hash": "0e1c69e479f7d442a18fedd84434d92a",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 78,
"avg_line_length": 36.69767441860465,
"alnum_prop": 0.7122940430925222,
"repo_name": "luotao1/Paddle",
"id": "673b143aba853688ff433639576dbe4675db2b73",
"size": "2185",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "cmake/external/rocksdb.cmake",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "58544"
},
{
"name": "C",
"bytes": "210300"
},
{
"name": "C++",
"bytes": "36771446"
},
{
"name": "CMake",
"bytes": "903079"
},
{
"name": "Cuda",
"bytes": "5200715"
},
{
"name": "Dockerfile",
"bytes": "4361"
},
{
"name": "Go",
"bytes": "49796"
},
{
"name": "Java",
"bytes": "16630"
},
{
"name": "Jinja",
"bytes": "23852"
},
{
"name": "MLIR",
"bytes": "39982"
},
{
"name": "Python",
"bytes": "36248258"
},
{
"name": "R",
"bytes": "1332"
},
{
"name": "Shell",
"bytes": "553175"
}
],
"symlink_target": ""
} |
package org.gradle.test.performance.mediummonolithicjavaproject.p81;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test1639 {
Production1639 objectUnderTest = new Production1639();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | {
"content_hash": "e956dc54e9df9f5a0c064e278b64c18a",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 68,
"avg_line_length": 26.70886075949367,
"alnum_prop": 0.6445497630331753,
"repo_name": "oehme/analysing-gradle-performance",
"id": "25ec19a810479e551aed97e2465c45d9ceaba30c",
"size": "2110",
"binary": false,
"copies": "1",
"ref": "refs/heads/before",
"path": "my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p81/Test1639.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "40770723"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>lambda: 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.13.0 / lambda - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
lambda
<small>
8.10.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2021-04-16 16:56:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-04-16 16:56:55 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 3 Virtual package relying on a GMP lib system installation
coq 8.13.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.11.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.1 Official release 4.11.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/lambda"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Lambda"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: pure lambda-calculus"
"keyword: confluence"
"keyword: parallel-moves lemma"
"keyword: Lévy's Cube Lemma"
"keyword: Church-Rosser"
"keyword: residual"
"keyword: Prism theorem"
"category: Computer Science/Lambda Calculi"
]
authors: [
"Gérard Huet"
]
bug-reports: "https://github.com/coq-contribs/lambda/issues"
dev-repo: "git+https://github.com/coq-contribs/lambda.git"
synopsis: "Residual Theory in Lambda-Calculus"
description: """
We present the complete development in Gallina of the
residual theory of beta-reduction in pure lambda-calculus. The main
result is the Prism Theorem, and its corollary Lévy's Cube Lemma, a
strong form of the parallel-moves lemma, itself a key step towards the
confluence theorem and its usual corollaries (Church-Rosser,
uniqueness of normal forms)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/lambda/archive/v8.10.0.tar.gz"
checksum: "md5=dce1f9ff2656b6917c69d35bf42c5201"
}
</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-lambda.8.10.0 coq.8.13.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0).
The following dependencies couldn't be met:
- coq-lambda -> coq < 8.11~ -> ocaml < 4.10
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-lambda.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</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": "58b07b2fb4d22ce74554a3d4eef370b0",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 157,
"avg_line_length": 40.815642458100555,
"alnum_prop": 0.5544757733369833,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "f2feca7af6fbbd602e4ce92656756b29c6f89a0b",
"size": "7311",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.11.1-2.0.7/released/8.13.0/lambda/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/* $NetBSD: vrc4173cmureg.h,v 1.2 2001/10/26 04:22:25 enami Exp $ */
/*-
* Copyright (c) 2001 TAKEMURA Shin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#define VRC4173CMU_IOBASE 0x040
#define VRC4173CMU_IOSIZE 0x004
#define VRC4173CMU_CLKMSK 0x00
#define VRC4173CMU_CLKMSK_48MOSC (1<<12)
#define VRC4173CMU_CLKMSK_48MPIN (1<<11)
#define VRC4173CMU_CLKMSK_48MUSB (1<<10)
#define VRC4173CMU_CLKMSK_AC97 (1<<8)
#define VRC4173CMU_CLKMSK_CARD2 (1<<7)
#define VRC4173CMU_CLKMSK_CARD1 (1<<6)
#define VRC4173CMU_CLKMSK_USB (1<<5)
#define VRC4173CMU_CLKMSK_PS2CH2 (1<<4)
#define VRC4173CMU_CLKMSK_PS2CH1 (1<<3)
#define VRC4173CMU_CLKMSK_AIU (1<<2)
#define VRC4173CMU_CLKMSK_KIU (1<<1)
#define VRC4173CMU_CLKMSK_PIU (1<<0)
#define VRC4173CMU_SRST 0x02
#define VRC4173CMU_SRST_AC97 (1<<3)
#define VRC4173CMU_SRST_CARD2 (1<<2)
#define VRC4173CMU_SRST_CARD1 (1<<1)
#define VRC4173CMU_SRST_USB (1<<0)
| {
"content_hash": "337388cd7c0459ec9bffa01e7db4dba5",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 77,
"avg_line_length": 43.48,
"alnum_prop": 0.7539098436062558,
"repo_name": "MarginC/kame",
"id": "e5d0f200883361fcb5deca54d9234f942d5f53a6",
"size": "2174",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "netbsd/sys/arch/hpcmips/vr/vrc4173cmureg.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arc",
"bytes": "7491"
},
{
"name": "Assembly",
"bytes": "14375563"
},
{
"name": "Awk",
"bytes": "313712"
},
{
"name": "Batchfile",
"bytes": "6819"
},
{
"name": "C",
"bytes": "356715789"
},
{
"name": "C++",
"bytes": "4231647"
},
{
"name": "DIGITAL Command Language",
"bytes": "11155"
},
{
"name": "Emacs Lisp",
"bytes": "790"
},
{
"name": "Forth",
"bytes": "253695"
},
{
"name": "GAP",
"bytes": "9964"
},
{
"name": "Groff",
"bytes": "2220485"
},
{
"name": "Lex",
"bytes": "168376"
},
{
"name": "Logos",
"bytes": "570213"
},
{
"name": "Makefile",
"bytes": "1778847"
},
{
"name": "Mathematica",
"bytes": "16549"
},
{
"name": "Objective-C",
"bytes": "529629"
},
{
"name": "PHP",
"bytes": "11283"
},
{
"name": "Perl",
"bytes": "151251"
},
{
"name": "Perl6",
"bytes": "2572"
},
{
"name": "Ruby",
"bytes": "7283"
},
{
"name": "Scheme",
"bytes": "76872"
},
{
"name": "Shell",
"bytes": "583253"
},
{
"name": "Stata",
"bytes": "408"
},
{
"name": "Yacc",
"bytes": "606054"
}
],
"symlink_target": ""
} |
from msrest.serialization import Model
class ReplicaInfo(Model):
"""Information about the identity, status, health, node name, uptime, and
other details about the replica.
:param replica_status: Possible values include: 'Invalid', 'InBuild',
'Standby', 'Ready', 'Down', 'Dropped'
:type replica_status: str or :class:`enum
<azure.servicefabric.models.enum>`
:param health_state: Possible values include: 'Invalid', 'Ok', 'Warning',
'Error', 'Unknown'
:type health_state: str or :class:`enum <azure.servicefabric.models.enum>`
:param node_name:
:type node_name: str
:param address: The address the replica is listening on.
:type address: str
:param last_in_build_duration_in_seconds: The last in build duration of
the replica in seconds.
:type last_in_build_duration_in_seconds: str
:param service_kind: Polymorphic Discriminator
:type service_kind: str
"""
_validation = {
'service_kind': {'required': True},
}
_attribute_map = {
'replica_status': {'key': 'ReplicaStatus', 'type': 'str'},
'health_state': {'key': 'HealthState', 'type': 'str'},
'node_name': {'key': 'NodeName', 'type': 'str'},
'address': {'key': 'Address', 'type': 'str'},
'last_in_build_duration_in_seconds': {'key': 'LastInBuildDurationInSeconds', 'type': 'str'},
'service_kind': {'key': 'ServiceKind', 'type': 'str'},
}
_subtype_map = {
'service_kind': {'Stateful': 'StatefulServiceReplicaInfo', 'Stateless': 'StatelessServiceInstanceInfo'}
}
def __init__(self, replica_status=None, health_state=None, node_name=None, address=None, last_in_build_duration_in_seconds=None):
self.replica_status = replica_status
self.health_state = health_state
self.node_name = node_name
self.address = address
self.last_in_build_duration_in_seconds = last_in_build_duration_in_seconds
self.service_kind = None
| {
"content_hash": "a893e6f9ea20cc74ea4827cd4c87009b",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 133,
"avg_line_length": 40.57142857142857,
"alnum_prop": 0.6413480885311871,
"repo_name": "AutorestCI/azure-sdk-for-python",
"id": "1f3cc3d49400e6e97950a4984b40de0118968872",
"size": "2462",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "azure-servicefabric/azure/servicefabric/models/replica_info.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "34619070"
}
],
"symlink_target": ""
} |
#ifndef _MNP_IMPL_H_
#define _MNP_IMPL_H_
#include "NetLib.h"
#include "MnpDriver.h"
#include "MnpDebug.h"
#define NET_ETHER_FCS_SIZE 4
#define MNP_SYS_POLL_INTERVAL (2 * TICKS_PER_MS) // 2 milliseconds
#define MNP_TIMEOUT_CHECK_INTERVAL (50 * TICKS_PER_MS) // 50 milliseconds
#define MNP_TX_TIMEOUT_TIME (500 * TICKS_PER_MS) // 500 milliseconds
#define MNP_INIT_NET_BUFFER_NUM 512
#define MNP_NET_BUFFER_INCREASEMENT 64
#define MNP_MAX_NET_BUFFER_NUM 65536
#define MNP_MAX_RCVD_PACKET_QUE_SIZE 256
#define MNP_RECEIVE_UNICAST 0x01
#define MNP_RECEIVE_BROADCAST 0x02
#define UNICAST_PACKET MNP_RECEIVE_UNICAST
#define BROADCAST_PACKET MNP_RECEIVE_BROADCAST
#define MNP_INSTANCE_DATA_SIGNATURE EFI_SIGNATURE_32 ('M', 'n', 'p', 'I')
#define MNP_INSTANCE_DATA_FROM_THIS(a) \
CR ( \
(a), \
MNP_INSTANCE_DATA, \
ManagedNetwork, \
MNP_INSTANCE_DATA_SIGNATURE \
)
typedef struct _MNP_INSTANCE_DATA {
UINT32 Signature;
MNP_SERVICE_DATA *MnpServiceData;
EFI_HANDLE Handle;
NET_LIST_ENTRY InstEntry;
EFI_MANAGED_NETWORK_PROTOCOL ManagedNetwork;
BOOLEAN Configured;
BOOLEAN Destroyed;
NET_LIST_ENTRY GroupCtrlBlkList;
NET_MAP RxTokenMap;
EFI_LOCK RxLock;
NET_LIST_ENTRY RxDeliveredPacketQueue;
NET_LIST_ENTRY RcvdPacketQueue;
UINTN RcvdPacketQueueSize;
EFI_MANAGED_NETWORK_CONFIG_DATA ConfigData;
UINT8 ReceiveFilter;
} MNP_INSTANCE_DATA;
typedef struct _MNP_GROUP_ADDRESS {
NET_LIST_ENTRY AddrEntry;
EFI_MAC_ADDRESS Address;
INTN RefCnt;
} MNP_GROUP_ADDRESS;
typedef struct _MNP_GROUP_CONTROL_BLOCK {
NET_LIST_ENTRY CtrlBlkEntry;
MNP_GROUP_ADDRESS *GroupAddress;
} MNP_GROUP_CONTROL_BLOCK;
typedef struct _MNP_RXDATA_WRAP {
NET_LIST_ENTRY WrapEntry;
MNP_INSTANCE_DATA *Instance;
EFI_MANAGED_NETWORK_RECEIVE_DATA RxData;
NET_BUF *Nbuf;
UINT64 TimeoutTick;
} MNP_RXDATA_WRAP;
EFI_STATUS
MnpInitializeServiceData (
IN MNP_SERVICE_DATA *MnpServiceData,
IN EFI_HANDLE ImageHandle,
IN EFI_HANDLE ControllerHandle
);
VOID
MnpFlushServiceData (
MNP_SERVICE_DATA *MnpServiceData
);
VOID
MnpInitializeInstanceData (
IN MNP_SERVICE_DATA *MnpServiceData,
IN MNP_INSTANCE_DATA *Instance
);
EFI_STATUS
MnpTokenExist (
IN NET_MAP *Map,
IN NET_MAP_ITEM *Item,
IN VOID *Arg
);
EFI_STATUS
MnpCancelTokens (
IN NET_MAP *Map,
IN NET_MAP_ITEM *Item,
IN VOID *Arg
);
VOID
MnpFlushRcvdDataQueue (
IN MNP_INSTANCE_DATA *Instance
);
EFI_STATUS
MnpConfigureInstance (
IN MNP_INSTANCE_DATA *Instance,
IN EFI_MANAGED_NETWORK_CONFIG_DATA *ConfigData OPTIONAL
);
EFI_STATUS
MnpGroupOp (
IN MNP_INSTANCE_DATA *Instance,
IN BOOLEAN JoinFlag,
IN EFI_MAC_ADDRESS *MacAddr OPTIONAL,
IN MNP_GROUP_CONTROL_BLOCK *CtrlBlk OPTIONAL
);
BOOLEAN
MnpIsValidTxToken (
IN MNP_INSTANCE_DATA *Instance,
IN EFI_MANAGED_NETWORK_COMPLETION_TOKEN *Token
);
VOID
MnpBuildTxPacket (
IN MNP_SERVICE_DATA *MnpServiceData,
IN EFI_MANAGED_NETWORK_TRANSMIT_DATA *TxData,
OUT UINT8 **PktBuf,
OUT UINT32 *PktLen
);
EFI_STATUS
MnpSyncSendPacket (
IN MNP_SERVICE_DATA *MnpServiceData,
IN UINT8 *Packet,
IN UINT32 Length,
IN EFI_MANAGED_NETWORK_COMPLETION_TOKEN *Token
);
EFI_STATUS
MnpInstanceDeliverPacket (
IN MNP_INSTANCE_DATA *Instance
);
VOID
EFIAPI
MnpRecycleRxData (
IN EFI_EVENT Event,
IN VOID *Context
);
EFI_STATUS
MnpReceivePacket (
IN MNP_SERVICE_DATA *MnpServiceData
);
NET_BUF *
MnpAllocNbuf (
IN MNP_SERVICE_DATA *MnpServiceData
);
VOID
MnpFreeNbuf (
IN MNP_SERVICE_DATA *MnpServiceData,
IN NET_BUF *Nbuf
);
VOID
EFIAPI
MnpCheckPacketTimeout (
IN EFI_EVENT Event,
IN VOID *Context
);
VOID
EFIAPI
MnpSystemPoll (
IN EFI_EVENT Event,
IN VOID *Context
);
EFI_STATUS
EFIAPI
MnpGetModeData (
IN EFI_MANAGED_NETWORK_PROTOCOL *This,
OUT EFI_MANAGED_NETWORK_CONFIG_DATA *MnpConfigData OPTIONAL,
OUT EFI_SIMPLE_NETWORK_MODE *SnpModeData OPTIONAL
);
EFI_STATUS
EFIAPI
MnpConfigure (
IN EFI_MANAGED_NETWORK_PROTOCOL *This,
IN EFI_MANAGED_NETWORK_CONFIG_DATA *MnpConfigData OPTIONAL
);
EFI_STATUS
EFIAPI
MnpMcastIpToMac (
IN EFI_MANAGED_NETWORK_PROTOCOL *This,
IN BOOLEAN Ipv6Flag,
IN EFI_IP_ADDRESS *IpAddress,
OUT EFI_MAC_ADDRESS *MacAddress
);
EFI_STATUS
EFIAPI
MnpGroups (
IN EFI_MANAGED_NETWORK_PROTOCOL *This,
IN BOOLEAN JoinFlag,
IN EFI_MAC_ADDRESS *MacAddress OPTIONAL
);
EFI_STATUS
EFIAPI
MnpTransmit (
IN EFI_MANAGED_NETWORK_PROTOCOL *This,
IN EFI_MANAGED_NETWORK_COMPLETION_TOKEN *Token
);
EFI_STATUS
EFIAPI
MnpCancel (
IN EFI_MANAGED_NETWORK_PROTOCOL *This,
IN EFI_MANAGED_NETWORK_COMPLETION_TOKEN *Token OPTIONAL
);
EFI_STATUS
EFIAPI
MnpReceive (
IN EFI_MANAGED_NETWORK_PROTOCOL *This,
IN EFI_MANAGED_NETWORK_COMPLETION_TOKEN *Token
);
EFI_STATUS
EFIAPI
MnpPoll (
IN EFI_MANAGED_NETWORK_PROTOCOL *This
);
#endif
| {
"content_hash": "8e5e1f9b3ff8e95e446836f91ff8733e",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 79,
"avg_line_length": 22.35135135135135,
"alnum_prop": 0.6159958542062532,
"repo_name": "kontais/EFI-MIPS",
"id": "6328cc8c03a8a38a18f9fc362d53bcb8d6194682",
"size": "6577",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Sample/Universal/Network/Mnp/Dxe/MnpImpl.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "271282"
},
{
"name": "C",
"bytes": "31244676"
},
{
"name": "C++",
"bytes": "1036348"
},
{
"name": "D",
"bytes": "45595"
},
{
"name": "Objective-C",
"bytes": "3469546"
},
{
"name": "Puppet",
"bytes": "3368"
},
{
"name": "Python",
"bytes": "7764111"
},
{
"name": "Shell",
"bytes": "10084"
}
],
"symlink_target": ""
} |
class Invisorql < Cask
url 'http://www.pozdeev.com/invisor/InvisorQL.zip'
homepage 'http://www.pozdeev.com/invisor/'
version 'latest'
sha256 :no_check
qlplugin 'InvisorQL.qlgenerator'
end
| {
"content_hash": "405d51fd6750768c95189e79b4223d43",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 52,
"avg_line_length": 28.285714285714285,
"alnum_prop": 0.7373737373737373,
"repo_name": "0asa/homebrew-cask",
"id": "35f02582260190db117691fbdf569e0bca8e83bf",
"size": "198",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "Casks/invisorql.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Intuit Bootcamp Demonstrations</title>
<link href="libs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="libs/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/site.css" rel="stylesheet">
</head>
<body>
<h1>Updated page</h1>
<script src="libs/jquery/dist/jquery.js"></script>
<script src="libs/bootstrap/dist/js/bootstrap.js"></script>
<script src="js/appjs.js"></script>
</body>
</html>
| {
"content_hash": "a06887df9a788064a1ec5c8bd1f56017",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 80,
"avg_line_length": 27.555555555555557,
"alnum_prop": 0.6895161290322581,
"repo_name": "Shikhanjali/bootcamp-sn",
"id": "71e537d0fd6d94a040f403d229d8dcd6c05364d2",
"size": "496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "33"
},
{
"name": "HTML",
"bytes": "496"
},
{
"name": "JavaScript",
"bytes": "870"
}
],
"symlink_target": ""
} |
<?php
namespace Drupal\Tests\Core\Annotation;
use Drupal\Core\Annotation\Translation;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Annotation\Translation
* @group Annotation
*/
class TranslationTest extends UnitTestCase {
/**
* The translation manager used for testing.
*
* @var \Drupal\Core\StringTranslation\TranslationInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $translationManager;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->translationManager = $this->getStringTranslationStub();
}
/**
* @covers ::get
*
* @dataProvider providerTestGet
*/
public function testGet(array $values, $expected) {
$container = new ContainerBuilder();
$container->set('string_translation', $this->translationManager);
\Drupal::setContainer($container);
$arguments = isset($values['arguments']) ? $values['arguments'] : array();
$options = isset($values['context']) ? array(
'context' => $values['context'],
) : array();
$annotation = new Translation($values);
$this->assertSame($expected, (string) $annotation->get());
}
/**
* Provides data to self::testGet().
*/
public function providerTestGet() {
$data = array();
$data[] = array(
array(
'value' => 'Foo',
),
'Foo'
);
$random = $this->randomMachineName();
$random_html_entity = '&' . $random;
$data[] = array(
array(
'value' => 'Foo @bar @baz %qux',
'arguments' => array(
'@bar' => $random,
'@baz' => $random_html_entity,
'%qux' => $random_html_entity,
),
'context' => $this->randomMachineName(),
),
'Foo ' . $random . ' &' . $random . ' <em class="placeholder">&' . $random . '</em>',
);
return $data;
}
}
| {
"content_hash": "9fb9a67fc4def3d6f0b5fb2f0f519bbc",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 102,
"avg_line_length": 24.576923076923077,
"alnum_prop": 0.5993740219092332,
"repo_name": "MGApcDev/MGApcDevCom",
"id": "ead56ae425109fb04d2cee3793f32dd4e0807dd4",
"size": "1917",
"binary": false,
"copies": "282",
"ref": "refs/heads/master",
"path": "core/tests/Drupal/Tests/Core/Annotation/TranslationTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "7927"
},
{
"name": "CSS",
"bytes": "513186"
},
{
"name": "HTML",
"bytes": "599529"
},
{
"name": "JavaScript",
"bytes": "938091"
},
{
"name": "PHP",
"bytes": "31007665"
},
{
"name": "Shell",
"bytes": "49920"
},
{
"name": "Visual Basic",
"bytes": "2202"
}
],
"symlink_target": ""
} |
Tic Tac Toe game in Elm-lang and `<canvas>`
http://tictactoe.szeremi.org/
# License
MIT
| {
"content_hash": "5c20e4124224894ed76f38a2ab203c82",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 43,
"avg_line_length": 13,
"alnum_prop": 0.7032967032967034,
"repo_name": "amcsi/elm-tic-tac-toe",
"id": "18d35ef886d8399506cec28c5cc4af519c898580",
"size": "110",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34"
},
{
"name": "Elm",
"bytes": "16186"
},
{
"name": "HTML",
"bytes": "546"
},
{
"name": "JavaScript",
"bytes": "1948"
}
],
"symlink_target": ""
} |
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Linq;
using Refit;
using System.Threading.Tasks;
using System.IO;
/* ******** Hey You! *********
*
* This is a generated file, and gets rewritten every time you build the
* project. If you want to edit it, you need to edit the mustache template
* in the Refit package */
namespace RefitInternalGenerated
{
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate)]
sealed class PreserveAttribute : Attribute
{
#pragma warning disable 0649
//
// Fields
//
public bool AllMembers;
public bool Conditional;
#pragma warning restore 0649
}
}
namespace FermentationController
{
using RefitInternalGenerated;
[Preserve]
public partial class AutoGeneratedIFermentationControllerAPI : IFermentationControllerAPI
{
public HttpClient Client { get; protected set; }
readonly Dictionary<string, Func<HttpClient, object[], object>> methodImpls;
public AutoGeneratedIFermentationControllerAPI(HttpClient client, IRequestBuilder requestBuilder)
{
methodImpls = requestBuilder.InterfaceHttpMethods.ToDictionary(k => k, v => requestBuilder.BuildRestResultFuncForMethod(v));
Client = client;
}
public virtual Task<string> Echo(string data)
{
var arguments = new object[] { data };
return (Task<string>) methodImpls["Echo"](Client, arguments);
}
public virtual Task SetTime(long time)
{
var arguments = new object[] { time };
return (Task) methodImpls["SetTime"](Client, arguments);
}
public virtual Task<string> GetStatus()
{
var arguments = new object[] { };
return (Task<string>) methodImpls["GetStatus"](Client, arguments);
}
public virtual Task<string> GetAllProfiles()
{
var arguments = new object[] { };
return (Task<string>) methodImpls["GetAllProfiles"](Client, arguments);
}
public virtual Task<string> GetProfile(string profileName)
{
var arguments = new object[] { profileName };
return (Task<string>) methodImpls["GetProfile"](Client, arguments);
}
public virtual Task StoreProfile(string profileName,byte[] payload,int offset)
{
var arguments = new object[] { profileName,payload,offset };
return (Task) methodImpls["StoreProfile"](Client, arguments);
}
public virtual Task ExecuteProfile(string profileName,int offset)
{
var arguments = new object[] { profileName,offset };
return (Task) methodImpls["ExecuteProfile"](Client, arguments);
}
public virtual Task TerminateProfile(string profileName,int offset)
{
var arguments = new object[] { profileName,offset };
return (Task) methodImpls["TerminateProfile"](Client, arguments);
}
public virtual Task TruncateProfile()
{
var arguments = new object[] { };
return (Task) methodImpls["TruncateProfile"](Client, arguments);
}
public virtual Task<string> GetRunHistory(string profileName)
{
var arguments = new object[] { profileName };
return (Task<string>) methodImpls["GetRunHistory"](Client, arguments);
}
public virtual Task GetTemperatureTrend(long startSecondsFromEpoch,long endSecondsFromEpoch)
{
var arguments = new object[] { startSecondsFromEpoch,endSecondsFromEpoch };
return (Task) methodImpls["GetTemperatureTrend"](Client, arguments);
}
public virtual Task<string> GetTemperature()
{
var arguments = new object[] { };
return (Task<string>) methodImpls["GetTemperature"](Client, arguments);
}
public virtual Task<string> GetTemperatureForProbe(int probeId)
{
var arguments = new object[] { probeId };
return (Task<string>) methodImpls["GetTemperatureForProbe"](Client, arguments);
}
}
}
| {
"content_hash": "1a82bb5b19a34dd9887caa6a3922a4ed",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 287,
"avg_line_length": 34.734375,
"alnum_prop": 0.6365272154745839,
"repo_name": "pdoh00/Time2Brew-FermentationController",
"id": "93ce620d647ef7f822fd17aa6519cec1fc238f48",
"size": "4450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Mobile/src/RefitStubs.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "6890"
},
{
"name": "Batchfile",
"bytes": "4688"
},
{
"name": "C",
"bytes": "1340861"
},
{
"name": "C#",
"bytes": "41177"
},
{
"name": "C++",
"bytes": "48014"
},
{
"name": "CSS",
"bytes": "3582"
},
{
"name": "HTML",
"bytes": "57231"
},
{
"name": "JavaScript",
"bytes": "39139"
},
{
"name": "Makefile",
"bytes": "79128"
},
{
"name": "Python",
"bytes": "7171"
},
{
"name": "Shell",
"bytes": "7967"
},
{
"name": "Visual Basic",
"bytes": "180232"
}
],
"symlink_target": ""
} |
int main(int argc, const char *argv[]) {
FLToolMain(argc, argv, [FLSyncFishLampTool class]);
return 0;
}
| {
"content_hash": "821147ac30ffbd3c39afcfe349a093a3",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 55,
"avg_line_length": 28.25,
"alnum_prop": 0.6637168141592921,
"repo_name": "fishlamp-released/FishLamp2",
"id": "f13a74674585435fe6e5d966e78ca821c6236494",
"size": "434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Deprecated/Experimental/Sink/Classes/main.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "56278"
},
{
"name": "C++",
"bytes": "3770"
},
{
"name": "Matlab",
"bytes": "2104"
},
{
"name": "Objective-C",
"bytes": "6583424"
},
{
"name": "Shell",
"bytes": "38669"
}
],
"symlink_target": ""
} |
@interface UIApplication (tvout)
- (void) startTVOut;
- (void) stopTVOut;
- (void) updateTVOut;
@end
@interface MPTVOutWindow : UIWindow
- (id)initWithVideoView:(id)fp8;
@end
@interface MPVideoView : UIView
- (id)initWithFrame:(struct CGRect)fp8;
@end
@implementation MPVideoView (tvout)
- (void) addSubview: (UIView *) aView
{
[super addSubview:aView];
}
@end
CGImageRef UIGetScreenImage();
@interface UIImage (tvout)
+ (UIImage *)imageWithScreenContents;
@end
@implementation UIImage (tvout)
+ (UIImage *)imageWithScreenContents
{
CGImageRef cgScreen = UIGetScreenImage();
if (cgScreen) {
UIImage *result = [UIImage imageWithCGImage:cgScreen];
CGImageRelease(cgScreen);
return result;
}
return nil;
}
@end
UIWindow* deviceWindow;
MPTVOutWindow* tvoutWindow;
NSTimer *updateTimer;
UIImage *image;
UIImageView *mirrorView;
BOOL done;
@implementation UIApplication (tvout)
// if you uncomment this, you won't need to call startTVOut in your app.
// but the home button will no longer work! Other badness may follow!
//
// - (void)reportAppLaunchFinished;
//{
// [self startTVOut];
//}
- (void) startTVOut;
{
// you need to have a main window already open when you call start
if (!tvoutWindow) {
deviceWindow = [self keyWindow];
MPVideoView *vidView = [[MPVideoView alloc] initWithFrame: CGRectZero];
tvoutWindow = [[MPTVOutWindow alloc] initWithVideoView:vidView];
[tvoutWindow makeKeyAndVisible];
tvoutWindow.userInteractionEnabled = NO;
mirrorView = [[UIImageView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait) {
mirrorView.transform = CGAffineTransformRotate(mirrorView.transform, M_PI * 1.5);
}
mirrorView.center = vidView.center;
[vidView addSubview: mirrorView];
[deviceWindow makeKeyAndVisible];
[NSThread detachNewThreadSelector:@selector(updateLoop) toTarget:self withObject:nil];
}
}
- (void) stopTVOut;
{
done = YES;
if (updateTimer) {
[updateTimer invalidate];
[updateTimer release];
updateTimer = nil;
}
if (tvoutWindow) {
[tvoutWindow release];
tvoutWindow = nil;
}
}
- (void) updateTVOut;
{
image = [UIImage imageWithScreenContents];
mirrorView.image = image;
}
- (void)updateLoop;
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
done = NO;
while ( ! done )
{
[self performSelectorOnMainThread:@selector(updateTVOut) withObject:nil waitUntilDone:NO];
[NSThread sleepForTimeInterval: (1.0/kFPS) ];
}
[pool release];
}
@end
| {
"content_hash": "f46639330d6d4200822d3175f707d474",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 97,
"avg_line_length": 21.941176470588236,
"alnum_prop": 0.7154346993489085,
"repo_name": "bryansum/urMus",
"id": "e76eafb1746ff5be6a7d452c7ef4bee5618eaf0c",
"size": "2807",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Classes/UIApplication+TVOut.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "863202"
},
{
"name": "C++",
"bytes": "84431"
},
{
"name": "JavaScript",
"bytes": "230182"
},
{
"name": "Lua",
"bytes": "196626"
},
{
"name": "Objective-C",
"bytes": "1070036"
},
{
"name": "Perl",
"bytes": "35622"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Encyclop. Mycol. (Paris), <b>1</b> Le Genre Inocybe 319 (1931)
#### Original name
Inocybe friesii R. Heim, 1931
### Remarks
null | {
"content_hash": "e8d7f2d5351cd2d3542b8244036fd7b1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 62,
"avg_line_length": 16.615384615384617,
"alnum_prop": 0.6898148148148148,
"repo_name": "mdoering/backbone",
"id": "8b9c85fc32b9a6cc3c01c088d40fa73688909ddb",
"size": "269",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Inocybaceae/Inocybe/Inocybe nitidiuscula/ Syn. Inocybe friesii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.ddlutils.model;
import java.io.Serializable;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.ddlutils.dynabean.DynaClassCache;
import org.apache.ddlutils.dynabean.SqlDynaClass;
import org.apache.ddlutils.dynabean.SqlDynaException;
/**
* Represents the database model, ie. the tables in the database. It also
* contains the corresponding dyna classes for creating dyna beans for the
* objects stored in the tables.
*
* @version $Revision: 636151 $
*/
public class Database implements Serializable
{
/** Unique ID for serialization purposes. */
private static final long serialVersionUID = -3160443396757573868L;
/** The name of the database model. */
private String _name;
/** The method for generating primary keys (currently ignored). */
private String _idMethod;
/** The version of the model. */
private String _version;
/** The tables. */
private ArrayList _tables = new ArrayList();
/** The dyna class cache for this model. */
private transient DynaClassCache _dynaClassCache = null;
/**
* Creates an empty model without a name.
*/
public Database()
{}
/**
* Creates an empty model with the given name.
*
* @param name The name
*/
public Database(String name)
{
_name = name;
}
/**
* Adds all tables from the other database to this database.
* Note that the other database is not changed.
*
* @param otherDb The other database model
*/
public void mergeWith(Database otherDb) throws ModelException
{
CloneHelper cloneHelper = new CloneHelper();
for (int tableIdx = 0; tableIdx < otherDb.getTableCount(); tableIdx++)
{
Table table = otherDb.getTable(tableIdx);
if (findTable(table.getName()) != null)
{
// TODO: It might make more sense to log a warning and overwrite the table (or merge them) ?
throw new ModelException("Cannot merge the models because table "+table.getName()+" already defined in this model");
}
else
{
addTable(cloneHelper.clone(table, true, false, this, true));
}
}
for (int tableIdx = 0; tableIdx < otherDb.getTableCount(); tableIdx++)
{
Table otherTable = otherDb.getTable(tableIdx);
Table localTable = findTable(otherTable.getName());
for (int fkIdx = 0; fkIdx < otherTable.getForeignKeyCount(); fkIdx++)
{
ForeignKey fk = otherTable.getForeignKey(fkIdx);
localTable.addForeignKey(cloneHelper.clone(fk, localTable, this, false));
}
}
}
/**
* Returns the name of this database model.
*
* @return The name
*/
public String getName()
{
return _name;
}
/**
* Sets the name of this database model.
*
* @param name The name
*/
public void setName(String name)
{
_name = name;
}
/**
* Returns the version of this database model.
*
* @return The version
*/
public String getVersion()
{
return _version;
}
/**
* Sets the version of this database model.
*
* @param version The version
*/
public void setVersion(String version)
{
_version = version;
}
/**
* Returns the method for generating primary key values.
*
* @return The method
*/
public String getIdMethod()
{
return _idMethod;
}
/**
* Sets the method for generating primary key values. Note that this
* value is ignored by DdlUtils and only for compatibility with Torque.
*
* @param idMethod The method
*/
public void setIdMethod(String idMethod)
{
_idMethod = idMethod;
}
/**
* Returns the number of tables in this model.
*
* @return The number of tables
*/
public int getTableCount()
{
return _tables.size();
}
/**
* Returns the tables in this model.
*
* @return The tables
*/
public Table[] getTables()
{
return (Table[])_tables.toArray(new Table[_tables.size()]);
}
/**
* Returns the table at the specified position.
*
* @param idx The index of the table
* @return The table
*/
public Table getTable(int idx)
{
return (Table)_tables.get(idx);
}
/**
* Adds a table.
*
* @param table The table to add
*/
public void addTable(Table table)
{
if (table != null)
{
_tables.add(table);
}
}
/**
* Adds a table at the specified position.
*
* @param idx The index where to insert the table
* @param table The table to add
*/
public void addTable(int idx, Table table)
{
if (table != null)
{
_tables.add(idx, table);
}
}
/**
* Adds the given tables.
*
* @param tables The tables to add
*/
public void addTables(Collection tables)
{
for (Iterator it = tables.iterator(); it.hasNext();)
{
addTable((Table)it.next());
}
}
/**
* Removes the given table. This method does not check whether there are foreign keys to the table.
*
* @param table The table to remove
*/
public void removeTable(Table table)
{
if (table != null)
{
_tables.remove(table);
}
}
/**
* Removes the indicated table. This method does not check whether there are foreign keys to the table.
*
* @param idx The index of the table to remove
*/
public void removeTable(int idx)
{
_tables.remove(idx);
}
/**
* Removes the given tables. This method does not check whether there are foreign keys to the tables.
*
* @param tables The tables to remove
*/
public void removeTables(Table[] tables)
{
_tables.removeAll(Arrays.asList(tables));
}
/**
* Removes all but the given tables. This method does not check whether there are foreign keys to the
* removed tables.
*
* @param tables The tables to keep
*/
public void removeAllTablesExcept(Table[] tables)
{
ArrayList allTables = new ArrayList(_tables);
allTables.removeAll(Arrays.asList(tables));
_tables.removeAll(allTables);
}
// Helper methods
/**
* Initializes the model by establishing the relationships between elements in this model encoded
* eg. in foreign keys etc. Also checks that the model elements are valid (table and columns have
* a name, foreign keys rference existing tables etc.)
*/
public void initialize() throws ModelException
{
// we have to setup
// * target tables in foreign keys
// * columns in foreign key references
// * columns in indices
// * columns in uniques
HashSet namesOfProcessedTables = new HashSet();
HashSet namesOfProcessedColumns = new HashSet();
HashSet namesOfProcessedFks = new HashSet();
HashSet namesOfProcessedIndices = new HashSet();
int tableIdx = 0;
if ((getName() == null) || (getName().length() == 0))
{
throw new ModelException("The database model has no name");
}
for (Iterator tableIt = _tables.iterator(); tableIt.hasNext(); tableIdx++)
{
Table curTable = (Table)tableIt.next();
if ((curTable.getName() == null) || (curTable.getName().length() == 0))
{
throw new ModelException("The table nr. "+tableIdx+" has no name");
}
if (namesOfProcessedTables.contains(curTable.getName()))
{
throw new ModelException("There are multiple tables with the name "+curTable.getName());
}
namesOfProcessedTables.add(curTable.getName());
namesOfProcessedColumns.clear();
namesOfProcessedFks.clear();
namesOfProcessedIndices.clear();
for (int idx = 0; idx < curTable.getColumnCount(); idx++)
{
Column column = curTable.getColumn(idx);
if ((column.getName() == null) || (column.getName().length() == 0))
{
throw new ModelException("The column nr. "+idx+" in table "+curTable.getName()+" has no name");
}
if (namesOfProcessedColumns.contains(column.getName()))
{
throw new ModelException("There are multiple columns with the name "+column.getName()+" in the table "+curTable.getName());
}
namesOfProcessedColumns.add(column.getName());
if ((column.getType() == null) || (column.getType().length() == 0))
{
throw new ModelException("The column nr. "+idx+" in table "+curTable.getName()+" has no type");
}
if ((column.getTypeCode() == Types.OTHER) && !"OTHER".equalsIgnoreCase(column.getType()))
{
throw new ModelException("The column nr. "+idx+" in table "+curTable.getName()+" has an unknown type "+column.getType());
}
namesOfProcessedColumns.add(column.getName());
}
for (int idx = 0; idx < curTable.getForeignKeyCount(); idx++)
{
ForeignKey fk = curTable.getForeignKey(idx);
String fkName = (fk.getName() == null ? "" : fk.getName());
String fkDesc = (fkName.length() == 0 ? "nr. " + idx : fkName);
if (fkName.length() > 0)
{
if (namesOfProcessedFks.contains(fkName))
{
throw new ModelException("There are multiple foreign keys in table "+curTable.getName()+" with the name "+fkName);
}
namesOfProcessedFks.add(fkName);
}
if (fk.getForeignTable() == null)
{
Table targetTable = findTable(fk.getForeignTableName(), true);
if (targetTable == null)
{
throw new ModelException("The foreignkey "+fkDesc+" in table "+curTable.getName()+" references the undefined table "+fk.getForeignTableName());
}
else
{
fk.setForeignTable(targetTable);
}
}
if (fk.getReferenceCount() == 0)
{
throw new ModelException("The foreignkey "+fkDesc+" in table "+curTable.getName()+" does not have any references");
}
for (int refIdx = 0; refIdx < fk.getReferenceCount(); refIdx++)
{
Reference ref = fk.getReference(refIdx);
if (ref.getLocalColumn() == null)
{
Column localColumn = curTable.findColumn(ref.getLocalColumnName(), true);
if (localColumn == null)
{
throw new ModelException("The foreignkey "+fkDesc+" in table "+curTable.getName()+" references the undefined local column "+ref.getLocalColumnName());
}
else
{
ref.setLocalColumn(localColumn);
}
}
if (ref.getForeignColumn() == null)
{
Column foreignColumn = fk.getForeignTable().findColumn(ref.getForeignColumnName(), true);
if (foreignColumn == null)
{
throw new ModelException("The foreignkey "+fkDesc+" in table "+curTable.getName()+" references the undefined local column "+ref.getForeignColumnName()+" in table "+fk.getForeignTable().getName());
}
else
{
ref.setForeignColumn(foreignColumn);
}
}
}
}
for (int idx = 0; idx < curTable.getIndexCount(); idx++)
{
Index index = curTable.getIndex(idx);
String indexName = (index.getName() == null ? "" : index.getName());
String indexDesc = (indexName.length() == 0 ? "nr. " + idx : indexName);
if (indexName.length() > 0)
{
if (namesOfProcessedIndices.contains(indexName))
{
throw new ModelException("There are multiple indices in table "+curTable.getName()+" with the name "+indexName);
}
namesOfProcessedIndices.add(indexName);
}
if (index.getColumnCount() == 0)
{
throw new ModelException("The index "+indexDesc+" in table "+curTable.getName()+" does not have any columns");
}
for (int indexColumnIdx = 0; indexColumnIdx < index.getColumnCount(); indexColumnIdx++)
{
IndexColumn indexColumn = index.getColumn(indexColumnIdx);
Column column = curTable.findColumn(indexColumn.getName(), true);
if (column == null)
{
throw new ModelException("The index "+indexDesc+" in table "+curTable.getName()+" references the undefined column "+indexColumn.getName());
}
else
{
indexColumn.setColumn(column);
}
}
}
}
}
/**
* Finds the table with the specified name, using case insensitive matching.
* Note that this method is not called getTable to avoid introspection
* problems.
*
* @param name The name of the table to find
* @return The table or <code>null</code> if there is no such table
*/
public Table findTable(String name)
{
return findTable(name, false);
}
/**
* Finds the table with the specified name, using case insensitive matching.
* Note that this method is not called getTable) to avoid introspection
* problems.
*
* @param name The name of the table to find
* @param caseSensitive Whether case matters for the names
* @return The table or <code>null</code> if there is no such table
*/
public Table findTable(String name, boolean caseSensitive)
{
for (Iterator iter = _tables.iterator(); iter.hasNext();)
{
Table table = (Table) iter.next();
if (caseSensitive)
{
if (table.getName().equals(name))
{
return table;
}
}
else
{
if (table.getName().equalsIgnoreCase(name))
{
return table;
}
}
}
return null;
}
/**
* Returns the indicated tables.
*
* @param tableNames The names of the tables
* @param caseSensitive Whether the case of the table names matters
* @return The tables
*/
public Table[] findTables(String[] tableNames, boolean caseSensitive)
{
ArrayList tables = new ArrayList();
if (tableNames != null)
{
for (int idx = 0; idx < tableNames.length; idx++)
{
Table table = findTable(tableNames[idx], caseSensitive);
if (table != null)
{
tables.add(table);
}
}
}
return (Table[])tables.toArray(new Table[tables.size()]);
}
/**
* Finds the tables whose names match the given regular expression.
*
* @param tableNameRegExp The table name regular expression
* @param caseSensitive Whether the case of the table names matters; if not, then the regular expression should
* assume that the table names are all-uppercase
* @return The tables
* @throws PatternSyntaxException If the regular expression is invalid
*/
public Table[] findTables(String tableNameRegExp, boolean caseSensitive) throws PatternSyntaxException
{
ArrayList tables = new ArrayList();
if (tableNameRegExp != null)
{
Pattern pattern = Pattern.compile(tableNameRegExp);
for (Iterator tableIt = _tables.iterator(); tableIt.hasNext();)
{
Table table = (Table)tableIt.next();
String tableName = table.getName();
if (!caseSensitive)
{
tableName = tableName.toUpperCase();
}
if (pattern.matcher(tableName).matches())
{
tables.add(table);
}
}
}
return (Table[])tables.toArray(new Table[tables.size()]);
}
/**
* Returns the dyna class cache. If none is available yet, a new one will be created.
*
* @return The dyna class cache
*/
private DynaClassCache getDynaClassCache()
{
if (_dynaClassCache == null)
{
_dynaClassCache = new DynaClassCache();
}
return _dynaClassCache;
}
/**
* Resets the dyna class cache. This should be done for instance when a column
* has been added or removed to a table.
*/
public void resetDynaClassCache()
{
_dynaClassCache = null;
}
/**
* Returns the {@link org.apache.ddlutils.dynabean.SqlDynaClass} for the given table name. If the it does not
* exist yet, a new one will be created based on the Table definition.
*
* @param tableName The name of the table to create the bean for
* @return The <code>SqlDynaClass</code> for the indicated table or <code>null</code>
* if the model contains no such table
*/
public SqlDynaClass getDynaClassFor(String tableName)
{
Table table = findTable(tableName);
return table != null ? getDynaClassCache().getDynaClass(table) : null;
}
/**
* Returns the {@link org.apache.ddlutils.dynabean.SqlDynaClass} for the given dyna bean.
*
* @param bean The dyna bean
* @return The <code>SqlDynaClass</code> for the given bean
*/
public SqlDynaClass getDynaClassFor(DynaBean bean)
{
return getDynaClassCache().getDynaClass(bean);
}
/**
* Creates a new dyna bean for the given table.
*
* @param table The table to create the bean for
* @return The new dyna bean
*/
public DynaBean createDynaBeanFor(Table table) throws SqlDynaException
{
return getDynaClassCache().createNewInstance(table);
}
/**
* Convenience method that combines {@link #createDynaBeanFor(Table)} and
* {@link #findTable(String, boolean)}.
*
* @param tableName The name of the table to create the bean for
* @param caseSensitive Whether case matters for the names
* @return The new dyna bean
*/
public DynaBean createDynaBeanFor(String tableName, boolean caseSensitive) throws SqlDynaException
{
return getDynaClassCache().createNewInstance(findTable(tableName, caseSensitive));
}
/**
* {@inheritDoc}
*/
public boolean equals(Object obj)
{
if (obj instanceof Database)
{
Database other = (Database)obj;
// Note that this compares case sensitive
return new EqualsBuilder().append(_name, other._name)
.append(_tables, other._tables)
.isEquals();
}
else
{
return false;
}
}
/**
* {@inheritDoc}
*/
public int hashCode()
{
return new HashCodeBuilder(17, 37).append(_name)
.append(_tables)
.toHashCode();
}
/**
* {@inheritDoc}
*/
public String toString()
{
StringBuffer result = new StringBuffer();
result.append("Database [name=");
result.append(getName());
result.append("; ");
result.append(getTableCount());
result.append(" tables]");
return result.toString();
}
/**
* Returns a verbose string representation of this database.
*
* @return The string representation
*/
public String toVerboseString()
{
StringBuffer result = new StringBuffer();
result.append("Database [");
result.append(getName());
result.append("] tables:");
for (int idx = 0; idx < getTableCount(); idx++)
{
result.append(" ");
result.append(getTable(idx).toVerboseString());
}
return result.toString();
}
}
| {
"content_hash": "569c923e48a16224e1e3c2d0cd0169f5",
"timestamp": "",
"source": "github",
"line_count": 694,
"max_line_length": 224,
"avg_line_length": 32.606628242074926,
"alnum_prop": 0.5256087321578505,
"repo_name": "jpcb/ddlutils",
"id": "ecaf99a11138a1f4b54b18a1353eb0723916ba38",
"size": "23453",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/apache/ddlutils/model/Database.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5261"
},
{
"name": "Java",
"bytes": "3161431"
},
{
"name": "Python",
"bytes": "1635"
},
{
"name": "XSLT",
"bytes": "13751"
}
],
"symlink_target": ""
} |
<!DOCTYPE compass-core-mapping PUBLIC
"-//Compass/Compass Core Mapping DTD 1.0//EN"
"http://www.opensymphony.com/compass/dtd/compass-core-mapping.dtd">
<compass-core-mapping package="org.compass.core.test.component.cyclic2">
<class name="ParentCycle" alias="parent">
<id name="id" />
<property name="value">
<meta-data>value</meta-data>
</property>
<component name="children" ref-alias="child" />
</class>
<class name="ChildCycle" alias="child" root="false">
<property name="value">
<meta-data>value</meta-data>
</property>
<component name="children" ref-alias="child" max-depth="3" />
</class>
</compass-core-mapping>
| {
"content_hash": "b7dabb579a7a565b55f9726a89bdd9a0",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 72,
"avg_line_length": 25.620689655172413,
"alnum_prop": 0.604306864064603,
"repo_name": "vthriller/opensymphony-compass-backup",
"id": "3e56a909f0cced5483293239f80fbcd900e67d03",
"size": "743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/test/org/compass/core/test/component/cyclic2/ParentChildCycle.cpm.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "189"
},
{
"name": "HTML",
"bytes": "31076"
},
{
"name": "Java",
"bytes": "4719137"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Mon Jul 18 10:42:01 PDT 2011 -->
<TITLE>
net.authorize.data.mobile Class Hierarchy (Authorize.Net Java SDK)
</TITLE>
<META NAME="date" CONTENT="2011-07-18">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="net.authorize.data.mobile Class Hierarchy (Authorize.Net Java SDK)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../net/authorize/data/echeck/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../net/authorize/data/reporting/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?net/authorize/data/mobile/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package net.authorize.data.mobile
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.Object<UL>
<LI TYPE="circle">net.authorize.data.mobile.<A HREF="../../../../net/authorize/data/mobile/MerchantContact.html" title="class in net.authorize.data.mobile"><B>MerchantContact</B></A> (implements java.io.Serializable)
<LI TYPE="circle">net.authorize.data.mobile.<A HREF="../../../../net/authorize/data/mobile/MobileDevice.html" title="class in net.authorize.data.mobile"><B>MobileDevice</B></A> (implements java.io.Serializable)
</UL>
</UL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../net/authorize/data/echeck/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../net/authorize/data/reporting/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?net/authorize/data/mobile/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| {
"content_hash": "070f845a4ef632bb1a686f900d5c6ed8",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 216,
"avg_line_length": 41.25806451612903,
"alnum_prop": 0.6229867083659109,
"repo_name": "YOTOV-LIMITED/sdk-android",
"id": "66ac71db17f399d481c73094fb33500e06cd28f3",
"size": "6395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/javadocs/net/authorize/data/mobile/package-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "637466"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W28653_text</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="page40.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 21px; margin-top: 63px;">
<p class="styleSans65.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Project: Indian Hills <br/> <br/>Site: 153N-100W—17/18 Well: Kline Federal 5300 41-18 11 2 Wellbore: Kline Federal 5300 41-18 11 2 Design: Design #1 </p>
</div>
<div style="position: absolute; margin-left: 63px; margin-top: 382px;">
<p class="styleSans121.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">4500 <br/>000 500 <br/>3 1 $525538 </p>
</div>
<div style="position: absolute; margin-left: 170px; margin-top: 892px;">
<p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">5300 41-1811T2 PBHL <br/> <br/>0 950 1900 2850 3800 4750 5700 6650 7600 8550 9500 10450 West(-)/East(+) </p>
</div>
<div style="position: absolute; margin-left: 0px; margin-top: 1338px;">
<p class="styleSans89.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Azimuths_ to True CASING DETAILS Magnetic No : <br/>TVD MD Name SiZ Magnetic Field MD - TVD +EI'W Dleg Target 10870-0 11142-0 7" Strength: 56438.3snT 0-0 - 0-0 - 0-0 0-00 <br/>Dip Angle: 72.99° 10392-5 - 10392-5 0.0 0.00 . 11141.7 . 10870.0 458.6 12.00 Date. 5/19/2014 M d I' |GRF2010 “931-7 - 10871-4 1238.6 2.00 0 6- 20743.0 . 10886.7 10050.0 0.00 5300 41-18 1172 PBHL <br/> </p>
</div>
<div style="position: absolute; margin-left: 42px; margin-top: 1742px;">
<p class="styleSans43.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">9600 0200 <br/>£an .moFmS 9.: <br/>I‘101300 </p>
</div>
<div style="position: absolute; margin-left: 170px; margin-top: 2210px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"> <br/>0 600 1200 1300 2400 3000 3600 4200 4800 5400 6000 6600 7200 7800 8400 9000 9600 10200 Vertical Section at 90.000 </p>
</div>
<div style="position: absolute; margin-left: 1232px; margin-top: 63px;">
<p class="styleSans22.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PETROLEUM </p>
</div>
<div style="position: absolute; margin-left: 1168px; margin-top: 382px;">
<p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 361px; margin-top: 510px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">SHL 467 FSL 237 FWL Sec 18 <br/> </p>
</div>
<div style="position: absolute; margin-left: 697px; margin-top: 699px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sec 18 </p>
</div>
<div style="position: absolute; margin-left: 318px; margin-top: 1742px;">
<p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">V KOP Build12°l100'h 7 7 H <br/>l <br/>. ‘ V . . r . - r ' ‘ ‘ ‘ ‘ ’ 530041-1811T2 PBHL <br/> </p>
</div>
<div style="position: absolute; margin-left: 1912px; margin-top: 42px;">
<p class="styleSans67.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">WELL DETAILS: Kline Federal 5300 41-18 11T2 <br/>Ground Level: 2057.0 Northing Easting Latittude Longitude 405170.05 120996956 48° 4' 7.880 N 103° 36' 11.950 W <br/> </p>
</div>
<div style="position: absolute; margin-left: 1275px; margin-top: 382px;">
<p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 1020px; margin-top: 488px;">
<p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Setbacks 200‘ ENV 500' MS </p>
</div>
<div style="position: absolute; margin-left: 1253px; margin-top: 701px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"> Sec17 V </p>
</div>
<div style="position: absolute; margin-left: 1508px; margin-top: 403px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2146px; margin-top: 488px;">
<p class="styleSans189.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Kline Federal 5300 41-18 9T _ <br/>.—.¢ <br/>E E U) D 0 L0 N V 1‘ V .C t O z \ 3 .C H 3 O (/J <br/>125 250 375 West(-)/East(+) (250 usft/in) <br/> </p>
</div>
<div style="position: absolute; margin-left: 1530px; margin-top: 510px;">
<p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PBHL 750 FSL 200 FEL <br/>Sec 17 </p>
</div>
</body>
</html>
| {
"content_hash": "f7953e751d6937e04071bf2479e6a7cc",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 504,
"avg_line_length": 62.56043956043956,
"alnum_prop": 0.6852274723344458,
"repo_name": "datamade/elpc_bakken",
"id": "ac915f0d70790c5d3acc00642149d7a8895aa095",
"size": "5724",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ocr_extracted/W28653_text/page41.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17512999"
},
{
"name": "HTML",
"bytes": "421900941"
},
{
"name": "Makefile",
"bytes": "991"
},
{
"name": "Python",
"bytes": "7186"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualShaderNodeCustom" inherits="VisualShaderNode" version="3.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
<brief_description>
Virtual class to define custom [VisualShaderNode]s for use in the Visual Shader Editor.
</brief_description>
<description>
By inheriting this class you can create a custom [VisualShader] script addon which will be automatically added to the Visual Shader Editor. The [VisualShaderNode]'s behavior is defined by overriding the provided virtual methods.
In order for the node to be registered as an editor addon, you must use the [code]tool[/code] keyword and provide a [code]class_name[/code] for your custom script. For example:
[codeblock]
tool
extends VisualShaderNodeCustom
class_name VisualShaderNodeNoise
[/codeblock]
</description>
<tutorials>
<link>$DOCS_URL/tutorials/plugins/editor/visual_shader_plugins.html</link>
</tutorials>
<methods>
<method name="_get_category" qualifiers="virtual">
<return type="String" />
<description>
Override this method to define the category of the associated custom node in the Visual Shader Editor's members dialog. The path may look like [code]"MyGame/MyFunctions/Noise"[/code].
Defining this method is [b]optional[/b]. If not overridden, the node will be filed under the "Custom" category.
</description>
</method>
<method name="_get_code" qualifiers="virtual">
<return type="String" />
<argument index="0" name="input_vars" type="Array" />
<argument index="1" name="output_vars" type="Array" />
<argument index="2" name="mode" type="int" />
<argument index="3" name="type" type="int" />
<description>
Override this method to define the actual shader code of the associated custom node. The shader code should be returned as a string, which can have multiple lines (the [code]"""[/code] multiline string construct can be used for convenience).
The [code]input_vars[/code] and [code]output_vars[/code] arrays contain the string names of the various input and output variables, as defined by [code]_get_input_*[/code] and [code]_get_output_*[/code] virtual methods in this class.
The output ports can be assigned values in the shader code. For example, [code]return output_vars[0] + " = " + input_vars[0] + ";"[/code].
You can customize the generated code based on the shader [code]mode[/code] (see [enum Shader.Mode]) and/or [code]type[/code] (see [enum VisualShader.Type]).
Defining this method is [b]required[/b].
</description>
</method>
<method name="_get_description" qualifiers="virtual">
<return type="String" />
<description>
Override this method to define the description of the associated custom node in the Visual Shader Editor's members dialog.
Defining this method is [b]optional[/b].
</description>
</method>
<method name="_get_global_code" qualifiers="virtual">
<return type="String" />
<argument index="0" name="mode" type="int" />
<description>
Override this method to add shader code on top of the global shader, to define your own standard library of reusable methods, varyings, constants, uniforms, etc. The shader code should be returned as a string, which can have multiple lines (the [code]"""[/code] multiline string construct can be used for convenience).
Be careful with this functionality as it can cause name conflicts with other custom nodes, so be sure to give the defined entities unique names.
You can customize the generated code based on the shader [code]mode[/code] (see [enum Shader.Mode]).
Defining this method is [b]optional[/b].
</description>
</method>
<method name="_get_input_port_count" qualifiers="virtual">
<return type="int" />
<description>
Override this method to define the amount of input ports of the associated custom node.
Defining this method is [b]required[/b]. If not overridden, the node has no input ports.
</description>
</method>
<method name="_get_input_port_name" qualifiers="virtual">
<return type="String" />
<argument index="0" name="port" type="int" />
<description>
Override this method to define the names of input ports of the associated custom node. The names are used both for the input slots in the editor and as identifiers in the shader code, and are passed in the [code]input_vars[/code] array in [method _get_code].
Defining this method is [b]optional[/b], but recommended. If not overridden, input ports are named as [code]"in" + str(port)[/code].
</description>
</method>
<method name="_get_input_port_type" qualifiers="virtual">
<return type="int" />
<argument index="0" name="port" type="int" />
<description>
Override this method to define the returned type of each input port of the associated custom node (see [enum VisualShaderNode.PortType] for possible types).
Defining this method is [b]optional[/b], but recommended. If not overridden, input ports will return the [constant VisualShaderNode.PORT_TYPE_SCALAR] type.
</description>
</method>
<method name="_get_name" qualifiers="virtual">
<return type="String" />
<description>
Override this method to define the name of the associated custom node in the Visual Shader Editor's members dialog and graph.
Defining this method is [b]optional[/b], but recommended. If not overridden, the node will be named as "Unnamed".
</description>
</method>
<method name="_get_output_port_count" qualifiers="virtual">
<return type="int" />
<description>
Override this method to define the amount of output ports of the associated custom node.
Defining this method is [b]required[/b]. If not overridden, the node has no output ports.
</description>
</method>
<method name="_get_output_port_name" qualifiers="virtual">
<return type="String" />
<argument index="0" name="port" type="int" />
<description>
Override this method to define the names of output ports of the associated custom node. The names are used both for the output slots in the editor and as identifiers in the shader code, and are passed in the [code]output_vars[/code] array in [method _get_code].
Defining this method is [b]optional[/b], but recommended. If not overridden, output ports are named as [code]"out" + str(port)[/code].
</description>
</method>
<method name="_get_output_port_type" qualifiers="virtual">
<return type="int" />
<argument index="0" name="port" type="int" />
<description>
Override this method to define the returned type of each output port of the associated custom node (see [enum VisualShaderNode.PortType] for possible types).
Defining this method is [b]optional[/b], but recommended. If not overridden, output ports will return the [constant VisualShaderNode.PORT_TYPE_SCALAR] type.
</description>
</method>
<method name="_get_return_icon_type" qualifiers="virtual">
<return type="int" />
<description>
Override this method to define the return icon of the associated custom node in the Visual Shader Editor's members dialog.
Defining this method is [b]optional[/b]. If not overridden, no return icon is shown.
</description>
</method>
<method name="_get_subcategory" qualifiers="virtual">
<return type="String" />
<description>
Override this method to define the subcategory of the associated custom node in the Visual Shader Editor's members dialog.
Defining this method is [b]optional[/b]. If not overridden, the node will be filed under the root of the main category (see [method _get_category]).
</description>
</method>
</methods>
<constants>
</constants>
</class>
| {
"content_hash": "a3f73dcd40159da9c530d0a2f286e4c5",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 322,
"avg_line_length": 60.77952755905512,
"alnum_prop": 0.7226324653452519,
"repo_name": "ex/godot",
"id": "957a4a27c4bafbde8f8cae58aedda61dde34d38e",
"size": "7719",
"binary": false,
"copies": "1",
"ref": "refs/heads/3.5",
"path": "doc/classes/VisualShaderNodeCustom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AIDL",
"bytes": "1633"
},
{
"name": "Batchfile",
"bytes": "26"
},
{
"name": "C",
"bytes": "1045182"
},
{
"name": "C#",
"bytes": "1061492"
},
{
"name": "C++",
"bytes": "39315087"
},
{
"name": "CMake",
"bytes": "606"
},
{
"name": "GAP",
"bytes": "62"
},
{
"name": "GDScript",
"bytes": "323212"
},
{
"name": "GLSL",
"bytes": "836846"
},
{
"name": "Java",
"bytes": "595274"
},
{
"name": "JavaScript",
"bytes": "194742"
},
{
"name": "Kotlin",
"bytes": "84098"
},
{
"name": "Makefile",
"bytes": "1421"
},
{
"name": "Objective-C",
"bytes": "20550"
},
{
"name": "Objective-C++",
"bytes": "365306"
},
{
"name": "PowerShell",
"bytes": "2713"
},
{
"name": "Python",
"bytes": "475722"
},
{
"name": "Shell",
"bytes": "30899"
}
],
"symlink_target": ""
} |
@class JPTopic;
@interface JPTopicVoiceView : UIView
@property(nonatomic,strong)JPTopic *topic;
@end
| {
"content_hash": "fd0748b73f06929108bf185a97a86cd3",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 42,
"avg_line_length": 20.4,
"alnum_prop": 0.7941176470588235,
"repo_name": "Rogue24/MyProjectDemo",
"id": "b9a1d643332f03a227fa6c6d812d5063d89a6812",
"size": "268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "健平不得姐 项目/健平不得姐/健平不得姐/开发场景/精华/View/JPTopicVoiceView.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "54687"
},
{
"name": "Objective-C",
"bytes": "2784448"
},
{
"name": "Objective-C++",
"bytes": "124423"
},
{
"name": "Ruby",
"bytes": "334"
},
{
"name": "Shell",
"bytes": "16418"
}
],
"symlink_target": ""
} |
<div>
<span class="grey-note">
Flight Doc ID: {{id}}
<a target="_blank" href="/_utils/document.html?{{db_name}}/{{id}}">{{raw_data_lnk}}</a>
</span>
<p>
<label for="flight_name">flight</label>
<input id="flightName" type="text" name="flight_name" readonly="readonly" value="{{flight_name}}" style="width: 10em" />
<label for="capacity">capacity</label>
<input id="flightCap" type="text" name="capacity" readonly="readonly" value="{{capacity}}" style="width: 5em" />
<label for="flight_date">flight date</label>
<input type="text" name="flight_date" readonly="readonly" value="{{flight_date}}" style="width: 10em" />
<div id="destination_counts"></div>
</p>
<br />
<table id="fltdetail" class="tablesorter Pairs">
<thead>
<tr>
<th colspan="10">Veteran</th>
<th colspan="11">Guardian</th>
</tr>
<tr>
<th>Name</th>
<th>Liability</th>
<th>Media</th>
<th>Medical</th>
<th>MedForm</th>
<th>MailCall</th>
<th>Adopt</th>
<th>Homecoming Destination</th>
<th>Jacket</th>
<th>Shirt</th>
<th>Apparel Notes</th>
<th>Apparel Notes</th>
<th>Shirt</th>
<th>Jacket</th>
<th>See Doc</th>
<th>Liability</th>
<th>Media</th>
<th>Medical</th>
<th>MedForm</th>
<th>Training</th>
<th>Paid</th>
<th>Books</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{{#pairs}}
<tr class="DataRow{{invalid_row}}" vetid="{{vet_id}}" grdid="{{grd_id}}">
<td class="Veteran colName" name="vet_name">{{vet_name_first}} {{vet_name_last}}</td>
<td class="Veteran colSeat {{vet_confirmed}}"><input type="checkbox" name="vet_flight_waiver" {{selVetFlightWaiver}} value="{{vet_flight_waiver}}" /></td>
<td class="Veteran colSeat {{vet_confirmed}}"><input type="checkbox" name="vet_flight_mediaWaiver" {{selVetFlightMediaWaiver}} value="{{vet_flight_mediaWaiver}}" /></td>
<td class="Veteran colSeat {{vet_confirmed}}"><input type="checkbox" name="vet_medical_release" {{selVetMedicalRelease}} value="{{vet_medical_release}}" /></td>
<td class="Veteran colSeat {{vet_confirmed}}"><input type="checkbox" name="vet_medical_form" {{selVetMedicalForm}} value="{{vet_medical_form}}" /></td>
<td class="Veteran colSeat {{vet_confirmed}}"><input type="checkbox" name="vet_mailcall_received" {{selVetMailCallReceived}} value="{{vet_mailcall_received}}" /></td>
<td class="Veteran colSeat {{vet_confirmed}}"><input type="checkbox" name="vet_mailcall_adopt" {{selVetMailCallAdopt}} value="{{vet_mailcall_adopt}}" /></td>
<td class="Veteran colName {{vet_confirmed}}"><input type="text" name="vet_homecoming_destination" pattern="[a-zA-Z0-9 ]{0,}" maxlength="30" value="{{vet_homecoming_destination}}" /></td>
<td class="Veteran colShirt {{vet_confirmed}}"><input type="text" name="vet_jacket_size" pattern="^(?:XS|S|M|L|XL|2XL|3XL|4XL|5XL)*$" maxlength="4" size="3" value="{{vet_apparel_jacket_size}}" /></td>
<td class="Veteran colShirt {{vet_confirmed}}"><input type="text" name="vet_shirt_size" pattern="^(?:XS|S|M|L|XL|2XL|3XL|4XL|5XL|WXS|WS|WM|WL|WXL|W2XL|W3XL|W4XL|W5XL)*$" maxlength="4" size="3" value="{{vet_apparel_shirt_size}}" />
App: {{vet_shirt_size}}
</td>
<td class="Veteran colNote {{vet_confirmed}}"><textarea rows=3 cols=40 name="vet_apparel_notes">{{vet_apparel_notes}}</textarea></td>
<td class="Guardian colNote {{grd_confirmed}}"><textarea rows=3 cols=40 name="grd_apparel_notes">{{grd_apparel_notes}}</textarea></td>
<td class="Guardian colShirt {{grd_confirmed}}"><input type="text" name="grd_shirt_size" pattern="^(?:XS|S|M|L|XL|2XL|3XL|4XL|5XL|WXS|WS|WM|WL|WXL|W2XL|W3XL|W4XL|W5XL)*$" maxlength="4" size="3" value="{{grd_apparel_shirt_size}}" />
App: {{grd_shirt_size}}
</td>
<td class="Guardian colShirt {{grd_confirmed}}"><input type="text" name="grd_jacket_size" pattern="^(?:XS|S|M|L|XL|2XL|3XL|4XL|5XL)*$" maxlength="4" size="3" value="{{grd_apparel_jacket_size}}" /></td>
<td class="Guardian colSeat {{grd_confirmed}}"><input type="checkbox" name="grd_flight_training_see_doc" {{selGrdFlightTrainingSeeDoc}} value="{{grd_flight_training_see_doc}}" /></td>
<td class="Guardian colSeat {{grd_confirmed}}"><input type="checkbox" name="grd_flight_waiver" {{selGrdFlightWaiver}} value="{{grd_flight_waiver}}" /></td>
<td class="Guardian colSeat {{grd_confirmed}}"><input type="checkbox" name="grd_flight_mediaWaiver" {{selGrdFlightMediaWaiver}} value="{{grd_flight_mediaWaiver}}" /></td>
<td class="Guardian colSeat {{grd_confirmed}}"><input type="checkbox" name="grd_medical_release" {{selGrdMedicalRelease}} value="{{grd_medical_release}}" /></td>
<td class="Guardian colSeat {{grd_confirmed}}"><input type="checkbox" name="grd_medical_form" {{selGrdMedicalForm}} value="{{grd_medical_form}}" /></td>
<td class="Guardian colSeat {{grd_confirmed}}">
{{grd_flight_training}}<br />
<input type="checkbox" name="grd_flight_training_complete" {{selGrdFlightTrainingComp}} value="{{grd_flight_training_complete}}" />
</td>
<td class="Guardian colSeat {{grd_confirmed}}"><input type="checkbox" name="grd_flight_paid" {{selGrdFlightPaid}} value="{{grd_flight_paid}}" /></td>
<td class="Guardian colSeat {{grd_confirmed}}">
<input type="number" name="grd_flight_booksOrdered" min="0" max="9" value="{{grd_flight_booksOrdered}}" style="width: 2em" />
</td>
<td class="Guardian colName" name="grd_name">{{grd_name_first}} {{grd_name_last}}</td>
</tr>
{{/pairs}}
</body>
</table>
</div>
| {
"content_hash": "aec67a375875b42f6c543adf1c5be514",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 245,
"avg_line_length": 66.30337078651685,
"alnum_prop": 0.607015760040671,
"repo_name": "shmakes/hf-basic",
"id": "b2b28bd293580f164cb33d95e288f26e19de4034",
"size": "5901",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "evently/flight_other/loggedIn/mustache.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "34488"
},
{
"name": "HTML",
"bytes": "112990"
},
{
"name": "JavaScript",
"bytes": "98529"
}
],
"symlink_target": ""
} |
package net.sourceforge.squirrel_sql.client.session.mainpanel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.MutableComboBoxModel;
import javax.swing.event.ListDataListener;
import net.sourceforge.squirrel_sql.fw.util.log.ILogger;
import net.sourceforge.squirrel_sql.fw.util.log.LoggerController;
import java.util.ArrayList;
/**
* TODO: JavaDoc
*
* @author Colin Bell
*/
public class SQLHistoryComboBoxModel extends DefaultComboBoxModel
{
/** Logger for this class. */
private static final ILogger s_log =
LoggerController.createLogger(SQLHistoryComboBoxModel.class);
/** Shared data model. */
private static MutableComboBoxModel s_sharedDataModel;
/** Actual data model. */
private MutableComboBoxModel _dataModel;
/** The currently selected model. */
private Object _selectedObject;
public SQLHistoryComboBoxModel(boolean useSharedModel)
{
super();
if (useSharedModel && s_sharedDataModel == null)
{
throw new IllegalStateException("Shared instance has not been initialized");
}
_dataModel = useSharedModel ? s_sharedDataModel : new DefaultComboBoxModel();
}
public synchronized static void initializeSharedInstance(Object[] data)
{
if (s_sharedDataModel != null)
{
s_log.error("Shared data model has already been initialized");
}
else
{
s_sharedDataModel = new DefaultComboBoxModel(data);
}
}
/**
* Is this model using the shared data model?
*
* @return <TT>true</TT> if this model is using the shared data model.
*/
public boolean isUsingSharedDataModel()
{
return _dataModel == s_sharedDataModel;
}
/**
* Specify whether this model is usning the shared data model.
*
* @param use <TT>true</TT> use the shared model.
*/
public synchronized void setUseSharedModel(boolean use)
{
if (isUsingSharedDataModel() != use)
{
_dataModel = use ? s_sharedDataModel : duplicateSharedDataModel();
}
}
/**
* Add an element to this model.
*
* This method is passed onto the data model that this data model is
* wrapped around.
*
* @param object The object to be added.
*/
public void addElement(Object object)
{
_dataModel.addElement(object);
}
/**
* Add an item at a specified index.
*
* This method is passed onto the data model that this data model is
* wrapped around.
*
* @param object The object to be added.
* @param index The index to add it at.
*/
public void insertElementAt(Object object, int index)
{
_dataModel.insertElementAt(object, index);
}
/**
* Remove the passed object from this collection.
*
* This method is passed onto the data model that this data model is
* wrapped around.
*
* @param object The object to be removed.
*/
public void removeElement(Object object)
{
_dataModel.removeElement(object);
}
/**
* Remove the element from this collection at the passed index.
*
* This method is passed onto the data model that this data model is
* wrapped around.
*
* @param index The index to remove an element from.
*/
public void removeElementAt(int index)
{
_dataModel.removeElementAt(index);
}
/**
* Retrieve the element currently selected. This is <EM>not</EM> passed
* on to the wrapped model as this model is responsible for keeping track
* of the currently selected item.
*
* @return The object currently selected.
*/
public Object getSelectedItem()
{
return _selectedObject;
}
/**
* @see javax.swing.ComboBoxModel#setSelectedItem(java.lang.Object)
*/
public void setSelectedItem(Object object)
{
_selectedObject = object;
fireContentsChanged(this, -1, -1);
}
/**
* This method is passed onto the data model that this data model is
* wrapped around.
*/
public void addListDataListener(ListDataListener arg0)
{
_dataModel.addListDataListener(arg0);
}
/**
* This method is passed onto the data model that this data model is
* wrapped around.
*/
public Object getElementAt(int arg0)
{
return _dataModel.getElementAt(arg0);
}
/**
* Retrieve the number of elements in this model.
*
* This method is passed onto the data model that this data model is
* wrapped around.
*
* @return Number of elements in this model.
*/
public int getSize()
{
return _dataModel.getSize();
}
/**
* This method is passed onto the data model that this data model is
* wrapped around.
*/
public void removeListDataListener(ListDataListener arg0)
{
_dataModel.removeListDataListener(arg0);
}
protected synchronized MutableComboBoxModel duplicateSharedDataModel()
{
MutableComboBoxModel newModel = new DefaultComboBoxModel();
for (int i = 0, limit = s_sharedDataModel.getSize(); i < limit; ++i)
{
SQLHistoryItem obj = (SQLHistoryItem)s_sharedDataModel.getElementAt(i);
newModel.addElement(obj.clone());
}
return newModel;
}
public ArrayList<SQLHistoryItem> getItems()
{
ArrayList<SQLHistoryItem> ret = new ArrayList<SQLHistoryItem>();
for (int i = 0; i < _dataModel.getSize(); i++)
{
ret.add((SQLHistoryItem) _dataModel.getElementAt(i));
}
return ret;
}
}
| {
"content_hash": "a8e14542944dcc8a367f10fe7ffa1823",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 79,
"avg_line_length": 23.795348837209303,
"alnum_prop": 0.7044566067240031,
"repo_name": "sdgdsffdsfff/bigtable-sql",
"id": "478b88a83ddafefe24cf700d0d9a91f2298b15f2",
"size": "5927",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/net/sourceforge/squirrel_sql/client/session/mainpanel/SQLHistoryComboBoxModel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2245"
},
{
"name": "Java",
"bytes": "3489167"
}
],
"symlink_target": ""
} |
cask "navicat-premium-essentials" do
version "16.0.13"
sha256 :no_check
url "https://download.navicat.com/download/navicatess#{version.major_minor.no_dots}_premium_en.dmg"
name "Navicat Premium Essentials"
desc "Database administration and development tool"
homepage "https://navicat.com/products/navicat-essentials"
livecheck do
cask "navicat-premium"
end
depends_on macos: ">= :mojave"
app "Navicat Premium Essentials.app"
end
| {
"content_hash": "d232c710db728cf78b8a562bf0ec7b27",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 101,
"avg_line_length": 26.88235294117647,
"alnum_prop": 0.7417943107221007,
"repo_name": "sscotth/homebrew-cask",
"id": "097f6c38486e7eee14aab8f34850bddbbcee592f",
"size": "457",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Casks/navicat-premium-essentials.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "249"
},
{
"name": "Python",
"bytes": "3630"
},
{
"name": "Ruby",
"bytes": "2969714"
},
{
"name": "Shell",
"bytes": "32035"
}
],
"symlink_target": ""
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _styles = require('../../../build/styles');
var _styles2 = _interopRequireDefault(_styles);
var _helper = require('../../helper/helper');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var PanelHeading = function (_Component) {
_inherits(PanelHeading, _Component);
function PanelHeading() {
_classCallCheck(this, PanelHeading);
return _possibleConstructorReturn(this, (PanelHeading.__proto__ || Object.getPrototypeOf(PanelHeading)).apply(this, arguments));
}
_createClass(PanelHeading, [{
key: 'createClassName',
value: function createClassName() {
return [_styles2.default.panelHeading, this.props.className].join(' ').trim();
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'p',
_extends({}, (0, _helper.getCallbacks)(this.props), {
className: this.createClassName(),
style: this.props.style
}),
this.props.children
);
}
}]);
return PanelHeading;
}(_react.Component);
PanelHeading.propTypes = {
children: _propTypes2.default.any,
style: _propTypes2.default.object,
className: _propTypes2.default.string
};
PanelHeading.defaultProps = {
className: '',
style: {}
};
exports.default = PanelHeading; | {
"content_hash": "f740967bd64b60261354e9e83afa7576",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 564,
"avg_line_length": 45.178082191780824,
"alnum_prop": 0.6952698605215282,
"repo_name": "bokuweb/re-bulma",
"id": "232bd82002c17a85c2c99035c90765d24c1dd5b5",
"size": "3298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/components/panel/panel-heading.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "428710"
},
{
"name": "HTML",
"bytes": "12205"
},
{
"name": "JavaScript",
"bytes": "486499"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>propcalc: 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 / extra-dev</a></li>
<li class="active"><a href="">8.11.dev / propcalc - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
propcalc
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2020-07-18 17:11:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-18 17:11:19 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.11.dev Formal proof management system
num 1.3 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.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/http://arxiv.org/abs/1503.08744"
license: "BSD"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/PropCalc"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: propositional calculus"
"keyword: classical logic"
"keyword: completeness"
"keyword: natural deduction"
"keyword: sequent calculus"
"keyword: cut elimination"
"category: Mathematics/Logic/Foundations"
]
authors: [
"Floris van Doorn <fpvdoorn@gmail.com> [http://www.contrib.andrew.cmu.edu/~fpv/]"
]
bug-reports: "https://github.com/coq-contribs/propcalc/issues"
dev-repo: "git+https://github.com/coq-contribs/propcalc.git"
synopsis: "Propositional Calculus"
description: """
Formalization of basic theorems about classical propositional logic. The main theorems are (1) the soundness and completeness of natural deduction calculus, (2) the equivalence between natural deduction calculus, Hilbert systems and sequent calculus and (3) cut elimination for sequent calculus."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/propcalc/archive/v8.10.0.tar.gz"
checksum: "md5=e1ab2584b2a3713b92c06f543803de34"
}
</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-propcalc.8.10.0 coq.8.11.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev).
The following dependencies couldn't be met:
- coq-propcalc -> coq < 8.11~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
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-propcalc.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "6009b72458257b32bef5421fc71522a4",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 313,
"avg_line_length": 41.758620689655174,
"alnum_prop": 0.5546380401871731,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "77046e049666051b6bb4d5e19b63aaa9038ad1e8",
"size": "7291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/extra-dev/8.11.dev/propcalc/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Overlay](./puppeteer.protocol.overlay.md) > [SetInspectModeRequest](./puppeteer.protocol.overlay.setinspectmoderequest.md) > [mode](./puppeteer.protocol.overlay.setinspectmoderequest.mode.md)
## Protocol.Overlay.SetInspectModeRequest.mode property
Set an inspection mode.
<b>Signature:</b>
```typescript
mode: InspectMode;
```
| {
"content_hash": "5d68900bb743c4fede78733c18a568ec",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 296,
"avg_line_length": 40.84615384615385,
"alnum_prop": 0.7250470809792844,
"repo_name": "GoogleChrome/puppeteer",
"id": "13d0d3b3081be2fa7ee81cd9e490b995910198bb",
"size": "531",
"binary": false,
"copies": "1",
"ref": "refs/heads/1060080_cross_origin_iframe",
"path": "new-docs/puppeteer.protocol.overlay.setinspectmoderequest.mode.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "393"
},
{
"name": "HTML",
"bytes": "17624"
},
{
"name": "JavaScript",
"bytes": "1087838"
},
{
"name": "TypeScript",
"bytes": "8164"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/marshall-lee/descendants_fetcher)
This gem provides functionality similar to [descendants_tracker](https://github.com/dkubb/descendants_tracker) but it doesn't store classes in the array. Instead of this it uses `ObjectSpace` approach to *fetch* descendant classes dynamically. It also separates `descendants` and `subclasses`: first is like `ancestors` but in opposite direction (*deep*), second matches strictly by superclass (*children*). See [examples below](#usage).
The main cool **feature** of this implementation is that unlike with `DescendantsTracker` parent class doesn't store references to descendant class objects when inherited. It means that it can be safely used for dynamically created classes (via `Class.new(...)`).
The main **caveat** of this implementation is that it's obviously slower than `DescendantsTracker`.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'descendants_fetcher'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install descendants_fetcher
## Usage
```ruby
class X
extend DescendantsFetcher
end
class X1 < X
end
class X2 < X
end
class Y < X1
end
X.descendants
# => [X, X1, X2, Y]
X.subclasses
# => [X1, X2]
X1.superclass
# => X
X2.superclass
# => X
Class.new(X) # This class object will be safely garbage-collected!
```
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/marshall-lee/descendants_fetcher.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
| {
"content_hash": "a3dda70092def31884be1908e0afccce",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 437,
"avg_line_length": 26.936507936507937,
"alnum_prop": 0.7472009428403065,
"repo_name": "marshall-lee/descendants_fetcher",
"id": "91e665d9e03ca2e993dbb1753e31cac944216a91",
"size": "1720",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3098"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>[ESUI EXAMPLE] - Select</title>
<link rel="stylesheet" href="page.css" type="text/css" />
<link rel="stylesheet" href="../../src/esui/css/ui-select.css" type="text/css" />
<!-- __debug__
<link rel="stylesheet" href="../../release/$((esuicss)).css" type="text/css" />
__debug__ -->
<script type="text/javascript" src="../../tool/tangram-1.3.9.js"></script>
<script type="text/javascript" src="../../tool/include.js"></script><!-- __debug__ -->
<!-- __debug__
<script type="text/javascript" src="../../release/$((esui))"></script>
__debug__ -->
<script>// __debug__
include( 'esui.Select' );// __debug__
</script><!-- __debug__ -->
</head>
<body>
<div class="header">[ESUI EXAMPLE] - Select</div>
<div class="main">
<table cellpadding="5" cellspacing="0" border="0">
<tr>
<td>正常样式</td>
<td><div ui="type:Select;id:mySelect;width:80"></div></td>
</tr>
<tr>
<td>执行命令</td>
<td><div ui="type:Select;id:mySelect2;skin:menu;width:80;staticText:更多操作"></div></td>
</tr>
<tr>
<td>小按钮</td>
<td><div ui="type:Select;id:mySelect3;skin:button;"></div></td>
</tr>
<tr>
<td>大按钮</td>
<td><div ui="type:Select;id:mySelect4;skin:largebutton;"></div></td>
</tr>
<tr>
<td>穿透样式</td>
<td><div ui="type:Select;id:mySelect5;skin:menu2;width:80;"></div></td>
</tr>
</table>
</div>
<script>
var datasource = [
{name:'昨天昨天', value: 0},
{name:'今天今天', value: 1},
{name:'明天明天', value: 2},
{name:'后天后天', value: 3}
];
esui.init( document.body, {
mySelect : { datasource: datasource },
mySelect2: { datasource: datasource, value: 2 },
mySelect3: { datasource: datasource, value: 2 },
mySelect4: { datasource: datasource, value: 2 },
mySelect5: { datasource: datasource, value: 2 }
} );
function changeHandler( value, item ) {
alert( value );
}
function clickHandler() {
this.onchange( this.getValue() );
return false;
}
esui.get('mySelect').onchange = changeHandler;
esui.get('mySelect2').onchange = changeHandler;
esui.get('mySelect2').onmainclick = clickHandler;
</script>
</body>
</html>
| {
"content_hash": "fdb7f4596fff55d79075e29b90a5d332",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 88,
"avg_line_length": 25.85542168674699,
"alnum_prop": 0.6178937558247903,
"repo_name": "erik168/ER",
"id": "dea10f4658cfb5fe44a0146fbcf8bac93aad1ce1",
"size": "2222",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/esui/select.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "554951"
},
{
"name": "PHP",
"bytes": "729"
},
{
"name": "Shell",
"bytes": "4086"
}
],
"symlink_target": ""
} |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2018] EMBL-European Bioinformatics Institute
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.
=cut
package Catalyst::Action::Serialize::YAML::XS;
use Moose;
use namespace::autoclean;
extends 'Catalyst::Action';
use YAML::XS;
our $VERSION = '1.00';
$VERSION = eval $VERSION;
sub execute {
my $self = shift;
my ( $controller, $c ) = @_;
my $stash_key = (
$controller->{'serialize'}
? $controller->{'serialize'}->{'stash_key'}
: $controller->{'stash_key'}
)
|| 'rest';
my $output = $self->serialize( $c->stash->{$stash_key} );
$c->response->output($output);
return 1;
}
sub serialize {
my $self = shift;
my $data = shift;
Dump($data);
}
__PACKAGE__->meta->make_immutable;
1;
| {
"content_hash": "41c2a26f56db7b8943abe51ec534f4c4",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 101,
"avg_line_length": 25.314814814814813,
"alnum_prop": 0.6854425749817118,
"repo_name": "ens-lgil/ensembl-rest",
"id": "5a8f8cd46bf70308cd1c8243041486e6c86db5e0",
"size": "1367",
"binary": false,
"copies": "2",
"ref": "refs/heads/release/93",
"path": "lib/Catalyst/Action/Serialize/YAML/XS.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "341080"
},
{
"name": "JavaScript",
"bytes": "112944"
},
{
"name": "Perl",
"bytes": "1041201"
},
{
"name": "Perl 6",
"bytes": "13853"
},
{
"name": "Ruby",
"bytes": "2766"
},
{
"name": "Shell",
"bytes": "5387"
}
],
"symlink_target": ""
} |
#include <aws/route53domains/model/Nameserver.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Route53Domains
{
namespace Model
{
Nameserver::Nameserver() :
m_nameHasBeenSet(false),
m_glueIpsHasBeenSet(false)
{
}
Nameserver::Nameserver(JsonView jsonValue) :
m_nameHasBeenSet(false),
m_glueIpsHasBeenSet(false)
{
*this = jsonValue;
}
Nameserver& Nameserver::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("GlueIps"))
{
Array<JsonView> glueIpsJsonList = jsonValue.GetArray("GlueIps");
for(unsigned glueIpsIndex = 0; glueIpsIndex < glueIpsJsonList.GetLength(); ++glueIpsIndex)
{
m_glueIps.push_back(glueIpsJsonList[glueIpsIndex].AsString());
}
m_glueIpsHasBeenSet = true;
}
return *this;
}
JsonValue Nameserver::Jsonize() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_glueIpsHasBeenSet)
{
Array<JsonValue> glueIpsJsonList(m_glueIps.size());
for(unsigned glueIpsIndex = 0; glueIpsIndex < glueIpsJsonList.GetLength(); ++glueIpsIndex)
{
glueIpsJsonList[glueIpsIndex].AsString(m_glueIps[glueIpsIndex]);
}
payload.WithArray("GlueIps", std::move(glueIpsJsonList));
}
return payload;
}
} // namespace Model
} // namespace Route53Domains
} // namespace Aws
| {
"content_hash": "910396b31b5ee9adae5fc3a434f81cbf",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 94,
"avg_line_length": 19.49367088607595,
"alnum_prop": 0.7032467532467532,
"repo_name": "jt70471/aws-sdk-cpp",
"id": "8462b80aba3bf15e01c1d9e98125bda26ae4534d",
"size": "1659",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-route53domains/source/model/Nameserver.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "13452"
},
{
"name": "C++",
"bytes": "278594037"
},
{
"name": "CMake",
"bytes": "653931"
},
{
"name": "Dockerfile",
"bytes": "5555"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "302182"
},
{
"name": "Python",
"bytes": "110380"
},
{
"name": "Shell",
"bytes": "4674"
}
],
"symlink_target": ""
} |
<?php
namespace Phony\Tests\Server;
use Phony\Server\Response;
class ResponseTest extends \PHPUnit_Framework_TestCase
{
public function testGetMethod()
{
$method = "POST";
$response = new Response($method);
$this->assertEquals($method, $response->getMethod());
}
public function testGetUri()
{
$method = "POST";
$uri = "/test";
$response = new Response($method, $uri);
$this->assertEquals($uri, $response->getUri());
}
public function testGetHttpCode()
{
$method = "POST";
$uri = "/test";
$statusCode = 200;
$response = new Response($method, $uri, $statusCode);
$this->assertEquals($statusCode, $response->getHttpCode());
}
public function testGetContentType()
{
$method = "POST";
$uri = "/test";
$contentType = "text/html";
$response = new Response($method, $uri, 200, $contentType);
$this->assertEquals($contentType, $response->getContentType());
}
public function testGetHeaderHasContentType()
{
$method = "POST";
$uri = "/test";
$contentType = "text/html";
$response = new Response($method, $uri, 200, $contentType);
$this->assertArrayHasKey("Content-Type", $response->getHeaders());
$this->assertEquals($contentType, $response->getHeaders()["Content-Type"]);
}
public function testGetHeadersHasExtraHeaders()
{
$method = "POST";
$uri = "/test";
$key = "X-PHP";
$value = "Codez";
$response = new Response($method, $uri, 200, "json", "", [$key => $value]);
$this->assertArrayHasKey($key, $response->getHeaders());
$this->assertEquals($value, $response->getHeaders()[$key]);
}
public function testGetBody()
{
$method = "POST";
$uri = "/test";
$body = "Hello World";
$response = new Response($method, $uri, 200, '', $body);
$this->assertEquals($body, $response->getBody());
}
}
| {
"content_hash": "f342cec236a608b4054aaea7bb6d7bab",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 83,
"avg_line_length": 28.51388888888889,
"alnum_prop": 0.5635655138821237,
"repo_name": "icambridge/phony",
"id": "6b9a2a0defcd92a9af3cf7ef3b353b56ac43a338",
"size": "2053",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Server/ResponseTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "29050"
}
],
"symlink_target": ""
} |
<?php
/**
* RmaAmb form.
*
* @package sf_sandbox
* @subpackage form
* @author Your name here
* @version SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class RmaAmbForm extends BaseRmaAmbForm
{
public function configure()
{
}
}
| {
"content_hash": "517706c24e9cd520f1829f4be70031a7",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 95,
"avg_line_length": 18,
"alnum_prop": 0.6597222222222222,
"repo_name": "luelher/gesser",
"id": "25458064485b6053170c595df9b8395f98e1783e",
"size": "288",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/form/doctrine/RmaAmbForm.class.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "11980929"
},
{
"name": "PHP",
"bytes": "20915238"
},
{
"name": "Shell",
"bytes": "7985"
}
],
"symlink_target": ""
} |
package tap
import (
"encoding/json"
)
// yaml serializes a message to YAML. This implementation uses JSON,
// which is a subset of YAML [1] and is implemented by Go's standard
// library.
//
// [1]: http://www.yaml.org/spec/1.2/spec.html#id2759572
func yaml(message interface{}, prefix string) (marshaled []byte, err error) {
marshaled, err = json.MarshalIndent(message, prefix, " ")
if err != nil {
return marshaled, err
}
marshaled = append(marshaled, []byte("\n")...)
return marshaled, err
}
| {
"content_hash": "29e9c1e19dbd33962962c6eaea0e62b1",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 77,
"avg_line_length": 25.45,
"alnum_prop": 0.6856581532416502,
"repo_name": "opencontainers/runtime-tools",
"id": "f848e64269bb426a10e9e83e1dccb79779d6855d",
"size": "526",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "vendor/github.com/mndrix/tap-go/yaml_json.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "465953"
},
{
"name": "Makefile",
"bytes": "3327"
},
{
"name": "Shell",
"bytes": "15513"
}
],
"symlink_target": ""
} |
define(function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace--nouba";
exports.cssText = require("../requirejs/text!./Nouba.css");
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| {
"content_hash": "08059e2c1a9bbca34debbe5f8c42bfe2",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 59,
"avg_line_length": 23.363636363636363,
"alnum_prop": 0.708171206225681,
"repo_name": "Colorsublime/colorsublime.github.io",
"id": "7fde789ae949c725904fd2c4b8e96ca7b38049bd",
"size": "1932",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "ace/lib/ace/theme/Nouba.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ABAP",
"bytes": "1037"
},
{
"name": "ActionScript",
"bytes": "1133"
},
{
"name": "Ada",
"bytes": "99"
},
{
"name": "Assembly",
"bytes": "506"
},
{
"name": "AutoHotkey",
"bytes": "720"
},
{
"name": "Batchfile",
"bytes": "260"
},
{
"name": "C#",
"bytes": "83"
},
{
"name": "C++",
"bytes": "808"
},
{
"name": "COBOL",
"bytes": "4"
},
{
"name": "CSS",
"bytes": "1048800"
},
{
"name": "Cirru",
"bytes": "520"
},
{
"name": "Clojure",
"bytes": "794"
},
{
"name": "CoffeeScript",
"bytes": "403"
},
{
"name": "ColdFusion",
"bytes": "86"
},
{
"name": "Common Lisp",
"bytes": "632"
},
{
"name": "D",
"bytes": "324"
},
{
"name": "Dart",
"bytes": "489"
},
{
"name": "Dockerfile",
"bytes": "2493"
},
{
"name": "Eiffel",
"bytes": "375"
},
{
"name": "Elixir",
"bytes": "692"
},
{
"name": "Elm",
"bytes": "487"
},
{
"name": "Erlang",
"bytes": "487"
},
{
"name": "Forth",
"bytes": "979"
},
{
"name": "Fortran",
"bytes": "713"
},
{
"name": "FreeMarker",
"bytes": "1017"
},
{
"name": "G-code",
"bytes": "521"
},
{
"name": "GLSL",
"bytes": "512"
},
{
"name": "Gherkin",
"bytes": "699"
},
{
"name": "Go",
"bytes": "641"
},
{
"name": "Groovy",
"bytes": "1080"
},
{
"name": "HTML",
"bytes": "1288890"
},
{
"name": "Haskell",
"bytes": "512"
},
{
"name": "Haxe",
"bytes": "447"
},
{
"name": "Io",
"bytes": "140"
},
{
"name": "JSONiq",
"bytes": "4"
},
{
"name": "Java",
"bytes": "1550"
},
{
"name": "JavaScript",
"bytes": "13412104"
},
{
"name": "Julia",
"bytes": "210"
},
{
"name": "Kotlin",
"bytes": "3556"
},
{
"name": "LSL",
"bytes": "2080"
},
{
"name": "Liquid",
"bytes": "1883"
},
{
"name": "LiveScript",
"bytes": "5747"
},
{
"name": "Lua",
"bytes": "981"
},
{
"name": "MATLAB",
"bytes": "203"
},
{
"name": "Makefile",
"bytes": "6612"
},
{
"name": "Mask",
"bytes": "597"
},
{
"name": "NSIS",
"bytes": "486"
},
{
"name": "Nix",
"bytes": "2212"
},
{
"name": "OCaml",
"bytes": "539"
},
{
"name": "Objective-C",
"bytes": "2672"
},
{
"name": "OpenSCAD",
"bytes": "333"
},
{
"name": "PHP",
"bytes": "351"
},
{
"name": "PLpgSQL",
"bytes": "2547"
},
{
"name": "Pascal",
"bytes": "1412"
},
{
"name": "Perl",
"bytes": "678"
},
{
"name": "PigLatin",
"bytes": "277"
},
{
"name": "PowerShell",
"bytes": "418"
},
{
"name": "Python",
"bytes": "478"
},
{
"name": "R",
"bytes": "2445"
},
{
"name": "Ruby",
"bytes": "2208"
},
{
"name": "Rust",
"bytes": "495"
},
{
"name": "Scala",
"bytes": "1541"
},
{
"name": "Scheme",
"bytes": "559"
},
{
"name": "Shell",
"bytes": "4256"
},
{
"name": "Swift",
"bytes": "476"
},
{
"name": "Tcl",
"bytes": "899"
},
{
"name": "TeX",
"bytes": "1345"
},
{
"name": "TypeScript",
"bytes": "1672"
},
{
"name": "VBScript",
"bytes": "938"
},
{
"name": "VHDL",
"bytes": "830"
},
{
"name": "Vala",
"bytes": "485"
},
{
"name": "Verilog",
"bytes": "274"
},
{
"name": "Vim Snippet",
"bytes": "228243"
},
{
"name": "Wollok",
"bytes": "419"
},
{
"name": "XQuery",
"bytes": "114"
},
{
"name": "Zeek",
"bytes": "689"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us">
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="Built-In type overview" />
<meta content="NULL, not a data type, SQL-92 data types, supported by Derby" name="DC.subject" />
<meta content="NULL, not a data type, SQL-92 data types, supported by Derby" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="crefsqlj31068.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="crefsqlj21305" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Built-In type overview</title>
</head>
<body id="crefsqlj21305"><a name="crefsqlj21305"><!-- --></a>
<h1 class="topictitle1">Built-In type overview</h1>
<div>
<p>The SQL type system is used by the language compiler to determine the compile-time
type of an expression and by the language execution system to determine the
runtime type of an expression, which can be a subtype or implementation of
the compile-time type.</p>
<p>Each type has associated with it values of that type. In addition, values
in the database or resulting from expressions can be NULL, which means the
value is missing or unknown. Although there are some places where the keyword
NULL can be explicitly used, it is not in itself a value, because it needs
to have a type associated with it.</p>
<p>The syntax presented in this section is the syntax you use when specifying
a column's data type in a CREATE TABLE statement.</p>
</div>
<div>
<div class="familylinks">
<div class="parentlink"><strong>Parent topic:</strong> <a href="crefsqlj31068.html" title="">Data types</a></div>
</div>
</div>
</body>
</html>
| {
"content_hash": "dd1290c45aff54545b8f9e95aefda986",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 261,
"avg_line_length": 47.51470588235294,
"alnum_prop": 0.7288765088207985,
"repo_name": "Kerensky256/Database",
"id": "46bf8e8d63262a5d1659a4292d22e98bd0f0ec6a",
"size": "3231",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "docs/html/ref/crefsqlj21305.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "119015"
},
{
"name": "Java",
"bytes": "303948"
},
{
"name": "JavaScript",
"bytes": "1654"
},
{
"name": "Shell",
"bytes": "14232"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqToDB.Mapping
{
using Common;
using Extensions;
using Linq;
using Reflection;
/// <summary>
/// Stores mapping entity descriptor.
/// </summary>
public class EntityDescriptor
{
/// <summary>
/// Creates descriptor instance.
/// </summary>
/// <param name="mappingSchema">Mapping schema, associated with descriptor.</param>
/// <param name="type">Mapping class type.</param>
public EntityDescriptor(MappingSchema mappingSchema, Type type)
{
TypeAccessor = TypeAccessor.GetAccessor(type);
Associations = new List<AssociationDescriptor>();
Columns = new List<ColumnDescriptor>();
Init(mappingSchema);
InitInheritanceMapping(mappingSchema);
}
/// <summary>
/// Gets mapping type accessor.
/// </summary>
public TypeAccessor TypeAccessor { get; private set; }
/// <summary>
/// Gets name of table or view in database.
/// </summary>
public string TableName { get; private set; }
/// <summary>
/// Gets optional schema/owner name, to override default name. See <see cref="LinqExtensions.SchemaName{T}(ITable{T}, string)"/> method for support information per provider.
/// </summary>
public string SchemaName { get; private set; }
/// <summary>
/// Gets optional database name, to override default database name. See <see cref="LinqExtensions.DatabaseName{T}(ITable{T}, string)"/> method for support information per provider.
/// </summary>
public string DatabaseName { get; private set; }
// TODO: V2: remove?
/// <summary>
/// Gets or sets column mapping rules for current mapping class or interface.
/// If <c>true</c>, properties and fields should be marked with one of those attributes to be used for mapping:
/// - <see cref="ColumnAttribute"/>;
/// - <see cref="PrimaryKeyAttribute"/>;
/// - <see cref="IdentityAttribute"/>;
/// - <see cref="ColumnAliasAttribute"/>.
/// Otherwise all supported members of scalar type will be used:
/// - public instance fields and properties;
/// - explicit interface implmentation properties.
/// Also see <seealso cref="Configuration.IsStructIsScalarType"/> and <seealso cref="ScalarTypeAttribute"/>.
/// </summary>
public bool IsColumnAttributeRequired { get; private set; }
/// <summary>
/// Gets list of column descriptors for current entity.
/// </summary>
public List<ColumnDescriptor> Columns { get; private set; }
/// <summary>
/// Gets list of association descriptors for current entity.
/// </summary>
public List<AssociationDescriptor> Associations { get; private set; }
/// <summary>
/// Gets mapping dictionary to map column aliases to target columns or aliases.
/// </summary>
public Dictionary<string,string> Aliases { get; private set; }
private List<InheritanceMapping> _inheritanceMappings;
/// <summary>
/// Gets list of inheritace mapping descriptors for current entity.
/// </summary>
public List<InheritanceMapping> InheritanceMapping
{
get
{
return _inheritanceMappings;
}
}
/// <summary>
/// Gets mapping class type.
/// </summary>
public Type ObjectType { get { return TypeAccessor.Type; } }
void Init(MappingSchema mappingSchema)
{
var ta = mappingSchema.GetAttribute<TableAttribute>(TypeAccessor.Type, a => a.Configuration);
if (ta != null)
{
TableName = ta.Name;
SchemaName = ta.Schema;
DatabaseName = ta.Database;
IsColumnAttributeRequired = ta.IsColumnAttributeRequired;
}
if (TableName == null)
{
TableName = TypeAccessor.Type.Name;
if (TypeAccessor.Type.IsInterfaceEx() && TableName.Length > 1 && TableName[0] == 'I')
TableName = TableName.Substring(1);
}
var attrs = new List<ColumnAttribute>();
foreach (var member in TypeAccessor.Members)
{
var aa = mappingSchema.GetAttribute<AssociationAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration);
if (aa != null)
{
Associations.Add(new AssociationDescriptor(
TypeAccessor.Type, member.MemberInfo, aa.GetThisKeys(), aa.GetOtherKeys(), aa.ExpressionPredicate, aa.Predicate, aa.Storage, aa.CanBeNull));
continue;
}
var ca = mappingSchema.GetAttribute<ColumnAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration);
if (ca != null)
{
if (ca.IsColumn)
{
if (ca.MemberName != null)
{
attrs.Add(new ColumnAttribute(member.Name, ca));
}
else
{
var cd = new ColumnDescriptor(mappingSchema, ca, member);
Columns.Add(cd);
_columnNames.Add(member.Name, cd);
}
}
}
else if (
!IsColumnAttributeRequired && mappingSchema.IsScalarType(member.Type) ||
mappingSchema.GetAttribute<IdentityAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration) != null ||
mappingSchema.GetAttribute<PrimaryKeyAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration) != null)
{
var cd = new ColumnDescriptor(mappingSchema, new ColumnAttribute(), member);
Columns.Add(cd);
_columnNames.Add(member.Name, cd);
}
else
{
var caa = mappingSchema.GetAttribute<ColumnAliasAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration);
if (caa != null)
{
if (Aliases == null)
Aliases = new Dictionary<string,string>();
Aliases.Add(member.Name, caa.MemberName);
}
}
}
var typeColumnAttrs = mappingSchema.GetAttributes<ColumnAttribute>(TypeAccessor.Type, a => a.Configuration);
foreach (var attr in typeColumnAttrs.Concat(attrs))
if (attr.IsColumn)
SetColumn(attr, mappingSchema);
}
void SetColumn(ColumnAttribute attr, MappingSchema mappingSchema)
{
if (attr.MemberName == null)
throw new LinqToDBException($"The Column attribute of the '{TypeAccessor.Type}' type must have MemberName.");
if (attr.MemberName.IndexOf('.') < 0)
{
var ex = TypeAccessor[attr.MemberName];
var cd = new ColumnDescriptor(mappingSchema, attr, ex);
Columns.Add(cd);
_columnNames.Add(attr.MemberName, cd);
}
else
{
var cd = new ColumnDescriptor(mappingSchema, attr, new MemberAccessor(TypeAccessor, attr.MemberName));
if (!string.IsNullOrWhiteSpace(attr.MemberName))
{
Columns.Add(cd);
_columnNames.Add(attr.MemberName, cd);
}
}
}
readonly Dictionary<string,ColumnDescriptor> _columnNames = new Dictionary<string, ColumnDescriptor>();
/// <summary>
/// Gets column descriptor by member name.
/// </summary>
/// <param name="memberName">Member name.</param>
/// <returns>Returns column descriptor or <c>null</c>, if descriptor not found.</returns>
public ColumnDescriptor this[string memberName]
{
get
{
if (!_columnNames.TryGetValue(memberName, out var cd))
if (Aliases != null && Aliases.TryGetValue(memberName, out var alias) && memberName != alias)
return this[alias];
return cd;
}
}
internal void InitInheritanceMapping(MappingSchema mappingSchema)
{
var mappingAttrs = mappingSchema.GetAttributes<InheritanceMappingAttribute>(ObjectType, a => a.Configuration, false);
var result = new List<InheritanceMapping>(mappingAttrs.Length);
if (mappingAttrs.Length > 0)
{
foreach (var m in mappingAttrs)
{
var mapping = new InheritanceMapping
{
Code = m.Code,
IsDefault = m.IsDefault,
Type = m.Type,
};
var ed = mapping.Type.Equals(ObjectType)
? this
: mappingSchema.GetEntityDescriptor(mapping.Type);
//foreach (var column in this.Columns)
//{
// if (ed.Columns.All(f => f.MemberName != column.MemberName))
// ed.Columns.Add(column);
//}
foreach (var column in ed.Columns)
{
if (Columns.All(f => f.MemberName != column.MemberName))
Columns.Add(column);
if (column.IsDiscriminator)
mapping.Discriminator = column;
}
mapping.Discriminator = mapping.Discriminator ?? Columns.FirstOrDefault(x => x.IsDiscriminator);
result.Add(mapping);
}
var discriminator = result.Select(m => m.Discriminator).FirstOrDefault(d => d != null);
if (discriminator == null)
throw new LinqException("Inheritance Discriminator is not defined for the '{0}' hierarchy.", ObjectType);
foreach (var mapping in result)
if (mapping.Discriminator == null)
mapping.Discriminator = discriminator;
}
_inheritanceMappings = result;
}
}
}
| {
"content_hash": "713b13600505566b7947ded4cc0f33ef",
"timestamp": "",
"source": "github",
"line_count": 277,
"max_line_length": 182,
"avg_line_length": 32.848375451263536,
"alnum_prop": 0.6355643477305198,
"repo_name": "genusP/linq2db",
"id": "2af39c01d68ae3e547678350569fe83b8d23f377",
"size": "9101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/LinqToDB/Mapping/EntityDescriptor.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3021"
},
{
"name": "C#",
"bytes": "5974769"
},
{
"name": "CoffeeScript",
"bytes": "20"
},
{
"name": "F#",
"bytes": "9977"
},
{
"name": "PLSQL",
"bytes": "22385"
},
{
"name": "PLpgSQL",
"bytes": "28536"
},
{
"name": "PowerShell",
"bytes": "14271"
},
{
"name": "SQLPL",
"bytes": "8076"
},
{
"name": "Shell",
"bytes": "2935"
},
{
"name": "Smalltalk",
"bytes": "11"
},
{
"name": "Visual Basic",
"bytes": "1660"
}
],
"symlink_target": ""
} |
<?php
require_once(__DIR__ . '/../autoload.php');
$messageBird = new \MessageBird\Client('YOUR_ACCESS_KEY'); // Set your own API access key here.
$hlr = new \MessageBird\Objects\Hlr();
$hlr->msisdn = 31612345678;
$hlr->reference = "Custom reference";
try {
$hlrResult = $messageBird->hlr->create($hlr);
var_export($hlrResult);
} catch (\MessageBird\Exceptions\AuthenticateException $e) {
// That means that your accessKey is unknown
echo 'wrong login';
} catch (\MessageBird\Exceptions\BalanceException $e) {
// That means that you are out of credits, so do something about it.
echo 'no balance';
} catch (\MessageBird\Exceptions\RequestException $e) {
echo $e->getMessage();
}
| {
"content_hash": "fec0f704116ed945b4198a78cb5ef77d",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 95,
"avg_line_length": 32.90909090909091,
"alnum_prop": 0.6726519337016574,
"repo_name": "messagebird/php-rest-api",
"id": "faaf914a61ba33314bc52525858138f35e78239c",
"size": "724",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/hlr-create.php",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "PHP",
"bytes": "258860"
}
],
"symlink_target": ""
} |
/*
Visual Studio-like style based on original C# coloring by Jason Diamond <jason@diamond.name>
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
padding-top: 0;
padding-bottom: 0;
color: black;
-webkit-text-size-adjust: none;
}
.hljs-comment,
.hljs-annotation,
.diff .hljs-header,
.hljs-chunk,
.apache .hljs-cbracket {
color: #008000;
}
.hljs-keyword,
.hljs-id,
.hljs-built_in,.css
.smalltalk .hljs-class,
.hljs-winutils,
.bash .hljs-variable,
.tex .hljs-command,
.hljs-request,
.hljs-status,
.nginx .hljs-title,
.xml .hljs-tag,
.xml .hljs-tag .hljs-value {
color: #00f;
}
.hljs-string,
.hljs-title,
.hljs-parent,
.hljs-tag .hljs-value,
.hljs-rules .hljs-value,
.ruby .hljs-symbol,
.ruby .hljs-symbol .hljs-string,
.hljs-template_tag,
.django .hljs-variable,
.hljs-addition,
.hljs-flow,
.hljs-stream,
.apache .hljs-tag,
.hljs-date,
.tex .hljs-formula,
.coffeescript .hljs-attribute {
color: #a31515;
}
.ruby .hljs-string,
.hljs-decorator,
.hljs-filter .hljs-argument,
.hljs-localvars,
.hljs-array,
.hljs-attr_selector,
.hljs-pseudo,
.hljs-pi,
.hljs-doctype,
.hljs-deletion,
.hljs-envvar,
.hljs-shebang,
.hljs-preprocessor,
.hljs-pragma,
.userType,
.apache .hljs-sqbracket,
.nginx .hljs-built_in,
.tex .hljs-special,
.hljs-prompt {
color: #2b91af;
}
.hljs-phpdoc,
.hljs-dartdoc,
.hljs-javadoc,
.hljs-xmlDocTag {
color: #808080;
}
.hljs-type,
.hljs-typename { font-weight: bold; }
.vhdl .hljs-string { color: #666666; }
.vhdl .hljs-literal { color: #a31515; }
.vhdl .hljs-attribute { color: #00b0e8; }
.xml .hljs-attribute { color: #f00; }
| {
"content_hash": "3693b69ccd9c12636853cc88930d47e8",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 92,
"avg_line_length": 16.851063829787233,
"alnum_prop": 0.6900252525252525,
"repo_name": "wcyz666/Autolab",
"id": "325bd26e7a29e7e966f9fea0558801d308fb3dd3",
"size": "1584",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "app/assets/stylesheets/highlightjs-styles/vs.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "85541"
},
{
"name": "CoffeeScript",
"bytes": "810"
},
{
"name": "HTML",
"bytes": "221993"
},
{
"name": "JavaScript",
"bytes": "269449"
},
{
"name": "Python",
"bytes": "34"
},
{
"name": "Ruby",
"bytes": "471890"
},
{
"name": "Shell",
"bytes": "120"
}
],
"symlink_target": ""
} |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert} from 'chrome://resources/js/assert.m.js';
import {MetadataItem} from './metadata_item.js';
import {MetadataRequest} from './metadata_request.js';
/**
* @abstract
*/
export class MetadataProvider {
/**
* @param {!Array<string>} validPropertyNames
*/
constructor(validPropertyNames) {
/**
* Set of valid property names. Key is the name of property and value is
* always true.
* @private @const {!Object<boolean>}
*/
this.validPropertyNames_ = {};
for (let i = 0; i < validPropertyNames.length; i++) {
this.validPropertyNames_[validPropertyNames[i]] = true;
}
}
checkPropertyNames(names) {
// Check if the property name is correct or not.
for (let i = 0; i < names.length; i++) {
assert(this.validPropertyNames_[names[i]], names[i]);
}
}
/**
* Obtains the metadata for the request.
* @abstract
* @param {!Array<!MetadataRequest>} requests
* @return {!Promise<!Array<!MetadataItem>>} Promise with obtained metadata.
* It should not return rejected promise. Instead it should return
* undefined property for property error, and should return empty
* MetadataItem for entry error.
*/
get(requests) {}
}
| {
"content_hash": "4f729fbad5cc4f796c99247bc7bc1ed6",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 78,
"avg_line_length": 29.97826086956522,
"alnum_prop": 0.6584481508339376,
"repo_name": "nwjs/chromium.src",
"id": "5c813724e55153835d8f04c3dc14af0a6bcdb178",
"size": "1379",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw70",
"path": "ui/file_manager/file_manager/foreground/js/metadata/metadata_provider.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
Local app to keep track of cryptocurrency markets
## Motivation
**Goal**
My goal is to create a local app that anyone can use to monitor and make trades on multiple markets. Using api keys from those markets just like others apps out there, except that the keys are local and not on someone elses server.
## Status
`Just started it`
| {
"content_hash": "c1656bf1d03df17cf1886fab0ccffebd",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 231,
"avg_line_length": 30.727272727272727,
"alnum_prop": 0.7692307692307693,
"repo_name": "mikebobadilla/cryptowatch",
"id": "a40a6dc9a7ca9b856563387937f7646fb8a80d98",
"size": "352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "189"
},
{
"name": "JavaScript",
"bytes": "3054"
}
],
"symlink_target": ""
} |
This project does not use ';' at the end of lines. | {
"content_hash": "09efae01a46ad835eafdcc4675886ead",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 50,
"avg_line_length": 50,
"alnum_prop": 0.72,
"repo_name": "DeividasK/tgoals",
"id": "21815b6b2e6aff5b28a0ad9ed0f1ce50d799445e",
"size": "76",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7124"
},
{
"name": "HTML",
"bytes": "1213"
},
{
"name": "JavaScript",
"bytes": "124891"
}
],
"symlink_target": ""
} |
(function($) {
var extend = function(out) {
out = out || {};
for (var i = 1; i < arguments.length; i++) {
if (!arguments[i]) {
continue;
}
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
out[key] = arguments[i][key];
}
}
}
return out;
};
/**
* Algolia Search Helper providing faceting and disjunctive faceting
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {hash} options an associative array defining the hitsPerPage, list of facets, the list of disjunctive facets and the default facet filters
*/
window.AlgoliaSearchHelper = function(client, index, options) {
/// Default options
var defaults = {
facets: [], // list of facets to compute
disjunctiveFacets: [], // list of disjunctive facets to compute
hitsPerPage: 20, // number of hits per page
defaultFacetFilters: [] // the default list of facetFilters
};
this.init(client, index, extend({}, defaults, options));
};
AlgoliaSearchHelper.prototype = {
/**
* Initialize a new AlgoliaSearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {hash} options an associative array defining the hitsPerPage, list of facets and list of disjunctive facets
* @return {AlgoliaSearchHelper}
*/
init: function(client, index, options) {
this.client = client;
this.index = index;
this.options = options;
this.page = 0;
this.refinements = {};
this.excludes = {};
this.disjunctiveRefinements = {};
this.extraQueries = [];
},
/**
* Perform a query
* @param {string} q the user query
* @param {function} searchCallback the result callback called with two arguments:
* success: boolean set to true if the request was successfull
* content: the query answer with an extra 'disjunctiveFacets' attribute
*/
search: function(q, searchCallback, searchParams) {
this.q = q;
this.searchCallback = searchCallback;
this.searchParams = searchParams || {};
this.page = this.page || 0;
this.refinements = this.refinements || {};
this.disjunctiveRefinements = this.disjunctiveRefinements || {};
this._search();
},
/**
* Remove all refinements (disjunctive + conjunctive)
*/
clearRefinements: function() {
this.disjunctiveRefinements = {};
this.refinements = {};
},
/**
* Ensure a facet refinement exists
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
addDisjunctiveRefine: function(facet, value) {
this.disjunctiveRefinements = this.disjunctiveRefinements || {};
this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {};
this.disjunctiveRefinements[facet][value] = true;
},
/**
* Ensure a facet refinement does not exist
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
removeDisjunctiveRefine: function(facet, value) {
this.disjunctiveRefinements = this.disjunctiveRefinements || {};
this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {};
try {
delete this.disjunctiveRefinements[facet][value];
} catch (e) {
this.disjunctiveRefinements[facet][value] = undefined; // IE compat
}
},
/**
* Ensure a facet refinement exists
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
addRefine: function(facet, value) {
var refinement = facet + ':' + value;
this.refinements = this.refinements || {};
this.refinements[refinement] = true;
},
/**
* Ensure a facet refinement does not exist
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
removeRefine: function(facet, value) {
var refinement = facet + ':' + value;
this.refinements = this.refinements || {};
this.refinements[refinement] = false;
},
/**
* Ensure a facet exclude exists
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
addExclude: function(facet, value) {
var refinement = facet + ':-' + value;
this.excludes = this.excludes || {};
this.excludes[refinement] = true;
},
/**
* Ensure a facet exclude does not exist
* @param {string} facet the facet to refine
* @param {string} value the associated value
*/
removeExclude: function(facet, value) {
var refinement = facet + ':-' + value;
this.excludes = this.excludes || {};
this.excludes[refinement] = false;
},
/**
* Toggle refinement state of an exclude
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {boolean} true if the facet has been found
*/
toggleExclude: function(facet, value) {
for (var i = 0; i < this.options.facets.length; ++i) {
if (this.options.facets[i] == facet) {
var refinement = facet + ':-' + value;
this.excludes[refinement] = !this.excludes[refinement];
this.page = 0;
this._search();
return true;
}
}
return false;
},
/**
* Toggle refinement state of a facet
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {boolean} true if the facet has been found
*/
toggleRefine: function(facet, value) {
for (var i = 0; i < this.options.facets.length; ++i) {
if (this.options.facets[i] == facet) {
var refinement = facet + ':' + value;
this.refinements[refinement] = !this.refinements[refinement];
this.page = 0;
this._search();
return true;
}
}
this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {};
for (var j = 0; j < this.options.disjunctiveFacets.length; ++j) {
if (this.options.disjunctiveFacets[j] == facet) {
this.disjunctiveRefinements[facet][value] = !this.disjunctiveRefinements[facet][value];
this.page = 0;
this._search();
return true;
}
}
return false;
},
/**
* Check the refinement state of a facet
* @param {string} facet the facet
* @param {string} value the associated value
* @return {boolean} true if refined
*/
isRefined: function(facet, value) {
var refinement = facet + ':' + value;
if (this.refinements[refinement]) {
return true;
}
if (this.disjunctiveRefinements[facet] && this.disjunctiveRefinements[facet][value]) {
return true;
}
return false;
},
/**
* Check the exclude state of a facet
* @param {string} facet the facet
* @param {string} value the associated value
* @return {boolean} true if refined
*/
isExcluded: function(facet, value) {
var refinement = facet + ':-' + value;
if (this.excludes[refinement]) {
return true;
}
return false;
},
/**
* Go to next page
*/
nextPage: function() {
this._gotoPage(this.page + 1);
},
/**
* Go to previous page
*/
previousPage: function() {
if (this.page > 0) {
this._gotoPage(this.page - 1);
}
},
/**
* Goto a page
* @param {integer} page The page number
*/
gotoPage: function(page) {
this._gotoPage(page);
},
/**
* Configure the page but do not trigger a reload
* @param {integer} page The page number
*/
setPage: function(page) {
this.page = page;
},
/**
* Configure the underlying index name
* @param {string} name the index name
*/
setIndex: function(name) {
this.index = name;
},
/**
* Get the underlying configured index name
*/
getIndex: function() {
return this.index;
},
/**
* Clear the extra queries added to the underlying batch of queries
*/
clearExtraQueries: function() {
this.extraQueries = [];
},
/**
* Add an extra query to the underlying batch of queries. Once you add queries
* to the batch, the 2nd parameter of the searchCallback will be an object with a `results`
* attribute listing all search results.
*/
addExtraQuery: function(index, query, params) {
this.extraQueries.push({ index: index, query: query, params: (params || {}) });
},
///////////// PRIVATE
/**
* Goto a page
* @param {integer} page The page number
*/
_gotoPage: function(page) {
this.page = page;
this._search();
},
/**
* Perform the underlying queries
*/
_search: function() {
this.client.startQueriesBatch();
this.client.addQueryInBatch(this.index, this.q, this._getHitsSearchParams());
var disjunctiveFacets = [];
var unusedDisjunctiveFacets = {};
var i = 0;
for (i = 0; i < this.options.disjunctiveFacets.length; ++i) {
var facet = this.options.disjunctiveFacets[i];
if (this._hasDisjunctiveRefinements(facet)) {
disjunctiveFacets.push(facet);
} else {
unusedDisjunctiveFacets[facet] = true;
}
}
for (i = 0; i < disjunctiveFacets.length; ++i) {
this.client.addQueryInBatch(this.index, this.q, this._getDisjunctiveFacetSearchParams(disjunctiveFacets[i]));
}
for (i = 0; i < this.extraQueries.length; ++i) {
this.client.addQueryInBatch(this.extraQueries[i].index, this.extraQueries[i].query, this.extraQueries[i].params);
}
var self = this;
this.client.sendQueriesBatch(function(success, content) {
if (!success) {
self.searchCallback(false, content);
return;
}
var aggregatedAnswer = content.results[0];
aggregatedAnswer.disjunctiveFacets = aggregatedAnswer.disjunctiveFacets || {};
aggregatedAnswer.facets_stats = aggregatedAnswer.facets_stats || {};
// create disjunctive facets from facets (disjunctive facets without refinements)
for (var facet in unusedDisjunctiveFacets) {
if (aggregatedAnswer.facets[facet] && !aggregatedAnswer.disjunctiveFacets[facet]) {
aggregatedAnswer.disjunctiveFacets[facet] = aggregatedAnswer.facets[facet];
try {
delete aggregatedAnswer.facets[facet];
} catch (e) {
aggregatedAnswer.facets[facet] = undefined; // IE compat
}
}
}
// aggregate the disjunctive facets
for (i = 0; i < disjunctiveFacets.length; ++i) {
for (var dfacet in content.results[i + 1].facets) {
aggregatedAnswer.disjunctiveFacets[dfacet] = content.results[i + 1].facets[dfacet];
if (self.disjunctiveRefinements[dfacet]) {
for (var value in self.disjunctiveRefinements[dfacet]) {
// add the disjunctive reginements if it is no more retrieved
if (!aggregatedAnswer.disjunctiveFacets[dfacet][value] && self.disjunctiveRefinements[dfacet][value]) {
aggregatedAnswer.disjunctiveFacets[dfacet][value] = 0;
}
}
}
}
// aggregate the disjunctive facets stats
for (var stats in content.results[i + 1].facets_stats) {
aggregatedAnswer.facets_stats[stats] = content.results[i + 1].facets_stats[stats];
}
}
// Backward compatibility
aggregatedAnswer.facetStats = aggregatedAnswer.facets_stats;
// add the excludes
for (var exclude in self.excludes) {
if (self.excludes[exclude]) {
var e = exclude.indexOf(':-');
var facet = exclude.slice(0, e);
var value = exclude.slice(e + 2);
aggregatedAnswer.facets[facet] = aggregatedAnswer.facets[facet] || {};
if (!aggregatedAnswer.facets[facet][value]) {
aggregatedAnswer.facets[facet][value] = 0;
}
}
}
// call the actual callback
if (self.extraQueries.length === 0) {
self.searchCallback(true, aggregatedAnswer);
} else {
// append the extra queries
var c = { results: [ aggregatedAnswer ] };
for (i = 0; i < self.extraQueries.length; ++i) {
c.results.push(content.results[1 + disjunctiveFacets.length + i]);
}
self.searchCallback(true, c);
}
});
},
/**
* Build search parameters used to fetch hits
* @return {hash}
*/
_getHitsSearchParams: function() {
var facets = [];
var i = 0;
for (i = 0; i < this.options.facets.length; ++i) {
facets.push(this.options.facets[i]);
}
for (i = 0; i < this.options.disjunctiveFacets.length; ++i) {
var facet = this.options.disjunctiveFacets[i];
if (!this._hasDisjunctiveRefinements(facet)) {
facets.push(facet);
}
}
return extend({}, {
hitsPerPage: this.options.hitsPerPage,
page: this.page,
facets: facets,
facetFilters: this._getFacetFilters()
}, this.searchParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @param {string} facet the associated facet name
* @return {hash}
*/
_getDisjunctiveFacetSearchParams: function(facet) {
return extend({}, this.searchParams, {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
facets: facet,
facetFilters: this._getFacetFilters(facet),
analytics: false
});
},
/**
* Test if there are some disjunctive refinements on the facet
*/
_hasDisjunctiveRefinements: function(facet) {
for (var value in this.disjunctiveRefinements[facet]) {
if (this.disjunctiveRefinements[facet][value]) {
return true;
}
}
return false;
},
/**
* Build facetFilters parameter based on current refinements
* @param {string} facet if set, the current disjunctive facet
* @return {hash}
*/
_getFacetFilters: function(facet) {
var facetFilters = [];
if (this.options.defaultFacetFilters) {
for (var i = 0; i < this.options.defaultFacetFilters.length; ++i) {
facetFilters.push(this.options.defaultFacetFilters[i]);
}
}
for (var refinement in this.refinements) {
if (this.refinements[refinement]) {
facetFilters.push(refinement);
}
}
for (var refinement in this.excludes) {
if (this.excludes[refinement]) {
facetFilters.push(refinement);
}
}
for (var disjunctiveRefinement in this.disjunctiveRefinements) {
if (disjunctiveRefinement != facet) {
var refinements = [];
for (var value in this.disjunctiveRefinements[disjunctiveRefinement]) {
if (this.disjunctiveRefinements[disjunctiveRefinement][value]) {
refinements.push(disjunctiveRefinement + ':' + value);
}
}
if (refinements.length > 0) {
facetFilters.push(refinements);
}
}
}
return facetFilters;
}
};
})();
| {
"content_hash": "296205d36f85b83b5edc64a7d781b461",
"timestamp": "",
"source": "github",
"line_count": 486,
"max_line_length": 150,
"avg_line_length": 32.62139917695473,
"alnum_prop": 0.5879273369496657,
"repo_name": "thomaspark/glyphsearch",
"id": "5316224da92289e4d9c5ee421ce4c75aae3f396f",
"size": "16992",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "bower_components/algoliasearch/src/algoliasearch.helper.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8257"
},
{
"name": "HTML",
"bytes": "6812"
},
{
"name": "Handlebars",
"bytes": "1832"
},
{
"name": "JavaScript",
"bytes": "10140"
}
],
"symlink_target": ""
} |
setTimeout(function () {
// Authy form helpers clobber bootstrap styles, need to add them back
$('.countries-input').addClass('form-control');
},200); | {
"content_hash": "f066fd034ff5f906bac4a2aae37f1849",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 73,
"avg_line_length": 40.5,
"alnum_prop": 0.6728395061728395,
"repo_name": "TwilioDevEd/authy2fa-csharp",
"id": "4f17558ff733e4c6bb1c099086d99d727b115349",
"size": "164",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Authy2FA/Scripts/fixform.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "100"
},
{
"name": "C#",
"bytes": "105654"
},
{
"name": "CSS",
"bytes": "537"
},
{
"name": "JavaScript",
"bytes": "11659"
}
],
"symlink_target": ""
} |
package org.mmtk.plan.poisoned;
import org.mmtk.plan.marksweep.MSCollector;
import org.vmmagic.pragma.*;
import org.vmmagic.unboxed.Address;
import org.vmmagic.unboxed.ObjectReference;
/**
* This class implements a poisoned collector, that is essentially a test
* case for read and write barriers in the VM.
*/
@Uninterruptible
public class PoisonedCollector extends MSCollector {
/****************************************************************************
*
* Collector read/write barriers.
*/
/**
* Store an object reference
*
* @param slot The location of the reference
* @param value The value to store
*/
@Inline
public void storeObjectReference(Address slot, ObjectReference value) {
slot.store(Poisoned.poison(value));
}
/**
* Load an object reference
*
* @param slot The location of the reference
* @return the object reference loaded from slot
*/
@Inline
public ObjectReference loadObjectReference(Address slot) {
return Poisoned.depoison(slot.loadWord());
}
}
| {
"content_hash": "71abb523630141726c5e39fc5024c0d8",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 79,
"avg_line_length": 24.904761904761905,
"alnum_prop": 0.6625239005736138,
"repo_name": "ut-osa/laminar",
"id": "abf8002298e495b031a482bbe16f8fd182ea8c3c",
"size": "1479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jikesrvm-3.0.0/MMTk/src/org/mmtk/plan/poisoned/PoisonedCollector.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "4526"
},
{
"name": "Assembly",
"bytes": "7753785"
},
{
"name": "Awk",
"bytes": "5239"
},
{
"name": "Bison",
"bytes": "75151"
},
{
"name": "C",
"bytes": "209779557"
},
{
"name": "C++",
"bytes": "5954668"
},
{
"name": "CSS",
"bytes": "11885"
},
{
"name": "Java",
"bytes": "12132154"
},
{
"name": "Makefile",
"bytes": "731243"
},
{
"name": "Objective-C",
"bytes": "564040"
},
{
"name": "Perl",
"bytes": "196100"
},
{
"name": "Python",
"bytes": "11786"
},
{
"name": "Ruby",
"bytes": "3219"
},
{
"name": "Scala",
"bytes": "12158"
},
{
"name": "Scilab",
"bytes": "22980"
},
{
"name": "Shell",
"bytes": "205177"
},
{
"name": "TeX",
"bytes": "62636"
},
{
"name": "UnrealScript",
"bytes": "20822"
},
{
"name": "XSLT",
"bytes": "6544"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.mediaconnect.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediaconnect-2018-11-14/StopFlow" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StopFlowResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/** The ARN of the flow that you stopped. */
private String flowArn;
/** The status of the flow when the StopFlow process begins. */
private String status;
/**
* The ARN of the flow that you stopped.
*
* @param flowArn
* The ARN of the flow that you stopped.
*/
public void setFlowArn(String flowArn) {
this.flowArn = flowArn;
}
/**
* The ARN of the flow that you stopped.
*
* @return The ARN of the flow that you stopped.
*/
public String getFlowArn() {
return this.flowArn;
}
/**
* The ARN of the flow that you stopped.
*
* @param flowArn
* The ARN of the flow that you stopped.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StopFlowResult withFlowArn(String flowArn) {
setFlowArn(flowArn);
return this;
}
/**
* The status of the flow when the StopFlow process begins.
*
* @param status
* The status of the flow when the StopFlow process begins.
* @see Status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* The status of the flow when the StopFlow process begins.
*
* @return The status of the flow when the StopFlow process begins.
* @see Status
*/
public String getStatus() {
return this.status;
}
/**
* The status of the flow when the StopFlow process begins.
*
* @param status
* The status of the flow when the StopFlow process begins.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Status
*/
public StopFlowResult withStatus(String status) {
setStatus(status);
return this;
}
/**
* The status of the flow when the StopFlow process begins.
*
* @param status
* The status of the flow when the StopFlow process begins.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Status
*/
public StopFlowResult withStatus(Status status) {
this.status = status.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getFlowArn() != null)
sb.append("FlowArn: ").append(getFlowArn()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof StopFlowResult == false)
return false;
StopFlowResult other = (StopFlowResult) obj;
if (other.getFlowArn() == null ^ this.getFlowArn() == null)
return false;
if (other.getFlowArn() != null && other.getFlowArn().equals(this.getFlowArn()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFlowArn() == null) ? 0 : getFlowArn().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public StopFlowResult clone() {
try {
return (StopFlowResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| {
"content_hash": "f90e4211b8b3bc6d9580e095d4c7745c",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 141,
"avg_line_length": 29.21212121212121,
"alnum_prop": 0.5993775933609958,
"repo_name": "aws/aws-sdk-java",
"id": "d93e3bdcf4c8da778c4adc47fd1ee5b049eb669d",
"size": "5400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-mediaconnect/src/main/java/com/amazonaws/services/mediaconnect/model/StopFlowResult.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from SDAWithVectorField import Obstacle
from SDAWithVectorField import Constants
class StationaryObstacle(Obstacle):
"""
Wrapper class for Stationary obstacles
"""
def __init__(self, point, radius, height):
"""
:param point: The point for the stationary obstacle
:type point: Numpy Array
:param radius: The radius of the obstacle
:type radius: Float
:param height: The height of the obstacle
:type height: Float
"""
super(StationaryObstacle, self).__init__(point)
self.radius = radius
self.height = height
self.type = "StationaryObstacle"
def get_radius(self):
"""
Return the radius of the obstacle plus that of the safety radius
"""
return self.radius
def get_height(self):
"""
The height of the obstacle
"""
return self.height
def get_type(self):
return self.__class__.__name__ | {
"content_hash": "c0a7be051fccd825de6752963963029f",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 72,
"avg_line_length": 25.842105263157894,
"alnum_prop": 0.59979633401222,
"repo_name": "FlintHill/SUAS-Competition",
"id": "086baf076da8f74e366f7e3055f804a0b3043430",
"size": "982",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SDAPackageWithVectorField/SDAWithVectorField/stationary_obstacle.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "164260"
},
{
"name": "HTML",
"bytes": "46489"
},
{
"name": "JavaScript",
"bytes": "105325"
},
{
"name": "PHP",
"bytes": "2701"
},
{
"name": "Python",
"bytes": "538468"
},
{
"name": "Shell",
"bytes": "1913"
}
],
"symlink_target": ""
} |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_rebel_specforce_guerrilla_human_female_01.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_base_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | {
"content_hash": "88f9c868cf6232f412ea82fd25b0984b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 95,
"avg_line_length": 25.46153846153846,
"alnum_prop": 0.7099697885196374,
"repo_name": "anhstudios/swganh",
"id": "c699bf91c80d44045cdd976424c0ddd611ac3b12",
"size": "476",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "data/scripts/templates/object/mobile/shared_dressed_rebel_specforce_guerrilla_human_female_01.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11887"
},
{
"name": "C",
"bytes": "7699"
},
{
"name": "C++",
"bytes": "2357839"
},
{
"name": "CMake",
"bytes": "41264"
},
{
"name": "PLSQL",
"bytes": "42065"
},
{
"name": "Python",
"bytes": "7503510"
},
{
"name": "SQLPL",
"bytes": "42770"
}
],
"symlink_target": ""
} |
<?php
$file = __DIR__.'/../vendor/autoload.php';
if (!file_exists($file)) {
throw new RuntimeException('Install dependencies to run test suite. "php composer.phar install --dev"');
}
$loader = require($file);
use \Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Component\ClassLoader\UniversalClassLoader;
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
AnnotationRegistry::registerAutoloadNamespace('Test', __DIR__.'/Fixtures/');
/**
* AnnotationRegistry need some help finding annotation class.
*/
$loader->addClassMap(array(
'Tpg\ExtjsBundle\Annotation\Model'=>__DIR__.'/../Annotation/Model.php',
'Tpg\ExtjsBundle\Annotation\Direct'=>__DIR__.'/../Annotation/Direct.php',
'Tpg\ExtjsBundle\Annotation\ModelProxy'=>__DIR__.'/../Annotation/ModelProxy.php',
));
$loader = new UniversalClassLoader();
$loader->registerNamespace('Test', __DIR__.'/Fixtures/');
$loader->register(); | {
"content_hash": "e4f30e08eedbba265be6ccf70b70b227",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 108,
"avg_line_length": 33.214285714285715,
"alnum_prop": 0.7150537634408602,
"repo_name": "SamEngenner/extjs-bundle",
"id": "f3b89714545b62bd3224504381b68c2d63c1f517",
"size": "930",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Tests/bootstrap.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "4914"
},
{
"name": "JavaScript",
"bytes": "3431007"
},
{
"name": "PHP",
"bytes": "151529"
}
],
"symlink_target": ""
} |
package thumbtack.inMemoryDatabase;
public class NoTransactionException extends Throwable
{
}
| {
"content_hash": "2edd9718fe07706b25e60f421759fe32",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 53,
"avg_line_length": 19,
"alnum_prop": 0.8526315789473684,
"repo_name": "gauravkm/InMemoryDatabase",
"id": "2a0da2ef15b943451e9420d4083bedc41ed08e4d",
"size": "95",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "thumbtack/inMemoryDatabase/NoTransactionException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "23441"
}
],
"symlink_target": ""
} |
package com.ztemt.test.mtbf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public abstract class Cer_MTBF_Telephony extends Cer_MTBF {
protected String getOperatorNumber() {
String operator = null;
String phoneNumber = null;
try {
Process p = Runtime.getRuntime().exec("getprop gsm.operator.numeric");
InputStreamReader in = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(in);
operator = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if ("46000".equals(operator) || "46002".equals(operator)
|| "46007".equals(operator)) {
phoneNumber = "10086";
} else if ("46001".equals(operator)) {
phoneNumber = "10010";
} else if ("46003".equals(operator)) {
phoneNumber = "10000";
} else {
phoneNumber = "";
}
return phoneNumber;
}
}
| {
"content_hash": "543938cb5f06005ea7a36e2314319051",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 82,
"avg_line_length": 30.942857142857143,
"alnum_prop": 0.5604801477377654,
"repo_name": "doctang/TestPlatform",
"id": "78ae7676bc399ed16109bf1883bfce648cb8ce54",
"size": "1083",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MTBF/src/com/ztemt/test/mtbf/Cer_MTBF_Telephony.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5624"
},
{
"name": "Java",
"bytes": "494787"
},
{
"name": "Makefile",
"bytes": "671"
},
{
"name": "Python",
"bytes": "1907"
},
{
"name": "Shell",
"bytes": "17099"
}
],
"symlink_target": ""
} |
package ru.justnero.study.dsmnm.lab02;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class StatsController extends BasicController {
private final ObservableList<TestLog> leftList = FXCollections.observableArrayList();
private final ObservableList<TestLog> rightList = FXCollections.observableArrayList();
@FXML
private TableView<TestLog> leftTable;
@FXML
private TableView<TestLog> rightTable;
@FXML
private LineChart<String, Long> chart;
private List<TData> list;
@SuppressWarnings("unused")
@FXML
public void initialize() {
initTable(leftTable, leftList);
initTable(rightTable, rightList);
}
void load(String fileName) {
list = read(fileName, 10000);
fillData();
}
private List<TData> read(String fileName, int maxCount) {
List<TData> list = new ArrayList<>(maxCount);
try (Scanner inp = new Scanner(Paths.get(fileName))) {
inp.nextLine();
for (int i = 0; i < maxCount; i++) {
list.add(TData.read(inp));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
private void fillData() {
int tests[] = new int[]{50, 500, 1600, 6000, 9500};
ITree leftTree = new AVLTree();
ITree rightTree = new BinTree();
XYChart.Series<String, Long> leftAddSeries = new XYChart.Series<>();
leftAddSeries.setName("AVL Добавление");
XYChart.Series<String, Long> leftFindSeries = new XYChart.Series<>();
leftFindSeries.setName("AVL Поиск");
XYChart.Series<String, Long> leftDelSeries = new XYChart.Series<>();
leftDelSeries.setName("AVL Удаление");
XYChart.Series<String, Long> rightAddSeries = new XYChart.Series<>();
rightAddSeries.setName("Bin Добавление");
XYChart.Series<String, Long> rightFindSeries = new XYChart.Series<>();
rightFindSeries.setName("Bin Поиск");
XYChart.Series<String, Long> rightDelSeries = new XYChart.Series<>();
rightDelSeries.setName("Bin Удаление");
leftList.clear();
rightList.clear();
for (int test : tests) {
fillTest(leftList, test, leftTree, leftAddSeries, leftFindSeries, leftDelSeries);
fillTest(rightList, test, rightTree, rightAddSeries, rightFindSeries, rightDelSeries);
}
chart.getData().clear();
chart.getData().add(leftAddSeries);
chart.getData().add(leftFindSeries);
chart.getData().add(leftDelSeries);
chart.getData().add(rightAddSeries);
chart.getData().add(rightFindSeries);
chart.getData().add(rightDelSeries);
}
private void fillTest(ObservableList<TestLog> list, int size, ITree tree,
XYChart.Series<String, Long> addSeries,
XYChart.Series<String, Long> findSeries,
XYChart.Series<String, Long> delSeries) {
tree.clear();
String category = String.valueOf(size);
int ids[] = generateRandomIds(5, size);
long times[] = new long[5];
TData data;
long time;
long average = 0;
for (int i = 0; i < size; i++) {
data = this.list.get(i);
time = System.nanoTime();
tree.add(data);
time = System.nanoTime() - time;
for (int j = 0; j < 5; j++) {
if (ids[j] == i) {
times[j] = time;
average += time;
}
}
}
average /= 5;
list.add(new TestLog(size, "Добавление", times[0], times[1], times[2], times[3], times[4], average));
addSeries.getData().add(new XYChart.Data<>(category, average));
average = 0;
for (int i = 0; i < 5; i++) {
data = this.list.get(ids[i]);
time = System.nanoTime();
tree.find(data);
time = System.nanoTime() - time;
times[i] = time;
average += time;
}
average /= 5;
list.add(new TestLog(size, "Поиск", times[0], times[1], times[2], times[3], times[4], average));
findSeries.getData().add(new XYChart.Data<>(category, average));
average = 0;
for (int i = 0; i < 5; i++) {
data = this.list.get(ids[i]);
time = System.nanoTime();
tree.remove(data);
time = System.nanoTime() - time;
times[i] = time;
average += time;
}
average /= 5;
list.add(new TestLog(size, "Удаление", times[0], times[1], times[2], times[3], times[4], average));
delSeries.getData().add(new XYChart.Data<>(category, average));
}
private int[] generateRandomIds(int count, int max) {
int result[] = new int[count];
Random rnd = new Random();
for (int i = 0; i < count; i++) {
result[i] = rnd.nextInt(max);
}
return result;
}
private void initTable(TableView<TestLog> table, ObservableList<TestLog> list) {
TableColumn<TestLog, Integer> sizeCol = new TableColumn<>("Размер");
sizeCol.prefWidthProperty().bind(table.widthProperty().divide(8));
sizeCol.setCellValueFactory(new PropertyValueFactory<>("size"));
table.getColumns().add(sizeCol);
TableColumn<TestLog, String> opCol = new TableColumn<>("Операция");
opCol.prefWidthProperty().bind(table.widthProperty().divide(8));
opCol.setCellValueFactory(new PropertyValueFactory<>("operation"));
table.getColumns().add(opCol);
TableColumn<TestLog, Long> timeCol;
for (int i = 1; i <= 5; i++) {
String is = String.valueOf(i);
timeCol = new TableColumn<>(is);
timeCol.prefWidthProperty().bind(table.widthProperty().divide(8));
timeCol.setCellValueFactory(new PropertyValueFactory<>("time" + is));
timeCol.setSortable(false);
table.getColumns().add(timeCol);
}
timeCol = new TableColumn<>("Среднее");
timeCol.prefWidthProperty().bind(table.widthProperty().divide(8));
timeCol.setCellValueFactory(new PropertyValueFactory<>("timeA"));
timeCol.setSortable(false);
table.getColumns().add(timeCol);
table.setItems(list);
}
}
| {
"content_hash": "1916fece58fb6d9f5d7d94d6c9de8b69",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 109,
"avg_line_length": 36.89673913043478,
"alnum_prop": 0.5949329798202976,
"repo_name": "justnero-ru/university",
"id": "90f03ce8c913d34e422db702c4418e01048b86fa",
"size": "6879",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "semestr.05/ТПО/Lab.11/code/src/ru/justnero/study/dsmnm/lab02/StatsController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "6105"
},
{
"name": "Batchfile",
"bytes": "2038"
},
{
"name": "BlitzBasic",
"bytes": "77"
},
{
"name": "C",
"bytes": "3412"
},
{
"name": "C#",
"bytes": "35567"
},
{
"name": "C++",
"bytes": "217532"
},
{
"name": "CMake",
"bytes": "2323"
},
{
"name": "CSS",
"bytes": "132"
},
{
"name": "Common Lisp",
"bytes": "13772"
},
{
"name": "Go",
"bytes": "23924"
},
{
"name": "Java",
"bytes": "523960"
},
{
"name": "JavaScript",
"bytes": "740"
},
{
"name": "Kotlin",
"bytes": "19491"
},
{
"name": "Makefile",
"bytes": "13801"
},
{
"name": "Mathematica",
"bytes": "831"
},
{
"name": "Matlab",
"bytes": "25167"
},
{
"name": "NewLisp",
"bytes": "471"
},
{
"name": "PHP",
"bytes": "6342"
},
{
"name": "Pascal",
"bytes": "28800"
},
{
"name": "Prolog",
"bytes": "29473"
},
{
"name": "SQLPL",
"bytes": "3249"
},
{
"name": "Shell",
"bytes": "5749"
}
],
"symlink_target": ""
} |
from tempest_lib import exceptions as lib_exc
from tempest.api.network import base
from tempest.common.utils import data_utils
from tempest import test
class NetworksNegativeTestJSON(base.BaseNetworkTest):
@test.attr(type=['negative'])
@test.idempotent_id('9293e937-824d-42d2-8d5b-e985ea67002a')
def test_show_non_existent_network(self):
non_exist_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound, self.networks_client.show_network,
non_exist_id)
@test.attr(type=['negative'])
@test.idempotent_id('d746b40c-5e09-4043-99f7-cba1be8b70df')
def test_show_non_existent_subnet(self):
non_exist_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound, self.client.show_subnet,
non_exist_id)
@test.attr(type=['negative'])
@test.idempotent_id('a954861d-cbfd-44e8-b0a9-7fab111f235d')
def test_show_non_existent_port(self):
non_exist_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound, self.client.show_port,
non_exist_id)
@test.attr(type=['negative'])
@test.idempotent_id('98bfe4e3-574e-4012-8b17-b2647063de87')
def test_update_non_existent_network(self):
non_exist_id = data_utils.rand_uuid()
self.assertRaises(
lib_exc.NotFound, self.networks_client.update_network,
non_exist_id, name="new_name")
@test.attr(type=['negative'])
@test.idempotent_id('03795047-4a94-4120-a0a1-bd376e36fd4e')
def test_delete_non_existent_network(self):
non_exist_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound,
self.networks_client.delete_network,
non_exist_id)
@test.attr(type=['negative'])
@test.idempotent_id('1cc47884-ac52-4415-a31c-e7ce5474a868')
def test_update_non_existent_subnet(self):
non_exist_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound, self.client.update_subnet,
non_exist_id, name='new_name')
@test.attr(type=['negative'])
@test.idempotent_id('a176c859-99fb-42ec-a208-8a85b552a239')
def test_delete_non_existent_subnet(self):
non_exist_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound,
self.client.delete_subnet, non_exist_id)
@test.attr(type=['negative'])
@test.idempotent_id('13d3b106-47e6-4b9b-8d53-dae947f092fe')
def test_create_port_on_non_existent_network(self):
non_exist_net_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound,
self.client.create_port, network_id=non_exist_net_id)
@test.attr(type=['negative'])
@test.idempotent_id('cf8eef21-4351-4f53-adcd-cc5cb1e76b92')
def test_update_non_existent_port(self):
non_exist_port_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound, self.client.update_port,
non_exist_port_id, name='new_name')
@test.attr(type=['negative'])
@test.idempotent_id('49ec2bbd-ac2e-46fd-8054-798e679ff894')
def test_delete_non_existent_port(self):
non_exist_port_id = data_utils.rand_uuid()
self.assertRaises(lib_exc.NotFound,
self.client.delete_port, non_exist_port_id)
| {
"content_hash": "abae23ca80758ab2cf640d486d5b5ebc",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 79,
"avg_line_length": 42.125,
"alnum_prop": 0.6409495548961425,
"repo_name": "xbezdick/tempest",
"id": "4d1971f9f2f262a5df9b61a79a11f446978f905b",
"size": "4052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tempest/api/network/test_networks_negative.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "2880166"
},
{
"name": "Shell",
"bytes": "8578"
}
],
"symlink_target": ""
} |
package com.github.paginationspring.example.jsf1.entity;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "PG_NBA_PLAYER")
public class PgNbaPlayer {
private int nbaPlayerId;
private String playerAlias;
private String firstName;
private String lastName;
private String position;
private String firstSeason;
private String lastSeason;
private BigDecimal heightFeet;
private BigDecimal heightInches;
private BigDecimal weight;
private String college;
@Id
@Column(name = "NBA_PLAYER_ID", unique = true, nullable = false, precision = 9, scale = 0)
public int getNbaPlayerId() {
return nbaPlayerId;
}
public void setNbaPlayerId(int nbaPlayerId) {
this.nbaPlayerId = nbaPlayerId;
}
@Column(name = "PLAYER_ALIAS", length = 50)
public String getPlayerAlias() {
return playerAlias;
}
public void setPlayerAlias(String playerAlias) {
this.playerAlias = playerAlias;
}
@Column(name = "FIRST_NAME", length = 50)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "LAST_NAME", length = 50)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "POSITION", length = 1)
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Column(name = "FIRST_SEASON", length = 4)
public String getFirstSeason() {
return firstSeason;
}
public void setFirstSeason(String firstSeason) {
this.firstSeason = firstSeason;
}
@Column(name = "LAST_SEASON", length = 4)
public String getLastSeason() {
return lastSeason;
}
public void setLastSeason(String lastSeason) {
this.lastSeason = lastSeason;
}
@Column(name = "HEIGHT_FEET", precision = 9, scale = 2)
public BigDecimal getHeightFeet() {
return heightFeet;
}
public void setHeightFeet(BigDecimal heightFeet) {
this.heightFeet = heightFeet;
}
@Column(name = "HEIGHT_INCHES", precision = 9, scale = 2)
public BigDecimal getHeightInches() {
return heightInches;
}
public void setHeightInches(BigDecimal heightInches) {
this.heightInches = heightInches;
}
@Column(name = "WEIGHT", precision = 9, scale = 2)
public BigDecimal getWeight() {
return weight;
}
public void setWeight(BigDecimal weight) {
this.weight = weight;
}
@Column(name = "COLLEGE", length = 100)
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
}
| {
"content_hash": "39fa9c6b2f9d4932ecaaed778e89de8b",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 94,
"avg_line_length": 26.310679611650485,
"alnum_prop": 0.7228782287822878,
"repo_name": "paginationspring/pagination-example-jsf1",
"id": "f5e32d830c0083f9096ec6e4798377c82a143f6e",
"size": "2710",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/paginationspring/example/jsf1/entity/PgNbaPlayer.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6798"
},
{
"name": "Java",
"bytes": "27692"
},
{
"name": "Shell",
"bytes": "813"
}
],
"symlink_target": ""
} |
<a href='https://github.com/angular/angular.js/edit/v1.5.x/src/ng/directive/ngEventDirs.js?message=docs(ngKeydown)%3A%20describe%20your%20change...#L246' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.5.2/src/ng/directive/ngEventDirs.js#L246' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">ngKeydown</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- directive in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>Specify custom behavior on keydown event.</p>
</div>
<div>
<h2>Directive Info</h2>
<ul>
<li>This directive executes at priority level 0.</li>
</ul>
<h2 id="usage">Usage</h2>
<div class="usage">
<ul>
<li>as attribute:
<pre><code><ANY ng-keydown="expression"> ... </ANY></code></pre>
</li>
</div>
<section class="api-section">
<h3>Arguments</h3>
<table class="variables-matrix input-arguments">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
ngKeydown
</td>
<td>
<a href="" class="label type-hint type-hint-expression">expression</a>
</td>
<td>
<p><a href="guide/expression">Expression</a> to evaluate upon
keydown. (Event object is available as <code>$event</code> and can be interrogated for keyCode, altKey, etc.)</p>
</td>
</tr>
</tbody>
</table>
</section>
<h2 id="example">Example</h2><p>
<div>
<plnkr-opener example-path="examples/example-example77"></plnkr-opener>
<div class="runnable-example"
path="examples/example-example77">
<div class="runnable-example-file"
name="index.html"
language="html"
type="html">
<pre><code><input ng-keydown="count = count + 1" ng-init="count=0"> key down count: {{count}}</code></pre>
</div>
<iframe class="runnable-example-frame" src="examples/example-example77/index.html" name="example-example77"></iframe>
</div>
</div>
</p>
</div>
| {
"content_hash": "55a186e4d289cad0cf9efdc4e3d02492",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 257,
"avg_line_length": 21.146551724137932,
"alnum_prop": 0.6074194863432532,
"repo_name": "bensonmyrtil/movie_manager",
"id": "af6b8e1022a378eb2cb6c023569575823b9dc8de",
"size": "2453",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "movie/static/movie/js/angular/1.5.2/docs/partials/api/ng/directive/ngKeydown.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "303710"
},
{
"name": "HTML",
"bytes": "3172741"
},
{
"name": "JavaScript",
"bytes": "6635475"
},
{
"name": "Python",
"bytes": "11694"
}
],
"symlink_target": ""
} |
/*! translation-dictionary v0.1.1 | https://github.com/rottmann/translation-dictionary | Peter Rottmann <rottmann@inveris.de> | MIT */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define(factory);
else if(typeof exports === 'object')
exports["TranslationDictionary"] = factory();
else
root["TranslationDictionary"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(1)
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/*global WITHOUT_EVENTS*/
'use strict';
if (typeof WITHOUT_EVENTS === 'undefined' || ! WITHOUT_EVENTS)
var EventEmitter = __webpack_require__(2).EventEmitter3;
if (typeof WITHOUT_EVENTS === 'undefined' || ! WITHOUT_EVENTS)
var inherits = __webpack_require__(3);
var sprintf = __webpack_require__(4).sprintf;
var vsprintf = __webpack_require__(4).vsprintf;
/**
* Polyfill
*/
if ( ! Number.isInteger)
Number.isInteger = function(value) {
return typeof value === 'number' &&
isFinite(value) &&
value > -9007199254740992 &&
value < 9007199254740992 &&
Math.floor(value) === value;
};
if ( ! Array.isArray)
Array.isArray = function(args) {
return Object.prototype.toString.call(args) === '[object Array]';
};
/**
* Defaults
*/
var DEFAULT_LOCALE = 'en';
var DEFAULT_NPLURALS = 2;
var DEFAULT_PLURALIZER = 1;
/**
* TranslationDictionary
*
* @fires changeBaseLocale (locale) Emitted after baseLocale changed.
* @fires changeLocale (locale) Emitted after locale changed.
* @fires changeTranslation (locale) Emitted after translation of the current locale changed.
* @fires missingPluralTranslation (text, locale) Emitted when the plural text is not found in translation.
* @fires missingTranslation (text, locale) Emitted when the text is not found in translation.
* @fires registerPluralizer (locale, pluralizer) Emitted after a new pluralizer was registered.
* @fires registerTranslation (locale) Emitted after a new translation was registered.
*/
var TranslationDictionary = function() {
this.baseLocale = DEFAULT_LOCALE;
this.baseNPlurals = DEFAULT_NPLURALS;
this.cache = {}; // cache for current locale
this.dict = {};
this.locale = DEFAULT_LOCALE;
this.nPlurals = {};
this.pluralizers = {};
this._createDictionary(this.baseLocale);
};
if (typeof WITHOUT_EVENTS === 'undefined' || ! WITHOUT_EVENTS)
inherits(TranslationDictionary, EventEmitter);
/**
* Get the current locale (default: 'en')
*
* @return {string}
*/
TranslationDictionary.prototype.getLocale = function() {
return this.locale;
};
/**
* Set a pluralizer for a locale with number of plurals
*
* @param {string} locale The locale for which to register the pluralizer.
* @param {callback|int} pluralizer A callback(number) that returns the index of the plural in dict[text].
* @param {int} [nPlurals=2] Number of plurals the language has.
*/
TranslationDictionary.prototype.registerPluralizer = function(locale, pluralizer, nPlurals) {
this.pluralizers[locale] = pluralizer;
this.nPlurals[locale] = nPlurals || DEFAULT_NPLURALS;
this.cache = {};
this.emit('registerPluralizer', locale, pluralizer);
};
/**
* Merge translations to a locale
*
* @param {string} locale The locale for which to register the translation.
* @param {object} translations An Object with the base locale text as key and the translation as value.
* {
* 'wolve' : 'vlk',
* 'wolves': [ // nPlurals for Czech is 3
* 'vlci',
* 'vlků'
* ]
* }
*/
TranslationDictionary.prototype.registerTranslation = function(locale, translations) {
this._createDictionary(locale);
// extend / overwrite dict entries
for (var text in translations) /*jshint -W089 */
this.dict[locale][text] = translations[text];
this.emit('registerTranslation', locale);
// emit when translation of the current locale changed
if (locale === this.locale && locale !== this.baseLocale)
this.emit('changeTranslation', locale);
};
/**
* Set the applications base language
*
* @param {string} locale Applications base locale.
* @param {int} nPlurals Number of plurals the base locale has.
*/
TranslationDictionary.prototype.setBaseLocale = function(locale, nPlurals) {
this.baseLocale = locale;
this.baseNPlurals = nPlurals || DEFAULT_NPLURALS;
this._createDictionary(locale); // ensure that an empty dictionary for the locale exists
this.emit('changeBaseLocale', locale);
};
/**
* Set the current locale
*
* @param {string} locale The locale registered before with registerTranslation / application base locale.
*/
TranslationDictionary.prototype.setLocale = function(locale) {
if (locale === this.locale)
return;
if ( ! this.dict[locale])
throw new Error('[dict] setLocale is called for an unregistered translation');
this.locale = locale;
this.cache = {};
this.emit('changeLocale', locale);
};
/**
* Translate a singular text
*
* @param {string} arguments[0] The text to translate.
* @param {mixed} [arguments[n]] Optional parameters for sprintf to replace markers in the text.
* Depending on the markers a list of parameters, an array, or an object can be used.
* translate('a text');
* translate('a text %s %s', 'str1', 'str2');
* translate('a text %s %s', [ 'str1', 'str2' ]);
* translate('a text %(name)s', { name: 'John Doe' });
*
* @return {string} Translated text.
*/
TranslationDictionary.prototype.translate = function(/*arguments*/) {
return this._translate(arguments);
};
/**
* Alias for translate()
*/
TranslationDictionary.prototype.__ = function(/*arguments*/) {
return this._translate(arguments);
};
/**
* Translate a text as singular or plural, depending on the count
*
* @param {string} arguments[0] The singular text to translate.
* @param {string} arguments[1..(nPlurals-1)] The plural text to translate.
* @param {mixed} arguments[nPlurals..n] The count and parameters for sprintf to replace markers in the text.
* Depending on the markers a list of parameters, an array, or an object can be used.
* translatePlural('a text', 'some text', 47);
* translatePlural('a text %d %s', 'some text %d %s', 47, 'str1');
* translatePlural('a text %d %s', 'some text %d %s', [ 47, 'str1' ]);
* translatePlural('a text %(name)s', 'some text %(name)s', { count: 47, name: 'John Doe' });
*
* @return {string} Translated text.
*/
TranslationDictionary.prototype.translatePlural = function(/*arguments*/) {
return this._translate(arguments, true);
};
/**
* Alias for translatePlural()
*/
TranslationDictionary.prototype._p = function(/*arguments*/) {
return this._translate(arguments, true);
};
/**
* Translation function called from translate() and translatePlural()
*
* @param {mixed} args Arguments from the calling functions.
* @param {boolean} withPlural With plural detection.
* @return {string} Translated text.
*/
TranslationDictionary.prototype._translate = function(args, withPlural) {
// cache
var hash = JSON.stringify(arguments);
if (hash in this.cache)
return this.cache[hash];
var index = 0;
var params; // int / array / object
var bnp = this.baseNPlurals;
var number;
if (withPlural) {
if (args.length >= bnp) {
if (typeof args[bnp - 1] !== 'string')
throw new Error('[dict] parameter ' + bnp + ' for plural must be a string for \'' + args[0] + '\'');
params = (args.length > (bnp + 1)) ? Array.prototype.slice.call(args, bnp) : args[bnp];
if (Number.isInteger(params))
number = params;
else {
if (Array.isArray(params)) {
if ( ! params[0])
throw new Error('[dict] parameter array is empty for \'' + args[0] + '\'');
number = params[0];
}
else if (typeof params === 'object') {
if ( ! params.count)
throw new Error('[dict] numeric object.count is missing for \'' + args[0] + '\'');
number = params.count;
}
if ( ! Number.isInteger(number))
throw new Error('[dict] numeric value is missing for \'' + args[0] + '\'');
}
index = this._pluralize(this.baseLocale, number);
} else {
throw new Error('[dict] plural string and numeric value are missing for \'' + args[0] + '\'');
}
}
else {
params = (args.length > bnp) ? Array.prototype.slice.call(args, (bnp - 1)) : args[(bnp - 1)];
}
var text = args[index];
if (this.locale !== this.baseLocale) {
var dictText = this.dict[this.locale][text];
if (dictText)
if (typeof dictText === 'string') {
text = dictText;
} else {
var localeIndex = this._pluralize(this.locale, number);
if (dictText.length >= localeIndex)
text = dictText[localeIndex - 1];
else
this.emit('missingPluralTranslation', text, this.locale);
}
else
this.emit('missingTranslation', text, this.locale);
}
if (typeof params !== 'undefined')
if (Array.isArray(params))
text = vsprintf(text, params);
else
text = sprintf(text, params);
this.cache[hash] = text;
return text;
};
/**
* Create a dictionary if not exists for a locale
* Set default pluralizer and clear the cache.
*
* @param {string} locale The locale.
*/
TranslationDictionary.prototype._createDictionary = function(locale) {
if ( ! this.dict[locale])
this.dict[locale] = {};
if ( ! this.pluralizers[locale])
this.registerPluralizer(locale, DEFAULT_PLURALIZER);
this.cache = {};
};
/**
* Execute the pluralizer
*
* @param {string} locale The locale for which the pluralizer should be used.
* @param {int} number The number to check and get the plural index.
* @return {int} Index of the plural form in dict[text].
*/
TranslationDictionary.prototype._pluralize = function(locale, number) {
var pluralizer = this.pluralizers[locale];
if (typeof pluralizer === 'function')
return pluralizer.call(this, number);
else
return number !== pluralizer ? 1 : 0;
};
if (typeof WITHOUT_EVENTS === 'undefined' || ! WITHOUT_EVENTS)
TranslationDictionary.prototype.emmit = function() { };
module.exports = TranslationDictionary;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Representation of a single EventEmitter function.
*
* @param {Function} fn Event handler to be called.
* @param {Mixed} context Context for function execution.
* @param {Boolean} once Only emit once
* @api private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Minimal EventEmitter interface that is molded against the Node.js
* EventEmitter interface.
*
* @constructor
* @api public
*/
function EventEmitter() { /* Nothing to set */ }
/**
* Holds the assigned EventEmitters by name.
*
* @type {Object}
* @private
*/
EventEmitter.prototype._events = undefined;
/**
* Return a list of assigned event listeners.
*
* @param {String} event The events that should be listed.
* @returns {Array}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event) {
if (!this._events || !this._events[event]) return [];
if (this._events[event].fn) return [this._events[event].fn];
for (var i = 0, l = this._events[event].length, ee = new Array(l); i < l; i++) {
ee[i] = this._events[event][i].fn;
}
return ee;
};
/**
* Emit an event to all registered event listeners.
*
* @param {String} event The name of the event.
* @returns {Boolean} Indication if we've emitted an event.
* @api public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
if (!this._events || !this._events[event]) return false;
var listeners = this._events[event]
, len = arguments.length
, args
, i;
if ('function' === typeof listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Register a new EventListener for the given event.
*
* @param {String} event Name of the event.
* @param {Functon} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this);
if (!this._events) this._events = {};
if (!this._events[event]) this._events[event] = listener;
else {
if (!this._events[event].fn) this._events[event].push(listener);
else this._events[event] = [
this._events[event], listener
];
}
return this;
};
/**
* Add an EventListener that's only called once.
*
* @param {String} event Name of the event.
* @param {Function} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true);
if (!this._events) this._events = {};
if (!this._events[event]) this._events[event] = listener;
else {
if (!this._events[event].fn) this._events[event].push(listener);
else this._events[event] = [
this._events[event], listener
];
}
return this;
};
/**
* Remove event listeners.
*
* @param {String} event The event we want to remove.
* @param {Function} fn The listener that we need to find.
* @param {Boolean} once Only remove once listeners.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, once) {
if (!this._events || !this._events[event]) return this;
var listeners = this._events[event]
, events = [];
if (fn) {
if (listeners.fn && (listeners.fn !== fn || (once && !listeners.once))) {
events.push(listeners);
}
if (!listeners.fn) for (var i = 0, length = listeners.length; i < length; i++) {
if (listeners[i].fn !== fn || (once && !listeners[i].once)) {
events.push(listeners[i]);
}
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) {
this._events[event] = events.length === 1 ? events[0] : events;
} else {
delete this._events[event];
}
return this;
};
/**
* Remove all listeners or only the listeners for the specified event.
*
* @param {String} event The event want to remove all listeners for.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
if (!this._events) return this;
if (event) delete this._events[event];
else this._events = {};
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
return this;
};
//
// Expose the module.
//
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.EventEmitter2 = EventEmitter;
EventEmitter.EventEmitter3 = EventEmitter;
//
// Expose the module.
//
module.exports = EventEmitter;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
(function(window) {
var re = {
not_string: /[^s]/,
number: /[dief]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
sign: /^[\+\-]/
}
function sprintf() {
var key = arguments[0], cache = sprintf.cache
if (!(cache[key] && cache.hasOwnProperty(key))) {
cache[key] = sprintf.parse(key)
}
return sprintf.format.call(null, cache[key], arguments)
}
sprintf.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = ""
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i])
if (node_type === "string") {
output[output.length] = parse_tree[i]
}
else if (node_type === "array") {
match = parse_tree[i] // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor]
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k]))
}
arg = arg[match[2][k]]
}
}
else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]]
}
else { // positional argument (implicit)
arg = argv[cursor++]
}
if (get_type(arg) == "function") {
arg = arg()
}
if (re.not_string.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) {
throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg)))
}
if (re.number.test(match[8])) {
is_positive = arg >= 0
}
switch (match[8]) {
case "b":
arg = arg.toString(2)
break
case "c":
arg = String.fromCharCode(arg)
break
case "d":
case "i":
arg = parseInt(arg, 10)
break
case "e":
arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential()
break
case "f":
arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg)
break
case "o":
arg = arg.toString(8)
break
case "s":
arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg)
break
case "u":
arg = arg >>> 0
break
case "x":
arg = arg.toString(16)
break
case "X":
arg = arg.toString(16).toUpperCase()
break
}
if (re.number.test(match[8]) && (!is_positive || match[3])) {
sign = is_positive ? "+" : "-"
arg = arg.toString().replace(re.sign, "")
}
else {
sign = ""
}
pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " "
pad_length = match[6] - (sign + arg).length
pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : ""
output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg)
}
}
return output.join("")
}
sprintf.cache = {}
sprintf.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree[parse_tree.length] = match[0]
}
else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree[parse_tree.length] = "%"
}
else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1
var field_list = [], replacement_field = match[2], field_match = []
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list[field_list.length] = field_match[1]
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") {
if ((field_match = re.key_access.exec(replacement_field)) !== null) {
field_list[field_list.length] = field_match[1]
}
else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list[field_list.length] = field_match[1]
}
else {
throw new SyntaxError("[sprintf] failed to parse named argument key")
}
}
}
else {
throw new SyntaxError("[sprintf] failed to parse named argument key")
}
match[2] = field_list
}
else {
arg_names |= 2
}
if (arg_names === 3) {
throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported")
}
parse_tree[parse_tree.length] = match
}
else {
throw new SyntaxError("[sprintf] unexpected placeholder")
}
_fmt = _fmt.substring(match[0].length)
}
return parse_tree
}
var vsprintf = function(fmt, argv, _argv) {
_argv = (argv || []).slice(0)
_argv.splice(0, 0, fmt)
return sprintf.apply(null, _argv)
}
/**
* helpers
*/
function get_type(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase()
}
function str_repeat(input, multiplier) {
return Array(multiplier + 1).join(input)
}
/**
* export to either browser or node.js
*/
if (true) {
exports.sprintf = sprintf
exports.vsprintf = vsprintf
}
else {
window.sprintf = sprintf
window.vsprintf = vsprintf
if (typeof define === "function" && define.amd) {
define(function() {
return {
sprintf: sprintf,
vsprintf: vsprintf
}
})
}
}
})(typeof window === "undefined" ? this : window);
/***/ }
/******/ ])
});
| {
"content_hash": "fc9a06814d4a1a0c6552936d9450597f",
"timestamp": "",
"source": "github",
"line_count": 837,
"max_line_length": 166,
"avg_line_length": 33.101553166069294,
"alnum_prop": 0.5429509853461344,
"repo_name": "rottmann/translation-dictionary",
"id": "98cf7d2dee1204b2f0dfc82cb9c0cfc9e870e323",
"size": "27707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/translation-dictionary.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "48657"
}
],
"symlink_target": ""
} |
#import <Foundation/Foundation.h>
#import "MMEnumAttributeContainer.h"
typedef NS_ENUM(NSUInteger, MMPasswordResetMethod){
MMPasswordResetMethodNOTIFICATION = 0,
MMPasswordResetMethodOLDPASSWORD,
MMPasswordResetMethodOTP,
};
@interface MMPasswordResetMethodContainer : NSObject <MMEnumAttributeContainer>
@end
| {
"content_hash": "a0a6871ccb790f790876d8ca997de513",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 79,
"avg_line_length": 23.357142857142858,
"alnum_prop": 0.8134556574923547,
"repo_name": "tutsplus/iOS-MagnetMessage",
"id": "fb0b7fcc1be87dd25da0ec9054f6419752b78f84",
"size": "954",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Pods/MagnetMaxCore/MagnetMax/Core/MMPasswordResetMethod.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ruby",
"bytes": "185"
},
{
"name": "Swift",
"bytes": "17740"
}
],
"symlink_target": ""
} |
package org.apache.asterix.builders;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.asterix.dataflow.data.nontagged.serde.SerializerDeserializerUtil;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.AbstractCollectionType;
import org.apache.asterix.om.utils.NonTaggedFormatUtil;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.api.IValueReference;
import org.apache.hyracks.data.std.util.GrowableArray;
import org.apache.hyracks.storage.common.arraylist.IntArrayList;
public abstract class AbstractListBuilder implements IAsterixListBuilder {
protected final GrowableArray outputStorage;
protected final DataOutputStream outputStream;
protected final IntArrayList offsets;
protected int metadataInfoSize;
protected byte[] offsetArray;
protected int offsetPosition;
protected int headerSize;
protected ATypeTag itemTypeTag;
protected final ATypeTag listType;
protected boolean fixedSize = false;
protected int numberOfItems;
public AbstractListBuilder(ATypeTag listType) {
this.outputStorage = new GrowableArray();
this.outputStream = (DataOutputStream) outputStorage.getDataOutput();
this.offsets = new IntArrayList(10, 10);
this.metadataInfoSize = 0;
this.offsetArray = null;
this.offsetPosition = 0;
this.listType = listType;
}
@Override
public void reset(AbstractCollectionType listType) {
this.outputStorage.reset();
this.offsetArray = null;
this.offsets.clear();
this.offsetPosition = 0;
this.numberOfItems = 0;
if (listType == null || listType.getItemType() == null) {
this.itemTypeTag = ATypeTag.ANY;
fixedSize = false;
} else {
this.itemTypeTag = listType.getItemType().getTypeTag();
fixedSize = NonTaggedFormatUtil.isFixedSizedCollection(listType.getItemType());
}
headerSize = 2;
metadataInfoSize = 8;
}
@Override
public void addItem(IValueReference item) throws HyracksDataException {
try {
byte[] data = item.getByteArray();
int start = item.getStartOffset();
int len = item.getLength();
byte serializedTypeTag = data[start];
if (!fixedSize && ((serializedTypeTag != ATypeTag.SERIALIZED_NULL_TYPE_TAG
&& serializedTypeTag != ATypeTag.SERIALIZED_MISSING_TYPE_TAG) || itemTypeTag == ATypeTag.ANY)) {
this.offsets.add(outputStorage.getLength());
}
if (toWriteTag(serializedTypeTag)) {
this.numberOfItems++;
this.outputStream.write(serializedTypeTag);
this.outputStream.write(data, start + 1, len - 1);
} else if (serializedTypeTag != ATypeTag.SERIALIZED_NULL_TYPE_TAG
&& serializedTypeTag != ATypeTag.SERIALIZED_MISSING_TYPE_TAG) {
this.numberOfItems++;
this.outputStream.write(data, start + 1, len - 1);
}
} catch (IOException e) {
throw new HyracksDataException(e);
}
}
private boolean toWriteTag(byte serializedTypeTag) {
boolean toWriteTag = itemTypeTag == ATypeTag.ANY;
toWriteTag = toWriteTag
|| (itemTypeTag == ATypeTag.NULL && serializedTypeTag == ATypeTag.SERIALIZED_NULL_TYPE_TAG);
return toWriteTag
|| (itemTypeTag == ATypeTag.MISSING && serializedTypeTag == ATypeTag.SERIALIZED_MISSING_TYPE_TAG);
}
@Override
public void write(DataOutput out, boolean writeTypeTag) throws HyracksDataException {
try {
if (!fixedSize) {
metadataInfoSize += offsets.size() * 4;
}
if (offsetArray == null || offsetArray.length < metadataInfoSize) {
offsetArray = new byte[metadataInfoSize];
}
SerializerDeserializerUtil.writeIntToByteArray(offsetArray,
headerSize + metadataInfoSize + outputStorage.getLength(), offsetPosition);
SerializerDeserializerUtil.writeIntToByteArray(offsetArray, this.numberOfItems, offsetPosition + 4);
if (!fixedSize) {
offsetPosition += 8;
for (int i = 0; i < offsets.size(); i++) {
SerializerDeserializerUtil.writeIntToByteArray(offsetArray,
offsets.get(i) + metadataInfoSize + headerSize, offsetPosition);
offsetPosition += 4;
}
}
if (writeTypeTag) {
out.writeByte(listType.serialize());
}
out.writeByte(itemTypeTag.serialize());
out.write(offsetArray, 0, metadataInfoSize);
out.write(outputStorage.getByteArray(), 0, outputStorage.getLength());
} catch (IOException e) {
throw new HyracksDataException(e);
}
}
}
| {
"content_hash": "d206a79cdd91b6185bb8992ac649022e",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 116,
"avg_line_length": 40.72,
"alnum_prop": 0.6357563850687623,
"repo_name": "heriram/incubator-asterixdb",
"id": "f64206e383080b7bbd9df45161ac4f53e1f41ce1",
"size": "5897",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "asterixdb/asterix-om/src/main/java/org/apache/asterix/builders/AbstractListBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8721"
},
{
"name": "C",
"bytes": "421"
},
{
"name": "CSS",
"bytes": "8823"
},
{
"name": "Crystal",
"bytes": "453"
},
{
"name": "Gnuplot",
"bytes": "89"
},
{
"name": "HTML",
"bytes": "127590"
},
{
"name": "Java",
"bytes": "18878313"
},
{
"name": "JavaScript",
"bytes": "274822"
},
{
"name": "Python",
"bytes": "281315"
},
{
"name": "Ruby",
"bytes": "3078"
},
{
"name": "Scheme",
"bytes": "1105"
},
{
"name": "Shell",
"bytes": "204981"
},
{
"name": "Smarty",
"bytes": "31412"
}
],
"symlink_target": ""
} |
import os
from os import path
import sys
from optparse import OptionParser
import json
dataset = {"dataset": {"listing": [], "ui": [], "manifest": [], "code": [] }}
def generate_target(source_dir, targetType):
for root, dirs, files in os.walk(source_dir):
if len(dirs) == 0:
entry = {"target": root}
dataset["dataset"][targetType].append(entry)
def main(args):
parser = OptionParser(usage="python %prog manifest_root_dir ui_xml_root_dir out_json_file", version="%prog 1.0")
(options, args) = parser.parse_args()
if len(args) != 3:
parser.error("Invalid number of arguments.")
if os.path.exists(args[2]):
sys.exit(args[0] + " already exists")
generate_target(args[0], "manifest")
generate_target(args[1], "ui")
with open(args[2], "w") as f:
f.write(json.dumps(dataset, indent=4, separators=(',', ': ')))
print "dataset config (for leveldb) has been written at " + args[2]
main(sys.argv[1:])
| {
"content_hash": "a6a271e4aac542e70067afa70b208bf2",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 116,
"avg_line_length": 35.214285714285715,
"alnum_prop": 0.6206896551724138,
"repo_name": "sieveable/sieveable-tools",
"id": "bdd161c22068445bac9cd5e53235699967547112",
"size": "1000",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "scripts/dataset_paths_writer.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "72701"
}
],
"symlink_target": ""
} |
The service auto instrument agent is a subset of language-based native agents. This kind of agents is based on
some language-specific features, especially those of a VM-based language.
## What does Auto Instrument mean?
Many users learned about these agents when they first heard that "Not a single line of code has to be changed". SkyWalking used to mention this in its readme page as well.
However, this does not reflect the full picture. For end users, it is true that they no longer have to modify their codes in most cases.
But it is important to understand that the codes are in fact still modified by the agent, which is usually known as "runtime code manipulation". The underlying logic is that the
auto instrument agent uses the VM interface for code modification to dynamically add in the instrument code, such as modifying the class in Java through
`javaagent premain`.
In fact, although the SkyWalking team has mentioned that most auto instrument agents are VM-based, you may build such tools during compiling time rather than
runtime.
## What are the limitations?
Auto instrument is very helpful, as you may perform auto instrument during compiling time, without having to depend on VM features. But there are also certain limitations that come with it:
- **Higher possibility of in-process propagation in many cases**. Many high-level languages, such as Java and .NET, are used for building business systems.
Most business logic codes run in the same thread for each request, which causes propagation to be based on thread ID, in order for the stack module to make sure that the context is safe.
- **Only works in certain frameworks or libraries**. Since the agents are responsible for modifying the codes during runtime, the codes are already known
to the agent plugin developers. There is usually a list of frameworks or libraries supported by this kind of probes.
For example, see the [SkyWalking Java agent supported list](https://github.com/apache/skywalking-java/blob/20fb8c81b3da76ba6628d34c12d23d3d45c973ef/docs/en/setup/service-agent/java-agent/Supported-list.md).
- **Cross-thread operations are not always supported**. Like what is mentioned above regarding in-process propagation, most codes (especially business codes)
run in a single thread per request. But in some other cases, they operate across different threads, such as assigning tasks to other threads, task pools or batch processes. Some languages may even provide coroutine or similar components like `Goroutine`, which allows developers to run async process with low payload. In such cases, auto instrument will face problems.
So, there's nothing mysterious about auto instrument. In short, agent developers write an activation script to make
instrument codes work for you. That's it!
## What is next?
If you want to learn about manual instrument libs in SkyWalking, see the [Manual instrument SDK](manual-sdk.md) section.
| {
"content_hash": "50da4f496de93c8ebc8497549023e36d",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 369,
"avg_line_length": 91.5,
"alnum_prop": 0.7991803278688525,
"repo_name": "apache/skywalking",
"id": "ee52af15288868eb49d2044ff471a5f7df91e21a",
"size": "2960",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "docs/en/concepts-and-designs/service-agent.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "10340"
},
{
"name": "Batchfile",
"bytes": "6422"
},
{
"name": "Dockerfile",
"bytes": "4853"
},
{
"name": "FreeMarker",
"bytes": "10653"
},
{
"name": "Go",
"bytes": "3209"
},
{
"name": "Java",
"bytes": "6273596"
},
{
"name": "JavaScript",
"bytes": "1367"
},
{
"name": "Lua",
"bytes": "8229"
},
{
"name": "Makefile",
"bytes": "6045"
},
{
"name": "PHP",
"bytes": "1052"
},
{
"name": "Python",
"bytes": "8798"
},
{
"name": "Shell",
"bytes": "32763"
},
{
"name": "TypeScript",
"bytes": "2515"
}
],
"symlink_target": ""
} |
In this section, we gonna talk about how atlas handles caching and batching. Here we will learn:
- What is caching and batching
- Why batching
- Why caching
- Defaults
- Enabling cache (careful)
# What is caching and batching (for atlas)
Let's clarify what is caching and batching for ***atlas***. Note that the definition of caching and batching may change depending on the context.
***caching***, for atlas, is the simple act of storing a ***request object*** in memory. This way, whenever we bind a request with the ***same id***, we would be in fact, binding a ***shared*** request. This way, whenever on component updates this request, the other component would also get affected. Also, if the request has already fetched data, it will not fetch the data again since it's already in memory. This provides a better UX for the user. To see more about ids, check the ***updating request state*** section.
***batching***, for atlas, is the act of merging requests into one. This might seems confusing(in fact it is), but it's not something that will affect you directly.
For understanding ***batching***, let's look at an example:
```js
requestA.fetch().then(response => console.log(response));
requestA.fetch().then(response => console.log(response));
requestA.fetch().then(response => console.log(response));
requestA.fetch().then(response => console.log(response));
```
How many requests are going to be executed? Well, the usual answer would be 4, but atlas uses batching, so it will merge all requests into one and all requests will get the same response. This helps keeping data and state consistent. In the end, only 1 request will be made.
# Why batching?
Well, that's a good question. Why batching? Why not simple fetching two times?
The thing is, if we are going to use cache and therefore, share a request object across multiple components, we need to keep data and the request state consistent. Batching avoid the case of muliple components being rendered at the same time with the same request and making multiple requests, which would cause multiple state changes and maybe each request could lead to different responses.
This is good for the server and for the client. The server will receive less requests and the client will have data and state consistency. Yay!
# Why caching?
Now what about caching?
Well caching is actually easier to explain. Caching not only provides a better UX for fast response but also helps keeping data shared across multiple components.
Suppose you have two components ***A*** and ***B***. Both sharing the same request object. Now suppose user clicks on a button on component ***A*** to refresh the data. What would happen?
Well, in a normal case, the data from component ***A*** would get updated, but component ***B*** would not be in sync with data that component ***A*** have. However using caching, whenever we refresh the data somewere, the state and the new data will be shared across all components using that request object. Which means, that after a refresh from component ***A***, component ***B*** would also receive the new data.
# Hard question
What happens if component ***A*** tells the request to refresh and after that component ***B*** does the same thing? Since component ***B*** made the request after, the response from component ***B*** should be the most updated. How atlas handle this case?
In atlas there can be ***only one request in flight***. So if component ***A*** tells atlas to refresh, it will start a request. When component ***B*** also tells atlas to refresh(and the request is still in flight), it will start a new request and change this new request in place of the older one. In other words, component ***A*** and ***B*** will get the same response from the last request!!!
# Defaults
By default, ***batching is enabled*** and cannot be disabled. ***Caching is disabled***, but can be enabled.
We don't recommend enabling caching for your entire ***AtlasMap***. Requests that use the method ***POST*** or similar usually should not use caching, since making a request that has a cached response would not trigger the post. ***Which is not what you want!***.
So, ***rule of the thumb***, only use caching for ***GET*** methods.
# Enabling cache
To enable cache using ***AtlasMap***, just use the ***cache*** option like the example below:
```js
import { AtlasMap } from 'react-api-atlas';
const config = {
host: 'yourhost',
resources: {
Users: {
path: '/users',
endPoints: {
getUsers: { // USE CACHE ONLY ON "GET" METHODS. GOOD :D
path: '/',
cache: true, //cache enabled
},
},
},
},
};
``` | {
"content_hash": "f89fd0e35dfd9a68996bc9d7c394a7eb",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 522,
"avg_line_length": 64.0945945945946,
"alnum_prop": 0.7170567151591819,
"repo_name": "gugamm/react-api-atlas",
"id": "fa2873e878455fc2c1b140519d5a38c62ec94d7b",
"size": "4766",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/caching-and-batching.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3545"
}
],
"symlink_target": ""
} |
/* @author holman
*
* Index file for directivesthat needed to be included in app
*/
// TODO remove ./module when an actual directive is included
define(['./module'], function() {});
| {
"content_hash": "8ca92d8e44c3f09b12a1055f5647eab5",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 61,
"avg_line_length": 26.571428571428573,
"alnum_prop": 0.6881720430107527,
"repo_name": "golmansax/my-ng-skeleton",
"id": "df7f38b92a56fbdc1e803a8247ea1d867db572c4",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/app/directives/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "8500"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<list>
<option name="HASKELL_CONSTRUCTOR">
<value>
<option name="FOREGROUND" value="67daf0"/>
</value>
</option>
<option name="HASKELL_TYPE">
<value>
<option name="FOREGROUND" value="73e3d0"/>
</value>
</option>
<option name="HASKELL_OPERATOR">
<value>
<option name="FOREGROUND" value="D5C42B"/>
</value>
</option>
<option name="HASKELL_SIGNATURE">
<value>
<option name="FOREGROUND" value="69CD16"/>
</value>
</option>
<option name="HASKELL_CLASS">
<value>
<option name="FOREGROUND" value="EB0D94"/>
</value>
</option>
</list>
| {
"content_hash": "f794a9ff916fb33aabd2a63784aada07",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 54,
"avg_line_length": 26.642857142857142,
"alnum_prop": 0.5214477211796247,
"repo_name": "anlun/haskell-idea-plugin",
"id": "62868dbc962fef08d779135d51e8b36047f236e8",
"size": "746",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugin/resources/colorSchemes/HaskellDracula.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Haskell",
"bytes": "4029"
},
{
"name": "Java",
"bytes": "290470"
},
{
"name": "Kotlin",
"bytes": "589546"
}
],
"symlink_target": ""
} |
using System;
namespace Indigo.Security.Exceptions
{
[Serializable]
public class UnkownUserNameException : IncorrectUserNameOrPasswordException
{
public UnkownUserNameException(string userName) : base("未知的用户名 [{0}]", userName)
{
}
}
} | {
"content_hash": "dd2ccac78690ce2df7b77f3334ad4b0d",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 88,
"avg_line_length": 23.916666666666668,
"alnum_prop": 0.6550522648083623,
"repo_name": "ynhng/Indigo.NET",
"id": "1bb4193d997b9ef3767f77348ab5aa13cf2dc1c5",
"size": "301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Indigo.Core/Security/Exceptions/UnknownUserNameException.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "108"
},
{
"name": "C#",
"bytes": "204897"
},
{
"name": "CSS",
"bytes": "580336"
},
{
"name": "JavaScript",
"bytes": "1262510"
}
],
"symlink_target": ""
} |
package org.folio.marccat.dao.persistence;
/**
* 2018 Paul Search Engine Java
*
* @author paulm
* @version $Revision: 1.1 $, $Date: 2018/01/01 14:09:42 $
* @since 1.0
*/
public class S_BIB1_SMNTC {
private int useNumber;
private int relationNumber;
private int positionNumber;
private int structureNumber;
private int truncationNumber;
private int completenessNumber;
private short recordTypeCode;
private short sortFormSkipInFilingCode;
private short sortFormFunctionCode;
private short sortFormTypeCode;
private short sortFormSubTypeCode;
private short sortFormMainTypeCode;
private byte secondaryIndexCode;
private String queryActionCode;
private String selectClause;
private String fromClause;
private String joinClause;
private String whereClause;
private String viewClause;
private boolean fullText;
//unused? properties
private boolean staticQueryWithoutUserView;
private boolean staticQueryWithUserView;
private int queryNumber;
private int timsCollectionNumber;
private String oracleHint;
@Override
public String toString() {
return "S_BIB1_SMNTC(use=" + getUseNumber() + ", rel=" + getRelationNumber() + ", pos=" +
getPositionNumber() + ", struc=" + getStructureNumber() + ", trunc=" + getTruncationNumber() +
", cmplt=" + getCompletenessNumber() + ")";
}
public int getUseNumber() {
return useNumber;
}
public void setUseNumber(int useNumber) {
this.useNumber = useNumber;
}
public int getRelationNumber() {
return relationNumber;
}
public void setRelationNumber(int relationNumber) {
this.relationNumber = relationNumber;
}
public int getPositionNumber() {
return positionNumber;
}
public void setPositionNumber(int positionNumber) {
this.positionNumber = positionNumber;
}
public int getStructureNumber() {
return structureNumber;
}
public void setStructureNumber(int structureNumber) {
this.structureNumber = structureNumber;
}
public int getTruncationNumber() {
return truncationNumber;
}
public void setTruncationNumber(int truncationNumber) {
this.truncationNumber = truncationNumber;
}
public int getCompletenessNumber() {
return completenessNumber;
}
public void setCompletenessNumber(int completenessNumber) {
this.completenessNumber = completenessNumber;
}
public short getRecordTypeCode() {
return recordTypeCode;
}
public void setRecordTypeCode(short recordTypeCode) {
this.recordTypeCode = recordTypeCode;
}
public short getSortFormSkipInFilingCode() {
return sortFormSkipInFilingCode;
}
public void setSortFormSkipInFilingCode(short sortFormSkipInFilingCode) {
this.sortFormSkipInFilingCode = sortFormSkipInFilingCode;
}
public short getSortFormFunctionCode() {
return sortFormFunctionCode;
}
public void setSortFormFunctionCode(short sortFormFunctionCode) {
this.sortFormFunctionCode = sortFormFunctionCode;
}
public short getSortFormTypeCode() {
return sortFormTypeCode;
}
public void setSortFormTypeCode(short sortFormTypeCode) {
this.sortFormTypeCode = sortFormTypeCode;
}
public short getSortFormSubTypeCode() {
return sortFormSubTypeCode;
}
public void setSortFormSubTypeCode(short sortFormSubTypeCode) {
this.sortFormSubTypeCode = sortFormSubTypeCode;
}
public short getSortFormMainTypeCode() {
return sortFormMainTypeCode;
}
public void setSortFormMainTypeCode(short sortFormMainTypeCode) {
this.sortFormMainTypeCode = sortFormMainTypeCode;
}
public byte getSecondaryIndexCode() {
return secondaryIndexCode;
}
public void setSecondaryIndexCode(byte secondaryIndexCode) {
this.secondaryIndexCode = secondaryIndexCode;
}
public String getQueryActionCode() {
return queryActionCode;
}
public void setQueryActionCode(String queryActionCode) {
this.queryActionCode = queryActionCode;
}
public String getSelectClause() {
return selectClause;
}
public void setSelectClause(String selectClause) {
this.selectClause = selectClause;
}
public String getFromClause() {
return fromClause;
}
public void setFromClause(String fromClause) {
this.fromClause = fromClause;
}
public String getJoinClause() {
return joinClause;
}
public void setJoinClause(String joinClause) {
this.joinClause = joinClause;
}
public String getWhereClause() {
return whereClause;
}
public void setWhereClause(String whereClause) {
this.whereClause = whereClause;
}
public String getViewClause() {
return viewClause;
}
public void setViewClause(String viewClause) {
this.viewClause = viewClause;
}
public boolean isFullText() {
return fullText;
}
public void setFullText(boolean fullText) {
this.fullText = fullText;
}
public boolean isStaticQueryWithoutUserView() {
return staticQueryWithoutUserView;
}
public void setStaticQueryWithoutUserView(boolean staticQueryWithoutUserView) {
this.staticQueryWithoutUserView = staticQueryWithoutUserView;
}
public boolean isStaticQueryWithUserView() {
return staticQueryWithUserView;
}
public void setStaticQueryWithUserView(boolean staticQueryWithUserView) {
this.staticQueryWithUserView = staticQueryWithUserView;
}
public int getQueryNumber() {
return queryNumber;
}
public void setQueryNumber(int queryNumber) {
this.queryNumber = queryNumber;
}
public int getTimsCollectionNumber() {
return timsCollectionNumber;
}
public void setTimsCollectionNumber(int timsCollectionNumber) {
this.timsCollectionNumber = timsCollectionNumber;
}
public String getOracleHint() {
return oracleHint;
}
public void setOracleHint(String oracleHint) {
this.oracleHint = oracleHint;
}
}
| {
"content_hash": "db1ec4acd3cd6703844eb072bad6cb46",
"timestamp": "",
"source": "github",
"line_count": 244,
"max_line_length": 100,
"avg_line_length": 23.922131147540984,
"alnum_prop": 0.7431899948603735,
"repo_name": "atcult/mod-cataloging",
"id": "9672b8a9c6233980a3f71a51f23af723be153fa4",
"size": "5837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/folio/marccat/dao/persistence/S_BIB1_SMNTC.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "301"
},
{
"name": "Java",
"bytes": "3468472"
},
{
"name": "PLpgSQL",
"bytes": "15766763"
},
{
"name": "Python",
"bytes": "612"
},
{
"name": "Shell",
"bytes": "38444"
}
],
"symlink_target": ""
} |
ntec
====
is an open-source information visualization and analysis tool that is available under the MIT license.
User features:
<ul>
<li>tables</li>
<li>charts</li>
<li>monitorization objects</li>
<li>filters</li>
<li>free draw objects</li>
<li>sql analysis tool</li>
</ul>
Admin features:
<ul>
<li>backoffice menus</li>
<li>frontoffice config</li>
<li>options template config</li>
<li>page config</li>
<li>templates config
<ul>
<li>CSS</li>
<li>charts</li>
<li>monitorization objects</li>
</ul>
</li>
<li>users config</li>
</ul>
| {
"content_hash": "cc6969519aeb148ee1c97f9d29382d42",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 102,
"avg_line_length": 17.6875,
"alnum_prop": 0.6643109540636042,
"repo_name": "nelsonjma/ntec",
"id": "03a2a9ebf418b3e9a41c59b2ce2e8caf126330eb",
"size": "566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "61539"
},
{
"name": "C#",
"bytes": "497255"
},
{
"name": "CSS",
"bytes": "132165"
},
{
"name": "JavaScript",
"bytes": "2031820"
}
],
"symlink_target": ""
} |
// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_RADIX_H
#define BITCOIN_RADIX_H
#include <rcu.h>
#include <util/system.h>
#include <array>
#include <atomic>
#include <cstdint>
#include <memory>
#include <type_traits>
template <typename T> struct PassthroughAdapter {
auto &&getId(const T &e) const { return e.getId(); }
};
/**
* This is a radix tree storing values identified by a unique key.
*
* The tree is composed of nodes (RadixNode) containing an array of
* RadixElement. The key is split into chunks of a few bits that serve as an
* index into that array. RadixElement is a discriminated union of either a
* RadixNode* representing the next level in the tree, or a T* representing a
* leaf. New RadixNode are added lazily when two leaves would go in the same
* slot.
*
* Reads walk the tree using sequential atomic loads, and insertions are done
* using CAS, which ensures both can be executed lock free. Removing any
* elements from the tree can also be done using CAS, but requires waiting for
* other readers before being destroyed. The tree uses RCU to track which thread
* is reading the tree, which allows deletion to wait for other readers to be up
* to speed before destroying anything. It is therefore crucial that the lock be
* taken before reading anything in the tree.
*/
template <typename T, typename Adapter = PassthroughAdapter<T>>
struct RadixTree : private Adapter {
private:
static const int BITS = 4;
static const int MASK = (1 << BITS) - 1;
static const size_t CHILD_PER_LEVEL = 1 << BITS;
using KeyType =
typename std::remove_reference<decltype(std::declval<Adapter &>().getId(
std::declval<T &>()))>::type;
static const size_t KEY_BITS = 8 * sizeof(KeyType);
static const uint32_t TOP_LEVEL = (KEY_BITS - 1) / BITS;
struct RadixElement;
struct RadixNode;
std::atomic<RadixElement> root;
public:
RadixTree() : root(RadixElement()) {}
~RadixTree() { root.load().decrementRefCount(); }
/**
* Copy semantic.
*/
RadixTree(const RadixTree &src) : RadixTree() {
{
RCULock lock;
RadixElement e = src.root.load();
e.incrementRefCount();
root = e;
}
// Make sure we the writes in the tree are behind us so
// this copy won't mutate behind our back.
RCULock::synchronize();
}
RadixTree &operator=(const RadixTree &rhs) {
{
RCULock lock;
RadixElement e = rhs.root.load();
e.incrementRefCount();
root.load().decrementRefCount();
root = e;
}
// Make sure we the writes in the tree are behind us so
// this copy won't mutate behind our back.
RCULock::synchronize();
return *this;
}
/**
* Move semantic.
*/
RadixTree(RadixTree &&src) : RadixTree() { *this = std::move(src); }
RadixTree &operator=(RadixTree &&rhs) {
{
RCULock lock;
RadixElement e = rhs.root.load();
rhs.root = root.load();
root = e;
}
return *this;
}
/**
* Insert a value into the tree.
* Returns true if the value was inserted, false if it was already present.
*/
bool insert(const RCUPtr<T> &value) { return insert(getId(*value), value); }
/**
* Get the value corresponding to a key.
* Returns the value if found, nullptr if not.
*/
RCUPtr<T> get(const KeyType &key) {
uint32_t level = TOP_LEVEL;
RCULock lock;
RadixElement e = root.load();
// Find a leaf.
while (e.isNode()) {
e = e.getNode()->get(level--, key)->load();
}
T *leaf = e.getLeaf();
if (leaf == nullptr || getId(*leaf) != key) {
// We failed to find the proper element.
return RCUPtr<T>();
}
// The leaf is non-null and the keys match. We have our guy.
return RCUPtr<T>::copy(leaf);
}
RCUPtr<const T> get(const KeyType &key) const {
T const *ptr = const_cast<RadixTree *>(this)->get(key).release();
return RCUPtr<const T>::acquire(ptr);
}
template <typename Callable> bool forEachLeaf(Callable &&func) const {
RCULock lock;
return forEachLeaf(root.load(), std::move(func));
}
#define SEEK_LEAF_LOOP() \
RadixElement e = eptr->load(); \
\
/* Walk down the tree until we find a leaf for our node. */ \
do { \
while (e.isNode()) { \
Node: \
auto nptr = e.getNode(); \
if (!nptr->isShared()) { \
eptr = nptr->get(level--, key); \
e = eptr->load(); \
continue; \
} \
\
auto copy = std::make_unique<RadixNode>(*nptr); \
if (!eptr->compare_exchange_strong(e, RadixElement(copy.get()))) { \
/* We failed to insert our subtree, just try again. */ \
continue; \
} \
\
/* We have a subtree, resume normal operations from there. */ \
e.decrementRefCount(); \
eptr = copy->get(level--, key); \
e = eptr->load(); \
copy.release(); \
} \
} while (0)
/**
* Remove an element from the tree.
* Returns the removed element, or nullptr if there isn't one.
*/
RCUPtr<T> remove(const KeyType &key) {
uint32_t level = TOP_LEVEL;
RCULock lock;
std::atomic<RadixElement> *eptr = &root;
SEEK_LEAF_LOOP();
T *leaf = e.getLeaf();
if (leaf == nullptr || getId(*leaf) != key) {
// We failed to find the proper element.
return RCUPtr<T>();
}
// We have the proper element, try to delete it.
if (eptr->compare_exchange_strong(e, RadixElement())) {
return RCUPtr<T>::acquire(leaf);
}
// The element was replaced, either by a subtree or another element.
if (e.isNode()) {
goto Node;
}
// The element in the slot is not the one we are looking for.
return RCUPtr<T>();
}
private:
KeyType getId(const T &value) const { return Adapter::getId(value); }
bool insert(const KeyType &key, RCUPtr<T> value) {
uint32_t level = TOP_LEVEL;
RCULock lock;
std::atomic<RadixElement> *eptr = &root;
while (true) {
SEEK_LEAF_LOOP();
// If the slot is empty, try to insert right there.
if (e.getLeaf() == nullptr) {
if (eptr->compare_exchange_strong(e,
RadixElement(value.get()))) {
value.release();
return true;
}
// CAS failed, we may have a node in there now.
if (e.isNode()) {
goto Node;
}
}
// The element was already in the tree.
const KeyType &leafKey = getId(*e.getLeaf());
if (key == leafKey) {
return false;
}
// There is an element there, but it isn't a subtree. We need to
// convert it into a subtree and resume insertion into that subtree.
auto newChild = std::make_unique<RadixNode>(level, leafKey, e);
if (eptr->compare_exchange_strong(e,
RadixElement(newChild.get()))) {
// We have a subtree, resume normal operations from there.
newChild.release();
} else {
// We failed to insert our subtree, clean it before it is freed.
newChild->get(level, leafKey)->store(RadixElement());
}
}
}
#undef SEEK_LEAF_LOOP
template <typename Callable>
bool forEachLeaf(RadixElement e, Callable &&func) const {
if (e.isLeaf()) {
T *leaf = e.getLeaf();
if (leaf != nullptr) {
return func(RCUPtr<T>::copy(leaf));
}
return true;
}
return e.getNode()->forEachChild(
[&](const std::atomic<RadixElement> *pElement) {
return forEachLeaf(pElement->load(), func);
});
}
struct RadixElement {
private:
union {
RadixNode *node;
T *leaf;
uintptr_t raw;
};
static const uintptr_t DISCRIMINANT = 0x01;
bool getDiscriminant() const { return (raw & DISCRIMINANT) != 0; }
public:
explicit RadixElement() noexcept : raw(DISCRIMINANT) {}
explicit RadixElement(RadixNode *nodeIn) noexcept : node(nodeIn) {}
explicit RadixElement(T *leafIn) noexcept : leaf(leafIn) {
raw |= DISCRIMINANT;
}
/**
* RadixElement is designed to be a dumb wrapper. This allows any
* container to release what is held by the RadixElement.
*/
void incrementRefCount() {
if (isNode()) {
RCUPtr<RadixNode>::copy(getNode()).release();
} else {
RCUPtr<T>::copy(getLeaf()).release();
}
}
void decrementRefCount() {
if (isNode()) {
RadixNode *ptr = getNode();
RCUPtr<RadixNode>::acquire(ptr);
} else {
T *ptr = getLeaf();
RCUPtr<T>::acquire(ptr);
}
}
/**
* Node features.
*/
bool isNode() const { return !getDiscriminant(); }
RadixNode *getNode() {
assert(isNode());
return node;
}
const RadixNode *getNode() const {
assert(isNode());
return node;
}
/**
* Leaf features.
*/
bool isLeaf() const { return getDiscriminant(); }
T *getLeaf() {
assert(isLeaf());
return reinterpret_cast<T *>(raw & ~DISCRIMINANT);
}
const T *getLeaf() const {
assert(isLeaf());
return const_cast<RadixElement *>(this)->getLeaf();
}
};
struct RadixNode {
IMPLEMENT_RCU_REFCOUNT(uint64_t);
private:
union {
std::array<std::atomic<RadixElement>, CHILD_PER_LEVEL> children;
std::array<RadixElement, CHILD_PER_LEVEL>
non_atomic_children_DO_NOT_USE;
};
public:
RadixNode(uint32_t level, const KeyType &key, RadixElement e)
: non_atomic_children_DO_NOT_USE() {
get(level, key)->store(e);
}
~RadixNode() {
for (RadixElement e : non_atomic_children_DO_NOT_USE) {
e.decrementRefCount();
}
}
RadixNode(const RadixNode &rhs) : non_atomic_children_DO_NOT_USE() {
for (size_t i = 0; i < CHILD_PER_LEVEL; i++) {
auto e = rhs.children[i].load();
e.incrementRefCount();
non_atomic_children_DO_NOT_USE[i] = e;
}
}
RadixNode &operator=(const RadixNode &) = delete;
std::atomic<RadixElement> *get(uint32_t level, const KeyType &key) {
return &children[(key >> uint32_t(level * BITS)) & MASK];
}
bool isShared() const { return refcount > 0; }
template <typename Callable> bool forEachChild(Callable &&func) const {
for (size_t i = 0; i < CHILD_PER_LEVEL; i++) {
if (!func(&children[i])) {
return false;
}
}
return true;
}
};
// Make sure the alignment works for T and RadixElement.
static_assert(alignof(T) > 1, "T's alignment must be 2 or more.");
static_assert(alignof(RadixNode) > 1,
"RadixNode alignment must be 2 or more.");
};
#endif // BITCOIN_RADIX_H
| {
"content_hash": "091725ec92b036f1c1c70a3032b17e3c",
"timestamp": "",
"source": "github",
"line_count": 399,
"max_line_length": 80,
"avg_line_length": 33.51629072681704,
"alnum_prop": 0.48665220967621325,
"repo_name": "Bitcoin-ABC/bitcoin-abc",
"id": "85cb206b1f861b900a6974b3a729be2616045f40",
"size": "13373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/radix.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28178"
},
{
"name": "C",
"bytes": "1160721"
},
{
"name": "C++",
"bytes": "9817660"
},
{
"name": "CMake",
"bytes": "195193"
},
{
"name": "CSS",
"bytes": "4284"
},
{
"name": "Dockerfile",
"bytes": "3559"
},
{
"name": "HTML",
"bytes": "25754"
},
{
"name": "Java",
"bytes": "41238"
},
{
"name": "JavaScript",
"bytes": "2366459"
},
{
"name": "Kotlin",
"bytes": "3712"
},
{
"name": "M4",
"bytes": "31132"
},
{
"name": "Makefile",
"bytes": "100617"
},
{
"name": "Objective-C++",
"bytes": "5811"
},
{
"name": "PHP",
"bytes": "94504"
},
{
"name": "Perl",
"bytes": "4551"
},
{
"name": "PowerShell",
"bytes": "2277"
},
{
"name": "Python",
"bytes": "2706993"
},
{
"name": "QMake",
"bytes": "798"
},
{
"name": "Ruby",
"bytes": "21108"
},
{
"name": "Rust",
"bytes": "54953"
},
{
"name": "Sage",
"bytes": "39795"
},
{
"name": "Shell",
"bytes": "167526"
},
{
"name": "TypeScript",
"bytes": "66320"
}
],
"symlink_target": ""
} |
package com.capitalone.dashboard.service;
import com.capitalone.dashboard.model.Feature;
import com.capitalone.dashboard.model.SprintEstimate;
import com.capitalone.dashboard.model.DataResponse;
import java.util.List;
import java.util.Optional;
import org.bson.types.ObjectId;
public interface FeatureService {
/**
* Retrieves all stories for a given team and their current sprint
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param teamId
* A given scope-owner's source-system ID
* @param agileType
* Agile type to be retrieved (e.g., kanban | scrum)
*
* @return A data response list of type Feature containing all features for
* the given team and current sprint
*/
DataResponse<List<Feature>> getRelevantStories(ObjectId componentId,
String teamId, Optional<String> agileType);
/**
* Retrieves a single story based on a back-end story number
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param storyNumber
* A back-end story ID used by a source system
*
* @return A data response list of type Feature containing a single story
*/
DataResponse<List<Feature>> getStory(ObjectId componentId,
String storyNumber);
/**
* Retrieves all unique super features and their total sub feature estimates
* for a given team and their current sprint
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param teamId
* A given scope-owner's source-system ID
* @param agileType
* Agile type to be retrieved (e.g., kanban | scrum)
* @param estimateMetricType
* The reporting metric (hours | storypoints)
*
* @return A data response list of type Feature containing the unique
* features plus their sub features' estimates associated to the
* current sprint and team
*/
DataResponse<List<Feature>> getFeatureEpicEstimates(ObjectId componentId,
String teamId, Optional<String> agileType, Optional<String> estimateMetricType);
/**
* Retrieves estimate total of all features in the current sprint and for
* the current team.
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param teamId
* A given scope-owner's source-system ID
* @param agileType
* Agile type to be retrieved (e.g., kanban | scrum)
* @param estimateMetricType
* The reporting metric (hours | storypoints)
*
* @return A data response list of type Feature containing the total
* estimate number for all features
*/
@Deprecated
DataResponse<List<Feature>> getTotalEstimate(ObjectId componentId,
String teamId, Optional<String> agileType, Optional<String> estimateMetricType);
/**
* Retrieves estimate in-progress of all features in the current sprint and
* for the current team.
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param teamId
* A given scope-owner's source-system ID
* @param agileType
* Agile type to be retrieved (e.g., kanban | scrum)
* @param estimateMetricType
* The reporting metric (hours | storypoints)
*
* @return A data response list of type Feature containing the in-progress
* estimate number for all features
*/
@Deprecated
DataResponse<List<Feature>> getInProgressEstimate(ObjectId componentId,
String teamId, Optional<String> agileType, Optional<String> estimateMetricType);
/**
* Retrieves estimate done of all features in the current sprint and for the
* current team.
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param teamId
* A given scope-owner's source-system ID
* @param agileType
* Agile type to be retrieved (e.g., kanban | scrum)
* @param estimateMetricType
* The reporting metric (hours | storypoints)
*
* @return A data response list of type Feature containing the done estimate
* number for all features
*/
@Deprecated
DataResponse<List<Feature>> getDoneEstimate(ObjectId componentId,
String teamId, Optional<String> agileType, Optional<String> estimateMetricType);
/**
* Retrieves estimate done of all features in the current sprint(s) for the current team
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param teamId
* A given scope-owner's source-system ID
* @param agileType
* Agile type to be retrieved (e.g., kanban | scrum)
* @param estimateMetricType
* The reporting metric (hours | storypoints)
*
* @return A data response list of type Feature containing the done estimate
* number for all features
*/
DataResponse<SprintEstimate> getAggregatedSprintEstimates(ObjectId componentId,
String teamId, Optional<String> agileType, Optional<String> estimateMetricType);
/**
* Retrieves the current sprint's detail for a given team.
*
* @param componentId
* The ID of the related UI component that will reference
* collector item content from this collector
* @param teamId
* A given scope-owner's source-system ID
* @param agileType
* Agile type to be retrieved (e.g., kanban | scrum)
*
* @return A data response list of type Feature containing several relevant
* sprint fields for the current team's sprint
*/
DataResponse<List<Feature>> getCurrentSprintDetail(ObjectId componentId,
String teamId, Optional<String> agileType);
}
| {
"content_hash": "78414ea9443d0a77cae3c81a56fd2a88",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 89,
"avg_line_length": 37.03048780487805,
"alnum_prop": 0.6910917174378396,
"repo_name": "harish961/Hygieia-WFN",
"id": "21966cad56747c9669be1d4bd0e7144d9b05b8f4",
"size": "6073",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "api/src/main/java/com/capitalone/dashboard/service/FeatureService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6427"
},
{
"name": "CSS",
"bytes": "341303"
},
{
"name": "CoffeeScript",
"bytes": "1126"
},
{
"name": "HTML",
"bytes": "293945"
},
{
"name": "Java",
"bytes": "1653090"
},
{
"name": "JavaScript",
"bytes": "4979785"
},
{
"name": "Makefile",
"bytes": "780"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Python",
"bytes": "3486"
},
{
"name": "Roff",
"bytes": "160"
},
{
"name": "Ruby",
"bytes": "3998"
},
{
"name": "Shell",
"bytes": "64975"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.