text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
<?php
/**
* File WriteTestConfigurationsTest.php
*
* @author Edward Pfremmer <[email protected]>
*/
namespace Epfremme\Everything\Tests\Handler\Setup;
use Epfremme\Collection\Collection;
use Epfremme\Everything\Composer\Json;
use Epfremme\Everything\Entity\Package;
use Epfremme\Everything\Filesystem\Cache;
use Epfremme\Everything\Handler\Package\FilterPackageVersions;
use Epfremme\Everything\Handler\Setup\GetBaseConfiguration;
use Epfremme\Everything\Handler\Setup\WriteTestConfigurations;
use Epfremme\Everything\Tests\Composer\JsonTest;
use Epfremme\Everything\Tests\Entity\PackageTest;
use Epfremme\Everything\Tests\Traits\SerializerTrait;
/**
* Class WriteTestConfigurationsTest
*
* @package Epfremme\Everything\Tests\Handler\Setup
*/
class WriteTestConfigurationsTest extends \PHPUnit_Framework_TestCase
{
use SerializerTrait;
/**
* @var Collection
*/
private $packages;
/**
* @var Cache|\Mockery\MockInterface
*/
private $cache;
/**
* @var Json
*/
private $json;
/**
* @var \ArrayObject
*/
private $base;
/**
* {@inheritdoc}
*/
public function setUp()
{
parent::setUp();
$serializer = $this->getSerializer();
$this->packages = new Collection([
'a/a' => $serializer->deserialize(str_replace('test/test', 'a/a', PackageTest::TEST_PACKAGE_JSON), Package::class, 'json'),
'b/b' => $serializer->deserialize(str_replace('test/test', 'b/b', PackageTest::TEST_PACKAGE_JSON), Package::class, 'json'),
'c/c' => $serializer->deserialize(str_replace('test/test', 'c/c', PackageTest::TEST_PACKAGE_JSON), Package::class, 'json'),
]);
$baseConfigHandler = new GetBaseConfiguration($this->packages);
$versionFilterHandler = new FilterPackageVersions('^1.0');
$this->packages->each(function(Package $package) use ($versionFilterHandler) {
$versionFilterHandler($package);
});
$this->cache = \Mockery::mock(Cache::class);
$this->json = new Json(JsonTest::TEST_COMPOSER_JSON);
$this->base = $baseConfigHandler();
}
public function testConstruct()
{
$handler = new WriteTestConfigurations($this->packages, $this->cache, $this->json);
$this->assertAttributeSame($this->packages, 'packages', $handler);
$this->assertAttributeSame($this->cache, 'cache', $handler);
$this->assertAttributeSame($this->json, 'json', $handler);
}
public function testInvoke()
{
$handler = new WriteTestConfigurations($this->packages, $this->cache, $this->json);
$this->cache->shouldReceive('addConfig')->with($this->json)->atMost()->times(2);
$this->assertSame($this->packages, $handler($this->base));
}
}
| {'content_hash': '4f56ddb4e2824fb58fd720715d15bf2e', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 135, 'avg_line_length': 30.301075268817204, 'alnum_prop': 0.6564939673527325, 'repo_name': 'epfremmer/test-everything', 'id': '355c6c760be37bb9445e9a9f1a176122708d3f86', 'size': '2818', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'tests/Handler/Setup/WriteTestConfigurationsTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '109885'}]} |
<?php
/**
* @see Zend_Gdata_Books_Extension_BooksLink
*/
require_once 'Zend/Gdata/Books/Extension/BooksLink.php';
/**
* Describes a thumbnail link
*
* @category Zend
* @package Zend_Gdata
* @subpackage Books
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Books_Extension_ThumbnailLink extends
Zend_Gdata_Books_Extension_BooksLink
{
/**
* Constructor for Zend_Gdata_Books_Extension_ThumbnailLink which
* Describes a thumbnail link
*
* @param string|null $href Linked resource URI
* @param string|null $rel Forward relationship
* @param string|null $type Resource MIME type
* @param string|null $hrefLang Resource language
* @param string|null $title Human-readable resource title
* @param string|null $length Resource length in octets
*/
public function __construct($href = null, $rel = null, $type = null,
$hrefLang = null, $title = null, $length = null)
{
$this->registerAllNamespaces(Zend_Gdata_Books::$namespaces);
parent::__construct($href, $rel, $type, $hrefLang, $title, $length);
}
}
| {'content_hash': 'c9de504b0b7746368cabb24b4e580bda', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 87, 'avg_line_length': 31.390243902439025, 'alnum_prop': 0.6456876456876457, 'repo_name': 'Riges/KawaiViewModel', 'id': '5d0c27ca9347a181f8395218ce381a3f18a1178c', 'size': '2073', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'www/libs/Zend/Gdata/Books/Extension/ThumbnailLink.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '640'}, {'name': 'JavaScript', 'bytes': '143901'}, {'name': 'PHP', 'bytes': '16453440'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Shell', 'bytes': '1036'}]} |
/**
* This file is part of the CernVM File System.
*
* LogCvmfs() handles all message output. It works like printf.
* It can log to a debug log file, stdout, stderr, and syslog.
* The tracer is a separate module, messages do not overlap with logging.
*
* The syslog setter routines are not thread-safe. They are meant to be
* invoked at the very first, single-threaded stage.
*
* If DEBUGMSG is undefined, pure debug messages are compiled into no-ops.
*/
#include "logging_internal.h" // NOLINT(build/include)
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <vector>
#include "platform.h"
#include "smalloc.h"
#include "util/mutex.h"
#include "util/posix.h"
#include "util/single_copy.h"
using namespace std; // NOLINT
#ifdef CVMFS_NAMESPACE_GUARD
namespace CVMFS_NAMESPACE_GUARD {
#endif
static void LogCustom(unsigned id, const std::string &message);
LogFacilities DefaultLogging::info = kLogSyslog;
LogFacilities DefaultLogging::error = kLogSyslogErr;
void DefaultLogging::Set(LogFacilities info, LogFacilities error) {
DefaultLogging::info = info;
DefaultLogging::error = error;
}
namespace {
const unsigned kMicroSyslogMax = 500 * 1024; // rotate after 500kB
pthread_mutex_t lock_stdout = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock_stderr = PTHREAD_MUTEX_INITIALIZER;
#ifdef DEBUGMSG
pthread_mutex_t lock_debug = PTHREAD_MUTEX_INITIALIZER;
FILE *file_debug = NULL;
string *path_debug = NULL;
#endif
const char *module_names[] = {
"unknown", "cache", "catalog", "sql",
"cvmfs", "hash", "download", "compress",
"quota", "talk", "monitor", "lru",
"fuse stub", "signature", "fs traversal", "catalog traversal",
"nfs maps", "publish", "spooler", "concurrency",
"utility", "glue buffer", "history", "unionfs",
"pathspec", "receiver", "upload s3", "upload http",
"s3fanout", "gc", "dns", "authz",
"reflog", "kvstore"};
int syslog_facility = LOG_USER;
int syslog_level = LOG_NOTICE;
char *syslog_prefix = NULL;
string *usyslog_dest = NULL;
int usyslog_fd = -1;
int usyslog_fd1 = -1;
unsigned usyslog_size = 0;
pthread_mutex_t lock_usyslock = PTHREAD_MUTEX_INITIALIZER;
const unsigned kMaxCustomlog = 3;
string *customlog_dests[] = {NULL, NULL, NULL};
int customlog_fds[] = {-1, -1, -1};
pthread_mutex_t customlog_locks[] = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER};
LogLevels max_log_level = kLogNormal;
static void (*alt_log_func)(const LogSource source, const int mask,
const char *msg) = NULL;
/**
* Circular buffer of the last $n$ calls to LogCvmfs(). Thread-safe class.
*/
class LogBuffer : SingleCopy {
public:
LogBuffer() : next_id_(0) {
int retval = pthread_mutex_init(&lock_, NULL);
assert(retval == 0);
}
~LogBuffer() {
pthread_mutex_destroy(&lock_);
}
void Append(const LogBufferEntry &entry) {
MutexLockGuard lock_guard(lock_);
size_t idx = next_id_++ % kBufferSize;
if (idx >= buffer_.size()) {
buffer_.push_back(entry);
} else {
buffer_[idx] = entry;
}
}
std::vector<LogBufferEntry> GetBuffer() {
// Return a buffer sorted from newest to oldest buffer
std::vector<LogBufferEntry> sorted_buffer;
MutexLockGuard lock_guard(lock_);
for (unsigned i = 1; i <= buffer_.size(); ++i) {
unsigned idx = (next_id_ - i) % kBufferSize;
sorted_buffer.push_back(buffer_[idx]);
}
return sorted_buffer;
}
void Clear() {
MutexLockGuard lock_guard(lock_);
next_id_ = 0;
buffer_.clear();
}
private:
static const unsigned kBufferSize = 10;
pthread_mutex_t lock_;
int next_id_;
std::vector<LogBufferEntry> buffer_;
};
LogBuffer g_log_buffer;
} // namespace
/**
* Sets the level that is used for all messages to the syslog facility.
*/
void SetLogSyslogLevel(const int level) {
switch (level) {
case 1:
syslog_level = LOG_DEBUG;
break;
case 2:
syslog_level = LOG_INFO;
break;
case 3:
syslog_level = LOG_NOTICE;
break;
default:
syslog_level = LOG_NOTICE;
break;
}
}
int GetLogSyslogLevel() {
switch (syslog_level) {
case LOG_DEBUG:
return 1;
case LOG_INFO:
return 2;
default:
return 3;
}
}
/**
* Sets the syslog facility to one of local0 .. local7.
* Falls back to LOG_USER if local_facility is not in [0..7]
*/
void SetLogSyslogFacility(const int local_facility) {
switch (local_facility) {
case 0:
syslog_facility = LOG_LOCAL0;
break;
case 1:
syslog_facility = LOG_LOCAL1;
break;
case 2:
syslog_facility = LOG_LOCAL2;
break;
case 3:
syslog_facility = LOG_LOCAL3;
break;
case 4:
syslog_facility = LOG_LOCAL4;
break;
case 5:
syslog_facility = LOG_LOCAL5;
break;
case 6:
syslog_facility = LOG_LOCAL6;
break;
case 7:
syslog_facility = LOG_LOCAL7;
break;
default:
syslog_facility = LOG_USER;
}
}
int GetLogSyslogFacility() {
switch (syslog_facility) {
case LOG_LOCAL0:
return 0;
case LOG_LOCAL1:
return 1;
case LOG_LOCAL2:
return 2;
case LOG_LOCAL3:
return 3;
case LOG_LOCAL4:
return 4;
case LOG_LOCAL5:
return 5;
case LOG_LOCAL6:
return 6;
case LOG_LOCAL7:
return 7;
default:
return -1;
}
}
/**
* The syslog prefix is used to distinguish multiple repositories in
* /var/log/messages
*/
void SetLogSyslogPrefix(const std::string &prefix) {
if (syslog_prefix) free(syslog_prefix);
if (prefix == "") {
syslog_prefix = NULL;
} else {
unsigned len = prefix.length() + 1;
syslog_prefix = static_cast<char *>(smalloc(len));
syslog_prefix[len - 1] = '\0';
memcpy(syslog_prefix, &prefix[0], prefix.length());
}
}
void SetLogSyslogShowPID(bool flag) {
openlog(NULL, flag ? LOG_PID : 0, GetLogSyslogFacility());
}
/**
* Set the maximum verbosity level. By default kLogNormal.
*/
void SetLogVerbosity(const LogLevels max_level) { max_log_level = max_level; }
/**
* "Micro-Syslog" write kLogSyslog messages into filename. It rotates this
* file. Requires for µCernVM
*/
void SetLogMicroSyslog(const std::string &filename) {
pthread_mutex_lock(&lock_usyslock);
if (usyslog_fd >= 0) {
close(usyslog_fd);
close(usyslog_fd1);
usyslog_fd = -1;
usyslog_fd1 = -1;
}
if (filename == "") {
delete usyslog_dest;
usyslog_dest = NULL;
pthread_mutex_unlock(&lock_usyslock);
return;
}
usyslog_fd = open(filename.c_str(), O_RDWR | O_APPEND | O_CREAT, 0600);
if (usyslog_fd < 0) {
fprintf(stderr, "could not open usyslog file %s (%d), aborting\n",
filename.c_str(), errno);
abort();
}
usyslog_fd1 = open((filename + ".1").c_str(), O_WRONLY | O_CREAT, 0600);
if (usyslog_fd1 < 0) {
fprintf(stderr, "could not open usyslog.1 file %s.1 (%d), aborting\n",
filename.c_str(), errno);
abort();
}
platform_stat64 info;
int retval = platform_fstat(usyslog_fd, &info);
assert(retval == 0);
usyslog_size = info.st_size;
usyslog_dest = new string(filename);
pthread_mutex_unlock(&lock_usyslock);
}
std::string GetLogMicroSyslog() {
pthread_mutex_lock(&lock_usyslock);
string result;
if (usyslog_dest) result = *usyslog_dest;
pthread_mutex_unlock(&lock_usyslock);
return result;
}
static void LogMicroSyslog(const std::string &message) {
if (message.size() == 0) return;
pthread_mutex_lock(&lock_usyslock);
if (usyslog_fd < 0) {
pthread_mutex_unlock(&lock_usyslock);
return;
}
int written = write(usyslog_fd, message.data(), message.size());
if ((written < 0) || (static_cast<unsigned>(written) != message.size())) {
close(usyslog_fd);
usyslog_fd = -1;
abort();
}
int retval = fsync(usyslog_fd);
assert(retval == 0);
usyslog_size += written;
if (usyslog_size >= kMicroSyslogMax) {
// Wipe out usyslog.1 file
retval = ftruncate(usyslog_fd1, 0);
assert(retval == 0);
// Copy from usyslog to usyslog.1
retval = lseek(usyslog_fd, 0, SEEK_SET);
assert(retval == 0);
unsigned char buf[4096];
int num_bytes;
do {
num_bytes = read(usyslog_fd, buf, 4096);
assert(num_bytes >= 0);
if (num_bytes == 0) break;
int written = write(usyslog_fd1, buf, num_bytes);
assert(written == num_bytes);
} while (num_bytes == 4096);
retval = lseek(usyslog_fd1, 0, SEEK_SET);
assert(retval == 0);
// Reset usyslog
retval = lseek(usyslog_fd, 0, SEEK_SET);
assert(retval == 0);
retval = ftruncate(usyslog_fd, 0);
assert(retval == 0);
usyslog_size = 0;
}
pthread_mutex_unlock(&lock_usyslock);
}
/**
* Changes the debug log file from stderr. No effect if DEBUGMSG is undefined.
*/
#ifdef DEBUGMSG
void SetLogDebugFile(const string &filename) {
if (filename == "") {
if ((file_debug != NULL) && (file_debug != stderr)) {
fclose(file_debug);
file_debug = NULL;
}
delete path_debug;
path_debug = NULL;
return;
}
if ((file_debug != NULL) && (file_debug != stderr)) {
if ((fclose(file_debug) < 0)) {
fprintf(stderr, "could not close current log file (%d), aborting\n",
errno);
abort();
}
}
int fd = open(filename.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0600);
if ((fd < 0) || ((file_debug = fdopen(fd, "a")) == NULL)) {
fprintf(stderr, "could not open debug log file %s (%d), aborting\n",
filename.c_str(), errno);
syslog(syslog_facility | LOG_ERR,
"could not open debug log file %s (%d), "
"aborting\n",
filename.c_str(), errno);
abort();
}
delete path_debug;
path_debug = new string(filename);
}
string GetLogDebugFile() {
if (path_debug) return *path_debug;
return "";
}
#endif
void SetAltLogFunc(void (*fn)(const LogSource source, const int mask,
const char *msg)) {
alt_log_func = fn;
}
/**
* Logs a message to one or multiple facilities specified by mask.
* Mask can be extended by a log level in the future, using the higher bits.
*
* @param[in] source Component that triggers the logging
* @param[in] mask Bit mask of log facilities
* @param[in] format Format string followed by arguments like printf
*/
void LogCvmfs(const LogSource source, const int mask, const char *format, ...) {
char *msg = NULL;
va_list variadic_list;
// Log level check, no flag set in mask means kLogNormal
#ifndef DEBUGMSG
int log_level = mask & ((2 * kLogNone - 1) ^ (kLogLevel0 - 1));
if (!log_level) log_level = kLogNormal;
if (log_level == kLogNone) return;
if (log_level > max_log_level) return;
#endif
// Format the message string
va_start(variadic_list, format);
int retval = vasprintf(&msg, format, variadic_list);
assert(retval != -1); // else: out of memory
va_end(variadic_list);
if (alt_log_func) {
(*alt_log_func)(source, mask, msg);
return;
}
#ifdef DEBUGMSG
if (mask & kLogDebug) {
pthread_mutex_lock(&lock_debug);
// Set the file pointer for debuging to stderr, if necessary
if (file_debug == NULL) file_debug = stderr;
// Get timestamp
time_t rawtime;
time(&rawtime);
struct tm now;
localtime_r(&rawtime, &now);
if (file_debug == stderr) pthread_mutex_lock(&lock_stderr);
fprintf(file_debug, "(%s) %s [%02d-%02d-%04d %02d:%02d:%02d %s]\n",
module_names[source], msg, (now.tm_mon) + 1, now.tm_mday,
(now.tm_year) + 1900, now.tm_hour, now.tm_min, now.tm_sec,
now.tm_zone);
fflush(file_debug);
if (file_debug == stderr) pthread_mutex_unlock(&lock_stderr);
pthread_mutex_unlock(&lock_debug);
}
#endif
if (mask & kLogStdout) {
pthread_mutex_lock(&lock_stdout);
if (mask & kLogShowSource) printf("(%s) ", module_names[source]);
printf("%s", msg);
if (!(mask & kLogNoLinebreak)) printf("\n");
fflush(stdout);
pthread_mutex_unlock(&lock_stdout);
}
if (mask & kLogStderr) {
pthread_mutex_lock(&lock_stderr);
if (mask & kLogShowSource) fprintf(stderr, "(%s) ", module_names[source]);
fprintf(stderr, "%s", msg);
if (!(mask & kLogNoLinebreak)) fprintf(stderr, "\n");
fflush(stderr);
pthread_mutex_unlock(&lock_stderr);
}
if (mask & (kLogSyslog | kLogSyslogWarn | kLogSyslogErr)) {
if (usyslog_dest) {
string fmt_msg(msg);
if (syslog_prefix) fmt_msg = "(" + string(syslog_prefix) + ") " + fmt_msg;
time_t rawtime;
time(&rawtime);
char fmt_time[26];
ctime_r(&rawtime, fmt_time);
fmt_msg = string(fmt_time, 24) + " " + fmt_msg;
fmt_msg.push_back('\n');
LogMicroSyslog(fmt_msg);
} else {
int level = syslog_level;
if (mask & kLogSyslogWarn) level = LOG_WARNING;
if (mask & kLogSyslogErr) level = LOG_ERR;
if (syslog_prefix) {
syslog(syslog_facility | level, "(%s) %s", syslog_prefix, msg);
} else {
syslog(syslog_facility | level, "%s", msg);
}
}
}
if (mask & (kLogCustom0 | kLogCustom1 | kLogCustom2)) {
string fmt_msg(msg);
if (syslog_prefix) fmt_msg = "(" + string(syslog_prefix) + ") " + fmt_msg;
if (!(mask & kLogNoLinebreak)) fmt_msg += "\n";
if (mask & kLogCustom0) LogCustom(0, fmt_msg);
if (mask & kLogCustom1) LogCustom(1, fmt_msg);
if (mask & kLogCustom2) LogCustom(2, fmt_msg);
}
// The log buffer can be read via extended attributes from cvmfs, therefore
// we provide an option to hide entries from the buffer if they contain
// sensitive information
if (!(mask & kLogSensitive))
g_log_buffer.Append(LogBufferEntry(source, mask, msg));
free(msg);
}
std::vector<LogBufferEntry> GetLogBuffer() {
return g_log_buffer.GetBuffer();
}
void ClearLogBuffer() {
g_log_buffer.Clear();
}
void PrintError(const string &message) {
LogCvmfs(kLogCvmfs, kLogStderr, "[ERROR] %s", message.c_str());
}
void PrintWarning(const string &message) {
LogCvmfs(kLogCvmfs, kLogStderr, "[WARNING] %s", message.c_str());
}
/**
* Opens a custom log file
*/
void SetLogCustomFile(unsigned id, const std::string &filename) {
assert(id < kMaxCustomlog);
pthread_mutex_lock(&customlog_locks[id]);
if (customlog_fds[id] >= 0) {
close(customlog_fds[id]);
customlog_fds[id] = -1;
}
if (filename.empty()) {
delete customlog_dests[id];
customlog_dests[id] = NULL;
pthread_mutex_unlock(&customlog_locks[id]);
return;
}
customlog_fds[id] = open(filename.c_str(), O_RDWR | O_APPEND | O_CREAT, 0600);
if (customlog_fds[id] < 0) {
LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
"could not open log file %s (%d), aborting",
filename.c_str(), errno);
abort();
}
delete customlog_dests[id];
customlog_dests[id] = new string(filename);
pthread_mutex_unlock(&customlog_locks[id]);
}
static void LogCustom(unsigned id, const std::string &message) {
assert(id < kMaxCustomlog);
if (message.size() == 0) return;
pthread_mutex_lock(&customlog_locks[id]);
assert(customlog_fds[id] >= 0);
bool retval_b = SafeWrite(customlog_fds[id], message.data(), message.size());
if (!retval_b) {
LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,
"could not write into log file %s (%d), aborting - lost: %s",
customlog_dests[id]->c_str(), errno, message.c_str());
abort();
}
int retval_i = fsync(customlog_fds[id]);
assert(retval_i == 0);
pthread_mutex_unlock(&customlog_locks[id]);
}
void LogShutdown() {
SetLogMicroSyslog("");
for (unsigned i = 0; i < kMaxCustomlog; ++i)
SetLogCustomFile(i, "");
}
#ifdef CVMFS_NAMESPACE_GUARD
} // namespace CVMFS_NAMESPACE_GUARD
#endif
| {'content_hash': '6efeb1cfa2a8b17e2cfd723ceb99ed0f', 'timestamp': '', 'source': 'github', 'line_count': 604, 'max_line_length': 80, 'avg_line_length': 26.582781456953644, 'alnum_prop': 0.6258719481813653, 'repo_name': 'DrDaveD/cvmfs', 'id': '119ab041aefd71fa86e8ee7362889a230b7e5e9e', 'size': '16057', 'binary': False, 'copies': '1', 'ref': 'refs/heads/devel', 'path': 'cvmfs/logging.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '122210'}, {'name': 'C++', 'bytes': '5160957'}, {'name': 'CMake', 'bytes': '159436'}, {'name': 'Dockerfile', 'bytes': '4438'}, {'name': 'Go', 'bytes': '346733'}, {'name': 'Makefile', 'bytes': '10684'}, {'name': 'Perl', 'bytes': '408977'}, {'name': 'Python', 'bytes': '137438'}, {'name': 'Rich Text Format', 'bytes': '4619'}, {'name': 'Ruby', 'bytes': '514'}, {'name': 'Shell', 'bytes': '690759'}, {'name': 'Smarty', 'bytes': '6811'}]} |
cask v1: 'dash' do
version :latest
sha256 :no_check
url 'https://newyork.kapeli.com/downloads/v3/Dash.zip'
appcast 'https://kapeli.com/Dash3.xml'
name 'Dash'
homepage 'https://kapeli.com/dash'
license :commercial
app 'Dash.app'
postflight do
suppress_move_to_applications
end
zap delete: [
'~/Library/Application Support/Dash',
'~/Library/Preferences/com.kapeli.dash.plist',
'~/Library/Preferences/com.kapeli.dashdoc.plist',
]
end
| {'content_hash': '40da2dcd0233d8946ec8d98ea7e864fa', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 67, 'avg_line_length': 24.181818181818183, 'alnum_prop': 0.6146616541353384, 'repo_name': 'askl56/homebrew-cask', 'id': 'bd64ec8e5d42e1b9c12a19c270f1d4c2be128e02', 'size': '532', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Casks/dash.rb', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Ruby', 'bytes': '1673717'}, {'name': 'Shell', 'bytes': '59881'}]} |
local rostermanager = require "core.rostermanager";
local datamanager = require "util.datamanager";
local jid = require "util.jid";
local DBI;
local connection;
local bare_sessions = bare_sessions;
local params = module:get_option("wordpress");
local module_host = module:get_host();
function load_contacts()
local groups = { default = {} };
local members = { };
local load_groups_sql = string.format("select ID id, groupname name from %suam_accessgroups", params.prefix);
local load_groups_stmt = connection:prepare(load_groups_sql);
if load_groups_stmt then
load_groups_stmt:execute();
-- Fetch groups
for group_row in load_groups_stmt:rows(true) do
groups[group_row.name] = {};
module:log("debug", "New group: %s", tostring(group_row.name));
-- Match user with group
local object_id_sql = string.format("select object_id from %suam_accessgroup_to_object where `group_id` = ?;", params.prefix);
local object_id_stmt = connection:prepare(object_id_sql);
if object_id_stmt then
object_id_stmt:execute(group_row.id);
for object_row in object_id_stmt:rows(true) do
-- Fetch user information
local user_sql = string.format("select user_login, display_name from %susers where `ID` = ?;", params.prefix);
local user_stmt = connection:prepare(user_sql);
if user_stmt then
user_stmt:execute(object_row.object_id);
if user_stmt:rowcount() > 0 then
local user_row = user_stmt:fetch(true);
bare_jid = string.format("%s@%s", user_row.user_login, module_host);
groups[group_row.name][bare_jid] = user_row.display_name or false;
members[bare_jid] = members[bare_jid] or {};
members[bare_jid][#members[bare_jid] + 1] = group_row.name;
module:log("debug", "New member of %s: %s", group_row.name, bare_jid);
end
user_stmt:close();
end
end
object_id_stmt:close();
end
end
load_groups_stmt:close();
end
module:log("info", "Groups loaded successfully");
return groups, members;
end
function inject_roster_contacts(username, host, roster)
local groups, members = load_contacts();
local user_jid = username.."@"..host;
module:log("debug", "Injecting group members to roster %s", user_jid);
if not members[user_jid] and not members[false] then return; end -- Not a member of any groups
local function import_jids_to_roster(group_name, groups)
for member_jid in pairs(groups[group_name]) do
-- Add them to roster
module:log("debug", "processing jid %s in group %s", tostring(member_jid), tostring(group_name));
if member_jid ~= user_jid then
if not roster[member_jid] then roster[member_jid] = {}; end
roster[member_jid].subscription = "both";
if groups[group_name][member_jid] then
roster[member_jid].name = groups[group_name][member_jid];
end
if not roster[member_jid].groups then
roster[member_jid].groups = { [group_name] = true };
end
roster[member_jid].groups[group_name] = true;
roster[member_jid].persist = false;
end
end
end
-- Find groups this JID is a member of
if members[user_jid] then
for _, group_name in ipairs(members[user_jid]) do
module:log("debug", "Importing group %s", group_name);
import_jids_to_roster(group_name, groups);
end
end
-- Import public groups
if members[false] then
for _, group_name in ipairs(members[false]) do
module:log("debug", "Importing group %s", group_name);
import_jids_to_roster(group_name, groups);
end
end
for online_jid, user in pairs(bare_sessions) do
if (online_jid ~= user_jid) and roster[online_jid] then
local other_roster = user.roster;
if not other_roster[user_jid] then
-- Don't need to make online user see new user but new user can see online user.
other_roster[user_jid] = {
subscription = "both";
persist = false;
};
end
end
end
if roster[false] then
roster[false].version = true;
end
end
function remove_virtual_contacts(username, host, datastore, data)
if host == module_host and datastore == "roster" then
local new_roster = {};
for jid, contact in pairs(data) do
if contact.persist ~= false then
new_roster[jid] = contact;
end
end
if new_roster[false] then
new_roster[false].version = nil; -- Version is void
end
return username, host, datastore, new_roster;
end
return username, host, datastore, data;
end
function module.load()
if params == nil then
-- Don't load this module to virtual host doesn't have wordpress option
return;
end;
initial_connection();
groups_wordpress_enable = params.groups
if not groups_wordpress_enable then return; end
module:hook("roster-load", inject_roster_contacts);
datamanager.add_callback(remove_virtual_contacts);
end
function module.unload()
datamanager.remove_callback(remove_virtual_contacts);
end
-- database methods from mod_storage_sql.lua
local function test_connection()
if not connection then return nil; end
if connection:ping() then
return true;
else
module:log("debug", "Database connection closed");
connection = nil;
end
end
local function connect()
if not test_connection() then
prosody.unlock_globals();
local dbh, err = DBI.Connect(
"MySQL", params.database,
params.username, params.password,
params.host, params.port
);
prosody.lock_globals();
if not dbh then
module:log("debug", "Database connection failed: %s", tostring(err));
return nil, err;
end
module:log("debug", "Successfully connected to database");
dbh:autocommit(false); -- don't commit automatically
connection = dbh;
return connection;
end
end
function initial_connection()
local ok;
prosody.unlock_globals();
ok, DBI = pcall(require, "DBI");
if not ok then
package.loaded["DBI"] = {};
module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI);
module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi");
end
prosody.lock_globals();
if not ok or not DBI.Connect then
return; -- Halt loading of this module
end
params.host = params.host or "localhost";
params.port = params.port or 3306;
params.database = params.database or "wordpress";
params.username = params.username or "root";
params.password = params.password or "";
params.prefix = params.prefix or "wp_";
params.groups = params.groups or false;
assert(connect());
end
| {'content_hash': '9bc8edfdedf931a27830bd85d13e92ee', 'timestamp': '', 'source': 'github', 'line_count': 219, 'max_line_length': 132, 'avg_line_length': 31.182648401826484, 'alnum_prop': 0.6498755308244253, 'repo_name': 'llun/wordpress-authenticator', 'id': '7e8e5ac2b99d79e6ba099df7314cfeb9e992e59d', 'size': '6861', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'prosody/mod_groups_wordpress.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Lua', 'bytes': '11291'}, {'name': 'Python', 'bytes': '13183'}]} |
using System;
using System.Drawing;
using System.Linq;
using Emgu.CV.Structure;
using Color = Microsoft.Xna.Framework.Color;
using Point = Microsoft.Xna.Framework.Point;
using Rect = Microsoft.Xna.Framework.Rectangle;
namespace Pentacorn.Vision
{
class Checkers
{
public Size Squares { get { return new Size(M, N); } }
public Size Saddles { get { return new Size(M - 1, N - 1); } }
public Rect Board { get; private set; }
public Size Square { get; private set; }
public Color WhiteColor { get; set; }
public Color BlackColor { get; set; }
public Color OtherColor { get; set; }
public Checkers(int m, int n, Point origin, Size square)
{
if ((m & 1) == (n & 1))
throw new Exception("Checker board must have even/odd M and N or vice versa.");
WhiteColor = Color.White;
BlackColor = Color.Black;
OtherColor = Color.White;
M = m;
N = n;
Square = square;
Board = new Rect(origin.X, origin.Y, M * square.Width, N * square.Height);
}
public PointF[][] GetImagePointsCopy(int num)
{
PointF[][] ops = new PointF[num][];
var m = Saddles.Width;
var n = Saddles.Height;
ops[0] = new PointF[m * n];
for (int y = 0; y < n; ++y)
for (int x = 0; x < m; ++x)
ops[0][y * m + x] = new PointF(Board.Left + (x + 1) * Square.Width, Board.Top + (y + 1) * Square.Height);
for (int i = 1; i < num; ++i)
ops[i] = ops[0].ToArray();
return ops;
}
public MCvPoint3D32f[] GetWorldPointsCopy()
{
var m = Saddles.Width;
var n = Saddles.Height;
var ops = new MCvPoint3D32f[m * n];
for (int y = 0; y < n; ++y)
for (int x = 0; x < m; ++x)
ops[y * m + x] = new MCvPoint3D32f(Board.Left + (x + 1) * Square.Width, Board.Top + (y + 1) * Square.Height, 0);
return ops;
}
private int M;
private int N;
}
}
| {'content_hash': 'ae02ed9e34cb510e4ea8f0858c921780', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 132, 'avg_line_length': 31.323943661971832, 'alnum_prop': 0.49280575539568344, 'repo_name': 'JaapSuter/Pentacorn', 'id': 'bdf199d03ea1187177f347463094ae73002df63b', 'size': '2224', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Backup/Nuke/Checkers.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '1379534'}, {'name': 'FLUX', 'bytes': '10475'}, {'name': 'Shell', 'bytes': '299'}]} |
package org.codice.imaging.jpeg2000;
/**
* Internal (package private) constants
*/
class PackageConstants {
static final int UNSIGNED_BYTE_LENGTH = 1;
static final int UNSIGNED_SHORT_LENGTH = 2;
static final int UNSIGNED_INT_LENGTH = 4;
static final int BOX_SIGNATURE_LENGTH = 4;
}
| {'content_hash': 'adf2dad1ebe55d053d1c5e20048c9832', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 47, 'avg_line_length': 23.615384615384617, 'alnum_prop': 0.7003257328990228, 'repo_name': 'bradh/codice-imaging-jpeg2000', 'id': '9a23a702b8511a49398783a09793b48ff1d7ec48', 'size': '1436', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/codice/imaging/jpeg2000/PackageConstants.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '55657'}]} |
puppet apply --modulepath=/src/zabbix-server/clean/modules /src/zabbix-server/clean/clean.pp
| {'content_hash': '34c411e3bbcd24a8eb378da4e6d2afe3', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 92, 'avg_line_length': 93.0, 'alnum_prop': 0.8064516129032258, 'repo_name': 'viljaste/docker-zabbix-server', 'id': '9fb8216b2c175224ba43f529bdf6a0dc8386c4cf', 'size': '114', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/zabbix-server/clean.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '14271'}, {'name': 'JavaScript', 'bytes': '2293'}, {'name': 'Puppet', 'bytes': '7858'}, {'name': 'Shell', 'bytes': '2879'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '90b7e190964ebcf83815ffc9cfb9c3e9', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '007ced56fd1b6aa8f34156a71a10dab457806b8b', 'size': '187', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Eriocephalus kingesii/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
"""
Interface with wcs.
Adapted from fermipy.skymap
"""
__author__ = "Alex Drlica-Wagner"
import numpy as np
from astropy.wcs import WCS
from astropy.io import fits
from astropy.coordinates import SkyCoord
def create_wcs(skydir, coordsys='CEL', projection='AIT',
cdelt=1.0, crpix=1., naxis=2, energies=None):
"""Create a WCS object.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate of the WCS reference point.
coordsys : str
projection : str
cdelt : float
crpix : float or (float,float)
In the first case the same value is used for x and y axes
naxis : {2, 3}
Number of dimensions of the projection.
energies : array-like
Array of energies that defines the third dimension if naxis=3.
"""
w = WCS(naxis=naxis)
if coordsys == 'CEL':
w.wcs.ctype[0] = 'RA---%s' % (projection)
w.wcs.ctype[1] = 'DEC--%s' % (projection)
w.wcs.crval[0] = skydir.icrs.ra.deg
w.wcs.crval[1] = skydir.icrs.dec.deg
elif coordsys == 'GAL':
w.wcs.ctype[0] = 'GLON-%s' % (projection)
w.wcs.ctype[1] = 'GLAT-%s' % (projection)
w.wcs.crval[0] = skydir.galactic.l.deg
w.wcs.crval[1] = skydir.galactic.b.deg
else:
raise Exception('Unrecognized coordinate system.')
try:
w.wcs.crpix[0] = crpix[0]
w.wcs.crpix[1] = crpix[1]
except IndexError:
w.wcs.crpix[0] = crpix
w.wcs.crpix[1] = crpix
w.wcs.cdelt[0] = -cdelt
w.wcs.cdelt[1] = cdelt
w = WCS(w.to_header())
if naxis == 3 and energies is not None:
w.wcs.crpix[2] = 1
w.wcs.crval[2] = energies[0]
w.wcs.cdelt[2] = energies[1] - energies[0]
w.wcs.ctype[2] = 'Energy'
w.wcs.cunit[2] = 'MeV'
return w
def create_image_wcs(skydir, cdelt, npix, coordsys='CEL', projection='AIT'):
"""Create a blank image and associated WCS object
"""
if np.isscalar(npix):
npix = [npix, npix]
crpix = np.array([n / 2. + 0.5 for n in npix])
wcs = create_wcs(skydir, coordsys, projection, cdelt, crpix)
return np.zeros(npix).T, wcs
def get_pixel_skydirs(npix, wcs):
"""Get a list of sky coordinates for the centers of every pixel.
"""
if np.isscalar(npix):
npix = [npix, npix]
xpix = np.linspace(0, npix[0] - 1., npix[0])
ypix = np.linspace(0, npix[1] - 1., npix[1])
xypix = np.meshgrid(xpix, ypix, indexing='ij')
return SkyCoord.from_pixel(np.ravel(xypix[0]),
np.ravel(xypix[1]), wcs)
def create_image_hdu(data, wcs, name=None):
"""Create a `astropy.io.fits.ImageHDU` object
"""
if name is None:
return fits.PrimaryHDU(data, header=wcs.to_header())
return fits.ImageHDU(data, header=wcs.to_header(),
name=name)
def write_image_hdu(filename, data, wcs, name=None, clobber=False):
"""Write an image to a file
"""
hdu = create_image_hdu(data, wcs, name)
hdu.writeto(filename, clobber=clobber)
| {'content_hash': '214013fe69e6a4dcc9371cb857670ea9', 'timestamp': '', 'source': 'github', 'line_count': 102, 'max_line_length': 76, 'avg_line_length': 30.08823529411765, 'alnum_prop': 0.5936787227109808, 'repo_name': 'kadrlica/dmsky', 'id': 'ef8c27beb81a9cee82e381540fe6919a09dcf29f', 'size': '3091', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dmsky/utils/wcs.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '215229'}]} |
/*
-------------------------------------------------------------------------------------------------------------------------------------------
redmark/examples/jobs/add_one_job.js
July 2nd, 2011
Redmark v1.0.0
Note: Assumes redmark has been installed through npm
Description:
An example demonstrating different ways to add a single job
-------------------------------------------------------------------------------------------------------------------------------------------
Redmark uses a SHA1 hash of the string representation of the function passed in to geneate a unique id to identify that
job. This allows you to later add jobs to a queue with either that unique id or with a copy of the function. This also serves
to prevent collisions that could affect the validity of each queue.
Both of the examples below achieve the same result.
*/
/* Option 1: inline the function that will be doing the work */
var queue = require("redmark");
var jobid = queue.seed(function() {
console.log("get to work!");
});
queue.add(jobid);
/* Option 2: pass in a function by reference */
var queue = require("redmark");
var work = function() {
console.log("get to work!");
};
var jobid = queue.seed(work);
queue.add(jobid); | {'content_hash': 'df5676e92cb8c774eacd0182c73fd741', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 139, 'avg_line_length': 37.3235294117647, 'alnum_prop': 0.5508274231678487, 'repo_name': 'benjisg/redmark', 'id': '67905107ba4a669094ef796e675106621011feab', 'size': '1269', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/jobs/add_one_job.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '13954'}]} |
package com.taobao.weex.devtools.inspector.protocol.module;
import android.content.Context;
import android.content.Intent;
import com.taobao.weex.WXEnvironment;
import com.taobao.weex.WXSDKEngine;
import com.taobao.weex.common.IWXDebugProxy;
import com.taobao.weex.devtools.debug.DebugBridge;
import com.taobao.weex.devtools.inspector.jsonrpc.JsonRpcPeer;
import com.taobao.weex.devtools.inspector.protocol.ChromeDevtoolsDomain;
import com.taobao.weex.devtools.inspector.protocol.ChromeDevtoolsMethod;
import com.taobao.weex.devtools.json.ObjectMapper;
import com.taobao.weex.devtools.json.annotation.JsonProperty;
import org.json.JSONObject;
import java.util.List;
/**
* Created by budao on 16/6/24.
*/
public class WxDebug implements ChromeDevtoolsDomain {
private static final String TAG = "WxDebug";
private final ObjectMapper mObjectMapper = new ObjectMapper();
public WxDebug() {
}
@ChromeDevtoolsMethod
public void callNative(JsonRpcPeer peer, JSONObject params) {
if (params != null) {
DebugBridge.getInstance().callNative(
params.optString("instance"),
params.optString("tasks"),
params.optString("callback"));
}
// another way to handle call native
// CallNative callNative = mObjectMapper.convertValue(params, CallNative.class);
// if (callNative != null) {
// try {
// String tasks = mObjectMapper.convertListToJsonArray(callNative.tasks).toString();
// Log.v(TAG, "WxDebug.callNative tasks " + tasks);
// DebugBridge.getInstance().callNative(callNative.instance,
// tasks,
// callNative.callback);
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// }
}
@ChromeDevtoolsMethod
public void reload(JsonRpcPeer peer, JSONObject params) {
WXSDKEngine.reload();
Context context = WXEnvironment.getApplication();
if (context != null) {
context.sendBroadcast(new Intent(IWXDebugProxy.ACTION_DEBUG_INSTANCE_REFRESH));
}
}
public static class CallNative {
@JsonProperty(required = true)
public String instance;
@JsonProperty(required = true)
public String callback;
@JsonProperty(required = true)
public List<Task> tasks;
}
public static class CallJS {
@JsonProperty(required = true)
public String method;
@JsonProperty(required = true)
public List<Object> args;
}
public static class Task {
@JsonProperty(required = true)
public String module;
@JsonProperty(required = true)
public String method;
@JsonProperty(required = true)
public List<String> args;
}
}
| {'content_hash': 'd3e23c1a0f006840191fe5e32c71f5e0', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 99, 'avg_line_length': 33.13333333333333, 'alnum_prop': 0.6428571428571429, 'repo_name': 'houfeng0923/weex', 'id': '22e195714bdd45ed92a066964a1672913d4ea184', 'size': '2982', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'android/inspector/src/main/java/com/taobao/weex/devtools/inspector/protocol/module/WxDebug.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '54186'}, {'name': 'CSS', 'bytes': '19569'}, {'name': 'HTML', 'bytes': '6747'}, {'name': 'IDL', 'bytes': '85'}, {'name': 'Java', 'bytes': '5566911'}, {'name': 'JavaScript', 'bytes': '3720731'}, {'name': 'Objective-C', 'bytes': '1209782'}, {'name': 'Ruby', 'bytes': '2294'}, {'name': 'Shell', 'bytes': '6289'}]} |
<?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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SWING</groupId>
<artifactId>SWING</artifactId>
<version>1.0-SNAPSHOT</version>
</project> | {'content_hash': 'dfd26a4aaf432f7e7976a7fdb5dc3268', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 108, 'avg_line_length': 34.5, 'alnum_prop': 0.6666666666666666, 'repo_name': 'rch9/oracle-sql-spbstu', 'id': '1c2a4f7a0e04e7e1af2ec54dc83d9cdac07c07eb', 'size': '414', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SWING/pom.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '10711'}, {'name': 'PLSQL', 'bytes': '47582'}]} |
import pytest
def test_get_index(app):
test_app = app.test_client()
response = test_app.get('/')
assert response.status_code == 200
| {'content_hash': '1e2e7a9ffbaf03ef5f11977ab80c3948', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 38, 'avg_line_length': 20.857142857142858, 'alnum_prop': 0.6506849315068494, 'repo_name': 'SuddenDevs/SuddenDev', 'id': 'dd627782106d76e80ff6d6d0a51e71cbec3c867d', 'size': '146', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/test_suddendev.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2357'}, {'name': 'HTML', 'bytes': '91153'}, {'name': 'JavaScript', 'bytes': '140'}, {'name': 'Python', 'bytes': '85434'}, {'name': 'Shell', 'bytes': '964'}]} |
import {Property} from '../backend/utils/description';
export interface EventListener {
name: string;
callback: Function;
}
export interface Node {
id: string;
isComponent: boolean;
changeDetection: string;
description: Array<Property>;
nativeElement: () => HTMLElement; // null on frontend
listeners: Array<EventListener>;
dependencies: Array<string>;
directives: Array<string>;
injectors: Array<string>;
providers: Array<Property>;
input: Array<string>;
output: Array<string>;
source: string;
name: string;
children: Array<Node>;
properties: {
[key: string]: any;
};
attributes: {
[key: string]: string;
};
classes: {
[key: string]: boolean;
};
styles: {
[key: string]: string;
};
}
| {'content_hash': '3add9b7568e47ae7584b0d3ea7b1c966', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 55, 'avg_line_length': 21.13888888888889, 'alnum_prop': 0.6557161629434954, 'repo_name': 'clbond/augury', 'id': '4d0f84accd408a2c0016c4836612e32e09ced1f9', 'size': '761', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'src/tree/node.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13802'}, {'name': 'HTML', 'bytes': '29049'}, {'name': 'JavaScript', 'bytes': '10210'}, {'name': 'Shell', 'bytes': '3245'}, {'name': 'TypeScript', 'bytes': '962635'}]} |
package org.kodejava.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class DisableCloseButtonDemo extends JFrame {
public DisableCloseButtonDemo() throws HeadlessException {
initialize();
}
private void initialize() {
// WindowConstants.DO_NOTHING_ON_CLOSE tell JFrame instance to do
// nothing when a window closing event occurs.
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
JButton button = new JButton("Close");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setSize(new Dimension(100, 100));
this.getContentPane().add(button);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisableCloseButtonDemo().setVisible(true);
}
});
}
}
| {'content_hash': '23c032c05e18aab3186d1adb46c0b734', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 75, 'avg_line_length': 30.7027027027027, 'alnum_prop': 0.6408450704225352, 'repo_name': 'kodejava/kodejava.project', 'id': 'd5f7eacd4387be59fdeb2c96f98a8d0e400ead31', 'size': '1136', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kodejava-swing/src/main/java/org/kodejava/example/swing/DisableCloseButtonDemo.java', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'HTML', 'bytes': '40950'}, {'name': 'Java', 'bytes': '822524'}, {'name': 'JavaScript', 'bytes': '25'}]} |
FROM balenalib/jetson-tx2-debian:stretch-build
# A few reasons for installing distribution-provided OpenJDK:
#
# 1. Oracle. Licensing prevents us from redistributing the official JDK.
#
# 2. Compiling OpenJDK also requires the JDK to be installed, and it gets
# really hairy.
#
# For some sample build times, see Debian's buildd logs:
# https://buildd.debian.org/status/logs.php?pkg=openjdk-8
RUN apt-get update && apt-get install -y --no-install-recommends \
bzip2 \
unzip \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
# Default to UTF-8 file.encoding
ENV LANG C.UTF-8
# add a simple script that can auto-detect the appropriate JAVA_HOME value
# based on whether the JDK or only the JRE is installed
RUN { \
echo '#!/bin/sh'; \
echo 'set -e'; \
echo; \
echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \
} > /usr/local/bin/docker-java-home \
&& chmod +x /usr/local/bin/docker-java-home
# do some fancy footwork to create a JAVA_HOME that's cross-architecture-safe
RUN ln -svT "/usr/lib/jvm/java-8-openjdk-$(dpkg --print-architecture)" /docker-java-home
ENV JAVA_HOME /docker-java-home
RUN set -ex; \
\
# deal with slim variants not having man page directories (which causes "update-alternatives" to fail)
if [ ! -d /usr/share/man/man1 ]; then \
mkdir -p /usr/share/man/man1; \
fi; \
\
apt-get update; \
apt-get install -y --no-install-recommends \
openjdk-8-jdk-headless \
; \
rm -rf /var/lib/apt/lists/*; \
\
# verify that "docker-java-home" returns what we expect
[ "$(readlink -f "$JAVA_HOME")" = "$(docker-java-home)" ]; \
\
# update-alternatives so that future installs of other OpenJDK versions don't change /usr/bin/java
update-alternatives --get-selections | awk -v home="$(readlink -f "$JAVA_HOME")" 'index($3, home) == 1 { $2 = "manual"; print | "update-alternatives --set-selections" }'; \
# ... and verify that it actually worked for one of the alternatives we care about
update-alternatives --query java | grep -q 'Status: manual'
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Stretch \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v8-jdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {'content_hash': 'bdfcf10ccadde2e1b25618d3e058aa48', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 679, 'avg_line_length': 48.15625, 'alnum_prop': 0.6998702141466581, 'repo_name': 'nghiant2710/base-images', 'id': '1bba8bdda08ff4669eb5b8a54ddcf1d4250df1ec', 'size': '3103', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'balena-base-images/openjdk/jetson-tx2/debian/stretch/8-jdk/build/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]} |
require 'spec_helper'
describe MandrillDm::DeliveryMethod do
let(:options) { { 'some_option_key' => 'some option value' } }
let(:delivery_method) { MandrillDm::DeliveryMethod.new(options) }
context '#initialize' do
it 'sets passed options to `settings` attr_accesor' do
expect(delivery_method.settings).to eql(options)
end
end
context '#deliver!' do
let(:mail_message) { instance_double(Mail::Message) }
let(:api_key) { '1234567890' }
let(:async) { false }
let(:dm_message) { instance_double(MandrillDm::Message) }
let(:response) { { 'some_response_key' => 'some response value' } }
let(:msgs_methods) { { send: response, send_template: response } }
let(:messages) { instance_double(Mandrill::Messages, msgs_methods) }
let(:api) { instance_double(Mandrill::API, messages: messages) }
before(:each) do
allow(Mandrill::API).to receive(:new).and_return(api)
allow(dm_message).to receive(:template).and_return(nil)
allow(MandrillDm).to receive_message_chain(
:configuration,
:api_key
).and_return(api_key)
allow(MandrillDm).to receive_message_chain(:configuration, :async).and_return(async)
allow(MandrillDm::Message).to receive(:new).and_return(dm_message)
end
subject { delivery_method.deliver!(mail_message) }
it 'instantiates the Mandrill API with the configured API key' do
expect(Mandrill::API).to receive(:new).with(api_key).and_return(api)
subject
end
it 'creates a Mandrill message from the Mail message' do
expect(MandrillDm::Message).to(
receive(:new).with(mail_message).and_return(dm_message)
)
subject
end
it 'sends the JSON version of the Mandrill message via the API' do
allow(dm_message).to receive(:to_json).and_return('Some message JSON')
expect(messages).to receive(:send).with('Some message JSON', false)
subject
end
it 'returns the response from sending the message' do
expect(subject).to eql(response)
end
it 'establishes the response for subsequent use' do
subject
expect(delivery_method.response).to eql(response)
end
describe 'with template' do
let!(:template_slug) { 'some-template-slug' }
let!(:html) { '<some>html</some>' }
let!(:message_json) { { html: html } }
before(:each) do
allow(dm_message).to receive(:to_json).and_return(message_json)
allow(dm_message).to receive(:template).and_return(template_slug)
allow(dm_message).to receive(:template_content).and_return(
[
name: 'body',
content: html
]
)
end
it 'sends the JSON version of the Mandrill Template message via the API' do
template_content = [{
name: 'body',
content: html
}]
expect(messages).to(
receive(:send_template).with(
template_slug,
template_content,
message_json,
async
)
)
subject
end
it 'establishes the response for subsequent use' do
subject
expect(delivery_method.response).to eql(response)
end
end
end
end
| {'content_hash': 'd930f25466d8446e90f23c804c78d52d', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 90, 'avg_line_length': 30.416666666666668, 'alnum_prop': 0.6161339421613394, 'repo_name': 'Sysqa/mandrill_dm', 'id': 'ec642d3c31ebec40c43a0976b8c74835512ac46a', 'size': '3285', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/mandrill_dm/delivery_method_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '35649'}]} |
<?php
namespace Lazer\Classes;
use Lazer\Classes\LazerException;
use Lazer\Classes\Database;
use Lazer\Classes\Relation;
use Lazer\Classes\Helpers;
abstract class Core_Database implements \IteratorAggregate, \Countable {
/**
* Contain returned data from file as object or array of objects
* @var mixed Data from table
*/
protected $data;
/**
* Name of file (table)
* @var string Name of table
*/
protected $name;
/**
* Object with setted data
* @var object Setted data
*/
protected $set;
/**
* ID of current row if setted
* @var integer Current ID
*/
protected $currentId;
/**
* Key if current row if setted
* @var integer Current key
*/
protected $currentKey;
/**
* Pending functions with values
* @see \Lazer\Classes\Core_Database::setPending()
* @var array
*/
protected $pending;
/**
* Information about to reset keys in array or not to
* @var integer
*/
protected $resetKeys = 1;
/**
* Factory pattern
* @param string $name Name of table
* @return \Lazer\Classes\Database
* @throws LazerException If there's problems with load file
*/
public static function table($name)
{
Helpers\Validate::table($name)->exists();
$self = new Database;
$self->name = $name;
$self->setFields();
$self->setPending();
return $self;
}
/**
* Get rows from table
* @uses Lazer\Classes\Helpers\Data::get() to get data from file
* @return array
*/
protected function getData()
{
return Helpers\Data::table($this->name)->get();
}
/**
* Setting data to Database::$data
*/
protected function setData()
{
$this->data = $this->getData();
}
/**
* Returns array key of row with specified ID
* @param integer $id Row ID
* @return integer Row key
* @throws LazerException If there's no data with that ID
*/
protected function getRowKey($id)
{
foreach ($this->getData() as $key => $data)
{
if ($data->id == $id)
{
return $key;
break;
}
}
throw new LazerException('No data found with ID: ' . $id);
}
/**
* Set NULL for currentId and currentKey
*/
protected function clearKeyInfo()
{
$this->currentId = $this->currentKey = NULL;
}
/**
* Setting fields with default values
* @uses Lazer\Classes\Helpers\Validate::isNumeric() to check if type of field is numeric
*/
protected function setFields()
{
$this->set = new \stdClass();
$schema = $this->schema();
foreach ($schema as $field => $type)
{
if (Helpers\Validate::isNumeric($type) AND $field != 'id')
{
$this->set->{$field} = 0;
}
else
{
$this->set->{$field} = null;
}
}
}
/**
* Set pending functions in right order with default values (Empty).
*/
protected function setPending()
{
$this->pending = array(
'where' => array(),
'orderBy' => array(),
'limit' => array(),
'with' => array(),
'groupBy' => array(),
);
}
/**
* Clear info about previous queries
*/
protected function clearQuery()
{
$this->setPending();
$this->clearKeyInfo();
}
/**
* Validating fields and setting variables to current operations
* @uses Lazer\Classes\Helpers\Validate::field() to check that field exist
* @uses Lazer\Classes\Helpers\Validate::type() to check that field type is correct
* @param string $name Field name
* @param mixed $value Field value
*/
public function __set($name, $value)
{
if (Helpers\Validate::table($this->name)->field($name) && Helpers\Validate::table($this->name)->type($name, $value))
{
$this->set->{$name} = $value;
}
}
/**
* Returning variable from Object
* @param string $name Field name
* @return mixed Field value
*/
public function __get($name)
{
if (isset($this->set->{$name}))
return $this->set->{$name};
throw new LazerException('There is no data');
}
/**
* Check if the given field exists
* @param string $name Field name
* @return boolean True if the field exists, false otherwise
*/
public function __isset($name)
{
return isset($this->set->{$name});
}
/**
* Execute pending functions
*/
protected function pending()
{
$this->setData();
foreach ($this->pending as $func => $args)
{
if (!empty($args))
{
call_user_func(array($this, $func . 'Pending'));
}
}
//clear pending values after executed query
$this->clearQuery();
}
/**
* Creating new table
*
* For example few fields:
*
* Database::create('news', array(
* 'title' => 'string',
* 'content' => 'string',
* 'rating' => 'double',
* 'author' => 'integer'
* ));
*
* Types of field:
* - boolean
* - integer
* - string
* - double (also for float type)
*
* ID field isn't required (it will be created automatically) but you can specify it at first place.
*
* @uses Lazer\Classes\Helpers\Data::arrToLower() to lower case keys and values of array
* @uses Lazer\Classes\Helpers\Data::exists() to check if data file exists
* @uses Lazer\Classes\Helpers\Config::exists() to check if config file exists
* @uses Lazer\Classes\Helpers\Validate::types() to check if type of fields are correct
* @uses Lazer\Classes\Helpers\Data::put() to save data file
* @uses Lazer\Classes\Helpers\Config::put() to save config file
* @param string $name Table name
* @param array $fields Field configuration
* @throws LazerException If table exist
*/
public static function create($name, array $fields)
{
$fields = Helpers\Validate::arrToLower($fields);
if (Helpers\Data::table($name)->exists() && Helpers\Config::table($name)->exists())
{
throw new LazerException('helper\Table "' . $name . '" already exists');
}
$types = array_values($fields);
Helpers\Validate::types($types);
if (!array_key_exists('id', $fields))
{
$fields = array('id' => 'integer') + $fields;
}
$data = new \stdClass();
$data->last_id = 0;
$data->schema = $fields;
$data->relations = new \stdClass();
Helpers\Data::table($name)->put(array());
Helpers\Config::table($name)->put($data);
}
/**
* Removing table with config
* @uses Lazer\Classes\Helpers\Data::remove() to remove data file
* @uses Lazer\Classes\Helpers\Config::remove() to remove config file
* @param string $name Table name
* @return boolean|LazerException
*/
public static function remove($name)
{
if (Helpers\Data::table($name)->remove() && Helpers\Config::table($name)->remove())
{
return TRUE;
}
}
/**
* Grouping results by one field
* @param string $column
* @return \Lazer\Classes\Core_Database
*/
public function groupBy($column)
{
if (Helpers\Validate::table($this->name)->field($column))
{
$this->resetKeys = 0;
$this->pending[__FUNCTION__] = $column;
}
return $this;
}
/**
* Grouping array pending method
*/
protected function groupByPending()
{
$column = $this->pending['groupBy'];
$grouped = array();
foreach ($this->data as $object)
{
$grouped[$object->{$column}][] = $object;
}
$this->data = $grouped;
}
/**
* JOIN other tables
* @param string $table relations separated by :
* @return \Lazer\Classes\Core_Database
*/
public function with($table)
{
$this->pending['with'][] = explode(':', $table);
return $this;
}
/**
* Pending function for with(), joining other tables to current
*/
protected function withPending()
{
$joins = $this->pending['with'];
foreach ($joins as $join)
{
$local = (count($join) > 1) ? array_slice($join, -2, 1)[0] : $this->name;
$foreign = end($join);
$relation = Relation::table($local)->with($foreign);
$data = $this->data;
foreach ($join as $part)
{
$data = $relation->build($data, $part);
}
}
}
/**
* Sorting data by field
* @param string $key Field name
* @param string $direction ASC|DESC
* @return \Lazer\Classes\Core_Database
*/
public function orderBy($key, $direction = 'ASC')
{
if (Helpers\Validate::table($this->name)->field($key))
{
$directions = array(
'ASC' => SORT_ASC,
'DESC' => SORT_DESC
);
$this->pending[__FUNCTION__][$key] = isset($directions[$direction]) ? $directions[$direction] : 'ASC';
}
return $this;
}
/**
* Sort an array of objects by more than one field.
* @
* @link http://blog.amnuts.com/2011/04/08/sorting-an-array-of-objects-by-one-or-more-object-property/ It's not mine algorithm
*/
protected function orderByPending()
{
$properties = $this->pending['orderBy'];
uasort($this->data, function($a, $b) use ($properties)
{
foreach ($properties as $column => $direction)
{
if (is_int($column))
{
$column = $direction;
$direction = SORT_ASC;
}
$collapse = function($node, $props)
{
if (is_array($props))
{
foreach ($props as $prop)
{
$node = (!isset($node->$prop)) ? null : $node->$prop;
}
return $node;
}
else
{
return (!isset($node->$props)) ? null : $node->$props;
}
};
$aProp = $collapse($a, $column);
$bProp = $collapse($b, $column);
if ($aProp != $bProp)
{
return ($direction == SORT_ASC) ? strnatcasecmp($aProp, $bProp) : strnatcasecmp($bProp, $aProp);
}
}
return FALSE;
});
}
/**
* Where function, like SQL
*
* Operators:
* - Standard operators (=, !=, >, <, >=, <=)
* - IN (only for array value)
* - NOT IN (only for array value)
*
* @param string $field Field name
* @param string $op Operator
* @param mixed $value Field value
* @return \Lazer\Classes\Core_Database
*/
public function where($field, $op, $value)
{
$this->pending['where'][] = array(
'type' => 'and',
'field' => $field,
'op' => $op,
'value' => $value,
);
return $this;
}
/**
* Alias for where()
* @param string $field Field name
* @param string $op Operator
* @param mixed $value Field value
* @return \Lazer\Classes\Core_Database
*/
public function andWhere($field, $op, $value)
{
$this->where($field, $op, $value);
return $this;
}
/**
* Alias for where(), setting OR for searching
* @param string $field Field name
* @param string $op Operator
* @param mixed $value Field value
* @return \Lazer\Classes\Core_Database
*/
public function orWhere($field, $op, $value)
{
$this->pending['where'][] = array(
'type' => 'or',
'field' => $field,
'op' => $op,
'value' => $value,
);
return $this;
}
/**
* Filter function for array_filter() in where()
* @param object $row
* @return boolean
*/
protected function wherePending()
{
$operator = array(
'=' => '==',
'!=' => '!=',
'>' => '>',
'<' => '<',
'>=' => '>=',
'<=' => '<=',
'and' => '&&',
'or' => '||'
);
$this->data = array_filter($this->data, function($row) use ($operator)
{
$clause = '';
$result = true;
foreach ($this->pending['where'] as $key => $condition)
{
extract($condition);
if (is_array($value) && $op == 'IN')
{
$value = (in_array($row->{$field}, $value)) ? 1 : 0;
$op = '==';
$field = 1;
}
elseif (!is_array($value) && in_array($op, array('LIKE', 'like')))
{
$regex = "/^" . str_replace('%', '(.*?)', preg_quote($value)) . "$/si";
$value = preg_match($regex, $row->{$field});
$op = '==';
$field = 1;
}
elseif (!is_array($value) && $op != 'IN')
{
$value = is_string($value) ?
'\'' . mb_strtolower($value) . '\'' :
$value;
$op = $operator[$op];
$field = is_string($row->{$field}) ?
'mb_strtolower($row->' . $field .')' :
'$row->' . $field;
}
$type = (!$key) ?
null :
$operator[$type];
$query = array($type, $field, $op, $value);
$clause .= implode(' ', $query) . ' ';
eval('$result = ' . $clause . ';');
}
return $result;
});
}
/**
* Returning data as indexed or assoc array.
* @param string $key Field that will be the key, NULL for Indexed
* @param string $value Field that will be the value
* @return array
*/
public function asArray($key = null, $value = null)
{
if (!is_null($key))
{
Helpers\Validate::table($this->name)->field($key);
}
if (!is_null($value))
{
Helpers\Validate::table($this->name)->field($value);
}
$datas = array();
if (!$this->resetKeys)
{
if (is_null($key) && is_null($value))
{
return $this->data;
}
else
{
foreach ($this->data as $rowKey => $data)
{
$datas[$rowKey] = array();
foreach ($data as $row)
{
if (is_null($key))
{
$datas[$rowKey][] = $row->{$value};
}
elseif (is_null($value))
{
$datas[$rowKey][$row->{$key}] = $row;
}
else
{
$datas[$rowKey][$row->{$key}] = $row->{$value};
}
}
}
}
}
else
{
if (is_null($key) && is_null($value))
{
foreach ($this->data as $data)
{
$datas[] = get_object_vars($data);
}
}
else
{
foreach ($this->data as $data)
{
if (is_null($key))
{
$datas[] = $data->{$value};
}
elseif (is_null($value))
{
$datas[$data->{$key}] = $data;
}
else
{
$datas[$data->{$key}] = $data->{$value};
}
}
}
}
return $datas;
}
/**
* Limit returned data
*
* Should be used at the end of chain, before end method
* @param integer $number Limit number
* @param integer $offset Offset number
* @return \Lazer\Classes\Core_Database
*/
public function limit($number, $offset = 0)
{
$this->pending['limit'] = array(
'offset' => $offset,
'number' => $number
);
return $this;
}
/**
* Pending function for limit()
*/
protected function limitPending()
{
$offset = $this->pending['limit']['offset'];
$num = $this->pending['limit']['number'];
$this->data = array_slice($this->data, $offset, $num);
}
/**
* Add new fields to table, array schema like in create() function
* @param array $fields Associative array
*/
public function addFields(array $fields)
{
$fields = Helpers\Validate::arrToLower($fields);
Helpers\Validate::types(array_values($fields));
$schema = $this->schema();
$fields = array_diff_assoc($fields, $schema);
if (!empty($fields))
{
$config = $this->config();
$config->schema = array_merge($schema, $fields);
$data = $this->getData();
foreach ($data as $key => $object)
{
foreach ($fields as $name => $type)
{
if (Helpers\Validate::isNumeric($type))
$data[$key]->{$name} = 0;
else
$data[$key]->{$name} = null;
}
}
Helpers\Data::table($this->name)->put($data);
Helpers\Config::table($this->name)->put($config);
}
}
/**
* Delete fields from array
* @param array $fields Indexed array
*/
public function deleteFields(array $fields)
{
$fields = Helpers\Validate::arrToLower($fields);
Helpers\Validate::table($this->name)->fields($fields);
$config = $this->config();
$config->schema = array_diff_key($this->schema(), array_flip($fields));
$data = $this->getData();
foreach ($data as $key => $object)
{
foreach ($fields as $name)
{
unset($data[$key]->{$name});
}
}
Helpers\Data::table($this->name)->put($data);
Helpers\Config::table($this->name)->put($config);
}
/**
* Returns table name
* @return string table name
*/
public function name()
{
return $this->name;
}
/**
* Returning object with config for table
* @return object Config
*/
public function config()
{
return Helpers\Config::table($this->name)->get();
}
/**
* Return array with names of fields
* @return array Fields
*/
public function fields()
{
return Helpers\Config::table($this->name)->fields();
}
/**
* Returning assoc array with types of fields
* @return array Fields type
*/
public function schema()
{
return Helpers\Config::table($this->name)->schema();
}
/**
* Returning assoc array with relationed tables
* @return array Fields type
*/
public function relations($tableName = null)
{
return Helpers\Config::table($this->name)->relations($tableName, true);
}
/**
* Returning last ID from table
* @return integer Last ID
*/
public function lastId()
{
return Helpers\Config::table($this->name)->lastId();
}
/**
* Saving inserted or updated data
*/
public function save()
{
$data = $this->getData();
if (!$this->currentId)
{
$config = $this->config();
$config->last_id++;
$this->set->id = $config->last_id;
array_push($data, $this->set);
Helpers\Config::table($this->name)->put($config);
}
else
{
$this->set->id = $this->currentId;
$data[$this->currentKey] = $this->set;
}
Helpers\Data::table($this->name)->put($data);
// $this->setFields();
}
/**
* Deleting loaded data
* @return boolean
*/
public function delete()
{
$data = $this->getData();
if (isset($this->currentId))
{
unset($data[$this->currentKey]);
}
else
{
$this->pending();
$old = $data;
$data = array_diff_key($old, $this->data);
}
$this->data = array_values($data);
return Helpers\Data::table($this->name)->put($this->data) ? true : false;
}
/**
* Return count in integer or array of integers (if grouped)
* @return mixed
*/
public function count()
{
if (!$this->resetKeys)
{
$count = array();
foreach ($this->data as $group => $data)
{
$count[$group] = count($data);
}
}
else
{
$count = count($this->data);
}
return $count;
}
/**
* Returns one row with specified ID
* @param integer $id Row ID
* @return \Lazer\Classes\Core_Database
*/
public function find($id = NULL)
{
if ($id !== NULL)
{
$data = $this->getData();
$this->currentId = $id;
$this->currentKey = $this->getRowKey($id);
foreach ($data[$this->currentKey] as $field => $value)
{
$this->set->{$field} = $value;
}
}
else
{
$this->limit(1)->findAll();
$data = $this->data;
if (count($data))
{
foreach ($data[0] as $field => $value)
{
$this->set->{$field} = $value;
}
$this->currentId = $this->set->id;
$this->currentKey = $this->getRowKey($this->currentId);
}
}
return clone $this;
}
/**
* Make data ready to read
*/
public function findAll()
{
$this->pending();
$this->data = $this->resetKeys ? array_values($this->data) : $this->data;
return clone $this;
}
/**
* Iterator for Data
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->data);
}
/**
* Debug functions, prints whole query with values
*/
public function debug()
{
$print = "Lazer::table(" . $this->name . ")\n";
foreach ($this->pending as $function => $values)
{
if (!empty($values))
{
if (is_array($values))
{
if (is_array(reset($values)))
{
foreach ($values as $value)
{
if ($function == 'where')
{
array_shift($value);
}
if ($function == 'with')
{
$params = implode(':', $value);
}
else
{
$params = implode(', ', $value);
}
$print .= "\t" . '->' . $function . '(' . $params . ')' . "\n";
}
}
else
{
$params = implode(', ', $values);
$print .= "\t" . '->' . $function . '(' . $params . ')' . "\n";
}
}
else
{
$print .= "\t" . '->' . $function . '(' . $values . ')' . "\n";
}
}
}
echo '<pre>' . print_r($print, true) . '</pre>';
$this->clearQuery();
}
}
| {'content_hash': 'c4c4c153e16a59d77eb5f367c443a7cc', 'timestamp': '', 'source': 'github', 'line_count': 942, 'max_line_length': 130, 'avg_line_length': 27.66772823779193, 'alnum_prop': 0.42945938687027585, 'repo_name': 'PaulaoDeveloper/JSKhanFramework', 'id': '706fd40f83306813f196e6867231093c7a4a7a1e', 'size': '26435', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/Sockets/vendor/greg0/lazer-database/src/Lazer/Classes/Core/Database.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '32'}, {'name': 'CSS', 'bytes': '11179'}, {'name': 'HTML', 'bytes': '28468'}, {'name': 'JavaScript', 'bytes': '48245'}, {'name': 'PHP', 'bytes': '6675'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<!-- CSS -->
<link href="../../css/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="../../css/flat-ui.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../../css/style.css">
<!-- Font-Awesome -->
<link rel="stylesheet" href="../../fonts/font-awesome/css/font-awesome.min.css">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. -->
<!--[if lt IE 9]>
<script src="js/vendor/html5shiv.js"></script>
<script src="js/vendor/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<a class="navbar-brand">CepatSembuh</a>
</div>
</div>
</nav>
<div class="container">
<center><img src="../../img/puskesmas/cakung/main.jpg" alt="cakung" class="faskes"></center>
<h5>Puskesmas Kelurahan Penggilingan Elok</h5>
<div class="faskes-desc">
<p><span class="fui-location"></span>Jl. Mentibu Perum Aneka Elok, Kec. Cakung<br></p>
</div>
<center><img src="../../img/iklan.png" class="ads"></center>
<hr>
<span class="ptx">Daftar Poli</span><br>
<span class="pentatonix">Poli Umum<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Poli Gigi<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Poli Anak<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Poli THT<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Mata<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Paru<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Gizi<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Poli FeLaSe<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Kusta<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Kulit<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Kanker<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Kandungan<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli VCT (HIV/AIDS)<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Penyakit Dalam<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Kesehatan Jiwa<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Poli Haji<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<div class="fasilitas">
<hr>
<span class="ptx">Fasilitas</span><br>
<span class="pentatonix">Apotek<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Laboratorium<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Neurologi<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Fisioterapi<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Akupuntur<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Kesehatan Ibu & Anak (KIA)<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Keluarga Berencana (KB)<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Poli Kesehatan Remaja<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Radiologi<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Rawat Inap<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Ruang Bersalin<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Unit Layanan 24 Jam<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Klinik Cervicita<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Klinik Gizi<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Klinik Diabetes Mellitus<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Klinik Lansia<span class="badge zrk"><i class="fa fa-check ksi"></i></span></span><br>
<span class="pentatonix">Klinik Kulit<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Klinik Gigi<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Klinik Mata<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<span class="pentatonix">Klinik THT<span class="badge mm"><i class="fa fa-times ksi"></i></span></span><br>
<div class="fasilitas">
<hr>
<span class="ptx">Staf Puskesmas</span><br>
<span class="pentatonix">Dokter Umum</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
<span class="pentatonix">Dokter Gigi</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
<span class="pentatonix">Apoteker</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
<span class="pentatonix">Perawat</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
<span class="pentatonix">Bidan</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
<span class="pentatonix">Ahli Gizi</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
<span class="pentatonix">Sanitarian</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
<span class="pentatonix">Administrasi</span><span class="badge"><i class="fa fa-check ksi"></i></span><br>
</div>
<center>
<hr>
<button class="btn btn-primary btn-hg btn-embossed" onclick="getNoAntri('puskesmas', 'cakung-penggilingan-elok', 'Puskesmas Kelurahan Penggilingan Elok')">
Dapatkan No Antri
</button>
<br><br>
<a class="btn btn-hg btn-info btn-embossed" href="tel:+62214807827">
<i class="fa fa-phone"></i>
Call Faskes
</a>
<br><br>
</center>
</div>
<!-- JS -->
<script src="../../js/main.js"></script>
<script src="../../js/vendor/jquery.min.js"></script>
<script src="../../js/flat-ui.min.js"></script>
<script src="../../js/profile.js"></script>
<script src="../../bower_components/firebase/firebase.js"></script>
<script src="../../js/responsive.js" charset="utf-8"></script>
</body>
</html>
| {'content_hash': 'd4e3f9a276252aa8c4861daf4659ffbf', 'timestamp': '', 'source': 'github', 'line_count': 107, 'max_line_length': 169, 'avg_line_length': 73.92523364485982, 'alnum_prop': 0.5905183312262958, 'repo_name': 'mercysmart/cepatsembuh', 'id': 'a69c448923f36f7ad0465e1308320872d2bc4037', 'size': '7910', 'binary': False, 'copies': '2', 'ref': 'refs/heads/v2', 'path': 'platforms/android/assets/www/puskesmas/faskes/cakung-penggilingan-elok.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '18827'}, {'name': 'C++', 'bytes': '5973'}, {'name': 'CSS', 'bytes': '352733'}, {'name': 'HTML', 'bytes': '1151746'}, {'name': 'Java', 'bytes': '94366'}, {'name': 'JavaScript', 'bytes': '144360'}, {'name': 'Objective-C', 'bytes': '45921'}, {'name': 'QML', 'bytes': '2765'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '62be884dd82bf8679029f7ef4297ca9a', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '08e982a4ec87ac3dbcad734cff43f0c69ebbc97e', 'size': '192', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Chiliadenus/Chiliadenus glutinosus/ Syn. Chiliadenus saxatilis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
title: PdfViewerNavigator
page_title: PdfViewerNavigator - RadPdfViewer
description: PdfViewerNavigator can be added associated witha a RadPdfViewer control to provide a predefined UI for the most common end user operations.
slug: winforms/pdfviewer/pdfviewernavigator
tags: pdfviewernavigator
published: True
position: 7
previous_url: pdfviewer-pdfviewernavigator
---
# PdfViewerNavigator
This article describes the features provided by __PdfViewerNavigator__. The following article shows how you can associate the __PdfViewerNavigator__ with __RadPdfViewer__: [Getting Started]({%slug winforms/pdfviewer/getting-started%}).
>caption Figure 1: PdfViewerNavigator

This control can be used with __RadPdfViewer__. It provides predefined UI for the most common operations used with PDF files. The following list contains all features:
* __Open File:__ You can open files with this button.
* __Print:__ Use this button to print the content.
* __SaveAs:__ Use this option to save the current file in a specific location.
* __Rotate:__ Rotate all pages clockwise or counter clockwise using the buttons.
* __Navigation:__ You can navigate trough the document by using the previous/next page buttons or manually typing the page number.
* __Pan__ and __Select:__ You can select text in the document or you can move the page with the mouse.
* __Zoom:__ You can use the buttons to increase/decrease the zoom factor or select it from the drop down.
* __FitWith__ and __FithPage:__ These buttons allows you to fit the page according to the current window size.
* __Search:__ You can search for a particular string and navigate among the results.
## Assembly References
If you add the __PdfViewerNavigator__ at run time you need to add references to the following assemblies:
* Telerik.WinControls.PdfViewer
* Telerik.WinControls
* Telerik.WinControls.UI
* TelerikCommon
* Telerik.Windows.Documents.Fixed
* Telerik.Windows.Documents.Core
# See Also
* [Design Time]({%slug winforms/pdfviewer/design-time%})
* [Getting Started]({%slug winforms/pdfviewer/getting-started%})
| {'content_hash': '6062da3116549657168b628d9a69169c', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 235, 'avg_line_length': 36.76271186440678, 'alnum_prop': 0.7731673582295989, 'repo_name': 'telerik/winforms-docs', 'id': 'f331249f09f87aafd745d38adb4b9fc51490961d', 'size': '2173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'controls/pdfviewer/pdfviewernavigator.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '96'}, {'name': 'CSS', 'bytes': '2296'}, {'name': 'HTML', 'bytes': '1629'}, {'name': 'JavaScript', 'bytes': '42129'}, {'name': 'Ruby', 'bytes': '882'}]} |
<?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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>jsp-customtag-scriptlet</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<jetty.version>9.4.9.v20180320</jetty.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jspc-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<keepSources>true</keepSources>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {'content_hash': '29dd8dfe20eb768344266192716e507d', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 103, 'avg_line_length': 35.888888888888886, 'alnum_prop': 0.5696594427244582, 'repo_name': 'backpaper0/sandbox', 'id': '26f9c2d980573a356409f2b6f8118cb3b914c5d4', 'size': '1938', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jsp-customtag-scriptlet/pom.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '109'}, {'name': 'CSS', 'bytes': '1311'}, {'name': 'Dockerfile', 'bytes': '1799'}, {'name': 'Gherkin', 'bytes': '498'}, {'name': 'Go', 'bytes': '1387'}, {'name': 'Groovy', 'bytes': '5528'}, {'name': 'HCL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '27028'}, {'name': 'Java', 'bytes': '740418'}, {'name': 'JavaScript', 'bytes': '89354'}, {'name': 'Makefile', 'bytes': '2174'}, {'name': 'Rust', 'bytes': '20123'}, {'name': 'Scala', 'bytes': '51043'}, {'name': 'Shell', 'bytes': '2456'}, {'name': 'TypeScript', 'bytes': '68205'}, {'name': 'Vim Script', 'bytes': '71'}]} |
package io.atomix.core.counter;
import io.atomix.primitive.PrimitiveType;
import io.atomix.primitive.config.PrimitiveConfig;
/**
* Distributed counter configuration.
*/
public class DistributedCounterConfig extends PrimitiveConfig<DistributedCounterConfig> {
@Override
public PrimitiveType getType() {
return DistributedCounterType.instance();
}
}
| {'content_hash': '3ed6b9b73f9db8a7016681e7d52a72c7', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 89, 'avg_line_length': 24.2, 'alnum_prop': 0.7933884297520661, 'repo_name': 'kuujo/copycat', 'id': '4964ea3b1a68804a3f049eb9eaa9126863961eb5', 'size': '976', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/io/atomix/core/counter/DistributedCounterConfig.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '947992'}, {'name': 'Shell', 'bytes': '2049'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'c1043c9dde797bd95025e65028a90934', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'eca8b370df65fa255e04cd3b82b5f60ddfb4bce5', 'size': '184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Bouvardia/Bouvardia ternifolia/ Syn. Bouvardia quaternifolia/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using System;
using System.Runtime.InteropServices;
namespace Examples
{
class Program
{
[STAThread]
static void Main(string[] args)
{
SolidEdgeFramework.Application application = null;
SolidEdgeFramework.Window window = null;
SolidEdgeFramework.View view = null;
try
{
// See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register();
// Attempt to connect to a running instance of Solid Edge.
application = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
// A 3D document must be open.
window = application.ActiveWindow as SolidEdgeFramework.Window;
if (window != null)
{
view = window.View;
var viewName = "TestView";
view.SaveCurrentView(viewName);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleMessageFilter.Unregister();
}
}
}
} | {'content_hash': '7b88747a95dc94066ce34aa2296ddb84', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 111, 'avg_line_length': 29.0, 'alnum_prop': 0.512539184952978, 'repo_name': 'SolidEdgeCommunity/docs', 'id': '1945dd9c4b207d5cebe440e5b28f5fbc7dceb21f', 'size': '1278', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docfx_project/snippets/SolidEdgeFramework.View.SaveCurrentView.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '38'}, {'name': 'C#', 'bytes': '5048212'}, {'name': 'C++', 'bytes': '2265'}, {'name': 'CSS', 'bytes': '148'}, {'name': 'PowerShell', 'bytes': '180'}, {'name': 'Smalltalk', 'bytes': '1996'}, {'name': 'Visual Basic', 'bytes': '10236277'}]} |
<?php
/**
* GIT DEPLOYMENT SCRIPT
*
* Used for automatically deploying websites via github or bitbucket, more deets here:
*
* https://gist.github.com/1809044
*/
// The commands
$commands = array(
'echo $PWD',
'whoami',
'git --version',
'git pull',
'git status',
'git submodule sync',
'git submodule update',
'git submodule status',
);
// Run the commands for output
$output = '';
foreach($commands AS $command){
// Run it
$tmp = shell_exec($command);
// Output
$output .= "<span style=\"color: #6BE234;\">\$</span> <span style=\"color: #729FCF;\">{$command}\n</span>";
$output .= htmlentities(trim($tmp)) . "\n";
}
// Make it pretty for manual user access (and why not?)
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>GIT DEPLOYMENT SCRIPT</title>
</head>
<body style="background-color: #000000; color: #FFFFFF; font-weight: bold; padding: 0 10px;">
<pre>
. ____ . ____________________________
|/ \| | |
[| <span style="color: #FF0000;">♥ ♥</span> |] | Git Deployment Script v0.1 |
|___==___| / |
|____________________________|
<?php echo $output; ?>
</pre>
</body>
</html>
| {'content_hash': 'd45f50655406c96f46ae51d81645af20', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 109, 'avg_line_length': 24.784313725490197, 'alnum_prop': 0.5300632911392406, 'repo_name': 'LuisEGR/hova-dir', 'id': 'c48b3e2f6baad58fe964286f63657ec92684e16b', 'size': '1264', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'deploy.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '6983'}, {'name': 'HTML', 'bytes': '17156'}, {'name': 'JavaScript', 'bytes': '31180'}, {'name': 'PHP', 'bytes': '154302'}]} |
(function () {
'use strict';
var module = angular.module('fim.base');
var _secretPhraseCache = {};
module.controller('secretPhraseModalController', function (items, $modalInstance, $scope,
$timeout, nxt, modals, plugins, $sce, db, KeyService) {
var walletPlugin = plugins.get('wallet');
$scope.SIMPLE = 'simple';
$scope.COMPLEX = 'complex';
$scope.state = items.sender ? $scope.SIMPLE : $scope.COMPLEX;
$scope.items = items;
// simple
$scope.items.valid = false;
$scope.items.secretNotFound = false;
// complex
$scope.items.selectedAccount = null;
$scope.items.accounts = [];
$scope.items.engineType = items.engineType || 'TYPE_FIM';
// simple + complex
$scope.items.secretPhrase = $scope.items.secretPhrase || '';
$scope.items.sender = items.sender || '';
if (items.sender && $scope.items.secretPhrase == '') {
$scope.items.secretPhrase = walletPlugin.getSecretPhrase(items.sender) || '';
if (!$scope.items.secretPhrase) {
$scope.items.secretPhrase = KeyService.get(items.sender);
if ($scope.items.secretPhrase) {
$scope.items.valid = true;
}
}
}
// DEBUG
//$scope.state = $scope.COMPLEX;
function accountFilter(account) {
var prefix = ($scope.items.engineType == 'TYPE_FIM') ? 'FIM-' : 'NXT-';
return account.id_rs.indexOf(prefix) == 0;
}
if ($scope.state == $scope.SIMPLE) {
$scope.items.messageHTML = $sce.getTrustedHtml(items.messageHTML||'This operation requires your secret passphrase. Either enter it by hand or click Open Wallet to load a wallet file containing your secret phrase.');
}
else {
$scope.items.messageHTML = $sce.getTrustedHtml(items.messageHTML||'This operation requires a sender and secret passphrase.');
db.accounts.where('id_rs').anyOf(walletPlugin.getKeys()).toArray().then(
function (accounts) {
$scope.$evalAsync(function () {
$scope.items.accounts = accounts.filter(accountFilter);
})
}
);
}
$scope.passphraseChange = function () {
$timeout(function () {
var engine = nxt.crypto($scope.items.sender);
var accountID = engine.getAccountId($scope.items.secretPhrase, true);
var valid = accountID == $scope.items.sender;
$scope.items.valid = valid;
});
}
$scope.passphraseChangeComplex = function () {
$timeout(function () {
$scope.items.sender = nxt.crypto($scope.items.engineType).getAccountId($scope.items.secretPhrase, true);
});
}
$scope.format = function (account) {
return account.id_rs + ' # ' + account.name;
}
$scope.selectedAccountChange = function () {
walletPlugin.getEntry($scope.items.selectedAccount.id_rs).then(
function (entry) {
$scope.$evalAsync(function () {
$scope.items.secretPhrase = entry.secretPhrase;
$scope.items.sender = entry.id_rs;
$scope.passphraseChangeComplex();
});
}
);
}
function getKeyFromWallet() {
if (items.sender) {
walletPlugin.getEntry(items.sender).then(
function (entry) {
$scope.$evalAsync(function () {
$scope.items.missing = false;
$scope.items.secretPhrase = entry.secretPhrase;
$scope.passphraseChange();
$modalInstance.close($scope.items);
});
}
);
}
}
if (walletPlugin.hasKey(items.sender)) {
getKeyFromWallet();
}
walletPlugin.createOnWalletFileSelectedPromise($scope).then(
function handleOnWalletFileSelectedPromiseSuccess() {
if ($scope.state == $scope.SIMPLE) {
getKeyFromWallet();
}
else {
db.accounts.where('id_rs').anyOf(walletPlugin.getKeys()).toArray().then(
function (accounts) {
$scope.$evalAsync(function () {
$scope.items.accounts = accounts.filter(accountFilter);
})
}
);
}
},
function handleOnWalletFileSelectedPromiseFailed() {
// $scope.items.invalidPassword = true;
// Must provide feedback here
}
);
$scope.close = function () {
if (walletPlugin.hasKey($scope.items.sender)) {
$modalInstance.close($scope.items);
}
else {
db.accounts.where('id_rs').anyOf($scope.items.sender).count().then(
function (count) {
if (count > 0) {
walletPlugin.saveToMemory($scope.items.sender, $scope.items.secretPhrase);
$modalInstance.close($scope.items);
}
else {
walletPlugin.confirmSaveToWallet().then(
function (confirmed) {
if (confirmed) {
/* Save the secret in the in-memory wallet - will ask the user to save the wallet */
walletPlugin.addEntry({
name: '',
id_rs: $scope.items.sender,
secretPhrase: $scope.items.secretPhrase
}).then(
function () {
$modalInstance.close($scope.items);
},
function () {
$modalInstance.dismiss();
}
);
}
else {
walletPlugin.saveToMemory($scope.items.sender, $scope.items.secretPhrase);
$modalInstance.close($scope.items);
}
}
);
}
}
);
}
}
$scope.dismiss = function () {
$modalInstance.dismiss();
}
});
})(); | {'content_hash': '0a0fcd2351e0f77cb43ac2bd09f4a020', 'timestamp': '', 'source': 'github', 'line_count': 180, 'max_line_length': 226, 'avg_line_length': 31.683333333333334, 'alnum_prop': 0.5614588812905489, 'repo_name': 'habibmasuro/mofowallet', 'id': 'bd3a91d129f9eb72d6c90db1b6199fb2468e5e2f', 'size': '5703', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/scripts/controllers/secretphrase-modal.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '24139'}, {'name': 'CSS', 'bytes': '90615'}, {'name': 'HTML', 'bytes': '368665'}, {'name': 'JavaScript', 'bytes': '1242696'}, {'name': 'Ruby', 'bytes': '725'}, {'name': 'Shell', 'bytes': '18258'}]} |
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
<parameter key="integrated_subscription.controller.subscription_wall_process.class">Integrated\Bundle\SubscriptionBundle\Controller\SubscriptionWallProcess</parameter>
</parameters>
<services>
<service id="integrated_subscription.controller.subscription_wall_process" class="%integrated_subscription.controller.subscription_wall_process.class%">
<argument type="service" id="templating" />
<argument type="service" id="form.factory" />
<argument type="service" id="router" />
</service>
</services>
</container>
| {'content_hash': 'f5913133f9520e757144a51d182a6541', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 175, 'avg_line_length': 40.86363636363637, 'alnum_prop': 0.6907675194660734, 'repo_name': 'Abdaaf444/integrated-subscription-bundle', 'id': 'b9eff1dbc0c69d418c7f6ac81da5d84452880a6f', 'size': '899', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Resources/config/process.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '6878'}, {'name': 'PHP', 'bytes': '46783'}]} |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.remote.http;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.net.HttpHeaders.CACHE_CONTROL;
import static com.google.common.net.HttpHeaders.CONTENT_LENGTH;
import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
import static com.google.common.net.HttpHeaders.EXPIRES;
import static com.google.common.net.MediaType.JSON_UTF_8;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.json.JsonException;
import org.openqa.selenium.remote.ErrorCodes;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.ResponseCodec;
import java.util.Optional;
import java.util.function.Supplier;
/**
* A response codec usable as a base for both the JSON and W3C wire protocols.
*
* @see <a href="https://w3.org/tr/webdriver">W3C WebDriver spec</a>
*/
public abstract class AbstractHttpResponseCodec implements ResponseCodec<HttpResponse> {
private final ErrorCodes errorCodes = new ErrorCodes();
private final Json json = new Json();
/**
* Encodes the given response as a HTTP response message. This method is guaranteed not to throw.
*
* @param response The response to encode.
* @return The encoded response.
*/
@Override
public HttpResponse encode(Supplier<HttpResponse> factory, Response response) {
int status = response.getStatus() == ErrorCodes.SUCCESS
? HTTP_OK
: HTTP_INTERNAL_ERROR;
byte[] data = json.toJson(getValueToEncode(response)).getBytes(UTF_8);
HttpResponse httpResponse = factory.get();
httpResponse.setStatus(status);
httpResponse.setHeader(CACHE_CONTROL, "no-cache");
httpResponse.setHeader(EXPIRES, "Thu, 01 Jan 1970 00:00:00 GMT");
httpResponse.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
httpResponse.setContent(data);
return httpResponse;
}
protected abstract Object getValueToEncode(Response response);
@Override
public Response decode(HttpResponse encodedResponse) {
String contentType = nullToEmpty(encodedResponse.getHeader(CONTENT_TYPE));
String content = encodedResponse.getContentString().trim();
try {
return reconstructValue(json.toType(content, Response.class));
} catch (JsonException e) {
if (contentType.startsWith("application/json")) {
throw new IllegalArgumentException(
"Cannot decode response content: " + content, e);
}
} catch (ClassCastException e) {
if (contentType.startsWith("application/json")) {
if (content.isEmpty()) {
// The remote server has died, but has already set some headers.
// Normally this occurs when the final window of the firefox driver
// is closed on OS X. Return null, as the return value _should_ be
// being ignored. This is not an elegant solution.
return new Response();
}
throw new IllegalArgumentException(
"Cannot decode response content: " + content, e);
}
}
Response response = new Response();
int statusCode = encodedResponse.getStatus();
if (statusCode < 200 || statusCode > 299) {
// 4xx represents an unknown command or a bad request.
if (statusCode > 399 && statusCode < 500) {
response.setStatus(ErrorCodes.UNKNOWN_COMMAND);
} else {
response.setStatus(ErrorCodes.UNHANDLED_ERROR);
}
}
if (encodedResponse.getContent().length > 0) {
response.setValue(content);
}
if (response.getValue() instanceof String) {
// We normalise to \n because Java will translate this to \r\n
// if this is suitable on our platform, and if we have \r\n, java will
// turn this into \r\r\n, which would be Bad!
response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
}
if (response.getStatus() != null && response.getState() == null) {
response.setState(errorCodes.toState(response.getStatus()));
} else if (response.getStatus() == null && response.getState() != null) {
response.setStatus(
errorCodes.toStatus(response.getState(),
Optional.of(encodedResponse.getStatus())));
} else if (statusCode == 200) {
response.setStatus(ErrorCodes.SUCCESS);
response.setState(errorCodes.toState(ErrorCodes.SUCCESS));
}
if (response.getStatus() != null) {
response.setState(errorCodes.toState(response.getStatus()));
} else if (statusCode == 200) {
response.setState(errorCodes.toState(ErrorCodes.SUCCESS));
}
return response;
}
protected abstract Response reconstructValue(Response response);
}
| {'content_hash': 'c3b5a5c140f2550cce08cfd8ac76a489', 'timestamp': '', 'source': 'github', 'line_count': 142, 'max_line_length': 99, 'avg_line_length': 40.13380281690141, 'alnum_prop': 0.7041586243200562, 'repo_name': 'juangj/selenium', 'id': '3883e132bf204d9702d4311bcc8c8b6f655e00cd', 'size': '5699', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'java/client/src/org/openqa/selenium/remote/http/AbstractHttpResponseCodec.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '825'}, {'name': 'Batchfile', 'bytes': '321'}, {'name': 'C', 'bytes': '62551'}, {'name': 'C#', 'bytes': '2766321'}, {'name': 'C++', 'bytes': '1868343'}, {'name': 'CSS', 'bytes': '27283'}, {'name': 'HTML', 'bytes': '1846575'}, {'name': 'Java', 'bytes': '4823618'}, {'name': 'JavaScript', 'bytes': '4687476'}, {'name': 'Makefile', 'bytes': '4655'}, {'name': 'Objective-C', 'bytes': '4376'}, {'name': 'Python', 'bytes': '827569'}, {'name': 'Ragel', 'bytes': '3086'}, {'name': 'Ruby', 'bytes': '909694'}, {'name': 'Shell', 'bytes': '2688'}, {'name': 'XSLT', 'bytes': '1047'}]} |
<?php
$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer->startSetup();
$installer->getConnection()->dropForeignKey($installer->getTable('design_change'), 'FK_DESIGN_CHANGE_STORE');
$storeIds = $installer->getConnection()->fetchCol(
"SELECT store_id FROM {$installer->getTable('core_store')}"
);
if (!empty($storeIds)) {
$storeIds = implode(',', $storeIds);
$installer->run("DELETE FROM {$installer->getTable('design_change')} WHERE store_id NOT IN ($storeIds)");
}
$installer->getConnection()->addConstraint(
'FK_DESIGN_CHANGE_STORE',
$installer->getTable('design_change'), 'store_id',
$installer->getTable('core_store'), 'store_id'
);
$installer->endSetup();
| {'content_hash': 'e7b405393ee923ce77b4fc73fe2c49e5', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 109, 'avg_line_length': 28.03846153846154, 'alnum_prop': 0.6748971193415638, 'repo_name': 'hansbonini/cloud9-magento', 'id': '365d8f5d7806fa05ff6be31ae50f9c0b65925dd6', 'size': '1680', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'vendor/firegento/magento/app/code/core/Mage/Core/sql/core_setup/mysql4-upgrade-0.8.10-0.8.11.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '20063'}, {'name': 'ApacheConf', 'bytes': '6515'}, {'name': 'Batchfile', 'bytes': '1036'}, {'name': 'CSS', 'bytes': '1761053'}, {'name': 'HTML', 'bytes': '5281773'}, {'name': 'JavaScript', 'bytes': '1126889'}, {'name': 'PHP', 'bytes': '47400395'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Ruby', 'bytes': '288'}, {'name': 'Shell', 'bytes': '3879'}, {'name': 'XSLT', 'bytes': '2135'}]} |
package com.lotaris.jee.validation;
import java.lang.annotation.Annotation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* Basic bean validation constraint implementation. When using this class, you will implement the
* <tt>validate</tt> method instead of the <tt>isValid</tt> method from {@link ConstraintValidator}.
* This allows the abstract validator to hide bean validation implementation details from you,
* making validations easier to write and test.
*
* <h2>What to implement</h2>
*
* <p>You must implement the <tt>validate</tt> method. A {@link IConstraintValidationContext} will
* be passed to your method. This object will allow you to add errors if you determine that the
* supplied value/object is invalid.</p>
*
* <h3>Minimal implementation</h3>
*
* <p>This validator implementation will use the default error message defined by your constraint
* annotation.</p>
*
* <p><pre>
* public class MyAnnotationValidator extends AbstractConstraintValidator<MyAnnotation, String> {
*
* @Override
* public void validate(String value, IConstraintValidationContext context) {
* if (isInvalid(value)) {
* context.addDefaultError();
* }
* }
* }
* </pre></p>
*
* <h3>Custom errors</h3>
*
* <p>Sometimes the static error message defined by your constraint annotation isn't enough. You
* might need to build the message dynamically based on the validated value. In this case, use the
* <tt>addError</tt> methods to override the default error message.</p>
*
* <p><pre>
* public class MyAnnotationValidator extends AbstractConstraintValidator<MyAnnotation, Object> {
*
* @Override
* public void validate(Object value, IConstraintValidationContext context) {
*
* if (isInvalid(value)) {
*
* // add the default error message
* context.addDefaultError();
*
* // add another error message
* context.addErrorAtCurrentLocation("Object is invalid.");
*
* // additional arguments are interpolated
* context.addErrorAtCurrentLocation("%s is invalid", value);
*
* // if you are validating a complex object, you can add errors to a specific property
* context.addError("name", "Name must be at most 25 characters long, got %d.", value.getName().length());
* }
* }
* }
* </pre></p>
*
* <h2>What to test</h2>
*
* <p>When testing, only test the <tt>validate</tt> method and not the <tt>isValid</tt> method. This
* allows you to mock the validation context and ignore bean validation implementation details.</p>
*
* <p><pre>
* public class CheckStringLengthValidatorUnitTests {
*
* @Mock
* private IConstraintValidationContext context;
* private CheckStringLengthValidator validator;
*
* @Before
* public void setUp() {
* MockitoAnnotations.initMocks(this);
* validator = new CheckStringLengthValidator();
* }
*
* @Test
* public void checkStringLengthValidatorShouldFailIfStringIsTooLong() {
* validator.validate("foooooooooooooo", context);
* verify(context).addDefaultError();
* verifyNoMoreInteractions(context);
* }
* }
* </pre></p>
*
* @author Simon Oulevay ([email protected])
* @param <A> the constraint annotation
* @param <T> the type of value to validate (e.g. String)
*/
public abstract class AbstractConstraintValidator<A extends Annotation, T> implements ConstraintValidator<A, T> {
@Override
public void initialize(A constraintAnnotation) {
// do nothing by default
}
/**
* Validates the specified object.
*
* @param object the object to validate
* @param context the context used to add and keep track of errors during validation
*/
public abstract void validate(T value, IConstraintValidationContext context);
@Override
public final boolean isValid(T value, ConstraintValidatorContext context) {
final IConstraintValidationContext wrapperContext = new ConstraintValidationContext(context);
validate(value, wrapperContext);
return !wrapperContext.hasErrors();
}
/**
* Wrapper around {@link ConstraintValidatorContext} to provide an easier-to-use validation API.
*/
private static class ConstraintValidationContext implements IConstraintValidationContext {
private boolean hasErrors;
private final ConstraintValidatorContext context;
public ConstraintValidationContext(ConstraintValidatorContext context) {
this.hasErrors = false;
this.context = context;
}
private ConstraintValidatorContext addErrors() {
if (!hasErrors) {
context.disableDefaultConstraintViolation();
hasErrors = true;
}
return context;
}
@Override
public boolean hasErrors() {
return hasErrors;
}
@Override
public IConstraintValidationContext addDefaultError() {
addErrors().buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addConstraintViolation();
return this;
}
@Override
public IConstraintValidationContext addError(String location, String message, Object... messageArgs) {
location = validateLocation(location);
addErrors().buildConstraintViolationWithTemplate(String.format(message, messageArgs)).addPropertyNode(location).addConstraintViolation();
return this;
}
@Override
public IConstraintValidationContext addArrayError(String location, int index, String message, Object... messageArgs) {
location = validateLocation(location);
addErrors().buildConstraintViolationWithTemplate(String.format(message, messageArgs)).addPropertyNode(location).addPropertyNode(String.valueOf(index)).addConstraintViolation();
return this;
}
@Override
public IConstraintValidationContext addErrorAtCurrentLocation(String message, Object... messageArgs) {
addErrors().buildConstraintViolationWithTemplate(String.format(message, messageArgs)).addConstraintViolation();
return this;
}
/**
* Validate and sanitize the error location.
* @param location The location
* @return The sanitized location.
* @throws IllegalArgumentException If the location contains dots or slash
*/
private String validateLocation(String location) throws IllegalArgumentException {
if (location.contains(".")) {
throw new IllegalArgumentException("Constraint violation error locations cannot contain dots.");
}
location = location.replaceFirst("^\\/", "");
if (location.contains("/")) {
throw new IllegalArgumentException("Constraint violation error locations cannot contain a slash except as the first character.");
}
return location;
}
}
}
| {'content_hash': '9761a13772dd7444f5e1a5080933ae20', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 179, 'avg_line_length': 34.303664921465966, 'alnum_prop': 0.73992673992674, 'repo_name': 'lotaris/jee-validation', 'id': '74c043c3c8922b45452a7c4ea0afee2517e4a0af', 'size': '6552', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/lotaris/jee/validation/AbstractConstraintValidator.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '181923'}]} |
package fakes // import "code.cloudfoundry.org/executor/initializer/fakes"
| {'content_hash': '47f3b302a4ea994f67fc9ee486228dc7', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 74, 'avg_line_length': 75.0, 'alnum_prop': 0.8133333333333334, 'repo_name': 'cloudfoundry-incubator/executor', 'id': '66a1a673e5e39a88de8c4febc604da66787287bf', 'size': '75', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'initializer/fakes/package.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '424359'}]} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Xml;
using Umbraco.Web.Routing;
using umbraco;
using System.Linq;
using umbraco.BusinessLogic;
using umbraco.presentation.preview;
using Umbraco.Core.Services;
using GlobalSettings = umbraco.GlobalSettings;
using Task = System.Threading.Tasks.Task;
namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
internal class PublishedContentCache : IPublishedContentCache
{
#region Routes cache
private readonly RoutesCache _routesCache = new RoutesCache(!UnitTesting);
private DomainHelper _domainHelper;
private DomainHelper GetDomainHelper(IDomainService domainService)
{
return _domainHelper ?? (_domainHelper = new DomainHelper(domainService));
}
// for INTERNAL, UNIT TESTS use ONLY
internal RoutesCache RoutesCache { get { return _routesCache; } }
// for INTERNAL, UNIT TESTS use ONLY
internal static bool UnitTesting = false;
public virtual IPublishedContent GetByRoute(UmbracoContext umbracoContext, bool preview, string route, bool? hideTopLevelNode = null)
{
if (route == null) throw new ArgumentNullException("route");
// try to get from cache if not previewing
var contentId = preview ? 0 : _routesCache.GetNodeId(route);
// if found id in cache then get corresponding content
// and clear cache if not found - for whatever reason
IPublishedContent content = null;
if (contentId > 0)
{
content = GetById(umbracoContext, preview, contentId);
if (content == null)
_routesCache.ClearNode(contentId);
}
// still have nothing? actually determine the id
hideTopLevelNode = hideTopLevelNode ?? GlobalSettings.HideTopLevelNodeFromPath; // default = settings
content = content ?? DetermineIdByRoute(umbracoContext, preview, route, hideTopLevelNode.Value);
// cache if we have a content and not previewing
if (content != null && preview == false)
AddToCacheIfDeepestRoute(umbracoContext, content, route);
return content;
}
private void AddToCacheIfDeepestRoute(UmbracoContext umbracoContext, IPublishedContent content, string route)
{
var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/')));
// so we have a route that maps to a content... say "1234/path/to/content" - however, there could be a
// domain set on "to" and route "4567/content" would also map to the same content - and due to how
// urls computing work (by walking the tree up to the first domain we find) it is that second route
// that would be returned - the "deepest" route - and that is the route we want to cache, *not* the
// longer one - so make sure we don't cache the wrong route
var deepest = UnitTesting == false
&& DomainHelper.ExistsDomainInPath(umbracoContext.Application.Services.DomainService.GetAll(false), content.Path, domainRootNodeId) == false;
if (deepest)
_routesCache.Store(content.Id, route);
}
public virtual string GetRouteById(UmbracoContext umbracoContext, bool preview, int contentId)
{
// try to get from cache if not previewing
var route = preview ? null : _routesCache.GetRoute(contentId);
// if found in cache then return
if (route != null)
return route;
// else actually determine the route
route = DetermineRouteById(umbracoContext, preview, contentId);
// node not found
if (route == null)
return null;
// find the content back, detect routes collisions: we should find ourselves back,
// else it means that another content with "higher priority" is sharing the same route.
// perf impact:
// - non-colliding, adds one complete "by route" lookup, only on the first time a url is computed (then it's cached anyways)
// - colliding, adds one "by route" lookup, the first time the url is computed, then one dictionary looked each time it is computed again
// assuming no collisions, the impact is one complete "by route" lookup the first time each url is computed
//
// U4-9121 - this lookup is too expensive when computing a large amount of urls on a front-end (eg menu)
// ... thinking about moving the lookup out of the path into its own async task, so we are not reporting errors
// in the back-office anymore, but at least we are not polluting the cache
// instead, refactored DeterminedIdByRoute to stop using XPath, with a 16x improvement according to benchmarks
// will it be enough?
var loopId = preview ? 0 : _routesCache.GetNodeId(route); // might be cached already in case of collision
if (loopId == 0)
{
var content = DetermineIdByRoute(umbracoContext, preview, route, GlobalSettings.HideTopLevelNodeFromPath);
// add the other route to cache so next time we have it already
if (content != null && preview == false)
AddToCacheIfDeepestRoute(umbracoContext, content, route);
loopId = content == null ? 0 : content.Id; // though... 0 here would be quite weird?
}
// cache if we have a route and not previewing and it's not a colliding route
// (the result of DetermineRouteById is always the deepest route)
if (/*route != null &&*/ preview == false && loopId == contentId)
_routesCache.Store(contentId, route);
// return route if no collision, else report collision
return loopId == contentId ? route : ("err/" + loopId);
}
IPublishedContent DetermineIdByRoute(UmbracoContext umbracoContext, bool preview, string route, bool hideTopLevelNode)
{
if (route == null) throw new ArgumentNullException("route");
//the route always needs to be lower case because we only store the urlName attribute in lower case
route = route.ToLowerInvariant();
var pos = route.IndexOf('/');
var path = pos == 0 ? route : route.Substring(pos);
var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos));
//check if we can find the node in our xml cache
var id = NavigateRoute(umbracoContext, preview, startNodeId, path, hideTopLevelNode);
if (id > 0) return GetById(umbracoContext, preview, id);
// if hideTopLevelNodePath is true then for url /foo we looked for /*/foo
// but maybe that was the url of a non-default top-level node, so we also
// have to look for /foo (see note in ApplyHideTopLevelNodeFromPath).
if (hideTopLevelNode && path.Length > 1 && path.IndexOf('/', 1) < 0)
{
var id2 = NavigateRoute(umbracoContext, preview, startNodeId, path, false);
if (id2 > 0) return GetById(umbracoContext, preview, id2);
}
return null;
}
private int NavigateRoute(UmbracoContext umbracoContext, bool preview, int startNodeId, string path, bool hideTopLevelNode)
{
var xml = GetXml(umbracoContext, preview);
XmlElement elt;
// empty path
if (path == string.Empty || path == "/")
{
if (startNodeId > 0)
{
elt = xml.GetElementById(startNodeId.ToString(CultureInfo.InvariantCulture));
return elt == null ? -1 : startNodeId;
}
elt = null;
var min = int.MaxValue;
foreach (var e in xml.DocumentElement.ChildNodes.OfType<XmlElement>())
{
var sortOrder = int.Parse(e.GetAttribute("sortOrder"));
if (sortOrder < min)
{
min = sortOrder;
elt = e;
}
}
return elt == null ? -1 : int.Parse(elt.GetAttribute("id"));
}
// non-empty path
elt = startNodeId <= 0
? xml.DocumentElement
: xml.GetElementById(startNodeId.ToString(CultureInfo.InvariantCulture));
if (elt == null) return -1;
var urlParts = path.Split(SlashChar, StringSplitOptions.RemoveEmptyEntries);
if (hideTopLevelNode && startNodeId <= 0)
{
foreach (var e in elt.ChildNodes.OfType<XmlElement>())
{
var id = NavigateElementRoute(e, urlParts);
if (id > 0) return id;
}
return -1;
}
return NavigateElementRoute(elt, urlParts);
}
private static bool UseLegacySchema
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema; }
}
private static int NavigateElementRoute(XmlElement elt, string[] urlParts)
{
var found = true;
var i = 0;
while (found && i < urlParts.Length)
{
found = false;
foreach (var child in elt.ChildNodes.OfType<XmlElement>())
{
var noNode = UseLegacySchema
? child.Name != "node"
: child.GetAttributeNode("isDoc") == null;
if (noNode) continue;
if (child.GetAttribute("urlName") != urlParts[i]) continue;
found = true;
elt = child;
break;
}
i++;
}
return found ? int.Parse(elt.GetAttribute("id")) : -1;
}
string DetermineRouteById(UmbracoContext umbracoContext, bool preview, int contentId)
{
var elt = GetXml(umbracoContext, preview).GetElementById(contentId.ToString(CultureInfo.InvariantCulture));
if (elt == null) return null;
var domainHelper = GetDomainHelper(umbracoContext.Application.Services.DomainService);
// walk up from that node until we hit a node with a domain,
// or we reach the content root, collecting urls in the way
var pathParts = new List<string>();
var eltId = int.Parse(elt.GetAttribute("id"));
var eltParentId = int.Parse(((XmlElement) elt.ParentNode).GetAttribute("id"));
var e = elt;
var id = eltId;
var hasDomains = domainHelper.NodeHasDomains(id);
while (hasDomains == false && id != -1)
{
// get the url
var urlName = e.GetAttribute("urlName");
pathParts.Add(urlName);
// move to parent node
e = (XmlElement) e.ParentNode;
id = int.Parse(e.GetAttribute("id"));
hasDomains = id != -1 && domainHelper.NodeHasDomains(id);
}
// no domain, respect HideTopLevelNodeFromPath for legacy purposes
if (hasDomains == false && GlobalSettings.HideTopLevelNodeFromPath)
ApplyHideTopLevelNodeFromPath(umbracoContext, eltId, eltParentId, pathParts);
// assemble the route
pathParts.Reverse();
var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc
var route = (id == -1 ? "" : id.ToString(CultureInfo.InvariantCulture)) + path;
return route;
}
static void ApplyHideTopLevelNodeFromPath(UmbracoContext umbracoContext, int nodeId, int parentId, IList<string> pathParts)
{
// in theory if hideTopLevelNodeFromPath is true, then there should be only once
// top-level node, or else domains should be assigned. but for backward compatibility
// we add this check - we look for the document matching "/" and if it's not us, then
// we do not hide the top level path
// it has to be taken care of in GetByRoute too so if
// "/foo" fails (looking for "/*/foo") we try also "/foo".
// this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but
// that's the way it works pre-4.10 and we try to be backward compat for the time being
if (parentId == -1)
{
var rootNode = umbracoContext.ContentCache.GetByRoute("/", true);
if (rootNode == null)
throw new Exception("Failed to get node at /.");
if (rootNode.Id == nodeId) // remove only if we're the default node
pathParts.RemoveAt(pathParts.Count - 1);
}
else
{
pathParts.RemoveAt(pathParts.Count - 1);
}
}
#endregion
#region XPath Strings
class XPathStringsDefinition
{
public int Version { get; private set; }
public string RootDocuments { get; private set; }
public XPathStringsDefinition(int version)
{
Version = version;
switch (version)
{
// legacy XML schema
case 0:
RootDocuments = "/root/node";
break;
// default XML schema as of 4.10
case 1:
RootDocuments = "/root/* [@isDoc]";
break;
default:
throw new Exception(string.Format("Unsupported Xml schema version '{0}').", version));
}
}
}
static XPathStringsDefinition _xPathStringsValue;
static XPathStringsDefinition XPathStrings
{
get
{
// in theory XPathStrings should be a static variable that
// we should initialize in a static ctor - but then test cases
// that switch schemas fail - so cache and refresh when needed,
// ie never when running the actual site
var version = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? 0 : 1;
if (_xPathStringsValue == null || _xPathStringsValue.Version != version)
_xPathStringsValue = new XPathStringsDefinition(version);
return _xPathStringsValue;
}
}
#endregion
#region Converters
private static IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing)
{
return xmlNode == null ? null : XmlPublishedContent.Get(xmlNode, isPreviewing);
}
private static IEnumerable<IPublishedContent> ConvertToDocuments(XmlNodeList xmlNodes, bool isPreviewing)
{
return xmlNodes.Cast<XmlNode>()
.Select(xmlNode => XmlPublishedContent.Get(xmlNode, isPreviewing));
}
#endregion
#region Getters
public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId)
{
return ConvertToDocument(GetXml(umbracoContext, preview).GetElementById(nodeId.ToString(CultureInfo.InvariantCulture)), preview);
}
public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview)
{
return ConvertToDocuments(GetXml(umbracoContext, preview).SelectNodes(XPathStrings.RootDocuments), preview);
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
if (string.IsNullOrWhiteSpace(xpath)) return null;
var xml = GetXml(umbracoContext, preview);
var node = vars == null
? xml.SelectSingleNode(xpath)
: xml.SelectSingleNode(xpath, vars);
return ConvertToDocument(node, preview);
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var xml = GetXml(umbracoContext, preview);
var node = vars == null
? xml.SelectSingleNode(xpath)
: xml.SelectSingleNode(xpath, vars);
return ConvertToDocument(node, preview);
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
if (string.IsNullOrWhiteSpace(xpath)) return Enumerable.Empty<IPublishedContent>();
var xml = GetXml(umbracoContext, preview);
var nodes = vars == null
? xml.SelectNodes(xpath)
: xml.SelectNodes(xpath, vars);
return ConvertToDocuments(nodes, preview);
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var xml = GetXml(umbracoContext, preview);
var nodes = vars == null
? xml.SelectNodes(xpath)
: xml.SelectNodes(xpath, vars);
return ConvertToDocuments(nodes, preview);
}
public virtual bool HasContent(UmbracoContext umbracoContext, bool preview)
{
var xml = GetXml(umbracoContext, preview);
if (xml == null)
return false;
var node = xml.SelectSingleNode(XPathStrings.RootDocuments);
return node != null;
}
public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview)
{
var xml = GetXml(umbracoContext, preview);
return xml.CreateNavigator();
}
public virtual bool XPathNavigatorIsNavigable { get { return false; } }
#endregion
#region Legacy Xml
static readonly ConditionalWeakTable<UmbracoContext, PreviewContent> PreviewContentCache
= new ConditionalWeakTable<UmbracoContext, PreviewContent>();
private Func<UmbracoContext, bool, XmlDocument> _xmlDelegate;
/// <summary>
/// Gets/sets the delegate used to retrieve the Xml content, generally the setter is only used for unit tests
/// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request
/// </summary>
/// <remarks>
/// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request
/// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff
/// that when run inside of a unit test fails.
/// </remarks>
internal Func<UmbracoContext, bool, XmlDocument> GetXmlDelegate
{
get
{
return _xmlDelegate ?? (_xmlDelegate = (context, preview) =>
{
if (preview)
{
var previewContent = PreviewContentCache.GetOrCreateValue(context); // will use the ctor with no parameters
previewContent.EnsureInitialized(context.UmbracoUser, StateHelper.Cookies.Preview.GetValue(), true, () =>
{
if (previewContent.ValidPreviewSet)
previewContent.LoadPreviewset();
});
if (previewContent.ValidPreviewSet)
return previewContent.XmlContent;
}
return content.Instance.XmlContent;
});
}
set
{
_xmlDelegate = value;
}
}
internal XmlDocument GetXml(UmbracoContext umbracoContext, bool preview)
{
var xml = GetXmlDelegate(umbracoContext, preview);
if (xml == null)
throw new Exception("The Xml cache is corrupt. Use the Health Check data integrity dashboard to fix it.");
return xml;
}
#endregion
#region XPathQuery
static readonly char[] SlashChar = new[] { '/' };
#endregion
#region Detached
public IPublishedProperty CreateDetachedProperty(PublishedPropertyType propertyType, object value, bool isPreviewing)
{
if (propertyType.IsDetachedOrNested == false)
throw new ArgumentException("Property type is neither detached nor nested.", "propertyType");
return new XmlPublishedProperty(propertyType, isPreviewing, value.ToString());
}
#endregion
}
} | {'content_hash': 'bab22a78d445820f9c19693b2a563180', 'timestamp': '', 'source': 'github', 'line_count': 519, 'max_line_length': 161, 'avg_line_length': 42.43159922928709, 'alnum_prop': 0.5848696757787667, 'repo_name': 'sargin48/Umbraco-CMS', 'id': 'e58bc73b254e9f4c2d877409641592d15e267871', 'size': '22022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev-v7', 'path': 'src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '483021'}, {'name': 'Batchfile', 'bytes': '13051'}, {'name': 'C#', 'bytes': '16128384'}, {'name': 'CSS', 'bytes': '646450'}, {'name': 'HTML', 'bytes': '718357'}, {'name': 'JavaScript', 'bytes': '4271420'}, {'name': 'PowerShell', 'bytes': '14687'}, {'name': 'Python', 'bytes': '876'}, {'name': 'Ruby', 'bytes': '765'}, {'name': 'XSLT', 'bytes': '50045'}]} |
using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using App.WP.Resources;
namespace App.WP
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public static PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += CheckForResetNavigation;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
// If the app has received a 'reset' navigation, then we need to check
// on the next navigation to see if the page stack should be reset
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
// Unregister the event so it doesn't get called again
RootFrame.Navigated -= ClearBackStackAfterReset;
// Only clear the stack for 'new' (forward) and 'refresh' navigations
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// For UI consistency, clear the entire page stack
while (RootFrame.RemoveBackEntry() != null)
{
; // do nothing
}
}
#endregion
// Initialize the app's font and flow direction as defined in its localized resource strings.
//
// To ensure that the font of your application is aligned with its supported languages and that the
// FlowDirection for each of those languages follows its traditional direction, ResourceLanguage
// and ResourceFlowDirection should be initialized in each resx file to match these values with that
// file's culture. For example:
//
// AppResources.es-ES.resx
// ResourceLanguage's value should be "es-ES"
// ResourceFlowDirection's value should be "LeftToRight"
//
// AppResources.ar-SA.resx
// ResourceLanguage's value should be "ar-SA"
// ResourceFlowDirection's value should be "RightToLeft"
//
// For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072.
//
private void InitializeLanguage()
{
try
{
// Set the font to match the display language defined by the
// ResourceLanguage resource string for each supported language.
//
// Fall back to the font of the neutral language if the Display
// language of the phone is not supported.
//
// If a compiler error is hit then ResourceLanguage is missing from
// the resource file.
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// Set the FlowDirection of all elements under the root frame based
// on the ResourceFlowDirection resource string for each
// supported language.
//
// If a compiler error is hit then ResourceFlowDirection is missing from
// the resource file.
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// If an exception is caught here it is most likely due to either
// ResourceLangauge not being correctly set to a supported language
// code or ResourceFlowDirection is set to a value other than LeftToRight
// or RightToLeft.
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
}
} | {'content_hash': '4f21c0d6316248d9e02fe3ce711e4e70', 'timestamp': '', 'source': 'github', 'line_count': 223, 'max_line_length': 127, 'avg_line_length': 40.45291479820628, 'alnum_prop': 0.6125706684403059, 'repo_name': 'feedhenry/fh-xamarin-sdk-blank-app', 'id': '2e9bb1e0c828d4918d7b72a5f6d7bd72ecdaac26', 'size': '9023', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'FHXamarinStarterApp/App.WP/App.xaml.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '18817'}]} |
module Azure::Compute::Mgmt::V2019_07_01
module Models
#
# This is the data disk image.
#
class GalleryDataDiskImage < GalleryDiskImage
include MsRestAzure
# @return [Integer] This property specifies the logical unit number of
# the data disk. This value is used to identify data disks within the
# Virtual Machine and therefore must be unique for each data disk
# attached to the Virtual Machine.
attr_accessor :lun
#
# Mapper for GalleryDataDiskImage class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'GalleryDataDiskImage',
type: {
name: 'Composite',
class_name: 'GalleryDataDiskImage',
model_properties: {
size_in_gb: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'sizeInGB',
type: {
name: 'Number'
}
},
host_caching: {
client_side_validation: true,
required: false,
serialized_name: 'hostCaching',
type: {
name: 'Enum',
module: 'HostCaching'
}
},
source: {
client_side_validation: true,
required: false,
serialized_name: 'source',
type: {
name: 'Composite',
class_name: 'GalleryArtifactVersionSource'
}
},
lun: {
client_side_validation: true,
required: true,
serialized_name: 'lun',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| {'content_hash': '567bfac9d96371b5c9bb08cbf4bdc9b8', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 76, 'avg_line_length': 28.943661971830984, 'alnum_prop': 0.4656934306569343, 'repo_name': 'Azure/azure-sdk-for-ruby', 'id': '5037e1798244584de8cd215bf90393d7dcb6b036', 'size': '2219', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'management/azure_mgmt_compute/lib/2019-07-01/generated/azure_mgmt_compute/models/gallery_data_disk_image.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '345216400'}, {'name': 'Shell', 'bytes': '305'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:osgi="http://www.springframework.org/schema/osgi"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/osgi
http://www.springframework.org/schema/osgi/spring-osgi.xsd">
<osgi:service id="ResultFilterInterface" ref="ResultFilter"
interface="eu.neclab.iotplatform.iotbroker.commons.interfaces.ResultFilterInterface" />
<osgi:reference id="KnowledgeBase"
interface="eu.neclab.iotplatform.iotbroker.commons.interfaces.KnowledgeBaseInterface"
cardinality="0..1" timeout="0"></osgi:reference>
</beans> | {'content_hash': 'e5e04ec9a76ba02503575a1c1cb4a7df', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 110, 'avg_line_length': 45.888888888888886, 'alnum_prop': 0.7360774818401937, 'repo_name': 'Fiware/iot.Aeron', 'id': 'aad7807805487aea68e9cf15f973e2960beb65ae', 'size': '826', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'eu.neclab.iotplatform.iotbroker.ext.resultfilter/META-INF/spring/resultFilter-osgi.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '50'}, {'name': 'CSS', 'bytes': '219144'}, {'name': 'HTML', 'bytes': '85436'}, {'name': 'Java', 'bytes': '1561971'}, {'name': 'JavaScript', 'bytes': '31654'}, {'name': 'Puppet', 'bytes': '2463'}, {'name': 'Shell', 'bytes': '53097'}]} |
using namespace std;
int ActionGenerator() {
int Action;
while(true) {
cout << endl << "SELECIONE UMA ACTION: " << endl;
cout << "[1 = ActionX]" << endl << "[2 = ActionZ]" << endl;
cin >> Action;
if (Action == 1 || Action == 2) return Action;
else {
cout << endl << "ACTION INVALIDA !" << endl;
cin.clear(); //Limpa a flag de erro quando há falha no parse do valor entrado
cin.ignore(); //Limpa o buffer
}
}
}
int main() {
cout << ActionGenerator() << endl << "ok" <<endl;
}
//https://pt.stackoverflow.com/q/41855/101
| {'content_hash': '8ebfeb493f7eaed9e2a2c94aedf6239e', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 89, 'avg_line_length': 28.227272727272727, 'alnum_prop': 0.5233494363929146, 'repo_name': 'bigown/SOpt', 'id': '5d55fe4ce896a5469e5a8a3c371c43aed7a4740d', 'size': '642', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'CPP/Console/GetChars2.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '318'}, {'name': 'C', 'bytes': '51493'}, {'name': 'C#', 'bytes': '93348'}, {'name': 'C++', 'bytes': '7209'}, {'name': 'Go', 'bytes': '720'}, {'name': 'Java', 'bytes': '12692'}, {'name': 'JavaScript', 'bytes': '2374'}, {'name': 'Lua', 'bytes': '574'}, {'name': 'PHP', 'bytes': '1829'}, {'name': 'Python', 'bytes': '4919'}, {'name': 'Ruby', 'bytes': '180'}, {'name': 'TypeScript', 'bytes': '1374'}, {'name': 'Visual Basic', 'bytes': '1034'}]} |
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* BooleanArraySerializer.java *
* *
* boolean array serializer class for Java. *
* *
* LastModified: Apr 17, 2016 *
* Author: Ma Bingyao <[email protected]> *
* *
\**********************************************************/
package hprose.io.serialize;
import static hprose.io.HproseTags.TagClosebrace;
import static hprose.io.HproseTags.TagList;
import static hprose.io.HproseTags.TagOpenbrace;
import java.io.IOException;
import java.io.OutputStream;
final class BooleanArraySerializer implements Serializer<boolean[]> {
public final static BooleanArraySerializer instance = new BooleanArraySerializer();
public final static void write(OutputStream stream, WriterRefer refer, boolean[] array) throws IOException {
if (refer != null) refer.set(array);
int length = array.length;
stream.write(TagList);
if (length > 0) {
ValueWriter.writeInt(stream, length);
}
stream.write(TagOpenbrace);
for (int i = 0; i < length; ++i) {
ValueWriter.write(stream, array[i]);
}
stream.write(TagClosebrace);
}
public final void write(Writer writer, boolean[] obj) throws IOException {
OutputStream stream = writer.stream;
WriterRefer refer = writer.refer;
if (refer == null || !refer.write(stream, obj)) {
write(stream, refer, obj);
}
}
}
| {'content_hash': 'd8976c205e5ba8fd12c2cd21e2744ad0', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 112, 'avg_line_length': 42.54716981132076, 'alnum_prop': 0.41419068736141906, 'repo_name': 'mikeqian/hprose-java', 'id': 'b4c40abc3cd88fc27a6aa19150d0c8ddc45be46f', 'size': '2255', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/hprose/io/serialize/BooleanArraySerializer.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1132456'}]} |
The lightweight alternative to jQuery. But more focused at plugins instead of having a large library. Aswell as jQuery 1 and 2 being slow and not up to date with most JS functions in the newer browsers.
QLib works basically like jQuery but has some tweaks.
No documentation yet. But it behaves quite like jQuery with some exceptions and other addons
## List of functions added as of the latest version
### Fully implemented:
// Static functions
* Q.version
* Q.ajax
* Q.getJSON
* Q.getFile
* Q.isNumber
* Q.isNode
* Q.isPlainObj
* Q.extend or Q.fn
* Q.load
* Q.ready
* Q.each
* Q.format
// Prototype functions
* Q.fn.first
* Q.fn.last
* Q.fn.children
* Q.fn.siblings
* Q.fn.parent
* Q.fn.parents
* Q.fn.parentsUntil
* Q.fn.eq
* Q.fn.each
* Q.fn.find
* Q.fn.filter
* Q.fn.trigger
* Q.fn.focus
* Q.fn.text
* Q.fn.html
* Q.fn.append
* Q.fn.prepend
* Q.fn.before
* Q.fn.after
* Q.fn.clear
* Q.fn.val
* Q.fn.remove
* Q.fn.clone
* Q.fn.show
* Q.fn.hide
* Q.fn.css
* Q.fn.outerHeight
* Q.fn.outerWidth
* Q.fn.offset
* Q.fn.position
* Q.fn.attr
* Q.fn.removeAttr
* Q.fn.hasAttr
* Q.fn.addClass
* Q.fn.removeClass
* Q.fn.hasClass
* Q.fn.data
* Q.fn.removeData
* Q.fn.hasData
### Partial implementation:
// Static functions
// Prototype functions
* Q.fn.on
* Q.fn.one
* Q.fn.off
### Planned implementation:
// Static functions
// Prototype functions
* Q.fn.wrap
* Q.fn.wrapAll
| {'content_hash': '987ef3d6f5cb0e7a30634996208b4178', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 202, 'avg_line_length': 17.641025641025642, 'alnum_prop': 0.7027616279069767, 'repo_name': 'iFaxity/QLib', 'id': 'b2fabfecdbcc517ec810884f40903c86774c6dab', 'size': '1383', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '271'}, {'name': 'HTML', 'bytes': '1224'}, {'name': 'JavaScript', 'bytes': '48506'}]} |
This is a fork of [mongoid-ancestry-0.2.3](https://github.com/skyeagle/mongoid-ancestry/tree/v0.2.3) with some fixes
===================================================================
##fixes in lib/mongoid-ancestry/instance_methods.rb
def current_search_scope
self.embedded? ? self._parent.send(self.base_class.to_s.tableize) : self.base_class
end
def parent_id= parent_id
self.parent = parent_id.blank? ? nil : current_search_scope.find(parent_id)
end
def parent
parent_id.blank? ? nil : current_search_scope.find(parent_id)
end
def root_id
(root_id == id) ? self : current_search.find(root_id)
end
def root
(root_id == id) ? self : current_search_scope.find(root_id)
end
def children
current_search_scope.where(child_conditions)
end
[](http://travis-ci.org/joe1chen/mongoid-ancestry)
Mongoid-ancestry is a gem/plugin that allows the records of a Ruby on Rails Mongoid model to be organised as a tree structure (or hierarchy). It uses a single, intuitively formatted database column, using a variation on the materialised path pattern. It exposes all the standard tree structure relations (ancestors, parent, root, children, siblings, descendants) and all of them can be fetched in a single query. Additional features are STI support, scopes, depth caching, depth constraints, easy migration from older plugins/gems, integrity checking, integrity restoration, arrangement of (sub)tree into hashes and different strategies for dealing with orphaned records.
## Installation
### It's Rails 3 only.
To apply Mongoid-ancestry to any Mongoid model, follow these simple steps:
1. Install
* Add to Gemfile: `gem 'mongoid-ancestry', git: 'https://github.com/shilovk/mongoid-ancestry-0.2.3'`
* Install required gems: `bundle install`
2. Add ancestry to your model
include Mongoid::Ancestry
has_ancestry
Your model is now a tree!
## Organising records into a tree
You can use the parent attribute to organise your records into a tree. If you have the id of the record you want
to use as a parent and don't want to fetch it, you can also use `parent_id`. Like any virtual model attributes,
parent and `parent_id` can be set using `parent=` and `parent_id=` on a record or by including them in the hash passed
to new, create, create!, `update_attributes` and `update_attributes!`. For example:
TreeNode.create :name => 'Stinky', :parent => TreeNode.create(:name => 'Squeeky')
or
TreeNode.create :name => 'Stinky', :parent_id => TreeNode.create(:name => 'Squeeky').id
#### Note: It doesn't work with `.create!` at the moment(mongoid bug? needs more investigation). But it absolutely will be fixed.
You can also create children through the children relation on a node:
node.children.create :name => 'Stinky'
## Navigating your tree
To navigate an Ancestry model, use the following methods on any instance / record:
parent Returns the parent of the record, nil for a root node
parent_id Returns the id of the parent of the record, nil for a root node
root Returns the root of the tree the record is in, self for a root node
root_id Returns the id of the root of the tree the record is in
is_root? Returns true if the record is a root node, false otherwise
ancestor_ids Returns a list of ancestor ids, starting with the root id and ending with the parent id
ancestors Scopes the model on ancestors of the record
path_ids Returns a list the path ids, starting with the root id and ending with the node's own id
path Scopes model on path records of the record
children Scopes the model on children of the record
child_ids Returns a list of child ids
has_children? Returns true if the record has any children, false otherwise
is_childless? Returns true is the record has no childen, false otherwise
siblings Scopes the model on siblings of the record, the record itself is included
sibling_ids Returns a list of sibling ids
has_siblings? Returns true if the record's parent has more than one child
is_only_child? Returns true if the record is the only child of its parent
descendants Scopes the model on direct and indirect children of the record
descendant_ids Returns a list of a descendant ids
subtree Scopes the model on descendants and itself
subtree_ids Returns a list of all ids in the record's subtree
depth Return the depth of the node, root nodes are at depth 0
## Options for has_ancestry
The `has_ancestry` methods supports the following options:
:ancestry_field Pass in a symbol to store ancestry in a different field
:orphan_strategy Instruct Ancestry what to do with children of a node that is destroyed:
:destroy All children are destroyed as well (default)
:rootify The children of the destroyed node become root nodes
:restrict An Error is raised if any children exist
:cache_depth Cache the depth of each node in the `ancestry_depth` field (default: false)
If you turn depth_caching on for an existing model:
- Mongoid has default configuration attribute `allow_dynamic_fields` as `true`.
You should manually add this depth field with `Integer` type and `0` as default value
into your model if `allow_dynamic_fields` is disabled in your configuration.
- Build cache: TreeNode.rebuild_depth_cache!
:depth_cache_field Pass in a symbol to store depth cache in a different field
## Scopes
Where possible, the navigation methods return scopes instead of records, this means additional ordering, conditions, limits, etc. can be applied and that the result can be either retrieved, counted or checked for existence. For example:
node.children.where(:name => 'Mary')
node.subtree.order_by([:name, :desc]).limit(10).each do; ...; end
node.descendants.count
For convenience, a couple of named scopes are included at the class level:
roots Root nodes
ancestors_of(node) Ancestors of node, node can be either a record or an id
children_of(node) Children of node, node can be either a record or an id
descendants_of(node) Descendants of node, node can be either a record or an id
subtree_of(node) Subtree of node, node can be either a record or an id
siblings_of(node) Siblings of node, node can be either a record or an id
Thanks to some convenient rails magic, it is even possible to create nodes through the children and siblings scopes:
node.children.create
node.siblings.create
TestNode.children_of(node_id).build
TestNode.siblings_of(node_id).create
## Selecting nodes by depth
When depth caching is enabled (see `has_ancestry` options), five more named scopes can be used to select nodes on their depth:
before_depth(depth) Return nodes that are less deep than depth (node.depth < depth)
to_depth(depth) Return nodes up to a certain depth (node.depth <= depth)
at_depth(depth) Return nodes that are at depth (node.depth == depth)
from_depth(depth) Return nodes starting from a certain depth (node.depth >= depth)
after_depth(depth) Return nodes that are deeper than depth (node.depth > depth)
The depth scopes are also available through calls to `descendants`, `descendant_ids`, `subtree`, `subtree_ids`, `path` and `ancestors`. In this case, depth values are interpreted relatively. Some examples:
node.subtree(:to_depth => 2) Subtree of node, to a depth of node.depth + 2 (self, children and grandchildren)
node.subtree.to_depth(5) Subtree of node to an absolute depth of 5
node.descendants(:at_depth => 2) Descendant of node, at depth node.depth + 2 (grandchildren)
node.descendants.at_depth(10) Descendants of node at an absolute depth of 10
node.ancestors.to_depth(3) The oldest 4 ancestors of node (its root and 3 more)
node.path(:from_depth => -2) The node's grandparent, parent and the node itself
node.ancestors(:from_depth => -6, :to_depth => -4)
node.path.from_depth(3).to_depth(4)
node.descendants(:from_depth => 2, :to_depth => 4)
node.subtree.from_depth(10).to_depth(12)
Please note that depth constraints cannot be passed to `ancestor_ids` and `path_ids`. The reason for this is that
both these relations can be fetched directly from the ancestry column without performing a database query. It would
require an entirely different method of applying the depth constraints which isn't worth the effort of implementing.
You can use `ancestors(depth_options).map(&:id)` or `ancestor_ids.slice(min_depth..max_depth)` instead.
## STI support
Ancestry works fine with STI. Just create a STI inheritance hierarchy and build an Ancestry tree from the different classes/models. All Ancestry relations that where described above will return nodes of any model type. If you do only want nodes of a specific subclass you'll have to add a condition on type for that.
## Arrangement
Ancestry can arrange an entire subtree into nested hashes for easy navigation after retrieval from the database. TreeNode.arrange could for example return:
{ #<TreeNode id: 100018, name: "Stinky", ancestry: nil>
=> { #<TreeNode id: 100019, name: "Crunchy", ancestry: "100018">
=> { #<TreeNode id: 100020, name: "Squeeky", ancestry: "100018/100019">
=> {}
}
}
}
The arrange method also works on a scoped class, for example:
TreeNode.where(:name => 'Crunchy').first.subtree.arrange
The arrange method takes Mongoid find options. If you want your hashes to be ordered, you should pass the order to the arrange method instead of to the scope. This only works for Ruby 1.9 and later since before that hashes weren't ordered. For example:
TreeNode.where(:name => 'Crunchy').subtree.arrange(:order => [:name, :asc])
## Migrating from plugin that uses parent_id column
With Mongoid-ancestry its easy to migrate from any of these plugins, to do so, use the `Model.build_ancestry_from_parent_ids!` method on your model. These steps provide a more detailed explanation:
1. Remove old tree plugin or gem and add in Mongoid-ancestry
* See 'Installation' for more info on installing and configuring gem
* Add to app/models/model.rb:
include Mongoid::Ancestry
has_ancestry
* Create indexes
2. Change your code
Most tree calls will probably work fine with ancestry
Others must be changed or proxied
Check if all your data is intact and all tests pass
3. Drop `parent_id` field
## Integrity checking and restoration
I don't see any way Mongoid-ancestry tree integrity could get compromised without explicitly setting cyclic parents or invalid ancestry and circumventing validation with `update_attribute`, if you do, please let me know.
Mongoid-ancestry includes some methods for detecting integrity problems and restoring integrity just to be sure. To check integrity use: `Model.check_ancestry_integrity!`. An Mongoid::Ancestry::Error will be raised if there are any problems. You can also specify `:report => :list` to return an array of exceptions or `:report => :echo` to echo any error messages. To restore integrity use: `Model.restore_ancestry_integrity!`.
For example, from IRB:
>> stinky = TreeNode.create :name => 'Stinky'
$ #<TreeNode id: 1, name: "Stinky", ancestry: nil>
>> squeeky = TreeNode.create :name => 'Squeeky', :parent => stinky
$ #<TreeNode id: 2, name: "Squeeky", ancestry: "1">
>> stinky.update_attribute :parent, squeeky
$ true
>> TreeNode.all
$ [#<TreeNode id: 1, name: "Stinky", ancestry: "1/2">, #<TreeNode id: 2, name: "Squeeky", ancestry: "1/2/1">]
>> TreeNode.check_ancestry_integrity!
!! Ancestry::AncestryIntegrityException: Conflicting parent id in node 1: 2 for node 1, expecting nil
>> TreeNode.restore_ancestry_integrity!
$ [#<TreeNode id: 1, name: "Stinky", ancestry: 2>, #<TreeNode id: 2, name: "Squeeky", ancestry: nil>]
Additionally, if you think something is wrong with your depth cache:
>> TreeNode.rebuild_depth_cache!
## Tests
The Mongoid-ancestry gem comes with rspec and guard(for automatically specs running) suite consisting of about 40 specs. It takes about 10 seconds to run. To run it yourself check out the repository from GitHub, run `bundle install`, run `guard` and press `Ctrl+\ ` or just `rake spec`.
## Internals
As can be seen in the previous section, Mongoid-ancestry stores a path from the root to the parent for every node. This is a variation on the materialised path database pattern. It allows to fetch any relation (siblings, descendants, etc.) in a single query without the complicated algorithms and incomprehensibility associated with left and right values. Additionally, any inserts, deletes and updates only affect nodes within the affected node's own subtree.
The materialised path pattern requires Mongoid-ancestry to use a `regexp` condition in order to fetch descendants. This should not be particularly slow however since the the condition never starts with a wildcard which allows the DBMS to use the column index. If you have any data on performance with a large number of records, please drop me line.
## Contact and copyright
It's a fork of [original ancestry](https://github.com/stefankroes/ancestry) gem but adopted to work with Mongoid.
All thanks should goes to Stefan Kroes for his great work.
Bug report? Faulty/incomplete documentation? Feature request? Please post an issue on [issues tracker](http://github.com/skyeagle/mongoid-ancestry/issues).
Copyright (c) 2009 Stefan Kroes, released under the MIT license
| {'content_hash': '8be83467d653a78f3c8ee7f849c5292b', 'timestamp': '', 'source': 'github', 'line_count': 255, 'max_line_length': 671, 'avg_line_length': 55.25098039215686, 'alnum_prop': 0.7121868124068422, 'repo_name': 'shilovk/mongoid-ancestry-0.2.3-fixes', 'id': '34891e97ca702d1ebe5c8f1e3f16c497d0f3410f', 'size': '14089', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '47714'}]} |
<component name="libraryTable">
<library name="appcompat-v7-24.0.0">
<ANNOTATIONS>
<root url="jar://$PROJECT_DIR$/Application/build/intermediates/exploded-aar/com.android.support/appcompat-v7/24.0.0/annotations.zip!/" />
</ANNOTATIONS>
<CLASSES>
<root url="jar://$PROJECT_DIR$/Application/build/intermediates/exploded-aar/com.android.support/appcompat-v7/24.0.0/jars/classes.jar!/" />
<root url="file://$PROJECT_DIR$/Application/build/intermediates/exploded-aar/com.android.support/appcompat-v7/24.0.0/res" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/Library/Android/sdk/extras/android/m2repository/com/android/support/appcompat-v7/24.0.0/appcompat-v7-24.0.0-sources.jar!/" />
</SOURCES>
</library>
</component> | {'content_hash': '94ecaf4655fd8b0d9e4681144625bb96', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 160, 'avg_line_length': 52.53333333333333, 'alnum_prop': 0.6967005076142132, 'repo_name': 'barakmatnas/speed', 'id': '7e6b8fcc0921228561c777a558b71bcec77dc5ca', 'size': '788', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.idea/libraries/appcompat_v7_24_0_0.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1148650'}]} |
var courses =
[
{
name: "Introduction to Computer Science",
slug: "introduction-to-computer-science",
campaignID: ObjectId("55b29efd1cd6abe8ce07db0d"),
concepts: ['basic_syntax', 'arguments', 'while_loops', 'strings', 'variables'],
description: "Learn basic syntax, while loops, and the CodeCombat environment.",
duration: NumberInt(1),
pricePerSeat: NumberInt(0),
free: true,
screenshot: "/images/pages/courses/101_info.png"
},
{
name: "Computer Science 2",
slug: "computer-science-2",
campaignID: ObjectId("562f88e84df18473073c74e2"),
concepts: ['basic_syntax', 'arguments', 'while_loops', 'strings', 'variables', 'if_statements'],
description: "Introduce Arguments, Variables, If Statements, and Arithmetic.",
duration: NumberInt(5),
pricePerSeat: NumberInt(400),
free: false,
screenshot: "/images/pages/courses/102_info.png"
},
{
name: "Computer Science 3",
slug: "computer-science-3",
campaignID: ObjectId("56462ac4410c528505e1160a"),
concepts: ['if_statements', 'arithmetic'],
description: "Introduces arithmetic, counters, advanced while loops, break, continue, arrays.",
duration: NumberInt(5),
pricePerSeat: NumberInt(400),
free: false,
screenshot: "/images/pages/courses/103_info.png"
},
{
name: "Computer Science 4",
slug: "computer-science-4",
campaignID: ObjectId("56462c1133f1478605ebd018"),
concepts: ['if_statements', 'arithmetic'],
description: "Introduces object literals, for loops, function definitions, drawing, and modulo.",
duration: NumberInt(5),
pricePerSeat: NumberInt(400),
free: false,
screenshot: "/images/pages/courses/104_info.png"
}
];
print("Finding course concepts..");
for (var i = 0; i < courses.length; i++) {
var concepts = {};
var cursor = db.campaigns.find({_id: courses[i].campaignID}, {'levels': 1});
if (cursor.hasNext()) {
var doc = cursor.next();
for (var levelID in doc.levels) {
for (var j = 0; j < doc.levels[levelID].concepts.length; j++) {
concepts[doc.levels[levelID].concepts[j]] = true;
}
}
}
courses[i].concepts = Object.keys(concepts);
}
print("Updating courses..");
for (var i = 0; i < courses.length; i++) {
db.courses.update({name: courses[i].name}, courses[i], {upsert: true});
}
print("Done.");
| {'content_hash': 'eb2ee518c9a11a98b33f19274dad50cf', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 101, 'avg_line_length': 34.231884057971016, 'alnum_prop': 0.6587637595258256, 'repo_name': 'weevilgenius/codecombat', 'id': 'ab475d26d07a4bcff3491567c9fa81a002c7177f', 'size': '2598', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'scripts/mongodb/updateCourses.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '277'}, {'name': 'CSS', 'bytes': '273256'}, {'name': 'CoffeeScript', 'bytes': '8068386'}, {'name': 'HTML', 'bytes': '430536'}, {'name': 'JavaScript', 'bytes': '369467'}, {'name': 'Python', 'bytes': '51084'}, {'name': 'Shell', 'bytes': '3136'}]} |
package com.microsoft.azure.management.netapp.v2019_11_01.implementation;
import java.util.Arrays;
import java.util.Iterator;
class IdParsingUtils {
public static String getValueFromIdByName(String id, String name) {
if (id == null) {
return null;
}
Iterable<String> iterable = Arrays.asList(id.split("/"));
Iterator<String> itr = iterable.iterator();
while (itr.hasNext()) {
String part = itr.next();
if (part != null && part.trim() != "") {
if (part.equalsIgnoreCase(name)) {
if (itr.hasNext()) {
return itr.next();
} else {
return null;
}
}
}
}
return null;
}
public static String getValueFromIdByPosition(String id, int pos) {
if (id == null) {
return null;
}
Iterable<String> iterable = Arrays.asList(id.split("/"));
Iterator <String> itr = iterable.iterator();
int index = 0;
while (itr.hasNext()) {
String part = itr.next();
if (part != null && part.trim() != "") {
if (index == pos) {
if (itr.hasNext()) {
return itr.next();
} else {
return null;
}
}
}
index++;
}
return null;
}
}
| {'content_hash': 'a8930fcfed9f345a839b912021911d82', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 73, 'avg_line_length': 29.745098039215687, 'alnum_prop': 0.44034278180619646, 'repo_name': 'selvasingh/azure-sdk-for-java', 'id': '6798c407be64d51db114e4de622a5a12ab6ada9f', 'size': '1747', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sdk/netapp/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/netapp/v2019_11_01/implementation/IdParsingUtils.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '29891970'}, {'name': 'JavaScript', 'bytes': '6198'}, {'name': 'PowerShell', 'bytes': '160'}, {'name': 'Shell', 'bytes': '609'}]} |
var env = require('./environment.js');
exports.config = {
seleniumAddress: env.seleniumAddress,
framework: 'jasmine',
specs: ['pass_spec.js'],
baseUrl: env.baseUrl,
plugins: [{
path: '../index.js',
failOnWarning: true,
logWarnings: false,
failOnError: false
}]
};
| {'content_hash': 'e0c860e00f03e43c0bba84b6368a55b3', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 39, 'avg_line_length': 20.928571428571427, 'alnum_prop': 0.6382252559726962, 'repo_name': 'angular/protractor-console-plugin', 'id': 'aa853e44640b8ae2efc7321f5997af6f6a8f941e', 'size': '293', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/consolePassLogWarnings.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1305'}, {'name': 'JavaScript', 'bytes': '17291'}]} |
scatterbytes.client package
===========================
Submodules
----------
scatterbytes.client.chunk module
--------------------------------
.. automodule:: scatterbytes.client.chunk
:members:
:undoc-members:
:show-inheritance:
scatterbytes.client.downloader module
-------------------------------------
.. automodule:: scatterbytes.client.downloader
:members:
:undoc-members:
:show-inheritance:
scatterbytes.client.jsonrpc module
----------------------------------
.. automodule:: scatterbytes.client.jsonrpc
:members:
:undoc-members:
:show-inheritance:
scatterbytes.client.node module
-------------------------------
.. automodule:: scatterbytes.client.node
:members:
:undoc-members:
:show-inheritance:
scatterbytes.client.util module
-------------------------------
.. automodule:: scatterbytes.client.util
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: scatterbytes.client
:members:
:undoc-members:
:show-inheritance:
| {'content_hash': '0996ab15b241199be51eabd940136f7e', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 46, 'avg_line_length': 19.574074074074073, 'alnum_prop': 0.5685903500473037, 'repo_name': 'ScatterBytes/scatterbytes', 'id': '604542fdfca20c3842fad94a56abf0b4a5ea23f8', 'size': '1057', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'docs/apidoc/scatterbytes.client.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '19068'}, {'name': 'JavaScript', 'bytes': '49784'}, {'name': 'Makefile', 'bytes': '5678'}, {'name': 'Python', 'bytes': '360495'}, {'name': 'Shell', 'bytes': '17959'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Feb 06 09:38:19 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.jolokia.access.Section.Consumer (BOM: * : All 2017.10.2 API)</title>
<meta name="date" content="2018-02-06">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.jolokia.access.Section.Consumer (BOM: * : All 2017.10.2 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/jolokia/access/Section.Consumer.html" title="interface in org.wildfly.swarm.jolokia.access">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.10.2</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/jolokia/access/class-use/Section.Consumer.html" target="_top">Frames</a></li>
<li><a href="Section.Consumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.jolokia.access.Section.Consumer" class="title">Uses of Interface<br>org.wildfly.swarm.jolokia.access.Section.Consumer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/jolokia/access/Section.Consumer.html" title="interface in org.wildfly.swarm.jolokia.access">Section.Consumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.jolokia.access">org.wildfly.swarm.jolokia.access</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.jolokia.access">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/jolokia/access/Section.Consumer.html" title="interface in org.wildfly.swarm.jolokia.access">Section.Consumer</a> in <a href="../../../../../../org/wildfly/swarm/jolokia/access/package-summary.html">org.wildfly.swarm.jolokia.access</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/jolokia/access/package-summary.html">org.wildfly.swarm.jolokia.access</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/jolokia/access/Section.Consumer.html" title="interface in org.wildfly.swarm.jolokia.access">Section.Consumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/jolokia/access/JolokiaAccess.html" title="class in org.wildfly.swarm.jolokia.access">JolokiaAccess</a></code></td>
<td class="colLast"><span class="typeNameLabel">JolokiaAccess.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/jolokia/access/JolokiaAccess.html#allow-org.wildfly.swarm.jolokia.access.Section.Consumer-">allow</a></span>(<a href="../../../../../../org/wildfly/swarm/jolokia/access/Section.Consumer.html" title="interface in org.wildfly.swarm.jolokia.access">Section.Consumer</a> config)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/jolokia/access/JolokiaAccess.html" title="class in org.wildfly.swarm.jolokia.access">JolokiaAccess</a></code></td>
<td class="colLast"><span class="typeNameLabel">JolokiaAccess.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/jolokia/access/JolokiaAccess.html#deny-org.wildfly.swarm.jolokia.access.Section.Consumer-">deny</a></span>(<a href="../../../../../../org/wildfly/swarm/jolokia/access/Section.Consumer.html" title="interface in org.wildfly.swarm.jolokia.access">Section.Consumer</a> config)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/jolokia/access/Section.Consumer.html" title="interface in org.wildfly.swarm.jolokia.access">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.10.2</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/jolokia/access/class-use/Section.Consumer.html" target="_top">Frames</a></li>
<li><a href="Section.Consumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {'content_hash': '46a62f306792d99840af58614dbc9669', 'timestamp': '', 'source': 'github', 'line_count': 172, 'max_line_length': 446, 'avg_line_length': 46.98837209302326, 'alnum_prop': 0.6445186834941846, 'repo_name': 'wildfly-swarm/wildfly-swarm-javadocs', 'id': 'a6492acb42c17a41d30d5ad8d9cf3876e97788d9', 'size': '8082', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '2017.10.2/apidocs/org/wildfly/swarm/jolokia/access/class-use/Section.Consumer.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
Bond futures
============
This documentation described the bond futures used in the main currencies (USD, EUR, GBP, JPY).
Security
--------
The **BondFuturesSecurityDefinition** describes the fungible instruments.
There are two constructors, one from all the details (in particular dates) and a shorter version where some dates are computed from the details of the bond.
In the first version, the inputs are the notice dates (start and end), the delivery dates (start and end), the basket, the conversion factors and the notional.
In the second version, the delivery dates are computed from the notice dates by adding the standard settlement lag of the bond in the basket. This standard approach does not work all all currencies. In particular the standard settlement lag for German government bond is 3 days while the lag between the notice date and the delivery is 2 days for EUR bond futures.
Some examples of actual bond futures can be found in the class **BondFuturesDataSets**: Bobl futures (June 2014) and 5-Year U.S. Treasury Note Futures (FVU1 - September 2011).
Transaction
-----------
The **BondFuturesTransactionDefinition** describes a specific trade or transaction done on the fungible instrument described in the previous section.
The transaction is constructed from the underlying and the quantity, the trade date and the trade price details.
| {'content_hash': '204f676c9807689177ec079ba22074d1', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 364, 'avg_line_length': 54.8, 'alnum_prop': 0.781021897810219, 'repo_name': 'nssales/OG-Platform', 'id': '26be02eec81bb688d11e8971feab35b78b57f4fc', 'size': '1370', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'docs/og-analytics/instruments/futures-bond.rst', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4064'}, {'name': 'CSS', 'bytes': '212432'}, {'name': 'GAP', 'bytes': '1490'}, {'name': 'Groovy', 'bytes': '11518'}, {'name': 'HTML', 'bytes': '284313'}, {'name': 'Java', 'bytes': '80833346'}, {'name': 'JavaScript', 'bytes': '1672518'}, {'name': 'PLSQL', 'bytes': '105'}, {'name': 'PLpgSQL', 'bytes': '13175'}, {'name': 'Protocol Buffer', 'bytes': '53119'}, {'name': 'SQLPL', 'bytes': '1004'}, {'name': 'Shell', 'bytes': '10958'}]} |
package cern.gp.capabilities;
import cern.gp.nodes.GPNode;
/**
* Capability an object implements so that it can be copied.
* This capability is invoked by the corresponding Action
*
* @see cern.gp.actions.CopyAction
* @author Vito Baggiolini
* @version $Revision: 1.2 $ $Date: 2006/09/25 08:52:36 $
*/
public interface CopyCapability extends Capability {
/**
* Tells this object that it has to be copied. The object
* has to interpret what copy means in its own context, which is done by
* implementing this interface.
* @param node the node representing the bean on which the capability has been activated
*/
public void copy(GPNode node);
}
| {'content_hash': '2d7bf55ed8355502687f3819b3f7773f', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 90, 'avg_line_length': 28.333333333333332, 'alnum_prop': 0.7161764705882353, 'repo_name': 'csrg-utfsm/acscb', 'id': '0398f90aa3ef21cd6be735b33692a0e415a639c6', 'size': '876', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'LGPL/CommonSoftware/ACSLaser/gp/src/cern/gp/capabilities/CopyCapability.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Awk', 'bytes': '633'}, {'name': 'Batchfile', 'bytes': '2346'}, {'name': 'C', 'bytes': '751150'}, {'name': 'C++', 'bytes': '7892598'}, {'name': 'CSS', 'bytes': '21364'}, {'name': 'Elixir', 'bytes': '906'}, {'name': 'Emacs Lisp', 'bytes': '1990066'}, {'name': 'FreeMarker', 'bytes': '7369'}, {'name': 'GAP', 'bytes': '14867'}, {'name': 'Gnuplot', 'bytes': '437'}, {'name': 'HTML', 'bytes': '1857062'}, {'name': 'Haskell', 'bytes': '764'}, {'name': 'Java', 'bytes': '13573740'}, {'name': 'JavaScript', 'bytes': '19058'}, {'name': 'Lex', 'bytes': '5101'}, {'name': 'Makefile', 'bytes': '1624406'}, {'name': 'Module Management System', 'bytes': '4925'}, {'name': 'Objective-C', 'bytes': '3223'}, {'name': 'PLSQL', 'bytes': '9496'}, {'name': 'Perl', 'bytes': '120411'}, {'name': 'Python', 'bytes': '4191000'}, {'name': 'Roff', 'bytes': '9920'}, {'name': 'Shell', 'bytes': '1198375'}, {'name': 'Smarty', 'bytes': '21615'}, {'name': 'Tcl', 'bytes': '227078'}, {'name': 'XSLT', 'bytes': '100454'}, {'name': 'Yacc', 'bytes': '5006'}]} |
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<header class="header">
<h1>
Welcome to {{title}}!
</h1>
</header>
<section class="main" style="background-color: white;">
<input class="new-todo" type="text" placeholder="What needs to be done?" (keyup.enter)="addTodo($event)">
<ul class="todo-list">
<li *ngFor="let todo of todos" [class.completed]="todo.done">
<div class="view">
<input class="toggle" type="checkbox" (click)="toggleDone(todo)" [checked]="todo.done">
<label>{{todo.description}}</label>
<button class="destroy" (click)="removeTodo(todo)"></button>
</div>
</li>
</ul>
</section>
`,
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'SaarJS Demo';
todos = [];
public addTodo(event) {
this.todos.push({description: event.target.value, done: false});
event.target.value = '';
}
public removeTodo(todo) {
const index = this.todos.indexOf(todo);
this.todos.splice(index, 1);
}
public toggleDone(todo) {
todo.done = !todo.done;
}
}
| {'content_hash': '4eea8df5a1692d4a4c1942d0b76a741e', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 111, 'avg_line_length': 26.704545454545453, 'alnum_prop': 0.5880851063829787, 'repo_name': 'SaarJS/meetup-2017-09', 'id': '268da21dfa8948c9a222a798b2278ff72bff9bb4', 'size': '1175', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'todomvc-saarjs-angular/src/app/todomvc.component.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '104598'}, {'name': 'HTML', 'bytes': '52202'}, {'name': 'JavaScript', 'bytes': '123510'}, {'name': 'TypeScript', 'bytes': '8445'}, {'name': 'Vue', 'bytes': '2310'}]} |
using UnityEngine;
/// Clears the entire screen. This script and GvrPostRender work together
/// to draw the whole screen in VR Mode. There should be exactly one of each
/// component in any GVR-enabled scene. It is part of the _GvrCamera_
/// prefab, which is included in _GvrMain_. The GvrViewer script will
/// create one at runtime if the scene doesn't already have it, so generally
/// it is not necessary to manually add it unless you wish to edit the _Camera_
/// component that it controls.
[RequireComponent(typeof(Camera))]
[AddComponentMenu("GoogleVR/GvrPreRender")]
public class GvrPreRender : MonoBehaviour {
public Camera cam { get; private set; }
void Awake() {
cam = GetComponent<Camera>();
}
void Start() {
// Ensure distortion shader variables are initialized, because we can't count on
// getting a ProfileChanged event on the first frame rendered.
SetShaderGlobals();
}
void Reset() {
#if UNITY_EDITOR
// Member variable 'cam' not always initialized when this method called in Editor.
// So, we'll just make a local of the same name.
var cam = GetComponent<Camera>();
#endif
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = Color.black;
cam.cullingMask = 0;
cam.useOcclusionCulling = false;
cam.depth = -100;
}
void OnPreCull() {
GvrViewer.Instance.UpdateState();
if (GvrViewer.Instance.ProfileChanged) {
SetShaderGlobals();
}
cam.clearFlags = GvrViewer.Instance.VRModeEnabled ?
CameraClearFlags.SolidColor : CameraClearFlags.Nothing;
}
private void SetShaderGlobals() {
// For any shaders that want to use these numbers for distortion correction. But only
// if distortion correction is needed, yet not already being handled by another method.
if (GvrViewer.Instance.VRModeEnabled
&& GvrViewer.Instance.DistortionCorrection == GvrViewer.DistortionCorrectionMethod.None) {
GvrProfile p = GvrViewer.Instance.Profile;
// Distortion vertex shader currently setup for only 6 coefficients.
if (p.viewer.inverse.Coef.Length > 6) {
Debug.LogWarning("Inverse distortion correction has more than 6 coefficents. "
+ "Shader only supports 6.");
}
Matrix4x4 mat = new Matrix4x4() {};
for (int i=0; i<p.viewer.inverse.Coef.Length; i++) {
mat[i] = p.viewer.inverse.Coef[i];
}
Shader.SetGlobalMatrix("_Undistortion", mat);
float[] rect = new float[4];
p.GetLeftEyeVisibleTanAngles(rect);
float r = GvrProfile.GetMaxRadius(rect);
Shader.SetGlobalFloat("_MaxRadSq", r*r);
}
}
}
| {'content_hash': '2cc78283b731a2c5b458daa8b4be94a2', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 98, 'avg_line_length': 37.84285714285714, 'alnum_prop': 0.6896942242355606, 'repo_name': 'enormand/cyber-space-shooter', 'id': '69f68f89d2327952d07e16bc2fa2bc0bc7aebba8', 'size': '3259', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'Assets/GoogleVR/Scripts/GvrPreRender.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '434957'}, {'name': 'GLSL', 'bytes': '4461'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>matrices: 25 s 🏆</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.10.0 / matrices - 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>
matrices
<small>
8.10.0
<span class="label label-success">25 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2021-12-31 19:49:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-31 19:49:08 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
coq 8.10.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/matrices"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Matrices"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: matrices"
"keyword: vectors"
"keyword: linear algebra"
"keyword: Coq modules"
"category: Mathematics/Algebra"
"date: 2003-03"
]
authors: [
"Nicolas Magaud"
]
bug-reports: "https://github.com/coq-contribs/matrices/issues"
dev-repo: "git+https://github.com/coq-contribs/matrices.git"
synopsis: "Ring properties for square matrices"
description: """
This contribution contains an operational formalization of square matrices.
(m,n)-Matrices are represented as vectors of length n. Each vector
(a row) is itself a vector whose length is m.
Vectors are actually implemented as dependent lists.
We define basic operations for this datatype (addition, product, neutral
elements O_n and I_n). We then prove the ring properties for these
operations. The development uses Coq modules to specify the interface
(the ring structure properties) as a signature.
This development deals with dependent types and partial functions.
Most of the functions are defined by dependent case analysis
and some functions such as getting a column require
the use of preconditions (to check whether we are within the
bounds of the matrix)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/matrices/archive/v8.10.0.tar.gz"
checksum: "md5=c3f92319ece9a306765b922ba591bc3f"
}
</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-matrices.8.10.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</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>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-matrices.8.10.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>14 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-matrices.8.10.0 coq.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>25 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 691 K</p>
<ul>
<li>142 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/matrices.glob</code></li>
<li>129 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/matrices.vo</code></li>
<li>118 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/vectors.vo</code></li>
<li>74 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/operators.vo</code></li>
<li>72 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/vectors.glob</code></li>
<li>70 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/operators.glob</code></li>
<li>27 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/matrices.v</code></li>
<li>27 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/carrier.vo</code></li>
<li>15 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/vectors.v</code></li>
<li>14 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/operators.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/carrier.glob</code></li>
<li>2 K <code>../ocaml-base-compiler.4.09.1/lib/coq/user-contrib/Matrices/carrier.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-matrices.8.10.0</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': '965831c1931593114682e1c4c1677c19', 'timestamp': '', 'source': 'github', 'line_count': 189, 'max_line_length': 159, 'avg_line_length': 45.492063492063494, 'alnum_prop': 0.5705978134449872, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'e974ceb4ac682b896594ee10b9ddf80880bd934f', 'size': '8623', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.09.1-2.0.6/released/8.10.0/matrices/8.10.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
<?php
session_start();
if (isset($_SESSION['adminLoggedIn'])){ // if admin not logged in, restrict access.
header( 'Location: /RoboX/admin/edit_products' ) ;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Internet Dreams</title>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" title="default" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" > </script>
<script type="text/javascript" src="/RoboX/cookies/cookies_enabled.js"></script>
<script src="/RoboX/admin/login/login.js" type="text/javascript"> </script>
</script>
<!-- jquery core -->
<script src="js/jquery/jquery-1.4.1.min.js" type="text/javascript"></script>
<!-- Custom jquery scripts -->
<script src="js/jquery/custom_jquery.js" type="text/javascript"></script>
<!-- MUST BE THE LAST SCRIPT IN <HEAD></HEAD></HEAD> png fix -->
<script src="js/jquery/jquery.pngFix.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).pngFix( );
});
</script>
</head>
<body id="login-bg">
<!-- Start: login-holder -->
<div id="login-holder">
<!-- start logo -->
<div id="logo-login">
<h1><a href="/RoboX/" ><img src="/RoboX/images/templatemo_logo.png" alt="RoboX"/></a> </h1>
</div>
<!-- end logo -->
<div class="clear"></div>
<!-- start loginbox ................................................................................. -->
<div id="loginbox">
<!-- start login-inner -->
<div id="login-inner">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Username-Email </th>
<td><input type="text" class="login-inp" id="input_login_id" /></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password" id="password" class="login-inp" /></td>
</tr>
<tr>
<th></th>
<td valign="top"><input type="checkbox" class="checkbox-size" id="login-check" />
<label for="login-check">Remember me</label></td>
</tr>
<tr>
<th></th>
<td><input type="button" class="submit-login" id="login"/><p id="errors_label"></p></td>
</tr>
</table>
</div>
<!-- end login-inner -->
<div class="clear"></div>
<a href="" class="forgot-pwd">Forgot Password?</a> </div>
<!-- end loginbox -->
<!-- start forgotbox ................................................................................... -->
<div id="forgotbox">
<div id="forgotbox-text">Please send us your email and we'll reset your password.</div>
<!-- start forgot-inner -->
<div id="forgot-inner">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Email address:</th>
<td><input type="text" value="" class="login-inp" /></td>
</tr>
<tr>
<th> </th>
<td><input type="button" class="submit-login" /></td>
</tr>
</table>
</div>
<!-- end forgot-inner -->
<div class="clear"></div>
<a href="" class="back-login">Back to login</a> </div>
<!-- end forgotbox -->
</div>
<!-- End: login-holder -->
</body>
</html> | {'content_hash': '84a3fce01959b6d29f781a3142abd27f', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 115, 'avg_line_length': 38.734693877551024, 'alnum_prop': 0.48366701791359323, 'repo_name': 'rdok/RoboX', 'id': '266df57bfbff7a7fcb0768163f8ffdf85caf5993', 'size': '3796', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'RoboX/admin/index.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '134389'}, {'name': 'JavaScript', 'bytes': '261151'}, {'name': 'PHP', 'bytes': '439082'}]} |
package core;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication(scanBasePackages = { "core", "spring" })
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
printBeansInContext(ctx);
}
protected static void printBeansInContext(ApplicationContext ctx) {
System.out.println("Let's inspect the beans provided by Spring Boot:");
Arrays.stream(ctx.getBeanDefinitionNames())
.sorted()
.forEach(beanName -> System.out.println(" - " + beanName));
}
}
| {'content_hash': 'ae6272948b6428a6e77e3f6e2bac78bf', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 80, 'avg_line_length': 33.958333333333336, 'alnum_prop': 0.6932515337423313, 'repo_name': 'caspianb/eAdapter', 'id': 'a2e41f04c8e4123c247dba1d4548856a4c33acce', 'size': '815', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/core/Application.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '97973'}]} |
// -----------------------------------------------------------------------------------------
// <copyright file="AZSIPRange.h" company="Microsoft">
// Copyright 2015 Microsoft Corporation
//
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://spdx.org/licenses/MIT
//
// 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.
// </copyright>
// -----------------------------------------------------------------------------------------
#import <Foundation/Foundation.h>
#import "AZSMacros.h"
/** A range of IPv4 addresses. Contains a minumum IP, maximum IP, and a string representing the range. */
@interface AZSIPRange : NSObject
/** The minimum IP address for this range, inclusive. */
@property (readonly) struct in_addr ipMinimum;
/** The maximum IP address for this range, inclusive. */
@property (readonly) struct in_addr ipMaximum;
/** The single IP address of range of IP addresses, represented as a string. */
@property (strong, readonly) NSString *rangeString;
/** Creates an IP range using the specified single IP address represented by the given string. The address must be IPv4.
@param ipString The single IP address.
@param error A pointer to a NSError*, to be set in the event of failure.
@returns The newly initialized IPRange or nil if the given string is invalid.
*/
-(instancetype) initWithSingleIPString:(NSString *)ipString error:(NSError *__autoreleasing *)error;
/** Creates an IP range encompassing the specified minimum and maximum IP addresses represented by the given strings. The addresses must be IPv4.
@param minimumString The minimum IP address.
@param maximumString The maximum IP address.
@param error A pointer to a NSError*, to be set in the event of failure.
@returns The newly initialized IPRange or nil if the given string is invalid.
*/
-(instancetype) initWithMinIPString:(NSString *)minimumString maxIPString:(NSString *)maximumString error:(NSError *__autoreleasing *)error;
/** Creates an IP range using the specified single IP address. The address must be IPv4.
@param ip The single IP address.
@returns The newly initialized IPRange.
*/
-(instancetype) initWithSingleIP:(struct in_addr)ip AZS_DESIGNATED_INITIALIZER;
/** Creates an IP range encompassing the specified minimum and maximum IP addresses. The addresses must be IPv4.
@param minimum The minimum IP address.
@param maximum The maximum IP address.
@returns The newly initialized IPRange.
*/
-(instancetype) initWithMinIP:(struct in_addr)minimum maxIP:(struct in_addr)maximum AZS_DESIGNATED_INITIALIZER;
@end
| {'content_hash': '92aee9cb52e5e9284aa4cd5e233fa321', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 145, 'avg_line_length': 45.33846153846154, 'alnum_prop': 0.7071598235493722, 'repo_name': 'seunghee2/Dorm-takki', 'id': 'c0d3b630353148497fbae5dc9323bcc7bdcc7d8f', 'size': '2947', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Pods/AZSClient/Lib/Azure Storage Client Library/Azure Storage Client Library/AZSIPRange.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Objective-C', 'bytes': '173'}, {'name': 'Ruby', 'bytes': '633'}, {'name': 'Swift', 'bytes': '32567'}]} |
package io.reactivex.netty.channel;
import io.netty.buffer.ByteBufAllocator;
import io.reactivex.netty.serialization.ContentTransformer;
import rx.Observable;
/**
* An interface to capture how one can write on a channel.
*
* @author Nitesh Kant
*/
public interface ChannelWriter<O> {
Observable<Void> writeAndFlush(O msg);
void write(O msg);
<R> void write(R msg, ContentTransformer<R> transformer);
void writeBytes(byte[] msg);
void writeString(String msg);
Observable<Void> flush();
ByteBufAllocator getAllocator();
<R> Observable<Void> writeAndFlush(R msg, ContentTransformer<R> transformer);
Observable<Void> writeBytesAndFlush(byte[] msg);
Observable<Void> writeStringAndFlush(String msg);
}
| {'content_hash': '468e145fef83c30fe72a1c22fa2c74e1', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 81, 'avg_line_length': 22.818181818181817, 'alnum_prop': 0.7277556440903055, 'repo_name': 'allenxwang/RxNetty', 'id': '8c3692cdb224d22683e47a41bda4821dc21be058', 'size': '753', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rx-netty/src/main/java/io/reactivex/netty/channel/ChannelWriter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '37679'}, {'name': 'Java', 'bytes': '320625'}, {'name': 'Shell', 'bytes': '7484'}]} |
namespace views {
X11DesktopWindowMoveClient::X11DesktopWindowMoveClient()
: move_loop_(this),
root_window_(NULL) {
}
X11DesktopWindowMoveClient::~X11DesktopWindowMoveClient() {}
void X11DesktopWindowMoveClient::OnMouseMovement(XMotionEvent* event) {
gfx::Point cursor_point(event->x_root, event->y_root);
gfx::Point system_loc = cursor_point - window_offset_;
root_window_->SetHostBounds(gfx::Rect(
system_loc, root_window_->GetHostSize()));
}
void X11DesktopWindowMoveClient::OnMouseReleased() {
EndMoveLoop();
}
void X11DesktopWindowMoveClient::OnMoveLoopEnded() {
root_window_ = NULL;
}
////////////////////////////////////////////////////////////////////////////////
// DesktopRootWindowHostLinux, aura::client::WindowMoveClient implementation:
aura::client::WindowMoveResult X11DesktopWindowMoveClient::RunMoveLoop(
aura::Window* source,
const gfx::Vector2d& drag_offset,
aura::client::WindowMoveSource move_source) {
window_offset_ = drag_offset;
root_window_ = source->GetRootWindow();
bool success = move_loop_.RunMoveLoop(source);
return success ? aura::client::MOVE_SUCCESSFUL : aura::client::MOVE_CANCELED;
}
void X11DesktopWindowMoveClient::EndMoveLoop() {
move_loop_.EndMoveLoop();
}
} // namespace views
| {'content_hash': '3fa73ea472dbac55395cbd4cd15bed68', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 80, 'avg_line_length': 29.72093023255814, 'alnum_prop': 0.6940532081377152, 'repo_name': 'pozdnyakov/chromium-crosswalk', 'id': '986e9459c3ad3d131ac0cabf6ddf075f7413fe1a', 'size': '1953', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'ui/views/widget/desktop_aura/x11_desktop_window_move_client.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '1176000'}, {'name': 'Awk', 'bytes': '9519'}, {'name': 'C', 'bytes': '75041908'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '176725300'}, {'name': 'CSS', 'bytes': '739308'}, {'name': 'DOT', 'bytes': '1559'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Java', 'bytes': '3846739'}, {'name': 'JavaScript', 'bytes': '21992206'}, {'name': 'Logos', 'bytes': '4517'}, {'name': 'M', 'bytes': '2190'}, {'name': 'Matlab', 'bytes': '2262'}, {'name': 'Objective-C', 'bytes': '7678425'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '1473208'}, {'name': 'Python', 'bytes': '10062755'}, {'name': 'R', 'bytes': '262'}, {'name': 'Shell', 'bytes': '1589962'}, {'name': 'Tcl', 'bytes': '277077'}, {'name': 'XSLT', 'bytes': '13493'}]} |
require 'yaml'
require 'json'
require 'pp'
# This class is used by Sunstone to set and return the views available to a user
# as well as available tabs.
class SunstoneViews
############################################################################
# Class Constants:
# - Configuration files
# - sunstone-views.yaml includes default group views
############################################################################
VIEWS_CONFIGURATION_FILE = ETC_LOCATION + "/sunstone-views.yaml"
VIEWS_CONFIGURATION_DIR = ETC_LOCATION + "/sunstone-views/"
def initialize(mode)
raise "Sunstone configuration file does not contain default view mode, aborting" if mode.nil?
@views_config = YAML.load_file(VIEWS_CONFIGURATION_FILE)
base_path = SUNSTONE_ROOT_DIR+'/public/js/'
@views = Hash.new
raise "The #{mode} view directory does not exists, aborting" if Dir[VIEWS_CONFIGURATION_DIR + mode].empty?
raise "The #{mode} view directory is empty, aborting" if Dir[VIEWS_CONFIGURATION_DIR + mode + '/*.yaml'].empty?
Dir[VIEWS_CONFIGURATION_DIR + mode + '/*.yaml'].each do |p_path|
reg = VIEWS_CONFIGURATION_DIR + mode + '/'
m = p_path.match(/^#{reg}(.*).yaml$/)
if m && m[1]
@views[m[1]] = YAML.load_file(p_path)
end
end
end
def view(user_name, group_name, view_name=nil)
available_views = available_views(user_name, group_name)
if view_name && available_views.include?(view_name)
return @views[view_name]
else
return @views[available_views.first]
end
end
# Return the name of the views avialable to a user. Those defined in the
# group template and configured in sunstone. If no view is defined in a
# group defaults in sunstone-views.yaml will be used.
#
def available_views(user_name, group_name)
onec = $cloud_auth.client(user_name)
user = OpenNebula::User.new_with_id(OpenNebula::User::SELF, onec)
available = Array.new
rc = user.info
if OpenNebula.is_error?(rc)
return available
end
user.groups.each { |gid|
group = OpenNebula::Group.new_with_id(gid, onec)
rc = group.info
if OpenNebula.is_error?(rc)
return available.uniq
end
if group["TEMPLATE/SUNSTONE/VIEWS"]
views_array = group["TEMPLATE/SUNSTONE/VIEWS"].split(",")
available << views_array.each{|v| v.strip!}
elsif @views_config['groups']
available << @views_config['groups'][group.name]
end
gadmins = group.admin_ids
gadmins_views = group["TEMPLATE/SUNSTONE/GROUP_ADMIN_VIEWS"]
if gadmins && gadmins.include?(user.id) && gadmins_views
views_array = gadmins_views.split(",")
available << views_array.each{|v| v.strip!}
end
}
available.flatten!
available.reject!{|v| [email protected]_key?(v)} #sanitize array views
return available.uniq if !available.empty?
# Fallback to default views if none is defined in templates
available << @views_config['users'][user_name] if @views_config['users']
if @views_config['groups']
available << @views_config['groups'][group_name]
end
available << @views_config['default']
group = OpenNebula::Group.new_with_id(user.gid, onec)
rc = group.info
if !OpenNebula.is_error?(rc)
gadmins = group.admin_ids
if gadmins && gadmins.include?(user.id)
available << @views_config['default_groupadmin']
end
end
available.flatten!
available.reject!{|v| [email protected]_key?(v)} #sanitize array views
return available.uniq
end
def get_all_views
@views.keys
end
def get_all_labels(group_name)
labels = []
if @views_config['labels_groups']
if @views_config['labels_groups'][group_name]
@views_config['labels_groups'][group_name].each{|l| labels.push(l)}
end
if @views_config['labels_groups']['default']
@views_config['labels_groups']['default'].each{|l| labels.push(l)}
end
end
return labels
end
def logo
@views_config['logo']
end
end
| {'content_hash': '44f7ee807948ab1869d03ba1f16cd538', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 119, 'avg_line_length': 32.09219858156028, 'alnum_prop': 0.56, 'repo_name': 'OpenNebula/one', 'id': 'e738f8798e058fd5342f762bf09994c20699b292', 'size': '5711', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/sunstone/models/SunstoneViews.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Augeas', 'bytes': '5809'}, {'name': 'C', 'bytes': '1582926'}, {'name': 'C++', 'bytes': '4972435'}, {'name': 'CSS', 'bytes': '77624'}, {'name': 'Go', 'bytes': '449317'}, {'name': 'HTML', 'bytes': '48493'}, {'name': 'Handlebars', 'bytes': '850880'}, {'name': 'Java', 'bytes': '517105'}, {'name': 'JavaScript', 'bytes': '6983132'}, {'name': 'Jinja', 'bytes': '3712'}, {'name': 'Lex', 'bytes': '10999'}, {'name': 'Makefile', 'bytes': '2832'}, {'name': 'Python', 'bytes': '199809'}, {'name': 'Roff', 'bytes': '2086'}, {'name': 'Ruby', 'bytes': '4919604'}, {'name': 'SCSS', 'bytes': '44872'}, {'name': 'Shell', 'bytes': '1116349'}, {'name': 'Yacc', 'bytes': '35951'}]} |
package org.fiteagle.sfa.common;
public enum GENISliverAllocationState {
geni_unallocated,
geni_allocated,
geni_provisioned;
}
| {'content_hash': '1b65539ba0699100f3f357822ee273b8', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 39, 'avg_line_length': 19.428571428571427, 'alnum_prop': 0.7720588235294118, 'repo_name': 'FITeagle/sfa.old', 'id': '885d5226cdcc1e55ef6119839345d0091b57afcd', 'size': '136', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/fiteagle/sfa/common/GENISliverAllocationState.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '648424'}]} |
package org.elasticsearch.xpack.transform.transforms;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.xpack.core.transform.transforms.TransformTaskState;
import org.elasticsearch.xpack.transform.Transform;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
class TransformContext {
public interface Listener {
void shutdown();
void fail(String failureMessage, ActionListener<Void> listener);
}
private final AtomicReference<TransformTaskState> taskState;
private final AtomicReference<String> stateReason;
private final Listener taskListener;
private volatile int numFailureRetries = Transform.DEFAULT_FAILURE_RETRIES;
private final AtomicInteger failureCount;
private volatile Instant changesLastDetectedAt;
private volatile boolean shouldStopAtCheckpoint;
// the checkpoint of this transform, storing the checkpoint until data indexing from source to dest is _complete_
// Note: Each indexer run creates a new future checkpoint which becomes the current checkpoint only after the indexer run finished
private final AtomicLong currentCheckpoint;
TransformContext(final TransformTaskState taskState, String stateReason, long currentCheckpoint, Listener taskListener) {
this.taskState = new AtomicReference<>(taskState);
this.stateReason = new AtomicReference<>(stateReason);
this.currentCheckpoint = new AtomicLong(currentCheckpoint);
this.taskListener = taskListener;
this.failureCount = new AtomicInteger(0);
this.shouldStopAtCheckpoint = shouldStopAtCheckpoint;
}
TransformTaskState getTaskState() {
return taskState.get();
}
void setTaskState(TransformTaskState newState) {
taskState.set(newState);
}
boolean setTaskState(TransformTaskState oldState, TransformTaskState newState) {
return taskState.compareAndSet(oldState, newState);
}
void resetTaskState() {
taskState.set(TransformTaskState.STARTED);
stateReason.set(null);
}
void setTaskStateToFailed(String reason) {
taskState.set(TransformTaskState.FAILED);
stateReason.set(reason);
}
void resetReasonAndFailureCounter() {
stateReason.set(null);
failureCount.set(0);
}
String getStateReason() {
return stateReason.get();
}
void setCheckpoint(long newValue) {
currentCheckpoint.set(newValue);
}
long getCheckpoint() {
return currentCheckpoint.get();
}
long getAndIncrementCheckpoint() {
return currentCheckpoint.getAndIncrement();
}
void setNumFailureRetries(int numFailureRetries) {
this.numFailureRetries = numFailureRetries;
}
int getNumFailureRetries() {
return numFailureRetries;
}
int getAndIncrementFailureCount() {
return failureCount.getAndIncrement();
}
void setChangesLastDetectedAt(Instant time) {
changesLastDetectedAt = time;
}
Instant getChangesLastDetectedAt() {
return changesLastDetectedAt;
}
public boolean shouldStopAtCheckpoint() {
return shouldStopAtCheckpoint;
}
public void setShouldStopAtCheckpoint(boolean shouldStopAtCheckpoint) {
this.shouldStopAtCheckpoint = shouldStopAtCheckpoint;
}
void shutdown() {
taskListener.shutdown();
}
void markAsFailed(String failureMessage) {
taskListener
.fail(
failureMessage,
ActionListener
.wrap(
r -> {
// Successfully marked as failed, reset counter so that task can be restarted
failureCount.set(0);
},
e -> {}
)
);
}
}
| {'content_hash': 'ed8f6b9795a681c439d25fce840853c2', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 134, 'avg_line_length': 30.037593984962406, 'alnum_prop': 0.6793491864831038, 'repo_name': 'uschindler/elasticsearch', 'id': 'a3fd0b6385e86ff2095dbdd083931d1faa1e043c', 'size': '4236', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/TransformContext.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '11082'}, {'name': 'Batchfile', 'bytes': '11226'}, {'name': 'Emacs Lisp', 'bytes': '3341'}, {'name': 'FreeMarker', 'bytes': '45'}, {'name': 'Groovy', 'bytes': '399054'}, {'name': 'HTML', 'bytes': '2186'}, {'name': 'Java', 'bytes': '46161265'}, {'name': 'Perl', 'bytes': '12007'}, {'name': 'Python', 'bytes': '19852'}, {'name': 'Shell', 'bytes': '105144'}]} |
package uk.gov.prototype.vitruvius.listener;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.json.impl.Json;
import org.vertx.testtools.TestVerticle;
import org.vertx.testtools.VertxAssert;
import uk.gov.prototype.vitruvius.elasticsearch.RepositoryESOperations;
import uk.gov.prototype.vitruvius.parser.domain.RepositoryInformation;
import uk.gov.prototype.vitruvius.parser.domain.RepositoryInformationBuilder;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
public class RepositoryInformationEventListenerTest extends TestVerticle {
private RepositoryInformationEventListener underTest;
private EventBus eb;
@Mock
private RepositoryESOperations repositoryESOperations;
@Test
public void canReturnRepositoryInformation() throws Exception {
MockitoAnnotations.initMocks(this);
underTest = new RepositoryInformationEventListener(repositoryESOperations);
eb = vertx.eventBus();
eb.registerHandler(underTest.handlerAddress(), underTest);
JsonObject eventPayload = new JsonObject();
eventPayload.putString("type", "service");
when(repositoryESOperations.getListOfRepositoryInformation(any(RepositoryESOperations.RepositoryInfoContext.class))).thenReturn(createList());
eb.send(underTest.handlerAddress(), eventPayload, new Handler<Message<String>>() {
@Override
public void handle(Message<String> reply) {
String data = reply.body();
List<RepositoryInformation> list = Json.decodeValue(data, List.class);
VertxAssert.assertThat(list.size(), is(2));
VertxAssert.testComplete();
}
});
}
private List<RepositoryInformation> createList() {
List<RepositoryInformation> list = new ArrayList<>();
list.add(new RepositoryInformationBuilder().build());
list.add(new RepositoryInformationBuilder().build());
return list;
}
}
| {'content_hash': '5cfbf6c538ad7e91a86cafeb9aff2f6e', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 150, 'avg_line_length': 34.71641791044776, 'alnum_prop': 0.7343078245915735, 'repo_name': 'alphagov/vitruvius', 'id': '9eda0458b99e5e94cdf7fdce1c27a9d61b094717', 'size': '2326', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vitruvius.vertx/src/test/java/uk/gov/prototype/vitruvius/listener/RepositoryInformationEventListenerTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '16111'}, {'name': 'HTML', 'bytes': '21021'}, {'name': 'Java', 'bytes': '171297'}, {'name': 'JavaScript', 'bytes': '40163'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="032aaf41-19e0-4da9-834c-3e4482a9a37e" name="Default" comment="" />
<ignored path="cordova_typescript.iws" />
<ignored path=".idea/workspace.xml" />
<file path="/index.ts" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697326357" ignored="false" />
<file path="/index.html" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697176387" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/CorodvaTypeScript/config.xml" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697402035" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/build/emulator/CorodvaTypeScript.app/config.xml" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697402035" ignored="false" />
<file path="$PROJECT_DIR$/platforms/android/res/xml/config.xml" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401696639392" ignored="false" />
<file path="$PROJECT_DIR$/plugins/org.apache.cordova.device/plugin.xml" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697402035" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/build/emulator/CorodvaTypeScript.app/www/js/index_old.js" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697314773" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/www/js/index_old.js" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697362493" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/www/js/index.js" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697314773" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/build/emulator/CorodvaTypeScript.app/www/js/index.js" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697270243" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/build/emulator/CorodvaTypeScript.app/www/cordova.js" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697362493" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/www/js/index.ts" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697402035" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/build/emulator/CorodvaTypeScript.app/www/js/index.ts" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697402035" ignored="false" />
<file path="$PROJECT_DIR$/platforms/ios/www/cordova.js" changelist="032aaf41-19e0-4da9-834c-3e4482a9a37e" time="1401697362493" ignored="false" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="DaemonCodeAnalyzer">
<disable_hints />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
<component name="FavoritesManager">
<favorites_list name="cordova_typescript" />
</component>
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="index.html" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/www/index.html">
<provider selected="true" editor-type-id="text-editor">
<state line="41" column="14" selection-start="1976" selection-end="1976" vertical-scroll-proportion="-15.333333">
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="index_old.js" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/www/js/index_old.js">
<provider selected="true" editor-type-id="text-editor">
<state line="21" column="38" selection-start="904" selection-end="904" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="index.ts" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/www/js/index.ts">
<provider selected="true" editor-type-id="text-editor">
<state line="21" column="27" selection-start="560" selection-end="560" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="index.js" pinned="false" current="true" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/www/js/index.js">
<provider selected="true" editor-type-id="text-editor">
<state line="17" column="38" selection-start="462" selection-end="462" vertical-scroll-proportion="0.4704797">
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FindManager">
<FindUsagesManager>
<setting name="OPEN_NEW_TAB" value="false" />
</FindUsagesManager>
</component>
<component name="IdeDocumentHistory">
<option name="changedFiles">
<list>
<option value="$PROJECT_DIR$/www/index.html" />
<option value="$PROJECT_DIR$/www/js/index.js" />
<option value="$PROJECT_DIR$/www/js/index.ts" />
</list>
</option>
</component>
<component name="ProjectFrameBounds">
<option name="x" value="10" />
<option name="y" value="22" />
<option name="width" value="1900" />
<option name="height" value="970" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectReloadState">
<option name="STATE" value="0" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1" splitterProportion="0.5">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents ProjectPane="true" />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
</navigator>
<panes>
<pane id="ProjectPane">
<subPane>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="www" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="www" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="js" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="cordova_typescript" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="www" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="js" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="index.ts" />
<option name="myItemType" value="com.intellij.plugins.watcher.projectView.NestingTreeNode" />
</PATH_ELEMENT>
</PATH>
</subPane>
</pane>
<pane id="Scope" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
</component>
<component name="RunManager">
<configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit">
<option name="VMOptions" />
<option name="arguments" />
<option name="filePath" />
<option name="scope" value="ALL" />
<option name="testName" />
<method />
</configuration>
<list size="0" />
</component>
<component name="ShelveChangesManager" show_recycled="false" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="032aaf41-19e0-4da9-834c-3e4482a9a37e" name="Default" comment="" />
<created>1401696230670</created>
<updated>1401696230670</updated>
</task>
<servers />
</component>
<component name="ToolWindowManager">
<frame x="10" y="22" width="1900" height="970" extended-state="0" />
<editor active="true" />
<layout>
<window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24986681" sideWeight="0.67058825" order="0" side_tool="false" content_ui="combo" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32941177" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
</layout>
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="VcsManagerConfiguration">
<option name="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" />
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" />
<option name="CHECK_NEW_TODO" value="true" />
<option name="myTodoPanelSettings">
<value>
<are-packages-shown value="false" />
<are-modules-shown value="false" />
<flatten-packages value="false" />
<is-autoscroll-to-source value="false" />
</value>
</option>
<option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" />
<option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" />
<option name="PERFORM_EDIT_IN_BACKGROUND" value="true" />
<option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" />
<option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" />
<option name="PERFORM_ROLLBACK_IN_BACKGROUND" value="false" />
<option name="CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND" value="false" />
<option name="CHANGED_ON_SERVER_INTERVAL" value="60" />
<option name="SHOW_ONLY_CHANGED_IN_SELECTION_DIFF" value="true" />
<option name="CHECK_COMMIT_MESSAGE_SPELLING" value="true" />
<option name="DEFAULT_PATCH_EXTENSION" value="patch" />
<option name="SHORT_DIFF_HORIZONTALLY" value="true" />
<option name="SHORT_DIFF_EXTRA_LINES" value="2" />
<option name="SOFT_WRAPS_IN_SHORT_DIFF" value="true" />
<option name="INCLUDE_TEXT_INTO_PATCH" value="false" />
<option name="INCLUDE_TEXT_INTO_SHELF" value="false" />
<option name="SHOW_FILE_HISTORY_DETAILS" value="true" />
<option name="SHOW_VCS_ERROR_NOTIFICATIONS" value="true" />
<option name="SHOW_DIRTY_RECURSIVELY" value="false" />
<option name="LIMIT_HISTORY" value="true" />
<option name="MAXIMUM_HISTORY_ROWS" value="1000" />
<option name="UPDATE_FILTER_SCOPE_NAME" />
<option name="USE_COMMIT_MESSAGE_MARGIN" value="false" />
<option name="COMMIT_MESSAGE_MARGIN_SIZE" value="72" />
<option name="WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN" value="false" />
<option name="FORCE_NON_EMPTY_COMMENT" value="false" />
<option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="false" />
<option name="LAST_COMMIT_MESSAGE" />
<option name="MAKE_NEW_CHANGELIST_ACTIVE" value="false" />
<option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" />
<option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" />
<option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" />
<option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" />
<option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" />
<option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" />
<option name="ACTIVE_VCS_NAME" />
<option name="UPDATE_GROUP_BY_PACKAGES" value="false" />
<option name="UPDATE_GROUP_BY_CHANGELIST" value="false" />
<option name="UPDATE_FILTER_BY_SCOPE" value="false" />
<option name="SHOW_FILE_HISTORY_AS_TREE" value="false" />
<option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/www/js/index_old.js">
<provider selected="true" editor-type-id="text-editor">
<state line="21" column="38" selection-start="904" selection-end="904" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/www/index.html">
<provider selected="true" editor-type-id="text-editor">
<state line="41" column="14" selection-start="1976" selection-end="1976" vertical-scroll-proportion="-15.333333">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/www/js/index.ts">
<provider selected="true" editor-type-id="text-editor">
<state line="21" column="27" selection-start="560" selection-end="560" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/www/js/index.js">
<provider selected="true" editor-type-id="text-editor">
<state line="17" column="38" selection-start="462" selection-end="462" vertical-scroll-proportion="0.4704797">
<folding />
</state>
</provider>
</entry>
</component>
</project>
| {'content_hash': '2588ac82611335c47c156095338f318a', 'timestamp': '', 'source': 'github', 'line_count': 337, 'max_line_length': 224, 'avg_line_length': 58.10979228486647, 'alnum_prop': 0.6494919062452127, 'repo_name': 'citizenme/PhoneGap-app', 'id': '09e4c399601d587c51e00d84378500dffffae4ac', 'size': '19583', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tech/cordova_typescript/.idea/workspace.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AppleScript', 'bytes': '8456'}, {'name': 'C', 'bytes': '7175'}, {'name': 'C#', 'bytes': '29974'}, {'name': 'C++', 'bytes': '16701'}, {'name': 'CSS', 'bytes': '1049882'}, {'name': 'D', 'bytes': '36020'}, {'name': 'Java', 'bytes': '3094379'}, {'name': 'JavaScript', 'bytes': '10790887'}, {'name': 'Objective-C', 'bytes': '1580210'}, {'name': 'PHP', 'bytes': '8120'}, {'name': 'Shell', 'bytes': '256941'}, {'name': 'TypeScript', 'bytes': '2681'}]} |
package org.uma.jmetal.algorithm.multiobjective.moead;
import org.uma.jmetal.algorithm.multiobjective.moead.util.MOEADUtils;
import org.uma.jmetal.operator.crossover.CrossoverOperator;
import org.uma.jmetal.operator.mutation.MutationOperator;
import org.uma.jmetal.problem.Problem;
import org.uma.jmetal.solution.doublesolution.DoubleSolution;
import org.uma.jmetal.util.point.impl.IdealPoint;
import org.uma.jmetal.util.point.impl.NadirPoint;
import org.uma.jmetal.util.solutionattribute.Ranking;
import org.uma.jmetal.util.solutionattribute.impl.DominanceRanking;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("serial")
public class MOEADD<S extends DoubleSolution> extends AbstractMOEAD<S> {
protected Ranking<S> ranking;
protected int[][] rankIdx; // index matrix for the non-domination levels
protected int[][] subregionIdx; // index matrix for subregion record
protected double[][] subregionDist; // distance matrix for perpendicular distance
protected int numRanks;
public MOEADD(Problem<S> problem,
int populationSize,
int resultPopulationSize,
int maxEvaluations,
CrossoverOperator<S> crossoverOperator,
MutationOperator<S> mutation,
AbstractMOEAD.FunctionType functionType,
String dataDirectory,
double neighborhoodSelectionProbability,
int maximumNumberOfReplacedSolutions,
int neighborSize) {
super(problem, populationSize, resultPopulationSize, maxEvaluations, crossoverOperator, mutation, functionType, dataDirectory, neighborhoodSelectionProbability, maximumNumberOfReplacedSolutions, neighborSize);
}
@Override
public void run() {
evaluations = 0;
population = new ArrayList<>(populationSize);
neighborhood = new int[populationSize][neighborSize];
lambda = new double[populationSize][problem.getNumberOfObjectives()];
idealPoint = new IdealPoint(problem.getNumberOfObjectives()); // ideal point for Pareto-based population
nadirPoint = new NadirPoint(problem.getNumberOfObjectives()); // nadir point for Pareto-based population
rankIdx = new int[populationSize][populationSize];
subregionIdx = new int[populationSize][populationSize];
subregionDist = new double[populationSize][populationSize];
// STEP 1. Initialization
initializeUniformWeight();
initializeNeighborhood();
initPopulation();
idealPoint.update(population);
nadirPoint.update(population);
// initialize the distance
for (int i = 0; i < populationSize; i++) {
double distance = calculateDistance2(
population.get(i), lambda[i], idealPoint.getValues(), nadirPoint.getValues());
subregionDist[i][i] = distance;
}
ranking = computeRanking(population);
for (int curRank = 0; curRank < ranking.getNumberOfSubFronts(); curRank++) {
List<S> front = ranking.getSubFront(curRank);
for (S s : front) {
int position = this.population.indexOf(s);
rankIdx[curRank][position] = 1;
}
}
// main procedure
do {
int[] permutation = new int[populationSize];
MOEADUtils.randomPermutation(permutation, populationSize);
for (int i = 0; i < populationSize; i++) {
int cid = permutation[i];
int type;
double rnd = randomGenerator.nextDouble();
// mating selection style
if (rnd < neighborhoodSelectionProbability) {
type = 1; // neighborhood
} else {
type = 2; // whole population
}
List<S> parents = matingSelection(cid, type);
List<S> children = crossoverOperator.execute(parents);
S child = children.get(0);
mutationOperator.execute(child);
problem.evaluate(child);
evaluations++;
idealPoint.update(child.getObjectives());
nadirPoint.update(child.getObjectives());
updateArchive(child);
}
} while (evaluations < maxEvaluations);
}
/**
* Initialize the population
*/
public void initPopulation() {
for (int i = 0; i < populationSize; i++) {
S newSolution = problem.createSolution();
problem.evaluate(newSolution);
evaluations++;
population.add(newSolution);
subregionIdx[i][i] = 1;
}
}
/**
* Select two parents for reproduction
*/
public List<S> matingSelection(int cid, int type) {
int rnd1, rnd2;
List<S> parents = new ArrayList<>(2);
int nLength = neighborhood[cid].length;
ArrayList<Integer> activeList = new ArrayList<>();
if (type == 1) {
for (int i = 0; i < nLength; i++) {
int idx = neighborhood[cid][i];
for (int j = 0; j < populationSize; j++) {
if (subregionIdx[idx][j] == 1) {
activeList.add(idx);
break;
}
}
}
if (activeList.size() < 2) {
activeList.clear();
for (int i = 0; i < populationSize; i++) {
for (int j = 0; j < populationSize; j++) {
if (subregionIdx[i][j] == 1) {
activeList.add(i);
break;
}
}
}
}
int activeSize = activeList.size();
rnd1 = randomGenerator.nextInt(0, activeSize - 1);
do {
rnd2 = randomGenerator.nextInt(0, activeSize - 1);
} while (rnd1 == rnd2); // in a very extreme case, this will be a dead loop
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
int id1 = activeList.get(rnd1);
int id2 = activeList.get(rnd2);
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[id1][i] == 1) {
list1.add(i);
}
if (subregionIdx[id2][i] == 1) {
list2.add(i);
}
}
int p1 = randomGenerator.nextInt(0, list1.size() - 1);
int p2 = randomGenerator.nextInt(0, list2.size() - 1);
parents.add(population.get(list1.get(p1)));
parents.add(population.get(list2.get(p2)));
} else {
for (int i = 0; i < populationSize; i++) {
for (int j = 0; j < populationSize; j++) {
if (subregionIdx[i][j] == 1) {
activeList.add(i);
break;
}
}
}
int activeSize = activeList.size();
rnd1 = randomGenerator.nextInt(0, activeSize - 1);
do {
rnd2 = randomGenerator.nextInt(0, activeSize - 1);
} while (rnd1 == rnd2); // in a very extreme case, this will be a dead loop
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
int id1 = activeList.get(rnd1);
int id2 = activeList.get(rnd2);
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[id1][i] == 1) {
list1.add(i);
}
if (subregionIdx[id2][i] == 1) {
list2.add(i);
}
}
int p1 = randomGenerator.nextInt(0, list1.size() - 1);
int p2 = randomGenerator.nextInt(0, list2.size() - 1);
parents.add(population.get(list1.get(p1)));
parents.add(population.get(list2.get(p2)));
}
return parents;
} // matingSelection
/**
* update the parent population by using the ENLU method, instead of fast non-dominated sorting
*/
public void updateArchive(S indiv) {
// find the location of 'indiv'
setLocation(indiv, idealPoint.getValues(), nadirPoint.getValues());
int location = (int) indiv.getAttribute("region");
numRanks = nondominated_sorting_add(indiv);
if (numRanks == 1) {
deleteRankOne(indiv, location);
} else {
ArrayList<S> lastFront = new ArrayList<>(populationSize);
int frontSize = countRankOnes(numRanks - 1);
if (frontSize == 0) { // the last non-domination level only contains 'indiv'
frontSize++;
lastFront.add(indiv);
} else {
for (int i = 0; i < populationSize; i++) {
if (rankIdx[numRanks - 1][i] == 1) {
lastFront.add((S) population.get(i));
}
}
if (((int) indiv.getAttribute(ranking.getAttributeIdentifier())) == (numRanks - 1)) {
// if (rankSolution.getOrDefault(indiv, 0) == (numRanks - 1)) {
frontSize++;
lastFront.add(indiv);
}
}
if (frontSize == 1 && lastFront.get(0).equals(indiv)) { // the last non-domination level only has 'indiv'
int curNC = countOnes(location);
if (curNC > 0) { // if the subregion of 'indiv' has other solution, drop 'indiv'
nondominated_sorting_delete(indiv);
} else { // if the subregion of 'indiv' has no solution, keep 'indiv'
deleteCrowdRegion1(indiv, location);
}
} else if (frontSize == 1 && !lastFront.get(0).equals(indiv)) { // the last non-domination level only has one solution, but not 'indiv'
int targetIdx = findPosition(lastFront.get(0));
int parentLocation = findRegion(targetIdx);
int curNC = countOnes(parentLocation);
if (parentLocation == location) {
curNC++;
}
if (curNC == 1) { // the subregion only has the solution 'targetIdx', keep solution 'targetIdx'
deleteCrowdRegion2(indiv, location);
} else { // the subregion contains some other solutions, drop solution 'targetIdx'
int indivRank = (int) indiv.getAttribute(ranking.getAttributeIdentifier());
int targetRank = (int) population.get(targetIdx).getAttribute(ranking.getAttributeIdentifier());
rankIdx[targetRank][targetIdx] = 0;
rankIdx[indivRank][targetIdx] = 1;
S targetSol = population.get(targetIdx);
replace(targetIdx, indiv);
subregionIdx[parentLocation][targetIdx] = 0;
subregionIdx[location][targetIdx] = 1;
// update the non-domination level structure
nondominated_sorting_delete(targetSol);
}
} else {
double indivFitness = fitnessFunction(indiv, lambda[location]);
// find the index of the solution in the last non-domination level, and its corresponding subregion
int[] idxArray = new int[frontSize];
int[] regionArray = new int[frontSize];
for (int i = 0; i < frontSize; i++) {
idxArray[i] = findPosition(lastFront.get(i));
if (idxArray[i] == -1) {
regionArray[i] = location;
} else {
regionArray[i] = findRegion(idxArray[i]);
}
}
// find the most crowded subregion, if more than one exist, keep them in 'crowdList'
ArrayList<Integer> crowdList = new ArrayList<>();
int crowdIdx;
int nicheCount = countOnes(regionArray[0]);
if (regionArray[0] == location) {
nicheCount++;
}
crowdList.add(regionArray[0]);
for (int i = 1; i < frontSize; i++) {
int curSize = countOnes(regionArray[i]);
if (regionArray[i] == location) {
curSize++;
}
if (curSize > nicheCount) {
crowdList.clear();
nicheCount = curSize;
crowdList.add(regionArray[i]);
} else if (curSize == nicheCount) {
crowdList.add(regionArray[i]);
}
}
// find the index of the most crowded subregion
if (crowdList.size() == 1) {
crowdIdx = crowdList.get(0);
} else {
int listLength = crowdList.size();
crowdIdx = crowdList.get(0);
double sumFitness = sumFitness(crowdIdx);
if (crowdIdx == location) {
sumFitness = sumFitness + indivFitness;
}
for (int i = 1; i < listLength; i++) {
int curIdx = crowdList.get(i);
double curFitness = sumFitness(curIdx);
if (curIdx == location) {
curFitness = curFitness + indivFitness;
}
if (curFitness > sumFitness) {
crowdIdx = curIdx;
sumFitness = curFitness;
}
}
}
switch (nicheCount) {
case 0:
System.out.println("Impossible empty subregion!!!");
break;
case 1:
// if the subregion of each solution in the last non-domination level only has one solution, keep them all
deleteCrowdRegion2(indiv, location);
break;
default:
// delete the worst solution from the most crowded subregion in the last non-domination level
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < frontSize; i++) {
if (regionArray[i] == crowdIdx) {
list.add(i);
}
}
if (list.isEmpty()) {
System.out.println("Cannot happen!!!");
} else {
double maxFitness, curFitness;
int targetIdx = list.get(0);
if (idxArray[targetIdx] == -1) {
maxFitness = indivFitness;
} else {
maxFitness = fitnessFunction(population.get(idxArray[targetIdx]), lambda[crowdIdx]);
}
for (int i = 1; i < list.size(); i++) {
int curIdx = list.get(i);
if (idxArray[curIdx] == -1) {
curFitness = indivFitness;
} else {
curFitness = fitnessFunction(population.get(idxArray[curIdx]), lambda[crowdIdx]);
}
if (curFitness > maxFitness) {
targetIdx = curIdx;
maxFitness = curFitness;
}
}
if (idxArray[targetIdx] == -1) {
nondominated_sorting_delete(indiv);
} else {
//indiv.getRank();
int indivRank = (int) indiv.getAttribute(ranking.getAttributeIdentifier());
//int targetRank = ((DoubleSolution) population.get(idxArray[targetIdx])).getRank();
int targetRank = (int) population.get(idxArray[targetIdx]).getAttribute(ranking.getAttributeIdentifier());
rankIdx[targetRank][idxArray[targetIdx]] = 0;
rankIdx[indivRank][idxArray[targetIdx]] = 1;
S targetSol = population.get(idxArray[targetIdx]);
replace(idxArray[targetIdx], indiv);
subregionIdx[crowdIdx][idxArray[targetIdx]] = 0;
subregionIdx[location][idxArray[targetIdx]] = 1;
// update the non-domination level structure
nondominated_sorting_delete(targetSol);
}
}
break;
}
}
}
}
/**
* update the non-domination level structure after deleting a solution
*/
public void nondominated_sorting_delete(S indiv) {
// find the non-domination level of 'indiv'
//int indivRank = indiv.getRank();
int indivRank = (int) indiv.getAttribute(ranking.getAttributeIdentifier());
ArrayList<Integer> curLevel = new ArrayList<>(); // used to keep the solutions in the current non-domination level
ArrayList<Integer> dominateList = new ArrayList<>(); // used to keep the solutions need to be moved
for (int i = 0; i < populationSize; i++) {
if (rankIdx[indivRank][i] == 1) {
curLevel.add(i);
}
}
int flag;
// find the solutions belonging to the 'indivRank+1'th level and are dominated by 'indiv'
int investigateRank = indivRank + 1;
if (investigateRank < numRanks) {
for (int i = 0; i < populationSize; i++) {
if (rankIdx[investigateRank][i] == 1) {
flag = 0;
if (checkDominance(indiv, population.get(i)) == 1) {
for (int j = 0; j < curLevel.size(); j++) {
if (checkDominance(population.get(i), population.get(curLevel.get(j))) == -1) {
flag = 1;
break;
}
}
if (flag == 0) { // the ith solution can move to the prior level
dominateList.add(i);
rankIdx[investigateRank][i] = 0;
rankIdx[investigateRank - 1][i] = 1;
//((DoubleSolution) population.get(i)).setRank(investigateRank - 1);
population.get(i).setAttribute(ranking.getAttributeIdentifier(), investigateRank - 1);
}
}
}
}
}
int curIdx;
int curListSize = dominateList.size();
while (curListSize != 0) {
curLevel.clear();
for (int i = 0; i < populationSize; i++) {
if (rankIdx[investigateRank][i] == 1) {
curLevel.add(i);
}
}
investigateRank = investigateRank + 1;
if (investigateRank < numRanks) {
for (int i = 0; i < curListSize; i++) {
curIdx = dominateList.get(i);
for (int j = 0; j < populationSize; j++) {
if (j == populationSize) {
System.err.println("There are problems");
}
if (rankIdx[investigateRank][j] == 1) {
flag = 0;
if (checkDominance(population.get(curIdx), population.get(j)) == 1) {
for (int k = 0; k < curLevel.size(); k++) {
if (checkDominance(population.get(j), population.get(curLevel.get(k))) == -1) {
flag = 1;
break;
}
}
if (flag == 0) {
dominateList.add(j);
rankIdx[investigateRank][j] = 0;
rankIdx[investigateRank - 1][j] = 1;
//((DoubleSolution) population.get(j)).setRank(investigateRank - 1);
population.get(j).setAttribute(ranking.getAttributeIdentifier(), investigateRank - 1);
}
}
}
}
}
}
for (int i = 0; i < curListSize; i++) {
dominateList.remove(0);
}
curListSize = dominateList.size();
}
}
/**
* update the non-domination level when adding a solution
*/
public int nondominated_sorting_add(S indiv) {
int flag = 0;
int flag1, flag2, flag3;
// count the number of non-domination levels
int num_ranks = 0;
ArrayList<Integer> frontSize = new ArrayList<>();
for (int i = 0; i < populationSize; i++) {
int rankCount = countRankOnes(i);
if (rankCount != 0) {
frontSize.add(rankCount);
num_ranks++;
} else {
break;
}
}
ArrayList<Integer> dominateList = new ArrayList<>(); // used to keep the solutions dominated by 'indiv'
int level = 0;
for (int i = 0; i < num_ranks; i++) {
level = i;
if (flag == 1) { // 'indiv' is non-dominated with all solutions in the ith non-domination level, then 'indiv' belongs to the ith level
//indiv.setRank(i - 1);
indiv.setAttribute(ranking.getAttributeIdentifier(), i - 1);
return num_ranks;
} else if (flag == 2) { // 'indiv' dominates some solutions in the ith level, but is non-dominated with some others, then 'indiv' belongs to the ith level, and move the dominated solutions to the next level
//indiv.setRank(i - 1);
indiv.setAttribute(ranking.getAttributeIdentifier(), i - 1);
int prevRank = i - 1;
// process the solutions belong to 'prevRank'th level and are dominated by 'indiv' ==> move them to 'prevRank+1'th level and find the solutions dominated by them
int curIdx;
int newRank = prevRank + 1;
int curListSize = dominateList.size();
for (int j = 0; j < curListSize; j++) {
curIdx = dominateList.get(j);
rankIdx[prevRank][curIdx] = 0;
rankIdx[newRank][curIdx] = 1;
//((DoubleSolution) population.get(curIdx)).setRank(newRank);
population.get(curIdx).setAttribute(ranking.getAttributeIdentifier(), newRank);
}
for (int j = 0; j < populationSize; j++) {
if (rankIdx[newRank][j] == 1) {
for (int k = 0; k < curListSize; k++) {
curIdx = dominateList.get(k);
if (checkDominance(population.get(curIdx), population.get(j)) == 1) {
dominateList.add(j);
break;
}
}
}
}
for (int j = 0; j < curListSize; j++) {
dominateList.remove(0);
}
// if there are still some other solutions moved to the next level, check their domination situation in their new level
prevRank = newRank;
newRank = newRank + 1;
curListSize = dominateList.size();
if (curListSize == 0) {
return num_ranks;
} else {
int allFlag = 0;
do {
for (int j = 0; j < curListSize; j++) {
curIdx = dominateList.get(j);
rankIdx[prevRank][curIdx] = 0;
rankIdx[newRank][curIdx] = 1;
//((DoubleSolution) population.get(curIdx)).setRank(newRank);
population.get(curIdx).setAttribute(ranking.getAttributeIdentifier(), newRank);
}
for (int j = 0; j < populationSize; j++) {
if (rankIdx[newRank][j] == 1) {
for (int k = 0; k < curListSize; k++) {
curIdx = dominateList.get(k);
if (checkDominance(population.get(curIdx), population.get(j)) == 1) {
dominateList.add(j);
break;
}
}
}
}
for (int j = 0; j < curListSize; j++) {
dominateList.remove(0);
}
curListSize = dominateList.size();
if (curListSize != 0) {
prevRank = newRank;
newRank = newRank + 1;
if (frontSize.size() > prevRank && curListSize == frontSize.get(prevRank)) { // if all solutions in the 'prevRank'th level are dominated by the newly added solution, move them all to the next level
allFlag = 1;
break;
}
}
} while (curListSize != 0);
if (allFlag == 1) { // move the solutions after the 'prevRank'th level to their next levels
int remainSize = num_ranks - prevRank;
int[][] tempRecord = new int[remainSize][populationSize];
int tempIdx = 0;
for (int j = 0; j < dominateList.size(); j++) {
tempRecord[0][tempIdx] = dominateList.get(j);
tempIdx++;
}
int k = 1;
int curRank = prevRank + 1;
while (curRank < num_ranks) {
tempIdx = 0;
for (int j = 0; j < populationSize; j++) {
if (rankIdx[curRank][j] == 1) {
tempRecord[k][tempIdx] = j;
tempIdx++;
}
}
curRank++;
k++;
}
k = 0;
curRank = prevRank;
while (curRank < num_ranks) {
int level_size = frontSize.get(curRank);
int tempRank;
for (int j = 0; j < level_size; j++) {
curIdx = tempRecord[k][j];
//tempRank = ((DoubleSolution) population.get(curIdx)).getRank();
tempRank = (int) population.get(curIdx).getAttribute(ranking.getAttributeIdentifier());
newRank = tempRank + 1;
//((DoubleSolution) population.get(curIdx)).setRank(newRank);
population.get(curIdx).setAttribute(ranking.getAttributeIdentifier(), newRank);
rankIdx[tempRank][curIdx] = 0;
rankIdx[newRank][curIdx] = 1;
}
curRank++;
k++;
}
num_ranks++;
}
if (newRank == num_ranks) {
num_ranks++;
}
return num_ranks;
}
} else if (flag == 3 || flag == 0) { // if 'indiv' is dominated by some solutions in the ith level, skip it, and term to the next level
flag1 = flag2 = flag3 = 0;
for (int j = 0; j < populationSize; j++) {
if (rankIdx[i][j] == 1) {
switch (checkDominance(indiv, population.get(j))) {
case 1: {
flag1 = 1;
dominateList.add(j);
break;
}
case 0: {
flag2 = 1;
break;
}
case -1: {
flag3 = 1;
break;
}
}
if (flag3 == 1) {
flag = 3;
break;
} else if (flag1 == 0 && flag2 == 1) {
flag = 1;
} else if (flag1 == 1 && flag2 == 1) {
flag = 2;
} else if (flag1 == 1 && flag2 == 0) {
flag = 4;
} else {
}
}
}
} else { // (flag == 4) if 'indiv' dominates all solutions in the ith level, solutions in the current level and beyond move their current next levels
//indiv.setRank(i - 1);
indiv.setAttribute(ranking.getAttributeIdentifier(), i - 1);
i = i - 1;
int remainSize = num_ranks - i;
int[][] tempRecord = new int[remainSize][populationSize];
int k = 0;
while (i < num_ranks) {
int tempIdx = 0;
for (int j = 0; j < populationSize; j++) {
if (rankIdx[i][j] == 1) {
tempRecord[k][tempIdx] = j;
tempIdx++;
}
}
i++;
k++;
}
k = 0;
//i = indiv.getRank();
i = (int) indiv.getAttribute(ranking.getAttributeIdentifier());
while (i < num_ranks) {
int level_size = frontSize.get(i);
int curIdx;
int curRank, newRank;
for (int j = 0; j < level_size; j++) {
curIdx = tempRecord[k][j];
//curRank = ((DoubleSolution) population.get(curIdx)).getRank();
curRank = (int) population.get(curIdx).getAttribute(ranking.getAttributeIdentifier());
newRank = curRank + 1;
//((DoubleSolution) population.get(curIdx)).setRank(newRank);
population.get(curIdx).setAttribute(ranking.getAttributeIdentifier(), newRank);
rankIdx[curRank][curIdx] = 0;
rankIdx[newRank][curIdx] = 1;
}
i++;
k++;
}
num_ranks++;
return num_ranks;
}
}
// if flag is still 3 after the for-loop, it means that 'indiv' is in the current last level
switch (flag) {
case 1:
//indiv.setRank(level);
indiv.setAttribute(ranking.getAttributeIdentifier(), level);
break;
case 2:
//indiv.setRank(level);
indiv.setAttribute(ranking.getAttributeIdentifier(), level);
int curIdx;
int tempSize = dominateList.size();
for (int i = 0; i < tempSize; i++) {
curIdx = dominateList.get(i);
//((DoubleSolution) population.get(curIdx)).setRank(level + 1);
population.get(curIdx).setAttribute(ranking.getAttributeIdentifier(), level + 1);
rankIdx[level][curIdx] = 0;
rankIdx[level + 1][curIdx] = 1;
}
num_ranks++;
break;
case 3:
//indiv.setRank(level + 1);
indiv.setAttribute(ranking.getAttributeIdentifier(), level + 1);
num_ranks++;
break;
default:
//indiv.setRank(level);
indiv.setAttribute(ranking.getAttributeIdentifier(), level);
for (int i = 0; i < populationSize; i++) {
if (rankIdx[level][i] == 1) {
//((DoubleSolution) population.get(i)).setRank(level + 1);
population.get(i).setAttribute(ranking.getAttributeIdentifier(), level + 1);
rankIdx[level][i] = 0;
rankIdx[level + 1][i] = 1;
}
}
num_ranks++;
break;
}
return num_ranks;
}
/**
* Delete a solution from the most crowded subregion (this function only happens when: it should
* delete 'indiv' based on traditional method. However, the subregion of 'indiv' only has one
* solution, so it should be kept)
*/
public void deleteCrowdRegion1(S indiv, int location) {
// find the most crowded subregion, if more than one such subregion exists, keep them in the crowdList
ArrayList<Integer> crowdList = new ArrayList<>();
int crowdIdx;
int nicheCount = countOnes(0);
crowdList.add(0);
for (int i = 1; i < populationSize; i++) {
int curSize = countOnes(i);
if (curSize > nicheCount) {
crowdList.clear();
nicheCount = curSize;
crowdList.add(i);
} else if (curSize == nicheCount) {
crowdList.add(i);
}
}
// find the index of the crowded subregion
if (crowdList.size() == 1) {
crowdIdx = crowdList.get(0);
} else {
int listLength = crowdList.size();
crowdIdx = crowdList.get(0);
double sumFitness = sumFitness(crowdIdx);
for (int i = 1; i < listLength; i++) {
int curIdx = crowdList.get(i);
double curFitness = sumFitness(curIdx);
if (curFitness > sumFitness) {
crowdIdx = curIdx;
sumFitness = curFitness;
}
}
}
// find the solution indices within the 'crowdIdx' subregion
ArrayList<Integer> indList = new ArrayList<>();
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[crowdIdx][i] == 1) {
indList.add(i);
}
}
// find the solution with the largest rank
ArrayList<Integer> maxRankList = new ArrayList<>();
//int maxRank = ((DoubleSolution) population.get(indList.get(0))).getRank();
int maxRank = (int) population.get(indList.get(0)).getAttribute(ranking.getAttributeIdentifier());
maxRankList.add(indList.get(0));
for (int i = 1; i < indList.size(); i++) {
//int curRank = ((DoubleSolution) population.get(indList.get(i))).getRank();
int curRank = (int) population.get(indList.get(i)).getAttribute(ranking.getAttributeIdentifier());
if (curRank > maxRank) {
maxRankList.clear();
maxRank = curRank;
maxRankList.add(indList.get(i));
} else if (curRank == maxRank) {
maxRankList.add(indList.get(i));
}
}
// find the solution with the largest rank and worst fitness
int rankSize = maxRankList.size();
int targetIdx = maxRankList.get(0);
double maxFitness = fitnessFunction(population.get(targetIdx), lambda[crowdIdx]);
for (int i = 1; i < rankSize; i++) {
int curIdx = maxRankList.get(i);
double curFitness = fitnessFunction(population.get(curIdx), lambda[crowdIdx]);
if (curFitness > maxFitness) {
targetIdx = curIdx;
maxFitness = curFitness;
}
}
//int indivRank = indiv.getRank();
int indivRank = (int) indiv.getAttribute(ranking.getAttributeIdentifier());
//int targetRank = ((DoubleSolution) population.get(targetIdx)).getRank();
int targetRank = (int) population.get(targetIdx).getAttribute(ranking.getAttributeIdentifier());
rankIdx[targetRank][targetIdx] = 0;
rankIdx[indivRank][targetIdx] = 1;
S targetSol = population.get(targetIdx);
replace(targetIdx, indiv);
subregionIdx[crowdIdx][targetIdx] = 0;
subregionIdx[location][targetIdx] = 1;
// update the non-domination level structure
nondominated_sorting_delete(targetSol);
}
/**
* delete a solution from the most crowded subregion (this function happens when: it should delete
* the solution in the 'parentLocation' subregion, but since this subregion only has one solution,
* it should be kept)
*/
public void deleteCrowdRegion2(S indiv, int location) {
double indivFitness = fitnessFunction(indiv, lambda[location]);
// find the most crowded subregion, if there are more than one, keep them in crowdList
ArrayList<Integer> crowdList = new ArrayList<>();
int crowdIdx;
int nicheCount = countOnes(0);
if (location == 0) {
nicheCount++;
}
crowdList.add(0);
for (int i = 1; i < populationSize; i++) {
int curSize = countOnes(i);
if (location == i) {
curSize++;
}
if (curSize > nicheCount) {
crowdList.clear();
nicheCount = curSize;
crowdList.add(i);
} else if (curSize == nicheCount) {
crowdList.add(i);
}
}
// determine the index of the crowded subregion
if (crowdList.size() == 1) {
crowdIdx = crowdList.get(0);
} else {
int listLength = crowdList.size();
crowdIdx = crowdList.get(0);
double sumFitness = sumFitness(crowdIdx);
if (crowdIdx == location) {
sumFitness = sumFitness + indivFitness;
}
for (int i = 1; i < listLength; i++) {
int curIdx = crowdList.get(i);
double curFitness = sumFitness(curIdx);
if (curIdx == location) {
curFitness = curFitness + indivFitness;
}
if (curFitness > sumFitness) {
crowdIdx = curIdx;
sumFitness = curFitness;
}
}
}
// find the solution indices within the 'crowdIdx' subregion
ArrayList<Integer> indList = new ArrayList<>();
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[crowdIdx][i] == 1) {
indList.add(i);
}
}
if (crowdIdx == location) {
int temp = -1;
indList.add(temp);
}
// find the solution with the largest rank
ArrayList<Integer> maxRankList = new ArrayList<>();
//int maxRank = ((DoubleSolution) population.get(indList.get(0))).getRank();
int maxRank = (int) population.get(indList.get(0)).getAttribute(ranking.getAttributeIdentifier());
maxRankList.add(indList.get(0));
for (int i = 1; i < indList.size(); i++) {
int curRank;
if (indList.get(i) == -1) {
//curRank = indiv.getRank();
curRank = (int) indiv.getAttribute(ranking.getAttributeIdentifier());
} else {
//curRank = ((DoubleSolution) population.get(indList.get(i))).getRank();
curRank = (int) population.get(indList.get(i)).getAttribute(ranking.getAttributeIdentifier());
}
if (curRank > maxRank) {
maxRankList.clear();
maxRank = curRank;
maxRankList.add(indList.get(i));
} else if (curRank == maxRank) {
maxRankList.add(indList.get(i));
}
}
double maxFitness;
int rankSize = maxRankList.size();
int targetIdx = maxRankList.get(0);
if (targetIdx == -1) {
maxFitness = indivFitness;
} else {
maxFitness = fitnessFunction(population.get(targetIdx), lambda[crowdIdx]);
}
for (int i = 1; i < rankSize; i++) {
double curFitness;
int curIdx = maxRankList.get(i);
if (curIdx == -1) {
curFitness = indivFitness;
} else {
curFitness = fitnessFunction(population.get(curIdx), lambda[crowdIdx]);
}
if (curFitness > maxFitness) {
targetIdx = curIdx;
maxFitness = curFitness;
}
}
if (targetIdx == -1) {
nondominated_sorting_delete(indiv);
} else {
//int indivRank = indiv.getRank();
int indivRank = (int) indiv.getAttribute(ranking.getAttributeIdentifier());
//int targetRank = ((DoubleSolution) population.get(targetIdx)).getRank();
int targetRank = (int) population.get(targetIdx).getAttribute(ranking.getAttributeIdentifier());
rankIdx[targetRank][targetIdx] = 0;
rankIdx[indivRank][targetIdx] = 1;
S targetSol = population.get(targetIdx);
replace(targetIdx, indiv);
subregionIdx[crowdIdx][targetIdx] = 0;
subregionIdx[location][targetIdx] = 1;
// update the non-domination level structure of the population
nondominated_sorting_delete(targetSol);
}
}
/**
* if there is only one non-domination level (i.e., all solutions are non-dominated with each
* other), we should delete a solution from the most crowded subregion
*/
public void deleteRankOne(S indiv, int location) {
double indivFitness = fitnessFunction(indiv, lambda[location]);
// find the most crowded subregion, if there are more than one, keep them in crowdList
ArrayList<Integer> crowdList = new ArrayList<>();
int crowdIdx;
int nicheCount = countOnes(0);
if (location == 0) {
nicheCount++;
}
crowdList.add(0);
for (int i = 1; i < populationSize; i++) {
int curSize = countOnes(i);
if (location == i) {
curSize++;
}
if (curSize > nicheCount) {
crowdList.clear();
nicheCount = curSize;
crowdList.add(i);
} else if (curSize == nicheCount) {
crowdList.add(i);
}
}
// determine the index of the crowded subregion
if (crowdList.size() == 1) {
crowdIdx = crowdList.get(0);
} else {
int listLength = crowdList.size();
crowdIdx = crowdList.get(0);
double sumFitness = sumFitness(crowdIdx);
if (crowdIdx == location) {
sumFitness = sumFitness + indivFitness;
}
for (int i = 1; i < listLength; i++) {
int curIdx = crowdList.get(i);
double curFitness = sumFitness(curIdx);
if (curIdx == location) {
curFitness = curFitness + indivFitness;
}
if (curFitness > sumFitness) {
crowdIdx = curIdx;
sumFitness = curFitness;
}
}
}
switch (nicheCount) {
case 0:
System.out.println("Empty subregion!!!");
break;
case 1:
// if every subregion only contains one solution, delete the worst from indiv's subregion
int targetIdx;
for (targetIdx = 0; targetIdx < populationSize; targetIdx++) {
if (subregionIdx[location][targetIdx] == 1) {
break;
}
}
double prev_func = fitnessFunction(population.get(targetIdx), lambda[location]);
if (indivFitness < prev_func) {
replace(targetIdx, indiv);
}
break;
default:
if (location == crowdIdx) { // if indiv's subregion is the most crowded one
deleteCrowdIndiv_same(location, nicheCount, indivFitness, indiv);
} else {
int curNC = countOnes(location);
int crowdNC = countOnes(crowdIdx);
if (crowdNC > (curNC + 1)) { // if the crowdIdx subregion is more crowded, delete one from this subregion
deleteCrowdIndiv_diff(crowdIdx, location, crowdNC, indiv);
} else if (crowdNC < (curNC + 1)) { // crowdNC == curNC, delete one from indiv's subregion
deleteCrowdIndiv_same(location, curNC, indivFitness, indiv);
} else { // crowdNC == (curNC + 1)
if (curNC == 0) {
deleteCrowdIndiv_diff(crowdIdx, location, crowdNC, indiv);
} else {
double rnd = randomGenerator.nextDouble();
if (rnd < 0.5) {
deleteCrowdIndiv_diff(crowdIdx, location, crowdNC, indiv);
} else {
deleteCrowdIndiv_same(location, curNC, indivFitness, indiv);
}
}
}
}
break;
}
}
/**
* calculate the sum of fitnesses of solutions in the location subregion
*/
public double sumFitness(int location) {
double sum = 0;
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[location][i] == 1) {
sum = sum + fitnessFunction(population.get(i), lambda[location]);
}
}
return sum;
}
/**
* delete one solution from the most crowded subregion, which is indiv's subregion. Compare
* indiv's fitness value and the worst one in this subregion
*/
public void deleteCrowdIndiv_same(int crowdIdx, int nicheCount, double indivFitness, S indiv) {
// find the solution indices within this crowdIdx subregion
ArrayList<Integer> indList = new ArrayList<>();
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[crowdIdx][i] == 1) {
indList.add(i);
}
}
// find the solution with the worst fitness value
int listSize = indList.size();
int worstIdx = indList.get(0);
double maxFitness = fitnessFunction(population.get(worstIdx), lambda[crowdIdx]);
for (int i = 1; i < listSize; i++) {
int curIdx = indList.get(i);
double curFitness = fitnessFunction(population.get(curIdx), lambda[crowdIdx]);
if (curFitness > maxFitness) {
worstIdx = curIdx;
maxFitness = curFitness;
}
}
// if indiv has a better fitness, use indiv to replace the worst one
if (indivFitness < maxFitness) {
replace(worstIdx, indiv);
}
}
/**
* delete one solution from the most crowded subregion, which is different from indiv's subregion.
* just use indiv to replace the worst solution in that subregion
*/
public void deleteCrowdIndiv_diff(int crowdIdx, int curLocation, int nicheCount, S indiv) {
// find the solution indices within this crowdIdx subregion
ArrayList<Integer> indList = new ArrayList<>();
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[crowdIdx][i] == 1) {
indList.add(i);
}
}
// find the solution with the worst fitness value
int worstIdx = indList.get(0);
double maxFitness = fitnessFunction(population.get(worstIdx), lambda[crowdIdx]);
for (int i = 1; i < nicheCount; i++) {
int curIdx = indList.get(i);
double curFitness = fitnessFunction(population.get(curIdx), lambda[crowdIdx]);
if (curFitness > maxFitness) {
worstIdx = curIdx;
maxFitness = curFitness;
}
}
// use indiv to replace the worst one
replace(worstIdx, indiv);
subregionIdx[crowdIdx][worstIdx] = 0;
subregionIdx[curLocation][worstIdx] = 1;
}
/**
* Count the number of 1s in the 'location'th subregion
*/
public int countOnes(int location) {
int count = 0;
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[location][i] == 1) {
count++;
}
}
return count;
}
/**
* count the number of 1s in a row of rank matrix
*/
public int countRankOnes(int location) {
int count = 0;
for (int i = 0; i < populationSize; i++) {
if (rankIdx[location][i] == 1) {
count++;
}
}
return count;
}
/**
* find the index of the solution 'indiv' in the population
*/
public int findPosition(S indiv) {
for (int i = 0; i < populationSize; i++) {
if (indiv.equals(population.get(i))) {
return i;
}
}
return -1;
}
/**
* find the subregion of the 'idx'th solution in the population
*/
public int findRegion(int idx) {
for (int i = 0; i < populationSize; i++) {
if (subregionIdx[i][idx] == 1) {
return i;
}
}
return -1;
}
/**
* Set the location of a solution based on the orthogonal distance
*/
public void setLocation(S indiv, double[] z_, double[] nz_) {
int minIdx;
double distance, minDist;
minIdx = 0;
distance = calculateDistance2(indiv, lambda[0], z_, nz_);
minDist = distance;
for (int i = 1; i < populationSize; i++) {
distance = calculateDistance2(indiv, lambda[i], z_, nz_);
if (distance < minDist) {
minIdx = i;
minDist = distance;
}
}
//indiv.setRegion(minIdx);
indiv.setAttribute("region", minIdx);
//indiv.Set_associateDist(minDist);
// indiv.setAttribute(ATTRIBUTES.DIST, minDist);
}
/**
* check the dominance relationship between a and b: 1 -> a dominates b, -1 -> b dominates a 0 ->
* non-dominated with each other
*/
public int checkDominance(S a, S b) {
int flag1 = 0;
int flag2 = 0;
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
if (a.getObjective(i) < b.getObjective(i)) {
flag1 = 1;
} else {
if (a.getObjective(i) > b.getObjective(i)) {
flag2 = 1;
}
}
}
if (flag1 == 1 && flag2 == 0) {
return 1;
} else {
if (flag1 == 0 && flag2 == 1) {
return -1;
} else {
return 0;
}
}
}
/**
* Calculate the perpendicular distance between the solution and reference line
*/
public double calculateDistance(S individual, double[] lambda,
double[] z_, double[] nz_) {
double scale;
double distance;
double[] vecInd = new double[problem.getNumberOfObjectives()];
double[] vecProj = new double[problem.getNumberOfObjectives()];
// normalize the weight vector (line segment)
double nd = norm_vector(lambda);
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
lambda[i] = lambda[i] / nd;
}
// vecInd has been normalized to the range [0,1]
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
vecInd[i] = (individual.getObjective(i) - z_[i]) / (nz_[i] - z_[i]);
}
scale = innerproduct(vecInd, lambda);
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
vecProj[i] = vecInd[i] - scale * lambda[i];
}
distance = norm_vector(vecProj);
return distance;
}
public double calculateDistance2(S indiv, double[] lambda,
double[] z_, double[] nz_) {
// normalize the weight vector (line segment)
double nd = norm_vector(lambda);
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
lambda[i] = lambda[i] / nd;
}
double[] realA = new double[problem.getNumberOfObjectives()];
double[] realB = new double[problem.getNumberOfObjectives()];
// difference between current point and reference point
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
realA[i] = (indiv.getObjective(i) - z_[i]);
}
// distance along the line segment
double d1 = Math.abs(innerproduct(realA, lambda));
// distance to the line segment
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
realB[i] = (indiv.getObjective(i) - (z_[i] + d1 * lambda[i]));
}
double distance = norm_vector(realB);
return distance;
}
/**
* Calculate the dot product of two vectors
*/
public double innerproduct(double[] vec1, double[] vec2) {
double sum = 0;
for (int i = 0; i < vec1.length; i++) {
sum += vec1[i] * vec2[i];
}
return sum;
}
/**
* Calculate the norm of the vector
*/
public double norm_vector(double[] z) {
double sum = 0;
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
sum += z[i] * z[i];
}
return Math.sqrt(sum);
}
public int countTest() {
int sum = 0;
for (int i = 0; i < populationSize; i++) {
for (int j = 0; j < populationSize; j++) {
if (subregionIdx[i][j] == 1) {
sum++;
}
}
}
return sum;
}
@Override
public String getName() {
return "MOEADD";
}
@Override
public String getDescription() {
return "An Evolutionary Many-Objective Optimization Algorithm Based on Dominance and Decomposition";
}
public void replace(int position, S solution) {
if (position > this.population.size()) {
population.add(solution);
} else {
S toRemove = population.get(position);
population.remove(toRemove);
population.add(position, solution);
}
}
protected Ranking<S> computeRanking(List<S> solutionList) {
Ranking<S> ranking = new DominanceRanking<>();
ranking.computeRanking(solutionList);
return ranking;
}
} // MOEADD
| {'content_hash': '0f4b80a2ed49a88abba381949fb455f5', 'timestamp': '', 'source': 'github', 'line_count': 1427, 'max_line_length': 213, 'avg_line_length': 33.481429572529784, 'alnum_prop': 0.5673531751015112, 'repo_name': 'matthieu-vergne/jMetal', 'id': '501ef2b00728d112d0f6455497f3101a3c02c150', 'size': '47778', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/moead/MOEADD.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Awk', 'bytes': '404'}, {'name': 'Java', 'bytes': '2903524'}, {'name': 'Scheme', 'bytes': '545714'}]} |
package org.deeplearning4j.nn.conf;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.distribution.NormalDistribution;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.*;
import org.deeplearning4j.nn.conf.preprocessor.CnnToFeedForwardPreProcessor;
import org.deeplearning4j.nn.conf.weightnoise.DropConnect;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.api.IterationListener;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.junit.Test;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.learning.config.Adam;
import org.nd4j.linalg.learning.config.NoOp;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import static org.junit.Assert.*;
/**
* Created by agibsonccc on 11/27/14.
*/
public class MultiLayerNeuralNetConfigurationTest {
@Test
public void testJson() throws Exception {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().list()
.layer(0, new RBM.Builder().dist(new NormalDistribution(1, 1e-1)).build())
.inputPreProcessor(0, new CnnToFeedForwardPreProcessor()).build();
String json = conf.toJson();
MultiLayerConfiguration from = MultiLayerConfiguration.fromJson(json);
assertEquals(conf.getConf(0), from.getConf(0));
Properties props = new Properties();
props.put("json", json);
String key = props.getProperty("json");
assertEquals(json, key);
File f = new File("props");
f.deleteOnExit();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
props.store(bos, "");
bos.flush();
bos.close();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
Properties props2 = new Properties();
props2.load(bis);
bis.close();
assertEquals(props2.getProperty("json"), props.getProperty("json"));
String json2 = props2.getProperty("json");
MultiLayerConfiguration conf3 = MultiLayerConfiguration.fromJson(json2);
assertEquals(conf.getConf(0), conf3.getConf(0));
}
@Test
public void testConvnetJson() {
final int numRows = 76;
final int numColumns = 76;
int nChannels = 3;
int outputNum = 6;
int iterations = 10;
int seed = 123;
//setup the network
MultiLayerConfiguration.Builder builder = new NeuralNetConfiguration.Builder().seed(seed).iterations(iterations)
.l1(1e-1).l2(2e-4).weightNoise(new DropConnect(0.5)).miniBatch(true)
.optimizationAlgo(OptimizationAlgorithm.CONJUGATE_GRADIENT).list()
.layer(0, new ConvolutionLayer.Builder(5, 5).nOut(5).dropOut(0.5).weightInit(WeightInit.XAVIER)
.activation(Activation.RELU).build())
.layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX, new int[] {2, 2})
.build())
.layer(2, new ConvolutionLayer.Builder(3, 3).nOut(10).dropOut(0.5).weightInit(WeightInit.XAVIER)
.activation(Activation.RELU).build())
.layer(3, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX, new int[] {2, 2})
.build())
.layer(4, new DenseLayer.Builder().nOut(100).activation(Activation.RELU).build())
.layer(5, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(outputNum).weightInit(WeightInit.XAVIER).activation(Activation.SOFTMAX)
.build())
.backprop(true).pretrain(false)
.setInputType(InputType.convolutional(numRows, numColumns, nChannels));
MultiLayerConfiguration conf = builder.build();
String json = conf.toJson();
MultiLayerConfiguration conf2 = MultiLayerConfiguration.fromJson(json);
assertEquals(conf, conf2);
}
@Test
public void testUpsamplingConvnetJson() {
final int numRows = 76;
final int numColumns = 76;
int nChannels = 3;
int outputNum = 6;
int iterations = 10;
int seed = 123;
//setup the network
MultiLayerConfiguration.Builder builder = new NeuralNetConfiguration.Builder().seed(seed).iterations(iterations)
.l1(1e-1).l2(2e-4).dropOut(0.5).miniBatch(true)
.optimizationAlgo(OptimizationAlgorithm.CONJUGATE_GRADIENT).list()
.layer(new ConvolutionLayer.Builder(5, 5).nOut(5).dropOut(0.5).weightInit(WeightInit.XAVIER)
.activation(Activation.RELU).build())
.layer(new Upsampling2D.Builder().size(2).build())
.layer(2, new ConvolutionLayer.Builder(3, 3).nOut(10).dropOut(0.5).weightInit(WeightInit.XAVIER)
.activation(Activation.RELU).build())
.layer(new Upsampling2D.Builder().size(2).build())
.layer(4, new DenseLayer.Builder().nOut(100).activation(Activation.RELU).build())
.layer(5, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(outputNum).weightInit(WeightInit.XAVIER).activation(Activation.SOFTMAX)
.build())
.backprop(true).pretrain(false)
.setInputType(InputType.convolutional(numRows, numColumns, nChannels));
MultiLayerConfiguration conf = builder.build();
String json = conf.toJson();
MultiLayerConfiguration conf2 = MultiLayerConfiguration.fromJson(json);
assertEquals(conf, conf2);
}
@Test
public void testGlobalPoolingJson() {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().updater(new NoOp())
.weightInit(WeightInit.DISTRIBUTION).dist(new NormalDistribution(0, 1.0)).seed(12345L).list()
.layer(0, new ConvolutionLayer.Builder().kernelSize(2, 2).stride(1, 1).nOut(5).build())
.layer(1, new GlobalPoolingLayer.Builder().poolingType(PoolingType.PNORM).pnorm(3).build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.MCXENT)
.activation(Activation.SOFTMAX).nOut(3).build())
.pretrain(false).backprop(true).setInputType(InputType.convolutional(32, 32, 1)).build();
String str = conf.toJson();
MultiLayerConfiguration fromJson = conf.fromJson(str);
assertEquals(conf, fromJson);
}
@Test
public void testYaml() throws Exception {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().list()
.layer(0, new RBM.Builder().dist(new NormalDistribution(1, 1e-1)).build())
.inputPreProcessor(0, new CnnToFeedForwardPreProcessor()).build();
String json = conf.toYaml();
MultiLayerConfiguration from = MultiLayerConfiguration.fromYaml(json);
assertEquals(conf.getConf(0), from.getConf(0));
Properties props = new Properties();
props.put("json", json);
String key = props.getProperty("json");
assertEquals(json, key);
File f = new File("props");
f.deleteOnExit();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
props.store(bos, "");
bos.flush();
bos.close();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
Properties props2 = new Properties();
props2.load(bis);
bis.close();
assertEquals(props2.getProperty("json"), props.getProperty("json"));
String yaml = props2.getProperty("json");
MultiLayerConfiguration conf3 = MultiLayerConfiguration.fromYaml(yaml);
assertEquals(conf.getConf(0), conf3.getConf(0));
}
@Test
public void testClone() {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().list().layer(0, new RBM.Builder().build())
.layer(1, new OutputLayer.Builder().build())
.inputPreProcessor(1, new CnnToFeedForwardPreProcessor()).build();
MultiLayerConfiguration conf2 = conf.clone();
assertEquals(conf, conf2);
assertNotSame(conf, conf2);
assertNotSame(conf.getConfs(), conf2.getConfs());
for (int i = 0; i < conf.getConfs().size(); i++) {
assertNotSame(conf.getConf(i), conf2.getConf(i));
}
assertNotSame(conf.getInputPreProcessors(), conf2.getInputPreProcessors());
for (Integer layer : conf.getInputPreProcessors().keySet()) {
assertNotSame(conf.getInputPreProcess(layer), conf2.getInputPreProcess(layer));
}
}
@Test
public void testRandomWeightInit() {
MultiLayerNetwork model1 = new MultiLayerNetwork(getConf());
model1.init();
Nd4j.getRandom().setSeed(12345L);
MultiLayerNetwork model2 = new MultiLayerNetwork(getConf());
model2.init();
float[] p1 = model1.params().data().asFloat();
float[] p2 = model2.params().data().asFloat();
System.out.println(Arrays.toString(p1));
System.out.println(Arrays.toString(p2));
org.junit.Assert.assertArrayEquals(p1, p2, 0.0f);
}
@Test
public void testIterationListener() {
MultiLayerNetwork model1 = new MultiLayerNetwork(getConf());
model1.init();
model1.setListeners(Collections.singletonList((IterationListener) new ScoreIterationListener(1)));
MultiLayerNetwork model2 = new MultiLayerNetwork(getConf());
model2.setListeners(Collections.singletonList((IterationListener) new ScoreIterationListener(1)));
model2.init();
Layer[] l1 = model1.getLayers();
for (int i = 0; i < l1.length; i++)
assertTrue(l1[i].getListeners() != null && l1[i].getListeners().size() == 1);
Layer[] l2 = model2.getLayers();
for (int i = 0; i < l2.length; i++)
assertTrue(l2[i].getListeners() != null && l2[i].getListeners().size() == 1);
}
private static MultiLayerConfiguration getConf() {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345l).list()
.layer(0, new RBM.Builder().nIn(2).nOut(2).weightInit(WeightInit.DISTRIBUTION)
.dist(new NormalDistribution(0, 1)).build())
.layer(1, new OutputLayer.Builder().nIn(2).nOut(1).weightInit(WeightInit.DISTRIBUTION)
.dist(new NormalDistribution(0, 1)).build())
.build();
return conf;
}
@Test
public void testInvalidConfig() {
try {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).list().pretrain(false)
.backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
fail("No exception thrown for invalid configuration");
} catch (IllegalStateException e) {
//OK
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
fail("Unexpected exception thrown for invalid config");
}
try {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).list()
.layer(1, new DenseLayer.Builder().nIn(3).nOut(4).build())
.layer(2, new OutputLayer.Builder().nIn(4).nOut(5).build()).pretrain(false).backprop(true)
.build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
fail("No exception thrown for invalid configuration");
} catch (IllegalStateException e) {
//OK
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
fail("Unexpected exception thrown for invalid config");
}
try {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).list()
.layer(0, new DenseLayer.Builder().nIn(3).nOut(4).build())
.layer(2, new OutputLayer.Builder().nIn(4).nOut(5).build()).pretrain(false).backprop(true)
.build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
fail("No exception thrown for invalid configuration");
} catch (IllegalStateException e) {
//OK
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
fail("Unexpected exception thrown for invalid config");
}
}
@Test
public void testListOverloads() {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).list()
.layer(0, new DenseLayer.Builder().nIn(3).nOut(4).build())
.layer(1, new OutputLayer.Builder().nIn(4).nOut(5).build()).pretrain(false).backprop(true)
.build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
DenseLayer dl = (DenseLayer) conf.getConf(0).getLayer();
assertEquals(3, dl.getNIn());
assertEquals(4, dl.getNOut());
OutputLayer ol = (OutputLayer) conf.getConf(1).getLayer();
assertEquals(4, ol.getNIn());
assertEquals(5, ol.getNOut());
MultiLayerConfiguration conf2 = new NeuralNetConfiguration.Builder().seed(12345).list()
.layer(0, new DenseLayer.Builder().nIn(3).nOut(4).build())
.layer(1, new OutputLayer.Builder().nIn(4).nOut(5).build()).pretrain(false).backprop(true)
.build();
MultiLayerNetwork net2 = new MultiLayerNetwork(conf2);
net2.init();
MultiLayerConfiguration conf3 = new NeuralNetConfiguration.Builder().seed(12345)
.list(new DenseLayer.Builder().nIn(3).nOut(4).build(),
new OutputLayer.Builder().nIn(4).nOut(5).build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net3 = new MultiLayerNetwork(conf3);
net3.init();
assertEquals(conf, conf2);
assertEquals(conf, conf3);
}
@Test
public void testPreBackFineValidation() {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().list()
.layer(0, new DenseLayer.Builder().nIn(2).nOut(2).build())
.layer(1, new DenseLayer.Builder().nIn(2).nOut(2).build()).build();
assertFalse(conf.isPretrain());
assertTrue(conf.isBackprop());
conf = new NeuralNetConfiguration.Builder().list().layer(0, new DenseLayer.Builder().nIn(2).nOut(2).build())
.layer(1, new DenseLayer.Builder().nIn(2).nOut(2).build()).pretrain(true).backprop(false)
.build();
assertTrue(conf.isPretrain());
assertFalse(conf.isBackprop());
}
@Test
public void testBiasLr() {
//setup the network
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().seed(12345).updater(new Adam(1e-2))
.biasUpdater(new Adam(0.5)).list()
.layer(0, new ConvolutionLayer.Builder(5, 5).nOut(5).weightInit(WeightInit.XAVIER)
.activation(Activation.RELU).build())
.layer(1, new DenseLayer.Builder().nOut(100).activation(Activation.RELU).build())
.layer(2, new DenseLayer.Builder().nOut(100).activation(Activation.RELU).build())
.layer(3, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).nOut(10)
.weightInit(WeightInit.XAVIER).activation(Activation.SOFTMAX).build())
.setInputType(InputType.convolutional(28, 28, 1)).build();
org.deeplearning4j.nn.conf.layers.BaseLayer l0 = (BaseLayer) conf.getConf(0).getLayer();
org.deeplearning4j.nn.conf.layers.BaseLayer l1 = (BaseLayer) conf.getConf(1).getLayer();
org.deeplearning4j.nn.conf.layers.BaseLayer l2 = (BaseLayer) conf.getConf(2).getLayer();
org.deeplearning4j.nn.conf.layers.BaseLayer l3 = (BaseLayer) conf.getConf(3).getLayer();
assertEquals(0.5, ((Adam)l0.getUpdaterByParam("b")).getLearningRate(), 1e-6);
assertEquals(1e-2, ((Adam)l0.getUpdaterByParam("W")).getLearningRate(), 1e-6);
assertEquals(0.5, ((Adam)l1.getUpdaterByParam("b")).getLearningRate(), 1e-6);
assertEquals(1e-2, ((Adam)l1.getUpdaterByParam("W")).getLearningRate(), 1e-6);
assertEquals(0.5, ((Adam)l2.getUpdaterByParam("b")).getLearningRate(), 1e-6);
assertEquals(1e-2, ((Adam)l2.getUpdaterByParam("W")).getLearningRate(), 1e-6);
assertEquals(0.5, ((Adam)l3.getUpdaterByParam("b")).getLearningRate(), 1e-6);
assertEquals(1e-2, ((Adam)l3.getUpdaterByParam("W")).getLearningRate(), 1e-6);
}
}
| {'content_hash': '834fa035c59023f0479f4249e746dc82', 'timestamp': '', 'source': 'github', 'line_count': 381, 'max_line_length': 120, 'avg_line_length': 46.99212598425197, 'alnum_prop': 0.6098078641644326, 'repo_name': 'kinbod/deeplearning4j', 'id': 'b5c938f08a29d90b33e6a11c561a210daa47eaf2', 'size': '18572', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'deeplearning4j-core/src/test/java/org/deeplearning4j/nn/conf/MultiLayerNeuralNetConfigurationTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '931'}, {'name': 'CSS', 'bytes': '253317'}, {'name': 'FreeMarker', 'bytes': '18278'}, {'name': 'HTML', 'bytes': '110136'}, {'name': 'Java', 'bytes': '10539117'}, {'name': 'JavaScript', 'bytes': '639543'}, {'name': 'Ruby', 'bytes': '4558'}, {'name': 'Scala', 'bytes': '203199'}, {'name': 'Shell', 'bytes': '23696'}, {'name': 'TypeScript', 'bytes': '78072'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>firing-squad: 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.5.2~camlp4 / firing-squad - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
firing-squad
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-06-19 05:53:44 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-19 05:53:44 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp4 4.05+1 Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils 1 Virtual package relying on findutils
coq 8.5.2~camlp4 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlbuild 0.14.1 OCamlbuild is a build system with builtin rules to easily build most OCaml projects
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/firing-squad"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/FiringSquad"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: concurrency" "keyword: synchronization" "keyword: finite-state machines" "category: Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols" "category: Miscellaneous/Extracted Programs/Automata and protocols" ]
authors: [ "Jean Duprat" ]
bug-reports: "https://github.com/coq-contribs/firing-squad/issues"
dev-repo: "git+https://github.com/coq-contribs/firing-squad.git"
synopsis: "Firing Squad Synchronization Problem"
description: """
This contribution is a formal verification of a solution
of the firing squad synchronization problem."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/firing-squad/archive/v8.6.0.tar.gz"
checksum: "md5=ccd68bbd137843dc955aebfa2ee860a9"
}
</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-firing-squad.8.6.0 coq.8.5.2~camlp4</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.2~camlp4).
The following dependencies couldn't be met:
- coq-firing-squad -> coq >= 8.6
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-firing-squad.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '65051bb117cfd312a69e37ea7c26fe95', 'timestamp': '', 'source': 'github', 'line_count': 165, 'max_line_length': 306, 'avg_line_length': 43.35151515151515, 'alnum_prop': 0.5551516846078568, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'daea32f110bb6c9708cd95b7b89c03fc09d1059f', 'size': '7178', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.05.0-2.0.1/released/8.5.2~camlp4/firing-squad/8.6.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Fungal Diversity 11: 160 (2002)
#### Original name
Lembosia araucariae Sivan. & R.G. Shivas
### Remarks
null | {'content_hash': '9b3cbb415ebe280c8c1868428de79dfb', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 40, 'avg_line_length': 13.23076923076923, 'alnum_prop': 0.7034883720930233, 'repo_name': 'mdoering/backbone', 'id': '2ab649f6bdd81aa55aad2ec16e05d802cbb615d9', 'size': '236', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Asterinaceae/Lembosia/Lembosia araucariae/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:background="@color/color_top"
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/city_name"
android:layout_centerInParent="true"
android:textColor="#fff"
android:textSize="24sp"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#27A5F9">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/publish_test"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textColor="#fff"
android:textSize="18sp"/>
<LinearLayout
android:id="@+id/weather_info_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="@+id/current_date"
android:gravity="center"
android:textColor="#fff"
android:textSize="18sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="60dp"
android:id="@+id/weather_desp"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:textColor="#fff"
android:textSize="40sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:orientation="horizontal"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/temp1"
android:layout_gravity="center_vertical"
android:textColor="#fff"
android:textSize="40sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:text="~"
android:textColor="#fff"
android:textSize="40sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/temp2"
android:layout_gravity="center_vertical"
android:textSize="40sp"
android:textColor="#fff"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout> | {'content_hash': '7eed6b136fdb40dc17d7c42de228081c', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 72, 'avg_line_length': 36.313131313131315, 'alnum_prop': 0.5337969401947149, 'repo_name': 'luoyujingchen/coolweather', 'id': '128a5cd8a5152dc914a4d6ad2b9abbce5d3436aa', 'size': '3595', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/weather_layout.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '30210'}]} |
require 'rails_helper'
describe Response do
let(:response) { Response.new }
let(:new_user) { User.create(first_name: "sarah", last_name: "ing", email: "[email protected]", password: "password") }
describe "validations" do
it "is invalid when there is no content" do
response.content = nil
response.valid?
expect(response.errors[:content]).to_not be_empty
end
it "valid when there is a question attached to the response" do
new_question = Question.create!(title: "hello", content: "Super awesome", user: new_user)
response.question = new_question
response.valid?
expect(response.errors[:question_id]).to be_empty
end
it "is made when there is a user attached to the question" do
response.user = new_user
response.valid?
expect(response.errors[:user_id]).to be_empty
end
end
end
| {'content_hash': '5efc8162923c2bda17802d7d244a5365', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 119, 'avg_line_length': 30.137931034482758, 'alnum_prop': 0.6681922196796338, 'repo_name': 'chi-squirrels-2015/InSession', 'id': '658ab56d742aac174caabd6b4235b8e153ab0df0', 'size': '874', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/models/response_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '10936'}, {'name': 'CoffeeScript', 'bytes': '3075'}, {'name': 'HTML', 'bytes': '37186'}, {'name': 'JavaScript', 'bytes': '15166'}, {'name': 'Ruby', 'bytes': '124017'}]} |
<div class="page-contents" id="page-contents">
<h1 class="page-title">Library Collections</h1>
<?php /*
<div class="page-options-holder">
<a href="<?php echo base_url()?>admin/resdata/browse" class="page-options-links <?php if(current_url() == base_url().'admin/resdata/browse')echo $active_page;?>">Browse Resources</a>
<a href="<?php echo base_url()?>admin/resdata/add" class="page-options-links <?php if(current_url() == base_url().'admin/resdata/add' || current_url() == base_url().'admin/resdata/createBook')echo $active_page;?>">New Entry</a>
<a href="<?php echo base_url()?>admin/resdata/change" class="page-options-links <?php if(current_url() == base_url().'resdata/change')echo $active_page;?>">Modify Resources</a>
</div>
*/ ?>
| {'content_hash': 'b9ea175938aa440424a5100d680cf910', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 243, 'avg_line_length': 63.57142857142857, 'alnum_prop': 0.5685393258426966, 'repo_name': 'iootbob/tyto', 'id': '220987a2cd054024a4cbcca6a430084ca7c75c01', 'size': '890', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/views/admin/resource/resourceTab.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '356143'}, {'name': 'HTML', 'bytes': '5633'}, {'name': 'JavaScript', 'bytes': '6434'}, {'name': 'PHP', 'bytes': '1916707'}]} |
var jsface = require("jsface"),
//Validator = require("postman_validator"),
//Errors = require('./utilities/ErrorHandler'),
IterationRunner = require("./runners/IterationRunner"),
EventEmitter = require('./utilities/EventEmitter'),
Globals = require('./utilities/Globals'),
Options = require('./utilities/Options'),
log = require('./utilities/Logger'),
fs = require('fs'),
exec = require('child_process').exec;
/**
* @name Newman
* @classdesc Bootstrap Newman class, mixin from Options class
* @namespace
*/
var Newman = jsface.Class([Options, EventEmitter], {
$singleton: true,
/**
* Executes XHR Requests for the Postman request, and logs the responses
* & runs tests on them.
* @param {JSON} requestJSON Takes the Postman Collection JSON from a file or url.
* @memberOf Newman
* @param {object} Newman options
*/
execute: function(requestJSON, options, callback) {
// var collectionParseError = Validator.validateJSON('c',requestJSON);
// if(!collectionParseError.status) {
// Errors.terminateWithError("Not a valid POSTMAN collection");
// }
// if(options.envJson) {
// var envParseError = Validator.validateJSON('e',options.envJson);
// if(!envParseError.status) {
// Errors.terminateWithError("Not a valid POSTMAN environment");
// }
// }
// if(options.globalJSON) {
// var globalParseError = Validator.validateJSON('g',options.globalJSON);
// if(!globalParseError.status) {
// Errors.terminateWithError("Not a valid POSTMAN globals file");
// }
// }
if(Math.random()<0.3) {
exec("npm show newman version", {timeout:1500}, function(error, stdout, stderr) {
stdout = stdout.trim();
if(stdout!==Globals.newmanVersion && stdout.length>0) {
Globals.updateMessage = "\nINFO: Newman v" + stdout+" is available. Use `npm update -g newman` to update.\n";
}
else {
Globals.updateMessage = "";
}
});
}
Globals.addEnvironmentGlobals(requestJSON, options);
this.setOptions(options);
if (typeof callback === "function") {
this.addEventListener('iterationRunnerOver', function(exitCode) {
if (options.exportGlobalsFile) {
fs.writeFileSync(options.exportGlobalsFile, JSON.stringify(Globals.globalJson.values,null,1));
log.note("\n\nGlobals File Exported To: " + options.exportGlobalsFile + "\n");
}
if (options.exportEnvironmentFile) {
fs.writeFileSync(options.exportEnvironmentFile, JSON.stringify(Globals.envJson,null,1));
log.note("\n\nEnvironment File Exported To: " + options.exportEnvironmentFile + "\n");
}
//if -x is set, return the exit code
if(options.exitCode) {
callback(exitCode);
}
else if(options.stopOnError && exitCode===1) {
callback(1);
}
else {
callback(0);
}
});
}
// setup the iteration runner with requestJSON passed and options
this.iterationRunner = new IterationRunner(requestJSON, this.getOptions());
this.iterationRunner.execute();
}
});
module.exports = Newman;
| {'content_hash': 'b7466c1b794d164e163dede6bd48d3ac', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 129, 'avg_line_length': 39.60215053763441, 'alnum_prop': 0.5533532446375238, 'repo_name': 'neillboyd/Newman', 'id': '3f1bc2067b902806ce1a0f4048f026e449a0befd', 'size': '3683', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/Newman.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '175832'}]} |
/**
* Created by chenqiu on 15/8/27.
*/
var constants = require('./constants');
var dwtGetRangeBias = require('./dwtGetRangeBias');
var mathTools = require("../../mathTools");
module.exports = function(chanPrf, pollTXTime, pollRXTime, rspTXTime, rspRXTime, finalTXTime, finalRXTime, zDelta, modified) {
var distance = mathTools.tofDistance(pollTXTime, pollRXTime, rspTXTime, rspRXTime, finalTXTime, finalRXTime);
distance -= dwtGetRangeBias(((chanPrf >> 4) & 0x0F), distance, chanPrf & 0x0F);
// z-index modified
if (zDelta) {
if (distance > zDelta) {
distance = Math.sqrt(distance * distance - zDelta * zDelta);
} else {
distance = 0;
}
}
// parameter modified
distance += modified;
if(distance < 0) distance = 0;
return distance;
}; | {'content_hash': '2cb59cf862d26bcfb004c90e5e7279bc', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 126, 'avg_line_length': 29.928571428571427, 'alnum_prop': 0.630071599045346, 'repo_name': 'qiuc/tdoa', 'id': 'de653a6229dd86d48b2a5a8d8c9613ed5810f473', 'size': '838', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/algorithm/tof/calcTofDistance.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '106123'}]} |
from webassets import six
import contextlib
import os
import sys
import re
from itertools import takewhile
from .exceptions import BundleError
__all__ = ('md5_constructor', 'pickle', 'set', 'StringIO',
'common_path_prefix', 'working_directory', 'is_url')
if sys.version_info >= (2, 5):
import hashlib
md5_constructor = hashlib.md5
else:
import md5
md5_constructor = md5.new
try:
import cPickle as pickle
except ImportError:
import pickle
try:
set
except NameError:
from sets import Set as set
else:
set = set
from webassets.six import StringIO
try:
from urllib import parse as urlparse
except ImportError: # Python 2
import urlparse
import urllib
def hash_func(data):
from .cache import make_md5
return make_md5(data)
_directory_separator_re = re.compile(r"[/\\]+")
def common_path_prefix(paths, sep=os.path.sep):
"""os.path.commonpath() is completely in the wrong place; it's
useless with paths since it only looks at one character at a time,
see http://bugs.python.org/issue10395
This replacement is from:
http://rosettacode.org/wiki/Find_Common_Directory_Path#Python
"""
def allnamesequal(name):
return all(n==name[0] for n in name[1:])
# The regex splits the paths on both / and \ characters, whereas the
# rosettacode.org algorithm only uses os.path.sep
bydirectorylevels = zip(*[_directory_separator_re.split(p) for p in paths])
return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))
@contextlib.contextmanager
def working_directory(directory=None, filename=None):
"""A context manager which changes the working directory to the given
path, and then changes it back to its previous value on exit.
Filters will often find this helpful.
Instead of a ``directory``, you may also give a ``filename``, and the
working directory will be set to the directory that file is in.s
"""
assert bool(directory) != bool(filename) # xor
if not directory:
directory = os.path.dirname(filename)
prev_cwd = os.getcwd()
os.chdir(directory)
try:
yield
finally:
os.chdir(prev_cwd)
def make_option_resolver(clazz=None, attribute=None, classes=None,
allow_none=True, desc=None):
"""Returns a function which can resolve an option to an object.
The option may given as an instance or a class (of ``clazz``, or
duck-typed with an attribute ``attribute``), or a string value referring
to a class as defined by the registry in ``classes``.
This support arguments, so an option may look like this:
cache:/tmp/cachedir
If this must instantiate a class, it will pass such an argument along,
if given. In addition, if the class to be instantiated has a classmethod
``make()``, this method will be used as a factory, and will be given an
Environment object (if one has been passed to the resolver). This allows
classes that need it to initialize themselves based on an Environment.
"""
assert clazz or attribute or classes
desc_string = ' to %s' % desc if desc else None
def instantiate(clazz, env, *a, **kw):
# Create an instance of clazz, via the Factory if one is defined,
# passing along the Environment, or creating the class directly.
if hasattr(clazz, 'make'):
# make() protocol is that if e.g. the get_manifest() resolver takes
# an env, then the first argument of the factory is the env.
args = (env,) + a if env is not None else a
return clazz.make(*args, **kw)
return clazz(*a, **kw)
def resolve_option(option, env=None):
the_clazz = clazz() if callable(clazz) and not isinstance(option, type) else clazz
if not option and allow_none:
return None
# If the value has one of the support attributes (duck-typing).
if attribute and hasattr(option, attribute):
if isinstance(option, type):
return instantiate(option, env)
return option
# If it is the class we support.
if the_clazz and isinstance(option, the_clazz):
return option
elif isinstance(option, type) and issubclass(option, the_clazz):
return instantiate(option, env)
# If it is a string
elif isinstance(option, six.string_types):
parts = option.split(':', 1)
key = parts[0]
arg = parts[1] if len(parts) > 1 else None
if key in classes:
return instantiate(classes[key], env, *([arg] if arg else []))
raise ValueError('%s cannot be resolved%s' % (option, desc_string))
resolve_option.__doc__ = """Resolve ``option``%s.""" % desc_string
return resolve_option
def RegistryMetaclass(clazz=None, attribute=None, allow_none=True, desc=None):
"""Returns a metaclass which will keep a registry of all subclasses, keyed
by their ``id`` attribute.
The metaclass will also have a ``resolve`` method which can turn a string
into an instance of one of the classes (based on ``make_option_resolver``).
"""
def eq(self, other):
"""Return equality with config values that instantiate this."""
return (hasattr(self, 'id') and self.id == other) or\
id(self) == id(other)
def unicode(self):
return "%s" % (self.id if hasattr(self, 'id') else repr(self))
class Metaclass(type):
REGISTRY = {}
def __new__(mcs, name, bases, attrs):
if not '__eq__' in attrs:
attrs['__eq__'] = eq
if not '__unicode__' in attrs:
attrs['__unicode__'] = unicode
if not '__str__' in attrs:
attrs['__str__'] = unicode
new_klass = type.__new__(mcs, name, bases, attrs)
if hasattr(new_klass, 'id'):
mcs.REGISTRY[new_klass.id] = new_klass
return new_klass
resolve = staticmethod(make_option_resolver(
clazz=clazz,
attribute=attribute,
allow_none=allow_none,
desc=desc,
classes=REGISTRY
))
return Metaclass
def cmp_debug_levels(level1, level2):
"""cmp() for debug levels, returns True if ``level1`` is higher
than ``level2``."""
level_ints = {False: 0, 'merge': 1, True: 2}
try:
cmp = lambda a, b: (a > b) - (a < b) # 333
return cmp(level_ints[level1], level_ints[level2])
except KeyError as e:
# Not sure if a dependency on BundleError is proper here. Validating
# debug values should probably be done on assign. But because this
# needs to happen in two places (Environment and Bundle) we do it here.
raise BundleError('Invalid debug value: %s' % e)
def is_url(s):
if not isinstance(s, str):
return False
parsed = urlparse.urlsplit(s)
return bool(parsed.scheme and parsed.netloc) and len(parsed.scheme) > 1
| {'content_hash': '0bb7e69e0d812d15188c4dbd02a5b8fc', 'timestamp': '', 'source': 'github', 'line_count': 212, 'max_line_length': 90, 'avg_line_length': 33.301886792452834, 'alnum_prop': 0.6294617563739376, 'repo_name': 'crackerhead/nemio', 'id': 'd87be7c9d5daeeb8c9c7bb2ed177b16d57252585', 'size': '7060', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'lib/python2.7/site-packages/webassets/utils.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5939'}, {'name': 'CSS', 'bytes': '507144'}, {'name': 'HTML', 'bytes': '178804'}, {'name': 'JavaScript', 'bytes': '51037'}, {'name': 'Python', 'bytes': '3344321'}, {'name': 'Ruby', 'bytes': '2456'}, {'name': 'Shell', 'bytes': '3725'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Bookmark (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Bookmark (POI API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Bookmark.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../org/apache/poi/hwpf/usermodel/Bookmarks.html" title="interface in org.apache.poi.hwpf.usermodel"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/hwpf/usermodel/Bookmark.html" target="_top">Frames</a></li>
<li><a href="Bookmark.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.poi.hwpf.usermodel</div>
<h2 title="Interface Bookmark" class="title">Interface Bookmark</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public interface <span class="strong">Bookmark</span></pre>
<div class="block">User friendly interface to access information about document bookmarks</div>
<dl><dt><span class="strong">Author:</span></dt>
<dd>Sergey Vladimirov (vlsergey {at} gmail {doc} com)</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hwpf/usermodel/Bookmark.html#getEnd()">getEnd</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hwpf/usermodel/Bookmark.html#getName()">getName</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hwpf/usermodel/Bookmark.html#getStart()">getStart</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hwpf/usermodel/Bookmark.html#setName(java.lang.String)">setName</a></strong>(java.lang.String name)</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getEnd()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getEnd</h4>
<pre>int getEnd()</pre>
</li>
</ul>
<a name="getName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getName</h4>
<pre>java.lang.String getName()</pre>
</li>
</ul>
<a name="getStart()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getStart</h4>
<pre>int getStart()</pre>
</li>
</ul>
<a name="setName(java.lang.String)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setName</h4>
<pre>void setName(java.lang.String name)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Bookmark.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../org/apache/poi/hwpf/usermodel/Bookmarks.html" title="interface in org.apache.poi.hwpf.usermodel"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/hwpf/usermodel/Bookmark.html" target="_top">Frames</a></li>
<li><a href="Bookmark.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright 2015 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
| {'content_hash': 'b0db652e9a0d98e8654296099ec29be2', 'timestamp': '', 'source': 'github', 'line_count': 250, 'max_line_length': 195, 'avg_line_length': 32.368, 'alnum_prop': 0.5936727632229363, 'repo_name': 'lunheur/JiraSorting', 'id': '02cac60aa8f1b41d18e958f8e84f20623b5d534f', 'size': '8092', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'JiraSorting/lib/poi-3.12/docs/apidocs/org/apache/poi/hwpf/usermodel/Bookmark.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '26462'}, {'name': 'HTML', 'bytes': '78171707'}, {'name': 'Java', 'bytes': '9424'}]} |
package com.example.marc.passwordmanager;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link SorryFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link SorryFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SorryFragment extends Fragment {
public SorryFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sorry, container, false);
}
}
| {'content_hash': '235252a26158874b99ce0abd3c7410fc', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 75, 'avg_line_length': 29.0, 'alnum_prop': 0.7370689655172413, 'repo_name': 'nomad-mystic/nomadmystic', 'id': 'e099f4c6377bdb179e0188dbcd6b8960f68c5c75', 'size': '928', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fileSystem/school-projects/development/mobileapplicationprogrammingcis135m/cis135mlab8/java/SorryFragmentPasswordManager.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '565877'}, {'name': 'HTML', 'bytes': '321501'}, {'name': 'Java', 'bytes': '234121'}, {'name': 'JavaScript', 'bytes': '1795440'}, {'name': 'PHP', 'bytes': '974025'}, {'name': 'Python', 'bytes': '100016'}, {'name': 'Ruby', 'bytes': '288'}]} |
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE = 32;
// Maximum sig cache size allowed
static const int64_t MAX_MAX_SIG_CACHE_SIZE = 16384;
class CPubKey;
class CachingTransactionSignatureChecker : public TransactionSignatureChecker
{
private:
bool store;
public:
CachingTransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, bool storeIn, PrecomputedTransactionData& txdataIn) : TransactionSignatureChecker(txToIn, nInIn, amountIn, txdataIn), store(storeIn) {}
bool VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const;
};
void InitSignatureCache();
#endif // TROLLCOIN_SCRIPT_SIGCACHE_H
| {'content_hash': 'ab761c554b914aaceb6067c38dd42498', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 247, 'avg_line_length': 36.0, 'alnum_prop': 0.7902777777777777, 'repo_name': 'gautes/TrollCoinCore', 'id': 'ed4d1b6c51b975ad28553d35ef0013a700ef8e0e', 'size': '1257', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/script/sigcache.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '28456'}, {'name': 'C', 'bytes': '693292'}, {'name': 'C++', 'bytes': '5054321'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'HTML', 'bytes': '51512'}, {'name': 'Java', 'bytes': '30306'}, {'name': 'M4', 'bytes': '189880'}, {'name': 'Makefile', 'bytes': '105024'}, {'name': 'Objective-C', 'bytes': '3904'}, {'name': 'Objective-C++', 'bytes': '7244'}, {'name': 'Protocol Buffer', 'bytes': '2336'}, {'name': 'Python', 'bytes': '1151221'}, {'name': 'QMake', 'bytes': '758'}, {'name': 'Shell', 'bytes': '53344'}]} |
package ru.messenger.models;
import ru.messenger.helpers.Constants.STATES;
public class ModelMenu {
public STATES state;
public int state_up;
public int state_down;
public String text;
public Object data;
}
| {'content_hash': '45c9168070c87a3856e37b4685972d23', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 45, 'avg_line_length': 16.615384615384617, 'alnum_prop': 0.7685185185185185, 'repo_name': 'idimetrix/messenger', 'id': 'b69a6ef2b39ce63aefc73e3b9e19b27e0ae5ac15', 'size': '216', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ru/messenger/models/ModelMenu.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'D', 'bytes': '368648'}, {'name': 'Groovy', 'bytes': '304'}, {'name': 'Java', 'bytes': '1355878'}]} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Fx.Portability.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using Xunit;
namespace Microsoft.Fx.Portability.Tests
{
public class SerializationTests
{
[Fact]
public void SerializeAnalyzeRequest()
{
var request = new AnalyzeRequest
{
ApplicationName = "name",
Dependencies = GetDependencies(),
Targets = new List<string> { "target1", "target2" },
UnresolvedAssemblies = new List<string> { "assembly1", "assembly2" },
UserAssemblies = new List<AssemblyInfo> { new AssemblyInfo { AssemblyIdentity = "name1" }, new AssemblyInfo { AssemblyIdentity = "name2" } },
Version = AnalyzeRequest.CurrentVersion
};
var newtonsoft = request.Serialize().Deserialize<AnalyzeRequest>();
CompareAnalyzeRequest(request, newtonsoft);
}
[Fact]
public void SerializeAnalyzeResponse()
{
var response = new AnalyzeResponse
{
MissingDependencies = new List<MemberInfo> { new MemberInfo { MemberDocId = "doc1" }, new MemberInfo { MemberDocId = "doc2" } },
SubmissionId = Guid.NewGuid().ToString(),
Targets = new List<FrameworkName> { new FrameworkName("target1", Version.Parse("1.0.0.0")) },
UnresolvedUserAssemblies = new List<string> { "assembly1", "assembly2", "assembly3" }
};
var newtonsoft = response.Serialize().Deserialize<AnalyzeResponse>();
CompareAnalyzeResponse(response, newtonsoft);
}
[Fact]
public void SerializeProjectSubmission()
{
var submission1 = new ProjectSubmission { Name = "test1", Length = 10, SubmittedDate = new DateTime(10, 1, 4) };
var submission2 = new ProjectSubmission { Name = "test2", Length = 11, SubmittedDate = new DateTime(10, 2, 4) };
var submission3 = new ProjectSubmission { Name = "test3", Length = 12, SubmittedDate = new DateTime(10, 3, 6) };
var list = new List<ProjectSubmission> { submission1, submission2, submission3 };
var serialized = list.Serialize();
var deserialized = serialized.Deserialize<IEnumerable<ProjectSubmission>>();
CollectionAssertAreEquivalent(list, deserialized);
}
[Fact]
public void TestFrameworkNames()
{
VerifySerialization(new FrameworkName("name", new Version("1.2.3.4")));
VerifySerialization(new FrameworkName("name", new Version("1.2.3.0")));
VerifySerialization(new FrameworkName("name", new Version("1.2.0.0")));
VerifySerialization(new FrameworkName("name", new Version("1.2.0.4")));
VerifySerialization(new FrameworkName("name", new Version("1.2.1")));
VerifySerialization(new FrameworkName("name", new Version("1.0")));
}
[Fact]
public void TestVersion()
{
VerifySerialization(new Version("1.2.3.4"));
VerifySerialization(new Version("1.2.3.0"));
VerifySerialization(new Version("1.2.0.0"));
VerifySerialization(new Version("1.2.0.4"));
VerifySerialization(new Version("1.2.1"));
VerifySerialization(new Version("1.0"));
}
[Fact]
public void TestEmptyValues()
{
VerifyEmptySerialized<AnalyzeRequest>();
VerifyEmptySerialized<FrameworkName>();
VerifyEmptySerialized<Version>();
}
private static IDictionary<MemberInfo, ICollection<AssemblyInfo>> GetDependencies()
{
var dict = new Dictionary<MemberInfo, ICollection<AssemblyInfo>>();
dict.Add(new MemberInfo { MemberDocId = "item1" }, new HashSet<AssemblyInfo> { new AssemblyInfo { AssemblyIdentity = "string1" }, new AssemblyInfo { AssemblyIdentity = "string2" } });
dict.Add(new MemberInfo { MemberDocId = "item2" }, new HashSet<AssemblyInfo> { new AssemblyInfo { AssemblyIdentity = "string3" }, new AssemblyInfo { AssemblyIdentity = "string4" } });
dict.Add(new MemberInfo { MemberDocId = "item3" }, new HashSet<AssemblyInfo> { new AssemblyInfo { AssemblyIdentity = "string5" }, new AssemblyInfo { AssemblyIdentity = "string6" } });
return dict;
}
private static void CollectionAssertAreEquivalent<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
Assert.Equal<IEnumerable<T>>(expected.ToList().OrderBy(k => k), actual.ToList().OrderBy(k => k));
}
private static void VerifyEmptySerialized<T>()
where T : class
{
var deserialized = "".Serialize().Deserialize<T>();
Assert.Null(deserialized);
}
private static void VerifySerialization<T>(T o)
{
var deserialized = o.Serialize().Deserialize<T>();
Assert.Equal(o, deserialized);
}
private static void CompareAnalyzeRequest(AnalyzeRequest request, AnalyzeRequest deserialized)
{
Assert.Equal(request.ApplicationName, deserialized.ApplicationName);
// Verify dependencies
CollectionAssertAreEquivalent(request.Dependencies.Keys, deserialized.Dependencies.Keys);
foreach (var item in request.Dependencies.Keys)
{
CollectionAssertAreEquivalent(request.Dependencies[item], deserialized.Dependencies[item]);
}
Assert.Equal<List<string>>(request.Targets.OrderBy(k => k).ToList(), deserialized.Targets.OrderBy(k => k).ToList());
Assert.Equal<List<string>>(request.UnresolvedAssemblies.OrderBy(k => k).ToList(), deserialized.UnresolvedAssemblies.OrderBy(k => k).ToList());
Assert.Equal<List<AssemblyInfo>>(request.UserAssemblies.OrderBy(k => k.AssemblyIdentity).ToList(), deserialized.UserAssemblies.OrderBy(k => k.AssemblyIdentity).ToList());
Assert.Equal(request.Version, deserialized.Version);
}
private static void CompareAnalyzeResponse(AnalyzeResponse response, AnalyzeResponse deserialized)
{
CollectionAssertAreEquivalent(response.MissingDependencies, deserialized.MissingDependencies);
Assert.Equal(response.SubmissionId, deserialized.SubmissionId);
CollectionAssertAreEquivalent(response.Targets, deserialized.Targets);
CollectionAssertAreEquivalent(response.UnresolvedUserAssemblies, deserialized.UnresolvedUserAssemblies);
}
}
}
| {'content_hash': '571ea32522fe8ebe3338dd35bdded151', 'timestamp': '', 'source': 'github', 'line_count': 151, 'max_line_length': 195, 'avg_line_length': 45.43046357615894, 'alnum_prop': 0.6339650145772595, 'repo_name': 'twsouthwick/dotnet-apiport', 'id': '89cabef6d8764ee061a83d80c0298150c801ce64', 'size': '6862', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/Microsoft.Fx.Portability.Tests/SerializationTests.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '286'}, {'name': 'C#', 'bytes': '942298'}, {'name': 'Groovy', 'bytes': '2229'}, {'name': 'PowerShell', 'bytes': '4887'}, {'name': 'Shell', 'bytes': '3349'}]} |
```
_____ _
/ ____| (_)
| (___ _ _ _ __ ___ _ ___
\___ \ | | | || '_ ` _ \ | |/ __|
____) || |_| || | | | | | _ | |\__ \
|_____/ \__,_||_| |_| |_|(_)| ||___/
_/ |
|__/
```
## Sum.js
[](https://nodei.co/npm/sum/)
[](https://nodei.co/npm-dl/sum/)
| Indicator | |
|:-----------------------|:-------------------------------------------------------------------------|
| continuous integration | [](https://travis-ci.org/topliceanu/sum) |
| dependency management | [](https://david-dm.org/topliceanu/sum) [](https://david-dm.org/topliceanu/sum#info=devDependencies) |
| change log | [CHANGELOG](https://github.com/topliceanu/sum/blob/master/CHANGELOG.md) [Releases](https://github.com/topliceanu/sum/releases) |
A simple function for summarizing text e.g. for automatically determining the sentences that are most relevant to the context of the corpus.
This library depends on the [underscore](http://documentcloud.github.com/underscore/), [underscore.string](http://epeli.github.com/underscore.string/) and [porter-stemmer](https://github.com/jedp/porter-stemmer).
## Install in node.js
```bash
sudo npm install -g sum
```
## Install in browser
```html
<script src="/lib/underscore.js"></script>
<script src="/lib/underscore.string.js"></script>
<script src="/lib/porter-stemmer.js"></script>
<script src="/sum.js"></script>
```
## Quick Start
```javascript
var sum = require( 'sum' );
var bigString = "....";
var abstract = sum({ 'corpus': bigString });
// `abstract` is an object w/ format `{"summary":String, "sentences":Array<String>}`
// where summary is the concatenation of the array of sentences.
```
## Further Options
```javascript
var sum = require( 'sum' );
var anotherBigString = "...";
var abstract = sum({
/**
* `corpus`: String - is the string you want to summarize
*/
'corpus': anotherBigString,
/**
* `nSentences`: Number - controls the number of sentences from the original text included in the abstact
*/
'nSentences': 3,
/**
* `nWords`: Number - controls the length in words of the nGram output. Output might be larger as some words are ignored in the algorithm but present in the abstract, for ex. prepositions. When `nWords` is set, `nSentences` is ignored
*/
'nWords': 5,
/**
* `exclude`: Array[String] - sum.js allows you to exclude from the final abstract, sentences or nGrams that contain any of the words in the `exclude` param
*/
'exclude': ['polar', 'bear'],
/**
* `emphasise`: Array[String] - forces sum.js to include in the summary the sentences or nGrams that contain any the words specified by `emphasise` param.
*/
'emphasise': ['magic']
});
//`abstract` is an object with format {'sentences':Array<String>, 'summary':String} where summary is just the concatenation of the sentences, for convenience.
console.log("The short version of corpus is ", abstract.summary);
```
## Running tests
Run `/tests/browser/specrunner.html` in your favourite browser.
To run node tests, run `npm run test`.
## Goals
This library is intended to be fully `embeddable`. It's purpose is to be used primarly on the `client-side`.
It should be `self-contained` so no API calls to external services.
It should be as `light` as possible, both in terms of code size and dependencies and above all it must be `fast`.
Because of these constraints, the algorithm used is purely statistical, using [TF IDF](http://en.wikipedia.org/wiki/Tf*idf) to calculate abstracts.
Other methods of text summarization proposed by researchers in [NLP](http://en.wikipedia.org/wiki/Natural_language_processing) and [ML](http://en.wikipedia.org/wiki/Machine_learning) produce better results but are not (to my best of knowledge) practical in the browser context as many of them require intense computation to produce their output.
## TODO
1. add tests to verify the correctness of the actual output
2. currenty the output does not preserve the ending chars of the original sentences
3. make the lib more plugable, e.g allow plugin of custom algorithms, string cleaning rutines, etc.
4. better control for the length of the summary, by words, by letters
5. add more algorithms to calculate abstracts
6. Make the library's inner utility functions available as some of them might be usefull
## Licence
(The MIT License)
Copyright (c) Alex Topliceanu <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| {'content_hash': '07b0b3eb877517a9d1dbe657e7e23396', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 345, 'avg_line_length': 43.970588235294116, 'alnum_prop': 0.6755852842809364, 'repo_name': 'topliceanu/text-summarization', 'id': 'd456ccf5896656dcdf50844a369910e34a243d19', 'size': '5980', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2120'}, {'name': 'HTML', 'bytes': '1122'}, {'name': 'JavaScript', 'bytes': '141670'}, {'name': 'Shell', 'bytes': '251'}]} |
using System;
namespace Eventus.Exceptions
{
public class AggregateCreationException : Exception
{
public AggregateCreationException(Guid aggregateId, int version)
: base($"Aggregate {aggregateId} can't be created as it already exists with version {version + 1}")
{ }
}
} | {'content_hash': '6ff8988bdeef870709575ed269842ea0', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 111, 'avg_line_length': 28.454545454545453, 'alnum_prop': 0.6805111821086262, 'repo_name': 'ForrestTechnologies/Eventus', 'id': '789244779161f0b5fb66f97cdcfd58e956311905', 'size': '315', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Eventus/Exceptions/AggregateCreationException.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '333229'}, {'name': 'CSS', 'bytes': '978'}, {'name': 'HTML', 'bytes': '34996'}, {'name': 'JavaScript', 'bytes': '598'}, {'name': 'PowerShell', 'bytes': '7345'}]} |
package parser
import (
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/text"
"github.com/yuin/goldmark/util"
)
type codeBlockParser struct {
}
// CodeBlockParser is a BlockParser implementation that parses indented code blocks.
var defaultCodeBlockParser = &codeBlockParser{}
// NewCodeBlockParser returns a new BlockParser that
// parses code blocks.
func NewCodeBlockParser() BlockParser {
return defaultCodeBlockParser
}
func (b *codeBlockParser) Trigger() []byte {
return nil
}
func (b *codeBlockParser) Open(parent ast.Node, reader text.Reader, pc Context) (ast.Node, State) {
line, segment := reader.PeekLine()
pos, padding := util.IndentPosition(line, reader.LineOffset(), 4)
if pos < 0 || util.IsBlank(line) {
return nil, NoChildren
}
node := ast.NewCodeBlock()
reader.AdvanceAndSetPadding(pos, padding)
_, segment = reader.PeekLine()
node.Lines().Append(segment)
reader.Advance(segment.Len() - 1)
return node, NoChildren
}
func (b *codeBlockParser) Continue(node ast.Node, reader text.Reader, pc Context) State {
line, segment := reader.PeekLine()
if util.IsBlank(line) {
node.Lines().Append(segment.TrimLeftSpaceWidth(4, reader.Source()))
return Continue | NoChildren
}
pos, padding := util.IndentPosition(line, reader.LineOffset(), 4)
if pos < 0 {
return Close
}
reader.AdvanceAndSetPadding(pos, padding)
_, segment = reader.PeekLine()
node.Lines().Append(segment)
reader.Advance(segment.Len() - 1)
return Continue | NoChildren
}
func (b *codeBlockParser) Close(node ast.Node, reader text.Reader, pc Context) {
// trim trailing blank lines
lines := node.Lines()
length := lines.Len() - 1
source := reader.Source()
for length >= 0 {
line := lines.At(length)
if util.IsBlank(line.Value(source)) {
length--
} else {
break
}
}
lines.SetSliced(0, length+1)
}
func (b *codeBlockParser) CanInterruptParagraph() bool {
return false
}
func (b *codeBlockParser) CanAcceptIndentedLine() bool {
return true
}
| {'content_hash': 'ed6eb916c0d2c0c525cf19af5e8fbe3d', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 99, 'avg_line_length': 25.139240506329113, 'alnum_prop': 0.7220543806646526, 'repo_name': 'sapk-fork/gitea', 'id': 'd02c21fc7133903011e024d416def05c6792adcb', 'size': '1986', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/yuin/goldmark/parser/code_block.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '156527'}, {'name': 'Dockerfile', 'bytes': '1253'}, {'name': 'Go', 'bytes': '4805825'}, {'name': 'JavaScript', 'bytes': '122408'}, {'name': 'Makefile', 'bytes': '25655'}, {'name': 'Perl', 'bytes': '36597'}, {'name': 'Roff', 'bytes': '164'}, {'name': 'Shell', 'bytes': '357092'}, {'name': 'TSQL', 'bytes': '117'}, {'name': 'Vue', 'bytes': '3220'}]} |
package org.normandra.data;
import org.normandra.EntitySession;
import org.normandra.NormandraException;
import org.normandra.association.ElementIdentity;
import org.normandra.association.LazyLoadedCollection;
import org.normandra.meta.EntityMeta;
import org.normandra.association.LazyEntityList;
import org.normandra.association.LazyEntitySet;
import org.normandra.util.ArraySet;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* a one-to-many or many-to-many collection accessor
* <p>
* <p>
* Date: 3/20/14
*/
public class ManyJoinColumnAccessor extends FieldColumnAccessor implements ColumnAccessor
{
private final ElementIdentity factory;
private final EntityMeta entity;
private final boolean lazy;
public ManyJoinColumnAccessor(final Field field, final EntityMeta meta, final boolean lazy, final ElementIdentity factory)
{
super(field);
this.factory = factory;
this.entity = meta;
this.lazy = lazy;
}
public EntityMeta getEntity()
{
return entity;
}
public boolean isLazy()
{
return lazy;
}
@Override
public boolean isLoaded(final Object entity) throws NormandraException
{
if (null == entity)
{
return false;
}
try
{
final Object value = this.get(entity);
if (null == value)
{
return false;
}
if (!(value instanceof Collection))
{
return false;
}
if (value instanceof LazyLoadedCollection)
{
return ((LazyLoadedCollection) value).isLoaded();
}
else
{
return true;
}
}
catch (final Exception e)
{
throw new NormandraException("Unable to determine if many-join accessor is loaded.", e);
}
}
protected final Collection<?> getCollection(final Object entity) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException
{
final Object obj = this.get(entity);
if (null == obj)
{
return Collections.emptyList();
}
if (obj instanceof Collection)
{
return (Collection) obj;
}
else
{
return Collections.emptyList();
}
}
@Override
public boolean isEmpty(final Object entity) throws NormandraException
{
try
{
return this.getCollection(entity).isEmpty();
}
catch (final Exception e)
{
throw new NormandraException("Unable to query join-column collection.", e);
}
}
@Override
public Collection getValue(final Object entity, EntitySession session) throws NormandraException
{
try
{
final Collection elements = this.getCollection(entity);
if (null == elements)
{
return Collections.emptyList();
}
if (elements instanceof LazyLoadedCollection)
{
return ((LazyLoadedCollection) elements).duplicate();
}
if (elements.isEmpty())
{
return Collections.emptyList();
}
final List keys = this.factory.fromEntities(session, this.getCollection(entity).toArray());
if (Set.class.isAssignableFrom(this.getField().getType()))
{
return Collections.unmodifiableSet(new ArraySet(keys));
}
else
{
return Collections.unmodifiableList(keys);
}
}
catch (final Exception e)
{
throw new NormandraException("Unable to get join-column collection.", e);
}
}
@Override
public boolean setValue(final Object entity, final DataHolder data, final EntitySession session) throws NormandraException
{
if (this.lazy)
{
try
{
// setup lazy loaded collection
if (Set.class.isAssignableFrom(this.getField().getType()))
{
return this.set(entity, new LazyEntitySet(session, this.entity, data, this.factory));
}
else
{
return this.set(entity, new LazyEntityList(session, this.entity, data, this.factory));
}
}
catch (final Exception e)
{
throw new NormandraException("Unable to set lazy join-column collection from data holder [" + data + "].", e);
}
}
else
{
// get data now, load entities
final Object value = data.get();
if (!(value instanceof Collection))
{
throw new NormandraException("Expect collection of primary key values for [" + this.getField() + "] but found [" + value + "].");
}
try
{
final Collection keys = (Collection) value;
if (keys.isEmpty())
{
this.set(entity, new ArraySet());
}
else
{
final List<Object> associations = session.get(this.entity, keys.toArray());
if (null == associations || associations.isEmpty())
{
this.set(entity, new ArraySet());
}
else
{
this.set(entity, new ArraySet<>(associations));
}
}
return true;
}
catch (final Exception e)
{
throw new NormandraException("Unable to set join-column collection from value [" + value + "].", e);
}
}
}
}
| {'content_hash': '75b72b938945a6a4a5ab46f29f09cacc', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 148, 'avg_line_length': 29.603864734299517, 'alnum_prop': 0.5349216710182768, 'repo_name': 'trajar/normandra', 'id': 'd8aed6ac9cc47f5df72fa7060df12cfe2fdef322', 'size': '16953', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/normandra/data/ManyJoinColumnAccessor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1457853'}]} |
<!--
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<mat-button-toggle-group
id="button-group"
class="button-group"
[disabled]="(isSubmissionSelected$ | async) || (disabled$ | async)"
[(value)]="selectedValue"
>
<mat-button-toggle
*ngIf="!(jobs$ | async).isEmpty()"
id="add-point-button"
class="add-point-button"
value="{{ pointValue }}"
(click)="onButtonClick()"
>
<img id="add-point-icon" class="add-point-icon" [src]="addPointIcon" />
</mat-button-toggle>
<mat-button-toggle
hidden
value="{{ polygonValue }}"
(click)="onButtonClick()"
>
add polygon
</mat-button-toggle>
</mat-button-toggle-group>
<div
*ngIf="selectedValue"
id="job-selector-section"
class="job-selector-section"
>
<mat-form-field appearance="fill">
<mat-label id="job-selector-label"
>Adding {{ selectedValue }} for</mat-label
>
<mat-select
id="job-selector"
[(value)]="selectedJobId"
(selectionChange)="onJobIdChange()"
>
<mat-option
*ngFor="let job of jobs$ | async"
id="job-selector-item-{{ job.id }}"
[value]="job.id"
>
<img [src]="jobPinUrl(job)" /> {{ job?.name }}
</mat-option>
</mat-select>
</mat-form-field>
<button id="cancel-button" mat-button (click)="onCancel()">Cancel</button>
</div>
| {'content_hash': 'b0131adf06b4fdeb7f259ba607382f0a', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 76, 'avg_line_length': 28.784615384615385, 'alnum_prop': 0.6477819347942276, 'repo_name': 'google/ground-platform', 'id': '4aa44572ab4700fdf21f03393ac7f02347771402', 'size': '1871', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/src/app/components/drawing-tools/drawing-tools.component.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '5378'}, {'name': 'HTML', 'bytes': '47013'}, {'name': 'JavaScript', 'bytes': '5840'}, {'name': 'SCSS', 'bytes': '26429'}, {'name': 'Shell', 'bytes': '2415'}, {'name': 'TypeScript', 'bytes': '413142'}]} |
export type ClassType = Function | (new (...args: any[]) => any);
export type KeyType = ClassType | Symbol | string;
export type RegKeyType = KeyType | undefined;
export type GetReturnType<T, ClsType> = T extends undefined
? ClsType extends { prototype: infer R }
? R
: any
: T;
| {'content_hash': '1952efef32b0482e014a7bc3950a1f5c', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 65, 'avg_line_length': 36.375, 'alnum_prop': 0.6735395189003437, 'repo_name': 'zhang740/power-di', 'id': '93f4fbeea8659edbf79c22c214fb2eff2e5711bd', 'size': '291', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/utils/types.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '900'}, {'name': 'TypeScript', 'bytes': '97627'}]} |
package pro.chukai.web.quartz.job;
import pro.chukai.web.mapper.AppLogMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pro.chukai.web.mapper.AppLogMapper;
public abstract class AbstractCronJob {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
protected AppLogMapper appLogMapper;
}
| {'content_hash': '44cceeacf95dee3054f0b7a57d2f14bc', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 71, 'avg_line_length': 31.76923076923077, 'alnum_prop': 0.8062953995157385, 'repo_name': 'wenchukai/wenchukai.com', 'id': '9c6456c05e0a543d6c032b8ffd93019b182d26c5', 'size': '413', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'service/webapp/src/main/java/pro/chukai/web/quartz/job/AbstractCronJob.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '19473'}, {'name': 'FreeMarker', 'bytes': '58345'}, {'name': 'Java', 'bytes': '165727'}, {'name': 'JavaScript', 'bytes': '373658'}]} |
package linprog.helper;
import com.joptimizer.optimizers.LPOptimizationRequest;
import com.joptimizer.optimizers.LPPrimalDualMethod;
public abstract class OptimizationStarter {
public static double[] runLinProg(OptimizationProblem problem) {
LPOptimizationRequest or = new LPOptimizationRequest();
or.setC(problem.lambda);
or.setG(problem.g);
or.setH(problem.h);
or.setA(problem.a_eq);
or.setB(problem.b_eq);
or.setLb(problem.x_lb);
or.setUb(problem.x_ub);
LPPrimalDualMethod opt = new LPPrimalDualMethod();
opt.setLPOptimizationRequest(or);
try {
opt.optimize();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(" --- done. ---");
double[] sol = opt.getLPOptimizationResponse().getSolution();
return sol;
}
}
//==== Check Matrix and Vector Sizes: ====
//System.out.println("Size of Matrices:");
//System.out.println("c: " + or.getC().size());
//System.out.println("G: " + or.getG().rows() + " x " + or.getG().columns());
//System.out.println("h: " + or.getH().size());
//System.out.println("A: " + or.getA().rows() + " x " + or.getA().columns());
//System.out.println("b: " + or.getB().size());
//System.out.println("lb: " + or.getLb().size());
//System.out.println("ub: " + or.getUb().size());
| {'content_hash': '69028e94832081af2739f4db4a54bd5b', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 79, 'avg_line_length': 28.21276595744681, 'alnum_prop': 0.6523378582202112, 'repo_name': 'SES-fortiss/SmartGridCoSimulation', 'id': 'a27f6dbfade76a54bed52cdac42856ebe301a764', 'size': '1326', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'examples/memap/src/main/java/linprog/helper/OptimizationStarter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '494'}, {'name': 'C++', 'bytes': '68972'}, {'name': 'CSS', 'bytes': '10495'}, {'name': 'HTML', 'bytes': '27854'}, {'name': 'Java', 'bytes': '23777284'}, {'name': 'JavaScript', 'bytes': '144441'}, {'name': 'Processing', 'bytes': '16761'}, {'name': 'Shell', 'bytes': '1069'}, {'name': 'Solidity', 'bytes': '18269'}]} |
package foam.lib.query;
import foam.lib.parse.PStream;
import foam.lib.parse.Parser;
import foam.lib.parse.ParserContext;
public class ValueParser
implements Parser {
@Override
public PStream parse(PStream ps, ParserContext x) {
StringBuilder s = new StringBuilder();
while ( ps.valid() ) {
char c = ps.head();
if ( c == ' ' ) break;
ps = ps.tail();
s.append(c);
}
return ps.setValue(new foam.mlang.Constant(s.toString()));
}
}
| {'content_hash': '1361baa3d8a9c1b8aad75c62531fee38', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 62, 'avg_line_length': 21.818181818181817, 'alnum_prop': 0.6416666666666667, 'repo_name': 'foam-framework/foam2', 'id': 'd733fa109febe5b8364e5933f4df9d9aee15448a', 'size': '480', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/foam/lib/query/ValueParser.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '20356'}, {'name': 'HTML', 'bytes': '10220505'}, {'name': 'Java', 'bytes': '977816'}, {'name': 'JavaScript', 'bytes': '7065731'}, {'name': 'Makefile', 'bytes': '7676'}, {'name': 'Shell', 'bytes': '5963'}, {'name': 'Swift', 'bytes': '19039'}]} |
package com.fionapet.business.facade;
import org.dubbo.x.facade.CURDRestService;
import org.dubbo.x.facade.RestResult;
import org.dubbo.x.util.ConstantVariable;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.fionapet.business.entity.MedicPrescription;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* 医生处方明细 接口
*
* Created by tom on 2016-07-18 11:56:08.
*/
@Path("medicprescriptions")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8})
@Api(value="medicprescriptions", description = "医生处方明细接口")
public interface MedicPrescriptionRestService extends CURDRestService<MedicPrescription>{
/**
* 医生处方明细
* @return
*/
@GET
@Path("")
@ApiOperation(value = "医生处方明细",
notes = "医生处方明细列表.")
RestResult<List<MedicPrescription>> list(@HeaderParam(ConstantVariable.HEADER_AUTHORIZATION_KEY) String token);
/**
* 医生处方明细 详细信息
*
* @return
*/
@GET
@Path("/{id}")
@ApiOperation(value = "详细信息",
notes = "医生处方明细详细信息.")
RestResult<MedicPrescription> detail(@HeaderParam(ConstantVariable.HEADER_AUTHORIZATION_KEY) String token, @ApiParam("id") @PathParam("id") String uuid);
@POST
@Path("")
@ApiOperation(value = "添加/修改医生处方明细", notes = "添加/修改医生处方明细")
RestResult<MedicPrescription> create(@HeaderParam(ConstantVariable.HEADER_AUTHORIZATION_KEY) String token,MedicPrescription medicPrescription);
@DELETE
@Path("/{id}")
@ApiOperation(value = "删除医生处方明细", notes = "删除医生处方明细")
RestResult<String> delete(@HeaderParam(ConstantVariable.HEADER_AUTHORIZATION_KEY) String token, @ApiParam("id") @PathParam("id") String uuid);
}
| {'content_hash': '6312f49ce06f72c32bb1ce8c3019fcb4', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 157, 'avg_line_length': 32.54385964912281, 'alnum_prop': 0.7159029649595687, 'repo_name': 'bqw5189/pet-hospital', 'id': 'cc61fb5d86a1c274794dacc21dd4b82cebd4bd60', 'size': '2047', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fionapet-business/fionapet-business-api/src/main/java/com/fionapet/business/facade/MedicPrescriptionRestService.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '279655'}, {'name': 'HTML', 'bytes': '15747'}, {'name': 'Java', 'bytes': '1482358'}, {'name': 'JavaScript', 'bytes': '6887556'}]} |
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| {'content_hash': 'afb372ec9f7d21af51948a5e51177c33', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 39, 'avg_line_length': 25.75, 'alnum_prop': 0.6601941747572816, 'repo_name': 'gsrushton/bft', 'id': '9fd4f02e3dec86abf092e6289a824cf947c0ce77', 'size': '171', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'engine/ui/src/windowingTest/cpp/Main.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '74584'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thumbnail Navigator Skin 11 - Jssor Slider, Carousel, Slideshow with Javascript Source Code</title>
</head>
<body style="font-family:Arial, Verdana;background-color:#fff;">
<!-- use jssor.slider.min.js instead for release -->
<!-- jssor.slider.min.js = (jssor.js + jssor.slider.js) -->
<script type="text/javascript" src="../js/jssor.js"></script>
<script type="text/javascript" src="../js/jssor.slider.js"></script>
<script>
jssor_slider1_starter = function (containerId) {
var options = {
$AutoPlay: false, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
$SlideDuration: 500, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500
$ThumbnailNavigatorOptions: {
$Class: $JssorThumbnailNavigator$, //[Required] Class to create thumbnail navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$ActionMode: 1, //[Optional] 0 None, 1 act by click, 2 act by mouse hover, 3 both, default value is 1
$AutoCenter: 3, //[Optional] Auto center thumbnail items in the thumbnail navigator container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 3
$Lanes: 1, //[Optional] Specify lanes to arrange thumbnails, default value is 1
$SpacingX: 3, //[Optional] Horizontal space between each thumbnail in pixel, default value is 0
$SpacingY: 3, //[Optional] Vertical space between each thumbnail in pixel, default value is 0
$DisplayPieces: 9, //[Optional] Number of pieces to display, default value is 1
$ParkingPosition: 250, //[Optional] The offset position to park thumbnail
$Orientation: 1, //[Optional] Orientation to arrange thumbnails, 1 horizental, 2 vertical, default value is 1
$DisableDrag: false //[Optional] Disable drag or not, default value is false
}
};
var jssor_slider1 = new $JssorSlider$(containerId, options);
};
</script>
<!-- Jssor Slider Begin -->
<!-- You can move inline styles to css file or css block. -->
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px;
height: 300px;">
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 600px; height: 300px; overflow: hidden;">
<div>
<img u="image" src="../img/photography/002.jpg" />
<img u="thumb" src="../img/photography/thumb-002.jpg" />
</div>
<div>
<img u="image" src="../img/photography/003.jpg" />
<img u="thumb" src="../img/photography/thumb-003.jpg" />
</div>
<div>
<img u="image" src="../img/photography/004.jpg" />
<img u="thumb" src="../img/photography/thumb-004.jpg" />
</div>
<div>
<img u="image" src="../img/photography/005.jpg" />
<img u="thumb" src="../img/photography/thumb-005.jpg" />
</div>
<div>
<img u="image" src="../img/photography/006.jpg" />
<img u="thumb" src="../img/photography/thumb-006.jpg" />
</div>
<div>
<img u="image" src="../img/photography/007.jpg" />
<img u="thumb" src="../img/photography/thumb-007.jpg" />
</div>
<div>
<img u="image" src="../img/photography/008.jpg" />
<img u="thumb" src="../img/photography/thumb-008.jpg" />
</div>
<div>
<img u="image" src="../img/photography/009.jpg" />
<img u="thumb" src="../img/photography/thumb-009.jpg" />
</div>
<div>
<img u="image" src="../img/photography/010.jpg" />
<img u="thumb" src="../img/photography/thumb-010.jpg" />
</div>
<div>
<img u="image" src="../img/photography/011.jpg" />
<img u="thumb" src="../img/photography/thumb-011.jpg" />
</div>
</div>
<!-- ThumbnailNavigator Skin Begin -->
<div u="thumbnavigator" class="jssort11" style="cursor: default; position: absolute; width: 600px; height: 60px; left:0px; bottom: 0px;">
<div style=" background-color: #000; filter:alpha(opacity=30); opacity:.3; width: 100%; height:100%;"></div>
<!-- Thumbnail Item Skin Begin -->
<style>
/* jssor slider thumbnail Navigator Skin 11 css */
/*
.jssort11 .p (normal)
.jssort11 .p:hover (normal mouseover)
.jssort11 .pav (active)
.jssort11 .pav:hover (active mouseover)
.jssort11 .pdn (mousedown)
*/
.jssort11 .p .t {
FILTER: alpha(opacity=45);
opacity: .45;
transition: opacity .6s;
-moz-transition: opacity .6s;
-webkit-transition: opacity .6s;
-o-transition: opacity .6s;
}
.jssort11 .pav .t, .jssort11 .pav:hover .t, .jssort11 .p:hover .t {
FILTER: alpha(opacity=100);
opacity: 1;
transition: none;
-moz-transition: none;
-webkit-transition: none;
-o-transition: none;
}
</style>
<div u="slides" style="cursor: move;">
<div u="prototype" class=p style="POSITION: absolute; WIDTH: 60px; HEIGHT: 30px; TOP: 0; LEFT: 0;">
<div u="thumbnailtemplate" class=t style=" WIDTH: 60px; HEIGHT: 30px; border: none;position:absolute; TOP: 0; LEFT: 0;"></div>
</div>
</div>
<!-- Thumbnail Item Skin End -->
</div>
<!-- ThumbnailNavigator Skin End -->
<a style="display: none" href="http://www.jssor.com">bootstrap slider</a>
<!-- Trigger -->
<script>
jssor_slider1_starter('slider1_container');
</script>
</div>
<!-- Jssor Slider End -->
</body>
</html> | {'content_hash': '94df7877cf63fb6e90b61abef18f9246', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 207, 'avg_line_length': 53.294117647058826, 'alnum_prop': 0.48206401766004414, 'repo_name': 'cArLiiToX/dtstore', 'id': '115c85a5afca5b8c8866dc40dcb843a67122aee7', 'size': '7250', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jssor/skin/thumbnail-11.source.html', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ActionScript', 'bytes': '19946'}, {'name': 'ApacheConf', 'bytes': '6723'}, {'name': 'CSS', 'bytes': '6407515'}, {'name': 'Erlang', 'bytes': '1088'}, {'name': 'Groovy', 'bytes': '10320'}, {'name': 'HTML', 'bytes': '7365239'}, {'name': 'JavaScript', 'bytes': '2660599'}, {'name': 'PHP', 'bytes': '53440797'}, {'name': 'Perl', 'bytes': '83695'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Prolog', 'bytes': '2246'}, {'name': 'R', 'bytes': '1102'}, {'name': 'Ruby', 'bytes': '894'}, {'name': 'Shell', 'bytes': '65776'}, {'name': 'XML', 'bytes': '16526909'}, {'name': 'XSLT', 'bytes': '2135'}]} |
#ifndef LPC43XX_UART_H
#define LPC43XX_UART_H
#include <libopencm3/cm3/common.h>
#include <libopencm3/lpc43xx/memorymap.h>
/* --- Convenience macros -------------------------------------------------- */
/* UART port base addresses (for convenience) */
#define UART0 USART0_BASE /* APB0 */
#define UART1 UART1_BASE /* APB0 */
#define UART2 USART2_BASE /* APB2 */
#define UART3 USART3_BASE /* APB2 */
/* --- UART registers ------------------------------------------------------- */
/* Receiver Buffer Register (DLAB=0) Read Only */
#define UART_RBR(port) MMIO32(port + 0x000) /* 8bits */
/* Transmitter Holding Register (DLAB=0) Write Only */
#define UART_THR(port) MMIO32(port + 0x000) /* 8bits */
/* Divisor Latch LSB Register (DLAB=1) */
#define UART_DLL(port) MMIO32(port + 0x000) /* 8bits */
/* Divisor Latch MSB Register (DLAB=1) */
#define UART_DLM(port) MMIO32(port + 0x004) /* 8bits */
/* Interrupt Enable Register (DLAB=0) */
#define UART_IER(port) MMIO32(port + 0x004)
/* Interrupt ID Register Read Only */
#define UART_IIR(port) MMIO32(port + 0x008)
/* FIFO Control Register Write Only */
#define UART_FCR(port) MMIO32(port + 0x008)
/* Line Control Register */
#define UART_LCR(port) MMIO32(port + 0x00C)
/* MCR only for UART1 */
/* Line Status Register */
#define UART_LSR(port) MMIO32(port + 0x014)
/* Auto Baud Control Register */
#define UART_ACR(port) MMIO32(port + 0x020)
/* IrDA Control Register only for UART0/2/3 */
#define UART_ICR(port) MMIO32(port + 0x024)
/* Fractional Divider Register */
#define UART_FDR(port) MMIO32(port + 0x028)
/* Oversampling Register only for UART0/2/3 */
#define UART_OSR(port) MMIO32(port + 0x02C)
/* Half-Duplex enable Register only for UART0/2/3 */
#define UART_HDEN(port) MMIO32(port + 0x040)
/* Smart card Interface Register Only for UART0/2/3 */
#define UART_SCICTRL(port) MMIO32(port + 0x048)
/* RS-485/EIA-485 Control Register */
#define UART_RS485CTRL(port) MMIO32(port + 0x04C)
/* RS-485/EIA-485 Address Match Register */
#define UART_RS485ADRMATCH(port) MMIO32(port + 0x050)
/* RS-485/EIA-485 Direction Control Delay Register */
#define UART_RS485DLY(port) MMIO32(port + 0x054)
/* Synchronous Mode Control Register only for UART0/2/3 */
#define UART_SYNCCTRL(port) MMIO32(port + 0x058)
/* Transmit Enable Register */
#define UART_TER(port) MMIO32(port + 0x05C)
/* --------------------- BIT DEFINITIONS ----------------------------------- */
/***********************************************************************
* Macro defines for Macro defines for UARTn Receiver Buffer Register
**********************************************************************/
/* UART Received Buffer mask bit (8 bits) */
#define UART_RBR_MASKBIT ((uint8_t)0xFF)
/***********************************************************************
* Macro defines for Macro defines for UARTn Transmit Holding Register
**********************************************************************/
/* UART Transmit Holding mask bit (8 bits) */
#define UART_THR_MASKBIT ((uint8_t)0xFF)
/***********************************************************************
* Macro defines for Macro defines for UARTn Divisor Latch LSB register
**********************************************************************/
/* Macro for loading least significant halfs of divisors */
#define UART_LOAD_DLL(div) ((div) & 0xFF)
/* Divisor latch LSB bit mask */
#define UART_DLL_MASKBIT ((uint8_t)0xFF)
/***********************************************************************
* Macro defines for Macro defines for UARTn Divisor Latch MSB register
**********************************************************************/
/* Divisor latch MSB bit mask */
#define UART_DLM_MASKBIT ((uint8_t)0xFF)
/* Macro for loading most significant halfs of divisors */
#define UART_LOAD_DLM(div) (((div) >> 8) & 0xFF)
/***********************************************************************
* Macro defines for Macro defines for UART interrupt enable register
**********************************************************************/
/* RBR Interrupt enable*/
#define UART_IER_RBRINT_EN (1 << 0)
/* THR Interrupt enable*/
#define UART_IER_THREINT_EN (1 << 1)
/* RX line status interrupt enable*/
#define UART_IER_RLSINT_EN (1 << 2)
/* Modem status interrupt enable */
#define UART1_IER_MSINT_EN (1 << 3)
/* CTS1 signal transition interrupt enable */
#define UART1_IER_CTSINT_EN (1 << 7)
/* Enables the end of auto-baud interrupt */
#define UART_IER_ABEOINT_EN (1 << 8)
/* Enables the auto-baud time-out interrupt */
#define UART_IER_ABTOINT_EN (1 << 9)
/* UART interrupt enable register bit mask */
#define UART_IER_BITMASK ((uint32_t)(0x307))
/* UART1 interrupt enable register bit mask */
#define UART1_IER_BITMASK ((uint32_t)(0x38F))
/**********************************************************************
* Macro defines for Macro defines for UART interrupt identification register
**********************************************************************/
/* Interrupt Status - Active low */
#define UART_IIR_INTSTAT_PEND (1 << 0)
/* Interrupt identification: Modem interrupt*/
#define UART1_IIR_INTID_MODEM (0 << 1)
/* Interrupt identification: THRE interrupt*/
#define UART_IIR_INTID_THRE (1 << 1)
/* Interrupt identification: Receive data available*/
#define UART_IIR_INTID_RDA (2 << 1)
/* Interrupt identification: Receive line status*/
#define UART_IIR_INTID_RLS (3 << 1)
/* Interrupt identification: Character time-out indicator*/
#define UART_IIR_INTID_CTI (6 << 1)
/* Interrupt identification: Interrupt ID mask */
#define UART_IIR_INTID_MASK (7 << 1)
/* These bits are equivalent to UnFCR[0] */
#define UART_IIR_FIFO_EN (3 << 6)
/* End of auto-baud interrupt */
#define UART_IIR_ABEO_INT (1 << 8)
/* Auto-baud time-out interrupt */
#define UART_IIR_ABTO_INT (1 << 9)
/* UART interrupt identification register bit mask */
#define UART_IIR_BITMASK ((uint32_t)(0x3CF))
/**********************************************************************
* Macro defines for Macro defines for UART FIFO control register
**********************************************************************/
/* UART FIFO enable */
#define UART_FCR_FIFO_EN (1 << 0)
/* UART FIFO RX reset */
#define UART_FCR_RX_RS (1 << 1)
/* UART FIFO TX reset */
#define UART_FCR_TX_RS (1 << 2)
/* UART DMA mode selection */
#define UART_FCR_DMAMODE_SEL (1 << 3)
/* UART FIFO trigger level 0: 1 character */
#define UART_FCR_TRG_LEV0 (0 << 6)
/* UART FIFO trigger level 1: 4 character */
#define UART_FCR_TRG_LEV1 (1 << 6)
/* UART FIFO trigger level 2: 8 character */
#define UART_FCR_TRG_LEV2 (2 << 6)
/* UART FIFO trigger level 3: 14 character */
#define UART_FCR_TRG_LEV3 (3 << 6)
/* UART FIFO control bit mask */
#define UART_FCR_BITMASK ((uint8_t)(0xCF))
#define UART_TX_FIFO_SIZE (16)
/**********************************************************************
* Macro defines for Macro defines for UART line control register
**********************************************************************/
/* UART 5 bit data mode */
#define UART_LCR_WLEN5 (0 << 0)
/* UART 6 bit data mode */
#define UART_LCR_WLEN6 (1 << 0)
/* UART 7 bit data mode */
#define UART_LCR_WLEN7 (2 << 0)
/* UART 8 bit data mode */
#define UART_LCR_WLEN8 (3 << 0)
/* UART One Stop Bits */
#define UART_LCR_ONE_STOPBIT (0 << 2)
/* UART Two Stop Bits */
#define UART_LCR_TWO_STOPBIT (1 << 2)
/* UART Parity Disabled / No Parity */
#define UART_LCR_NO_PARITY (0 << 3)
/* UART Parity Enable */
#define UART_LCR_PARITY_EN (1 << 3)
/* UART Odd Parity Select */
#define UART_LCR_PARITY_ODD (0 << 4)
/* UART Even Parity Select */
#define UART_LCR_PARITY_EVEN (1 << 4)
/* UART force 1 stick parity */
#define UART_LCR_PARITY_SP_1 (1 << 5)
/* UART force 0 stick parity */
#define UART_LCR_PARITY_SP_0 ((1 << 5) | (1 << 4))
/* UART Transmission Break enable */
#define UART_LCR_BREAK_EN (1 << 6)
/* UART Divisor Latches Access bit enable */
#define UART_LCR_DLAB_EN (1 << 7)
/* UART line control bit mask */
#define UART_LCR_BITMASK ((uint8_t)(0xFF))
/**********************************************************************
* Macro defines for Macro defines for UART line status register
**********************************************************************/
/* Line status register: Receive data ready */
#define UART_LSR_RDR (1 << 0)
/* Line status register: Overrun error */
#define UART_LSR_OE (1 << 1)
/* Line status register: Parity error */
#define UART_LSR_PE (1 << 2)
/* Line status register: Framing error */
#define UART_LSR_FE (1 << 3)
/* Line status register: Break interrupt */
#define UART_LSR_BI (1 << 4)
/* Line status register: Transmit holding register empty */
#define UART_LSR_THRE (1 << 5)
/* Line status register: Transmitter empty */
#define UART_LSR_TEMT (1 << 6)
/* Error in RX FIFO */
#define UART_LSR_RXFE (1 << 7)
/* UART Line status bit mask */
#define UART_LSR_BITMASK ((uint8_t)(0xFF))
#define UART_LSR_ERROR_MASK \
(UART_LSR_OE | UART_LSR_PE | UART_LSR_FE | UART_LSR_BI | UART_LSR_RXFE)
/**********************************************************************
* Macro defines for Macro defines for UART Scratch Pad Register
**********************************************************************/
/* UART Scratch Pad bit mask */
#define UART_SCR_BIMASK ((uint8_t)(0xFF))
/***********************************************************************
* Macro defines for Macro defines for UART Auto baudrate control register
**********************************************************************/
/* UART Auto-baud start */
#define UART_ACR_START (1 << 0)
/* UART Auto baudrate Mode 1 */
#define UART_ACR_MODE (1 << 1)
/* UART Auto baudrate restart */
#define UART_ACR_AUTO_RESTART (1 << 2)
/* UART End of auto-baud interrupt clear */
#define UART_ACR_ABEOINT_CLR (1 << 8)
/* UART Auto-baud time-out interrupt clear */
#define UART_ACR_ABTOINT_CLR (1 << 9)
/* UART Auto Baudrate register bit mask */
#define UART_ACR_BITMASK ((uint32_t)(0x307))
/*********************************************************************
* Macro defines for Macro defines for UART IrDA control register
**********************************************************************/
/* IrDA mode enable */
#define UART_ICR_IRDAEN (1 << 0)
/* IrDA serial input inverted */
#define UART_ICR_IRDAINV (1 << 1)
/* IrDA fixed pulse width mode */
#define UART_ICR_FIXPULSE_EN (1 << 2)
/* PulseDiv - Configures the pulse when FixPulseEn = 1 */
#define UART_ICR_PULSEDIV(n) ((uint32_t)((n&0x07)<<3))
/* UART IRDA bit mask */
#define UART_ICR_BITMASK ((uint32_t)(0x3F))
/**********************************************************************
* Macro defines for Macro defines for UART half duplex register
**********************************************************************/
/* enable half-duplex mode*/
#define UART_HDEN_HDEN (1 << 0)
/**********************************************************************
* Macro defines for Macro defines for UART smart card interface control register
**********************************************************************/
/* enable asynchronous half-duplex smart card interface*/
#define UART_SCICTRL_SCIEN (1 << 0)
/* NACK response is inhibited*/
#define UART_SCICTRL_NACKDIS (1 << 1)
/* ISO7816-3 protocol T1 is selected*/
#define UART_SCICTRL_PROTSEL_T1 (1 << 2)
/* number of retransmission*/
#define UART_SCICTRL_TXRETRY(n) ((uint32_t)((n&0x07)<<5))
/* Extra guard time*/
#define UART_SCICTRL_GUARDTIME(n) ((uint32_t)((n&0xFF)<<8))
/*********************************************************************
* Macro defines for Macro defines for UART synchronous control register
**********************************************************************/
/* enable synchronous mode*/
#define UART_SYNCCTRL_SYNC (1 << 0)
/* synchronous master mode*/
#define UART_SYNCCTRL_CSRC_MASTER (1 << 1)
/* sample on falling edge*/
#define UART_SYNCCTRL_FES (1 << 2)
/* to be defined*/
#define UART_SYNCCTRL_TSBYPASS (1 << 3)
/* continuous running clock enable (master mode only) */
#define UART_SYNCCTRL_CSCEN (1 << 4)
/* Do not send start/stop bit */
#define UART_SYNCCTRL_NOSTARTSTOP (1 << 5)
/* stop continuous clock */
#define UART_SYNCCTRL_CCCLR (1 << 6)
/*********************************************************************
* Macro defines for Macro defines for UART Fractional divider register
**********************************************************************/
/* Baud-rate generation pre-scaler divisor */
#define UART_FDR_DIVADDVAL(n) ((uint32_t)(n&0x0F))
/* Baud-rate pre-scaler multiplier value */
#define UART_FDR_MULVAL(n) ((uint32_t)((n<<4)&0xF0))
/* UART Fractional Divider register bit mask */
#define UART_FDR_BITMASK ((uint32_t)(0xFF))
/*********************************************************************
* Macro defines for Macro defines for UART Tx Enable register
**********************************************************************/
#define UART_TER_TXEN (1 << 0) /* Transmit enable bit */
/**********************************************************************
* Macro defines for Macro defines for UART FIFO Level register
**********************************************************************/
/* Reflects the current level of the UART receiver FIFO */
#define UART_FIFOLVL_RX(n) ((uint32_t)(n&0x0F))
/* Reflects the current level of the UART transmitter FIFO */
#define UART_FIFOLVL_TX(n) ((uint32_t)((n>>8)&0x0F))
/* UART FIFO Level Register bit mask */
#define UART_FIFOLVL_BITMASK ((uint32_t)(0x0F0F))
/*********************************************************************
* UART enum
**********************************************************************/
/*
* UART Databit type definitions
*/
typedef enum {
UART_DATABIT_5 = UART_LCR_WLEN5,/* UART 5 bit data mode */
UART_DATABIT_6 = UART_LCR_WLEN6,/* UART 6 bit data mode */
UART_DATABIT_7 = UART_LCR_WLEN7,/* UART 7 bit data mode */
UART_DATABIT_8 = UART_LCR_WLEN8/* UART 8 bit data mode */
} uart_databit_t;
/*
* UART Stop bit type definitions
*/
typedef enum {
/* UART 1 Stop Bits Select */
UART_STOPBIT_1 = UART_LCR_ONE_STOPBIT,
/* UART 2 Stop Bits Select */
UART_STOPBIT_2 = UART_LCR_TWO_STOPBIT
} uart_stopbit_t;
/*
* UART Parity type definitions
*/
typedef enum {
/* No parity */
UART_PARITY_NONE = UART_LCR_NO_PARITY,
/* Odd parity */
UART_PARITY_ODD = (UART_LCR_PARITY_ODD | UART_LCR_PARITY_EN),
/* Even parity */
UART_PARITY_EVEN = (UART_LCR_PARITY_EVEN | UART_LCR_PARITY_EN),
/* Forced 1 stick parity */
UART_PARITY_SP_1 = (UART_LCR_PARITY_SP_1 | UART_LCR_PARITY_EN),
/* Forced 0 stick parity */
UART_PARITY_SP_0 = (UART_LCR_PARITY_SP_0 | UART_LCR_PARITY_EN)
} uart_parity_t;
typedef enum {
UART0_NUM = UART0,
UART1_NUM = UART1,
UART2_NUM = UART2,
UART3_NUM = UART3
} uart_num_t;
typedef enum {
UART_NO_ERROR = 0,
UART_TIMEOUT_ERROR = 1
} uart_error_t;
typedef enum {
UART_RX_NO_DATA = 0,
UART_RX_DATA_READY = 1,
UART_RX_DATA_ERROR = 2
} uart_rx_data_ready_t;
/* function prototypes */
BEGIN_DECLS
/* Init UART and set PLL1 as clock source (PCLK) */
void uart_init(uart_num_t uart_num, uart_databit_t data_nb_bits,
uart_stopbit_t data_nb_stop, uart_parity_t data_parity,
uint16_t uart_divisor, uint8_t uart_divaddval, uint8_t uart_mulval);
uart_rx_data_ready_t uart_rx_data_ready(uart_num_t uart_num);
uint8_t uart_read(uart_num_t uart_num);
uint8_t uart_read_timeout(uart_num_t uart_num, uint32_t rx_timeout_nb_cycles,
uart_error_t *error);
void uart_write(uart_num_t uart_num, uint8_t data);
END_DECLS
#endif
| {'content_hash': '3992f4c2ec22dfe68097a35d353350a3', 'timestamp': '', 'source': 'github', 'line_count': 421, 'max_line_length': 80, 'avg_line_length': 40.6104513064133, 'alnum_prop': 0.5099140200035094, 'repo_name': 'grodansparadis/stm32f103c8-board', 'id': '28830e3578cec7f8fd6ca7254a861d44a5ebd1c3', 'size': '17867', 'binary': False, 'copies': '32', 'ref': 'refs/heads/master', 'path': 'code/freertos_stm32f103rb6/libopencm3/lpc43xx/uart.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '9178'}, {'name': 'C', 'bytes': '5685581'}, {'name': 'C++', 'bytes': '253275'}, {'name': 'Eagle', 'bytes': '1856107'}, {'name': 'Makefile', 'bytes': '3833'}, {'name': 'Objective-C', 'bytes': '9922'}, {'name': 'Prolog', 'bytes': '910'}]} |
package com.intellij.codeInsight.editorActions;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.LanguageParserDefinitions;
import com.intellij.lang.ParserDefinition;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
public class SelectionQuotingTypedHandler extends TypedHandlerDelegate {
private static final ExtensionPointName<UnquotingFilter> EP_NAME = ExtensionPointName.create("com.intellij.selectionUnquotingFilter");
@NotNull
@Override
public Result beforeSelectionRemoved(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
SelectionModel selectionModel = editor.getSelectionModel();
if (CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE && selectionModel.hasSelection() && isDelimiter(c)) {
String selectedText = selectionModel.getSelectedText();
if (selectedText != null && selectedText.length() == 1) {
char selectedChar = selectedText.charAt(0);
if (isSimilarDelimiters(selectedChar, c) &&
selectedChar != c &&
!shouldSkipReplacementOfQuotesOrBraces(file, editor, selectedText, c) &&
replaceQuotesBySelected(c, editor, file, selectionModel, selectedChar)) {
return Result.STOP;
}
}
}
if (CodeInsightSettings.getInstance().SURROUND_SELECTION_ON_QUOTE_TYPED && selectionModel.hasSelection() && isDelimiter(c)) {
String selectedText = selectionModel.getSelectedText();
if (!StringUtil.isEmpty(selectedText)) {
final int selectionStart = selectionModel.getSelectionStart();
final int selectionEnd = selectionModel.getSelectionEnd();
if (isReplaceInComparisonOperation(file, selectionStart, selectedText, c)) {
return super.beforeSelectionRemoved(c, project, editor, file);
}
if (selectedText.length() > 1) {
final char firstChar = selectedText.charAt(0);
final char lastChar = selectedText.charAt(selectedText.length() - 1);
if (isSimilarDelimiters(firstChar, c) && lastChar == getMatchingDelimiter(firstChar) &&
(isQuote(firstChar) || firstChar != c) && !shouldSkipReplacementOfQuotesOrBraces(file, editor, selectedText, c) &&
!containsQuoteInside(selectedText, lastChar)) {
selectedText = selectedText.substring(1, selectedText.length() - 1);
}
}
final int caretOffset = selectionModel.getSelectionStart();
final char c2 = getMatchingDelimiter(c);
final String newText = c + selectedText + c2;
boolean ltrSelection = selectionModel.getLeadSelectionOffset() != selectionModel.getSelectionEnd();
boolean restoreStickySelection = editor instanceof EditorEx && ((EditorEx)editor).isStickySelection();
selectionModel.removeSelection();
editor.getDocument().replaceString(selectionStart, selectionEnd, newText);
int startOffset = caretOffset + 1;
int endOffset = caretOffset + newText.length() - 1;
int length = editor.getDocument().getTextLength();
// selection is removed here
if (endOffset <= length) {
if (restoreStickySelection) {
EditorEx editorEx = (EditorEx)editor;
CaretModel caretModel = editorEx.getCaretModel();
caretModel.moveToOffset(ltrSelection ? startOffset : endOffset);
editorEx.setStickySelection(true);
caretModel.moveToOffset(ltrSelection ? endOffset : startOffset);
}
else {
if (ltrSelection || editor instanceof EditorWindow) {
editor.getSelectionModel().setSelection(startOffset, endOffset);
}
else {
editor.getSelectionModel().setSelection(endOffset, startOffset);
}
editor.getCaretModel().moveToOffset(ltrSelection ? endOffset : startOffset);
}
if (c == '{') {
int startOffsetToReformat = startOffset - 1;
int endOffsetToReformat = length > endOffset ? endOffset + 1 : endOffset;
CodeStyleManager.getInstance(project).reformatText(file, startOffsetToReformat, endOffsetToReformat);
}
}
return Result.STOP;
}
}
return super.beforeSelectionRemoved(c, project, editor, file);
}
private static boolean isReplaceInComparisonOperation(@NotNull PsiFile file, int offset, @NotNull String selectedText, char c) {
if ((c == '<' || c == '>') && selectedText.length() <= 3 && isOnlyComparisons(selectedText)) {
PsiElement elementAtOffset = file.findElementAt(offset);
if (elementAtOffset != null) {
IElementType tokenType = elementAtOffset.getNode().getElementType();
ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(elementAtOffset.getLanguage());
if (parserDefinition != null &&
(parserDefinition.getCommentTokens().contains(tokenType) ||
parserDefinition.getStringLiteralElements().contains(tokenType))) {
return false;
}
}
return true;
}
return false;
}
private static boolean isOnlyComparisons(@NotNull String text) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c != '>' && c != '<' && c != '=' && c != '!') {
return false;
}
}
return true;
}
private static boolean containsQuoteInside(String selectedText, char quote) {
return selectedText.indexOf(quote, 1) != selectedText.length() - 1;
}
private static boolean replaceQuotesBySelected(char c,
@NotNull Editor editor,
@NotNull PsiFile file,
@NotNull SelectionModel selectionModel,
char selectedChar) {
int selectionStart = selectionModel.getSelectionStart();
PsiElement element = file.findElementAt(selectionStart);
while (element != null) {
TextRange textRange = element.getTextRange();
if (textRange != null && textRange.getLength() >= 2) {
boolean isAtStart = textRange.getStartOffset() == selectionStart;
if (isAtStart || textRange.getEndOffset() == selectionStart + 1 && isQuote(c)) {
int matchingCharOffset = isAtStart ? textRange.getEndOffset() - 1 : textRange.getStartOffset();
Document document = editor.getDocument();
CharSequence charsSequence = document.getCharsSequence();
if (matchingCharOffset < charsSequence.length()) {
char matchingChar = charsSequence.charAt(matchingCharOffset);
boolean otherQuoteMatchesSelected =
isAtStart ? matchingChar == getMatchingDelimiter(selectedChar) : selectedChar == getMatchingDelimiter(matchingChar);
if (otherQuoteMatchesSelected &&
!containsQuoteInside(document.getText(textRange), charsSequence.charAt(textRange.getEndOffset() - 1))) {
replaceChar(document, textRange.getStartOffset(), c);
char c2 = getMatchingDelimiter(c);
replaceChar(document, textRange.getEndOffset() - 1, c2);
editor.getCaretModel().moveToOffset(selectionModel.getSelectionEnd());
selectionModel.removeSelection();
return true;
}
}
}
}
if (element instanceof PsiFile) break;
element = element.getParent();
}
return false;
}
public static boolean shouldSkipReplacementOfQuotesOrBraces(PsiFile psiFile, Editor editor, String selectedText, char c) {
return EP_NAME.getExtensionList().stream().anyMatch(filter -> filter.skipReplacementQuotesOrBraces(psiFile, editor, selectedText, c));
}
private static char getMatchingDelimiter(char c) {
if (c == '(') return ')';
if (c == '[') return ']';
if (c == '{') return '}';
if (c == '<') return '>';
return c;
}
private static boolean isDelimiter(final char c) {
return isBracket(c) || isQuote(c);
}
private static boolean isBracket(final char c) {
return c == '(' || c == '{' || c == '[' || c == '<';
}
private static boolean isQuote(final char c) {
return c == '"' || c == '\'' || c == '`';
}
private static boolean isSimilarDelimiters(final char c1, final char c2) {
return (isBracket(c1) && isBracket(c2)) || (isQuote(c1) && isQuote(c2));
}
private static void replaceChar(Document document, int offset, char newChar) {
document.replaceString(offset, offset + 1, String.valueOf(newChar));
}
public static abstract class UnquotingFilter {
public abstract boolean skipReplacementQuotesOrBraces(@NotNull PsiFile file,
@NotNull Editor editor,
@NotNull String selectedText,
char c);
}
}
| {'content_hash': '0a5cff28e5f8beb01dd95140bfeb8c3a', 'timestamp': '', 'source': 'github', 'line_count': 208, 'max_line_length': 138, 'avg_line_length': 46.4375, 'alnum_prop': 0.6502743555233461, 'repo_name': 'ingokegel/intellij-community', 'id': 'c4fcd2748226daf3ad541c90567423adac991112', 'size': '9780', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectionQuotingTypedHandler.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911
// .1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//
package org.ecloudmanager.tmrk.cloudapi.model;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Java class for SshKeyReferencesResourceType complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="SshKeyReferencesResourceType">
* <complexContent>
* <extension base="{}ResourceType">
* <sequence>
* <element name="SshKey" type="{}SshKeyReferenceType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SshKeyReferencesResourceType", propOrder = {
"sshKey"
})
@XmlSeeAlso({
SshKeyReferenceListType.class
})
public class SshKeyReferencesResourceType
extends ResourceType {
@XmlElement(name = "SshKey", nillable = true)
protected List<SshKeyReferenceType> sshKey;
/**
* Gets the value of the sshKey property.
* <p/>
* <p/>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the sshKey property.
* <p/>
* <p/>
* For example, to add a new item, do as follows:
* <pre>
* getSshKey().add(newItem);
* </pre>
* <p/>
* <p/>
* <p/>
* Objects of the following type(s) are allowed in the list
* {@link SshKeyReferenceType }
*/
public List<SshKeyReferenceType> getSshKey() {
if (sshKey == null) {
sshKey = new ArrayList<SshKeyReferenceType>();
}
return this.sshKey;
}
}
| {'content_hash': '004127177bf1a6b71d3dbb5a5a377945', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 116, 'avg_line_length': 29.72972972972973, 'alnum_prop': 0.6522727272727272, 'repo_name': 'rextrebat/ecloudmanager', 'id': '07b6ebb471b42acc8a40929aca39fb0c968b49ae', 'size': '2200', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/SshKeyReferencesResourceType.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '116224'}, {'name': 'HTML', 'bytes': '298374'}, {'name': 'Java', 'bytes': '3360862'}, {'name': 'JavaScript', 'bytes': '3673705'}, {'name': 'SystemVerilog', 'bytes': '855'}]} |
Phar front controller with weird SCRIPT_NAME
--SKIPIF--
<?php if (!extension_loaded("phar")) die("skip"); ?>
--ENV--
SCRIPT_NAME=/huh?
REQUEST_URI=/huh?
--FILE_EXTERNAL--
files/frontcontroller8.phar
--EXPECTF--
oops did not run
%a | {'content_hash': '08fec6b042e4bd9d7964f420ee7d8f38', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 52, 'avg_line_length': 20.90909090909091, 'alnum_prop': 0.7043478260869566, 'repo_name': 'lunaczp/learning', 'id': 'de6960c244482fc9933e864a13d18d5f450107c9', 'size': '239', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'language/c/testPhpSrc/php-5.6.17/ext/phar/tests/frontcontroller30.phpt', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '4526'}, {'name': 'Assembly', 'bytes': '14500403'}, {'name': 'Awk', 'bytes': '21252'}, {'name': 'Batchfile', 'bytes': '2526'}, {'name': 'C', 'bytes': '381839655'}, {'name': 'C++', 'bytes': '10162228'}, {'name': 'CMake', 'bytes': '68196'}, {'name': 'CSS', 'bytes': '3943'}, {'name': 'D', 'bytes': '1022'}, {'name': 'DTrace', 'bytes': '4528'}, {'name': 'Fortran', 'bytes': '1834'}, {'name': 'GAP', 'bytes': '4344'}, {'name': 'GDB', 'bytes': '31864'}, {'name': 'Gnuplot', 'bytes': '148'}, {'name': 'Go', 'bytes': '732'}, {'name': 'HTML', 'bytes': '86756'}, {'name': 'Java', 'bytes': '8286'}, {'name': 'JavaScript', 'bytes': '238365'}, {'name': 'Lex', 'bytes': '121233'}, {'name': 'Limbo', 'bytes': '1609'}, {'name': 'Lua', 'bytes': '96'}, {'name': 'M4', 'bytes': '483288'}, {'name': 'Makefile', 'bytes': '1915601'}, {'name': 'Nix', 'bytes': '180099'}, {'name': 'Objective-C', 'bytes': '1742504'}, {'name': 'OpenEdge ABL', 'bytes': '4238'}, {'name': 'PHP', 'bytes': '27984629'}, {'name': 'Pascal', 'bytes': '74868'}, {'name': 'Perl', 'bytes': '317465'}, {'name': 'Perl 6', 'bytes': '6916'}, {'name': 'Python', 'bytes': '21547'}, {'name': 'R', 'bytes': '1112'}, {'name': 'Roff', 'bytes': '435717'}, {'name': 'Scilab', 'bytes': '22980'}, {'name': 'Shell', 'bytes': '468206'}, {'name': 'UnrealScript', 'bytes': '20840'}, {'name': 'Vue', 'bytes': '563'}, {'name': 'XSLT', 'bytes': '7946'}, {'name': 'Yacc', 'bytes': '172805'}, {'name': 'sed', 'bytes': '2073'}]} |
"""
Display output of a given script.
Display output of any executable script set by `script_path`. Only the first
two lines of output will be used. The first line is used as the displayed
text. If the output has two or more lines, the second line is set as the text
color (and should hence be a valid hex color code such as #FF0000 for red).
The script should not have any parameters, but it could work.
Configuration parameters:
button_show_notification: button to show notification with full output
(default None)
cache_timeout: how often we refresh this module in seconds
(default 15)
convert_numbers: convert decimal numbers to a numeric type
(default True)
format: see placeholders below (default '{output}')
localize: should script output be localized (if available)
(default True)
script_path: script you want to show output of (compulsory)
(default None)
strip_output: shall we strip leading and trailing spaces from output
(default False)
Format placeholders:
{lines} number of lines in the output
{output} output of script given by "script_path"
Examples:
```
external_script {
format = "my name is {output}"
script_path = "/usr/bin/whoami"
}
```
@author frimdo [email protected]
SAMPLE OUTPUT
{'full_text': 'script output'}
example
{'full_text': 'It is now: Wed Feb 22 22:24:13'}
"""
import re
STRING_ERROR = "missing script_path"
class Py3status:
""" """
# available configuration parameters
button_show_notification = None
cache_timeout = 15
convert_numbers = True
format = "{output}"
localize = True
script_path = None
strip_output = False
def post_config_hook(self):
if not self.script_path:
raise Exception(STRING_ERROR)
def external_script(self):
output_lines = None
response = {}
response["cached_until"] = self.py3.time_in(self.cache_timeout)
try:
self.output = self.py3.command_output(
self.script_path, shell=True, localized=self.localize
)
output_lines = self.output.splitlines()
if len(output_lines) > 1:
output_color = output_lines[1]
if re.search(r"^#[0-9a-fA-F]{6}$", output_color):
response["color"] = output_color
except self.py3.CommandError as e:
# something went wrong show error to user
output = e.output or e.error
self.py3.error(output)
if output_lines:
output = output_lines[0]
if self.strip_output:
output = output.strip()
# If we get something that looks numeric then we convert it
# to a numeric type because this can be helpful. for example:
#
# external_script {
# format = "file is [\?if=output>10 big|small]"
# script_path = "cat /tmp/my_file | wc -l"
# }
if self.convert_numbers is True:
try:
output = int(output)
except ValueError:
try:
output = float(output)
except ValueError:
pass
else:
output = ""
response["full_text"] = self.py3.safe_format(
self.format, {"output": output, "lines": len(output_lines)}
)
return response
def on_click(self, event):
button = event["button"]
if button == self.button_show_notification:
self.py3.notify_user(self.output)
self.py3.prevent_refresh()
if __name__ == "__main__":
"""
Run module in test mode.
"""
from py3status.module_test import module_test
module_test(Py3status)
| {'content_hash': '81747cb44fa30d4a2ec0f4b105a5cb95', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 77, 'avg_line_length': 30.752, 'alnum_prop': 0.5931321540062435, 'repo_name': 'ultrabug/py3status', 'id': 'f103c95aca87f6316d13ceb0487a9a9b3b7dbff1', 'size': '3844', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'py3status/modules/external_script.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '6762'}, {'name': 'Makefile', 'bytes': '252'}, {'name': 'Python', 'bytes': '1157282'}, {'name': 'Shell', 'bytes': '643'}]} |
package org.apache.spark.sql
import java.io.File
import scala.collection.mutable
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.catalog.CatalogColumnStat
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSQLContext
import org.apache.spark.sql.test.SQLTestData.ArrayData
import org.apache.spark.sql.types._
import org.apache.spark.util.Utils
/**
* End-to-end suite testing statistics collection and use on both entire table and columns.
*/
class StatisticsCollectionSuite extends StatisticsCollectionTestBase with SharedSQLContext {
import testImplicits._
test("estimates the size of a limit 0 on outer join") {
withTempView("test") {
Seq(("one", 1), ("two", 2), ("three", 3), ("four", 4)).toDF("k", "v")
.createOrReplaceTempView("test")
val df1 = spark.table("test")
val df2 = spark.table("test").limit(0)
val df = df1.join(df2, Seq("k"), "left")
val sizes = df.queryExecution.analyzed.collect { case g: Join =>
g.stats.sizeInBytes
}
assert(sizes.size === 1, s"number of Join nodes is wrong:\n ${df.queryExecution}")
assert(sizes.head === BigInt(128),
s"expected exact size 96 for table 'test', got: ${sizes.head}")
}
}
test("analyzing views is not supported") {
def assertAnalyzeUnsupported(analyzeCommand: String): Unit = {
val err = intercept[AnalysisException] {
sql(analyzeCommand)
}
assert(err.message.contains("ANALYZE TABLE is not supported"))
}
val tableName = "tbl"
withTable(tableName) {
spark.range(10).write.saveAsTable(tableName)
val viewName = "view"
withView(viewName) {
sql(s"CREATE VIEW $viewName AS SELECT * FROM $tableName")
assertAnalyzeUnsupported(s"ANALYZE TABLE $viewName COMPUTE STATISTICS")
assertAnalyzeUnsupported(s"ANALYZE TABLE $viewName COMPUTE STATISTICS FOR COLUMNS id")
}
}
}
test("statistics collection of a table with zero column") {
val table_no_cols = "table_no_cols"
withTable(table_no_cols) {
val rddNoCols = sparkContext.parallelize(1 to 10).map(_ => Row.empty)
val dfNoCols = spark.createDataFrame(rddNoCols, StructType(Seq.empty))
dfNoCols.write.format("json").saveAsTable(table_no_cols)
sql(s"ANALYZE TABLE $table_no_cols COMPUTE STATISTICS")
checkTableStats(table_no_cols, hasSizeInBytes = true, expectedRowCounts = Some(10))
}
}
test("analyze empty table") {
val table = "emptyTable"
withTable(table) {
val df = Seq.empty[Int].toDF("key")
df.write.format("json").saveAsTable(table)
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS noscan")
val fetchedStats1 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = None)
assert(fetchedStats1.get.sizeInBytes == 0)
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS")
val fetchedStats2 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = Some(0))
assert(fetchedStats2.get.sizeInBytes == 0)
val expectedColStat =
"key" -> CatalogColumnStat(Some(0), None, None, Some(0),
Some(IntegerType.defaultSize), Some(IntegerType.defaultSize))
// There won't be histogram for empty column.
Seq("true", "false").foreach { histogramEnabled =>
withSQLConf(SQLConf.HISTOGRAM_ENABLED.key -> histogramEnabled) {
checkColStats(df, mutable.LinkedHashMap(expectedColStat))
}
}
}
}
test("analyze column command - unsupported types and invalid columns") {
val tableName = "column_stats_test1"
withTable(tableName) {
Seq(ArrayData(Seq(1, 2, 3), Seq(Seq(1, 2, 3)))).toDF().write.saveAsTable(tableName)
// Test unsupported data types
val err1 = intercept[AnalysisException] {
sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS data")
}
assert(err1.message.contains("does not support statistics collection"))
// Test invalid columns
val err2 = intercept[AnalysisException] {
sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS some_random_column")
}
assert(err2.message.contains("does not exist"))
}
}
test("test table-level statistics for data source table") {
val tableName = "tbl"
withTable(tableName) {
sql(s"CREATE TABLE $tableName(i INT, j STRING) USING parquet")
Seq(1 -> "a", 2 -> "b").toDF("i", "j").write.mode("overwrite").insertInto(tableName)
// noscan won't count the number of rows
sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS noscan")
checkTableStats(tableName, hasSizeInBytes = true, expectedRowCounts = None)
// without noscan, we count the number of rows
sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS")
checkTableStats(tableName, hasSizeInBytes = true, expectedRowCounts = Some(2))
}
}
test("SPARK-15392: DataFrame created from RDD should not be broadcasted") {
val rdd = sparkContext.range(1, 100).map(i => Row(i, i))
val df = spark.createDataFrame(rdd, new StructType().add("a", LongType).add("b", LongType))
assert(df.queryExecution.analyzed.stats.sizeInBytes >
spark.sessionState.conf.autoBroadcastJoinThreshold)
assert(df.selectExpr("a").queryExecution.analyzed.stats.sizeInBytes >
spark.sessionState.conf.autoBroadcastJoinThreshold)
}
test("column stats round trip serialization") {
// Make sure we serialize and then deserialize and we will get the result data
val df = data.toDF(stats.keys.toSeq :+ "carray" : _*)
Seq(stats, statsWithHgms).foreach { s =>
s.zip(df.schema).foreach { case ((k, v), field) =>
withClue(s"column $k with type ${field.dataType}") {
val roundtrip = CatalogColumnStat.fromMap("table_is_foo", field.name, v.toMap(k))
assert(roundtrip == Some(v))
}
}
}
}
test("analyze column command - result verification") {
// (data.head.productArity - 1) because the last column does not support stats collection.
assert(stats.size == data.head.productArity - 1)
val df = data.toDF(stats.keys.toSeq :+ "carray" : _*)
checkColStats(df, stats)
// test column stats with histograms
withSQLConf(SQLConf.HISTOGRAM_ENABLED.key -> "true", SQLConf.HISTOGRAM_NUM_BINS.key -> "2") {
checkColStats(df, statsWithHgms)
}
}
test("column stats collection for null columns") {
val dataTypes: Seq[(DataType, Int)] = Seq(
BooleanType, ByteType, ShortType, IntegerType, LongType,
DoubleType, FloatType, DecimalType.SYSTEM_DEFAULT,
StringType, BinaryType, DateType, TimestampType
).zipWithIndex
val df = sql("select " + dataTypes.map { case (tpe, idx) =>
s"cast(null as ${tpe.sql}) as col$idx"
}.mkString(", "))
val expectedColStats = dataTypes.map { case (tpe, idx) =>
(s"col$idx", CatalogColumnStat(Some(0), None, None, Some(1),
Some(tpe.defaultSize.toLong), Some(tpe.defaultSize.toLong)))
}
// There won't be histograms for null columns.
Seq("true", "false").foreach { histogramEnabled =>
withSQLConf(SQLConf.HISTOGRAM_ENABLED.key -> histogramEnabled) {
checkColStats(df, mutable.LinkedHashMap(expectedColStats: _*))
}
}
}
test("SPARK-25028: column stats collection for null partitioning columns") {
val table = "analyze_partition_with_null"
withTempDir { dir =>
withTable(table) {
sql(s"""
|CREATE TABLE $table (value string, name string)
|USING PARQUET
|PARTITIONED BY (name)
|LOCATION '${dir.toURI}'""".stripMargin)
val df = Seq(("a", null), ("b", null)).toDF("value", "name")
df.write.mode("overwrite").insertInto(table)
sql(s"ANALYZE TABLE $table PARTITION (name) COMPUTE STATISTICS")
val partitions = spark.sessionState.catalog.listPartitions(TableIdentifier(table))
assert(partitions.head.stats.get.rowCount.get == 2)
}
}
}
test("number format in statistics") {
val numbers = Seq(
BigInt(0) -> (("0.0 B", "0")),
BigInt(100) -> (("100.0 B", "100")),
BigInt(2047) -> (("2047.0 B", "2.05E+3")),
BigInt(2048) -> (("2.0 KiB", "2.05E+3")),
BigInt(3333333) -> (("3.2 MiB", "3.33E+6")),
BigInt(4444444444L) -> (("4.1 GiB", "4.44E+9")),
BigInt(5555555555555L) -> (("5.1 TiB", "5.56E+12")),
BigInt(6666666666666666L) -> (("5.9 PiB", "6.67E+15")),
BigInt(1L << 10 ) * (1L << 60) -> (("1024.0 EiB", "1.18E+21")),
BigInt(1L << 11) * (1L << 60) -> (("2.36E+21 B", "2.36E+21"))
)
numbers.foreach { case (input, (expectedSize, expectedRows)) =>
val stats = Statistics(sizeInBytes = input, rowCount = Some(input))
val expectedString = s"sizeInBytes=$expectedSize, rowCount=$expectedRows," +
s" hints=none"
assert(stats.simpleString == expectedString)
}
}
test("change stats after truncate command") {
val table = "change_stats_truncate_table"
withTable(table) {
spark.range(100).select($"id", $"id" % 5 as "value").write.saveAsTable(table)
// analyze to get initial stats
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS id, value")
val fetched1 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = Some(100))
assert(fetched1.get.sizeInBytes > 0)
assert(fetched1.get.colStats.size == 2)
// truncate table command
sql(s"TRUNCATE TABLE $table")
val fetched2 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = Some(0))
assert(fetched2.get.sizeInBytes == 0)
assert(fetched2.get.colStats.isEmpty)
}
}
test("change stats after set location command") {
val table = "change_stats_set_location_table"
val tableLoc = new File(spark.sessionState.catalog.defaultTablePath(TableIdentifier(table)))
Seq(false, true).foreach { autoUpdate =>
withSQLConf(SQLConf.AUTO_SIZE_UPDATE_ENABLED.key -> autoUpdate.toString) {
withTable(table) {
spark.range(100).select($"id", $"id" % 5 as "value").write.saveAsTable(table)
// analyze to get initial stats
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS id, value")
val fetched1 = checkTableStats(
table, hasSizeInBytes = true, expectedRowCounts = Some(100))
assert(fetched1.get.sizeInBytes > 0)
assert(fetched1.get.colStats.size == 2)
// set location command
val initLocation = spark.sessionState.catalog.getTableMetadata(TableIdentifier(table))
.storage.locationUri.get.toString
withTempDir { newLocation =>
sql(s"ALTER TABLE $table SET LOCATION '${newLocation.toURI.toString}'")
if (autoUpdate) {
val fetched2 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = None)
assert(fetched2.get.sizeInBytes == 0)
assert(fetched2.get.colStats.isEmpty)
// set back to the initial location
sql(s"ALTER TABLE $table SET LOCATION '$initLocation'")
val fetched3 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = None)
assert(fetched3.get.sizeInBytes == fetched1.get.sizeInBytes)
} else {
checkTableStats(table, hasSizeInBytes = false, expectedRowCounts = None)
// SPARK-19724: clean up the previous table location.
waitForTasksToFinish()
Utils.deleteRecursively(tableLoc)
}
}
}
}
}
}
test("change stats after insert command for datasource table") {
val table = "change_stats_insert_datasource_table"
Seq(false, true).foreach { autoUpdate =>
withSQLConf(SQLConf.AUTO_SIZE_UPDATE_ENABLED.key -> autoUpdate.toString) {
withTable(table) {
sql(s"CREATE TABLE $table (i int, j string) USING PARQUET")
// analyze to get initial stats
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS i, j")
val fetched1 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = Some(0))
assert(fetched1.get.sizeInBytes == 0)
assert(fetched1.get.colStats.size == 2)
// table lookup will make the table cached
spark.table(table)
assert(isTableInCatalogCache(table))
// insert into command
sql(s"INSERT INTO TABLE $table SELECT 1, 'abc'")
if (autoUpdate) {
val fetched2 = checkTableStats(table, hasSizeInBytes = true, expectedRowCounts = None)
assert(fetched2.get.sizeInBytes > 0)
assert(fetched2.get.colStats.isEmpty)
} else {
checkTableStats(table, hasSizeInBytes = false, expectedRowCounts = None)
}
// check that tableRelationCache inside the catalog was invalidated after insert
assert(!isTableInCatalogCache(table))
}
}
}
}
test("invalidation of tableRelationCache after inserts") {
val table = "invalidate_catalog_cache_table"
Seq(false, true).foreach { autoUpdate =>
withSQLConf(SQLConf.AUTO_SIZE_UPDATE_ENABLED.key -> autoUpdate.toString) {
withTable(table) {
spark.range(100).write.saveAsTable(table)
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS")
spark.table(table)
val initialSizeInBytes = getTableFromCatalogCache(table).stats.sizeInBytes
spark.range(100).write.mode(SaveMode.Append).saveAsTable(table)
spark.table(table)
assert(getTableFromCatalogCache(table).stats.sizeInBytes == 2 * initialSizeInBytes)
}
}
}
}
test("invalidation of tableRelationCache after table truncation") {
val table = "invalidate_catalog_cache_table"
Seq(false, true).foreach { autoUpdate =>
withSQLConf(SQLConf.AUTO_SIZE_UPDATE_ENABLED.key -> autoUpdate.toString) {
withTable(table) {
spark.range(100).write.saveAsTable(table)
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS")
spark.table(table)
sql(s"TRUNCATE TABLE $table")
spark.table(table)
assert(getTableFromCatalogCache(table).stats.sizeInBytes == 0)
}
}
}
}
test("invalidation of tableRelationCache after alter table add partition") {
val table = "invalidate_catalog_cache_table"
Seq(false, true).foreach { autoUpdate =>
withSQLConf(SQLConf.AUTO_SIZE_UPDATE_ENABLED.key -> autoUpdate.toString) {
withTempDir { dir =>
withTable(table) {
val path = dir.getCanonicalPath
sql(s"""
|CREATE TABLE $table (col1 int, col2 int)
|USING PARQUET
|PARTITIONED BY (col2)
|LOCATION '${dir.toURI}'""".stripMargin)
sql(s"ANALYZE TABLE $table COMPUTE STATISTICS")
spark.table(table)
assert(getTableFromCatalogCache(table).stats.sizeInBytes == 0)
spark.catalog.recoverPartitions(table)
val df = Seq((1, 2), (1, 2)).toDF("col2", "col1")
df.write.parquet(s"$path/col2=1")
sql(s"ALTER TABLE $table ADD PARTITION (col2=1) LOCATION '${dir.toURI}'")
spark.table(table)
val cachedTable = getTableFromCatalogCache(table)
val cachedTableSizeInBytes = cachedTable.stats.sizeInBytes
val defaultSizeInBytes = conf.defaultSizeInBytes
if (autoUpdate) {
assert(cachedTableSizeInBytes != defaultSizeInBytes && cachedTableSizeInBytes > 0)
} else {
assert(cachedTableSizeInBytes == defaultSizeInBytes)
}
}
}
}
}
}
test("Simple queries must be working, if CBO is turned on") {
withSQLConf(SQLConf.CBO_ENABLED.key -> "true") {
withTable("TBL1", "TBL") {
import org.apache.spark.sql.functions._
val df = spark.range(1000L).select('id,
'id * 2 as "FLD1",
'id * 12 as "FLD2",
lit("aaa") + 'id as "fld3")
df.write
.mode(SaveMode.Overwrite)
.bucketBy(10, "id", "FLD1", "FLD2")
.sortBy("id", "FLD1", "FLD2")
.saveAsTable("TBL")
sql("ANALYZE TABLE TBL COMPUTE STATISTICS ")
sql("ANALYZE TABLE TBL COMPUTE STATISTICS FOR COLUMNS ID, FLD1, FLD2, FLD3")
val df2 = spark.sql(
"""
|SELECT t1.id, t1.fld1, t1.fld2, t1.fld3
|FROM tbl t1
|JOIN tbl t2 on t1.id=t2.id
|WHERE t1.fld3 IN (-123.23,321.23)
""".stripMargin)
df2.createTempView("TBL2")
sql("SELECT * FROM tbl2 WHERE fld3 IN ('qqq', 'qwe') ").queryExecution.executedPlan
}
}
}
}
| {'content_hash': 'ae634d1a9571404209e897d01212abf2', 'timestamp': '', 'source': 'github', 'line_count': 416, 'max_line_length': 100, 'avg_line_length': 40.63221153846154, 'alnum_prop': 0.6361592616695261, 'repo_name': 'guoxiaolongzte/spark', 'id': '02dc32d5f90ba27beabd62a5a0cb89e18fda7e8d', 'size': '17703', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '35161'}, {'name': 'Batchfile', 'bytes': '30468'}, {'name': 'C', 'bytes': '1493'}, {'name': 'CSS', 'bytes': '26884'}, {'name': 'Dockerfile', 'bytes': '8760'}, {'name': 'HTML', 'bytes': '70229'}, {'name': 'HiveQL', 'bytes': '1823426'}, {'name': 'Java', 'bytes': '3446787'}, {'name': 'JavaScript', 'bytes': '196727'}, {'name': 'Makefile', 'bytes': '9397'}, {'name': 'PLpgSQL', 'bytes': '191716'}, {'name': 'PowerShell', 'bytes': '3856'}, {'name': 'Python', 'bytes': '2839950'}, {'name': 'R', 'bytes': '1151677'}, {'name': 'Roff', 'bytes': '15677'}, {'name': 'SQLPL', 'bytes': '3603'}, {'name': 'Scala', 'bytes': '27886942'}, {'name': 'Shell', 'bytes': '203384'}, {'name': 'Thrift', 'bytes': '33605'}, {'name': 'q', 'bytes': '146878'}]} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Lecanora lazarenkoi f. lazarenkoi
### Remarks
null | {'content_hash': '72433376f15a160aab8ac78baa6f49f8', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 33, 'avg_line_length': 10.615384615384615, 'alnum_prop': 0.717391304347826, 'repo_name': 'mdoering/backbone', 'id': '24b9b7a0518cd611910f53ba224d6e7a97b77b80', 'size': '192', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Lecanoraceae/Lecanora/Lecanora lazarenkoi/Lecanora lazarenkoi lazarenkoi/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
/* */
'use strict';
var $ = require('./$'),
safe = require('./$.uid').safe,
assert = require('./$.assert'),
forOf = require('./$.for-of'),
$has = $.has,
isObject = $.isObject,
hide = $.hide,
isExtensible = Object.isExtensible || isObject,
id = 0,
ID = safe('id'),
WEAK = safe('weak'),
LEAK = safe('leak'),
method = require('./$.array-methods'),
find = method(5),
findIndex = method(6);
function findFrozen(store, key) {
return find(store.array, function(it) {
return it[0] === key;
});
}
function leakStore(that) {
return that[LEAK] || hide(that, LEAK, {
array: [],
get: function(key) {
var entry = findFrozen(this, key);
if (entry)
return entry[1];
},
has: function(key) {
return !!findFrozen(this, key);
},
set: function(key, value) {
var entry = findFrozen(this, key);
if (entry)
entry[1] = value;
else
this.array.push([key, value]);
},
'delete': function(key) {
var index = findIndex(this.array, function(it) {
return it[0] === key;
});
if (~index)
this.array.splice(index, 1);
return !!~index;
}
})[LEAK];
}
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function(that, iterable) {
$.set(assert.inst(that, C, NAME), ID, id++);
if (iterable != undefined)
forOf(iterable, IS_MAP, that[ADDER], that);
});
require('./$.mix')(C.prototype, {
'delete': function(key) {
if (!isObject(key))
return false;
if (!isExtensible(key))
return leakStore(this)['delete'](key);
return $has(key, WEAK) && $has(key[WEAK], this[ID]) && delete key[WEAK][this[ID]];
},
has: function has(key) {
if (!isObject(key))
return false;
if (!isExtensible(key))
return leakStore(this).has(key);
return $has(key, WEAK) && $has(key[WEAK], this[ID]);
}
});
return C;
},
def: function(that, key, value) {
if (!isExtensible(assert.obj(key))) {
leakStore(that).set(key, value);
} else {
$has(key, WEAK) || hide(key, WEAK, {});
key[WEAK][that[ID]] = value;
}
return that;
},
leakStore: leakStore,
WEAK: WEAK,
ID: ID
};
| {'content_hash': 'd0831991f7ea247077386a94a1fac2e2', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 90, 'avg_line_length': 26.511363636363637, 'alnum_prop': 0.5297899699957137, 'repo_name': 'Mteuahasan/ror-microblog', 'id': 'be4cba15d29922789fef69835a1a68e8e669b33c', 'size': '2333', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'public/jspm_packages/npm/[email protected]/modules/$.collection-weak.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '146150'}, {'name': 'CoffeeScript', 'bytes': '211'}, {'name': 'HTML', 'bytes': '16468'}, {'name': 'JavaScript', 'bytes': '5788479'}, {'name': 'LiveScript', 'bytes': '13522'}, {'name': 'Makefile', 'bytes': '706'}, {'name': 'Ruby', 'bytes': '56963'}, {'name': 'Shell', 'bytes': '2713'}]} |
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class AAL_Admin_Ui {
/**
* @var AAL_Activity_Log_List_Table
*/
protected $_list_table = null;
protected $_screens = array();
public function create_admin_menu() {
$menu_capability = current_user_can( 'view_all_aryo_activity_log' ) ? 'view_all_aryo_activity_log' : 'edit_pages';
$this->_screens['main'] = add_menu_page( _x( 'Activity Log', 'Page and Menu Title', 'aryo-activity-log' ), _x( 'Activity Log', 'Page and Menu Title', 'aryo-activity-log' ), $menu_capability, 'activity_log_page', array( &$this, 'activity_log_page_func' ), '', '2.1' );
// Just make sure we are create instance.
add_action( 'load-' . $this->_screens['main'], array( &$this, 'get_list_table' ) );
}
public function activity_log_page_func() {
$this->get_list_table()->prepare_items();
?>
<div class="wrap">
<h1 class="aal-page-title"><?php _ex( 'Activity Log', 'Page and Menu Title', 'aryo-activity-log' ); ?></h1>
<form id="activity-filter" method="get">
<input type="hidden" name="page" value="<?php echo esc_attr( $_REQUEST['page'] ); ?>" />
<?php $this->get_list_table()->display(); ?>
</form>
</div>
<?php // TODO: move to a separate file. ?>
<style>
.aal-pt {
color: #ffffff;
padding: 1px 4px;
margin: 0 5px;
font-size: 1em;
border-radius: 3px;
background: #808080;
font-family: inherit;
}
.toplevel_page_activity_log_page .manage-column {
width: auto;
}
.toplevel_page_activity_log_page .column-description {
width: 20%;
}
#adminmenu #toplevel_page_activity_log_page div.wp-menu-image:before {
content: "\f321";
}
@media (max-width: 767px) {
.toplevel_page_activity_log_page .manage-column {
width: auto;
}
.toplevel_page_activity_log_page .column-date,
.toplevel_page_activity_log_page .column-author {
display: table-cell;
width: auto;
}
.toplevel_page_activity_log_page .column-ip,
.toplevel_page_activity_log_page .column-description,
.toplevel_page_activity_log_page .column-label {
display: none;
}
.toplevel_page_activity_log_page .column-author .avatar {
display: none;
}
}
</style>
<?php
}
public function admin_header() {
// TODO: move to a separate file.
?><style>
#adminmenu #toplevel_page_activity_log_page div.wp-menu-image:before {
content: "\f321";
}
</style>
<?php
}
public function ajax_aal_install_elementor_set_admin_notice_viewed() {
update_user_meta( get_current_user_id(), '_aal_elementor_install_notice', 'true' );
}
public function admin_notices() {
if ( ! current_user_can( 'install_plugins' ) || $this->_is_elementor_installed() )
return;
if ( 'true' === get_user_meta( get_current_user_id(), '_aal_elementor_install_notice', true ) )
return;
if ( ! in_array( get_current_screen()->id, array( 'toplevel_page_activity_log_page', 'dashboard', 'plugins', 'plugins-network' ) ) ) {
return;
}
add_action( 'admin_footer', array( &$this, 'print_js' ) );
$install_url = self_admin_url( 'plugin-install.php?tab=search&s=elementor' );
?>
<style>
.notice.aal-notice {
border-left-color: #9b0a46 !important;
padding: 20px;
}
.rtl .notice.aal-notice {
border-right-color: #9b0a46 !important;
}
.notice.aal-notice .aal-notice-inner {
display: table;
width: 100%;
}
.notice.aal-notice .aal-notice-inner .aal-notice-icon,
.notice.aal-notice .aal-notice-inner .aal-notice-content,
.notice.aal-notice .aal-notice-inner .aal-install-now {
display: table-cell;
vertical-align: middle;
}
.notice.aal-notice .aal-notice-icon {
color: #9b0a46;
font-size: 50px;
width: 50px;
}
.notice.aal-notice .aal-notice-content {
padding: 0 20px;
}
.notice.aal-notice p {
padding: 0;
margin: 0;
}
.notice.aal-notice h3 {
margin: 0 0 5px;
}
.notice.aal-notice .aal-install-now {
text-align: center;
}
.notice.aal-notice .aal-install-now .aal-install-button {
background-color: #9b0a46;
color: #fff;
border-color: #7c1337;
box-shadow: 0 1px 0 #7c1337;
padding: 5px 30px;
height: auto;
line-height: 20px;
text-transform: capitalize;
}
.notice.aal-notice .aal-install-now .aal-install-button i {
padding-right: 5px;
}
.rtl .notice.aal-notice .aal-install-now .aal-install-button i {
padding-right: 0;
padding-left: 5px;
}
.notice.aal-notice .aal-install-now .aal-install-button:hover {
background-color: #a0124a;
}
.notice.aal-notice .aal-install-now .aal-install-button:active {
box-shadow: inset 0 1px 0 #7c1337;
transform: translateY(1px);
}
@media (max-width: 767px) {
.notice.aal-notice {
padding: 10px;
}
.notice.aal-notice .aal-notice-inner {
display: block;
}
.notice.aal-notice .aal-notice-inner .aal-notice-content {
display: block;
padding: 0;
}
.notice.aal-notice .aal-notice-inner .aal-notice-icon,
.notice.aal-notice .aal-notice-inner .aal-install-now {
display: none;
}
}
</style>
<div class="notice updated is-dismissible aal-notice aal-install-elementor">
<div class="aal-notice-inner">
<div class="aal-notice-icon">
<img src="<?php echo plugins_url( 'assets/images/elementor-logo.png', ACTIVITY_LOG__FILE__ ); ?>" alt="Elementor Logo" />
</div>
<div class="aal-notice-content">
<h3><?php _e( 'Do You Like Activity Log? You\'ll Love Elementor!', 'aryo-activity-log' ); ?></h3>
<p><?php _e( 'Create high-end, pixel perfect websites at record speeds. Any theme, any page, any design. The most advanced frontend drag & drop page builder.', 'aryo-activity-log' ); ?>
<a href="https://go.elementor.com/learn/" target="_blank"><?php _e( 'Learn more about Elementor', 'aryo-activity-log' ); ?></a>.</p>
</div>
<div class="aal-install-now">
<a class="button aal-install-button" href="<?php echo $install_url; ?>"><i class="dashicons dashicons-download"></i><?php _e( 'Install Now For Free!', 'aryo-activity-log' ); ?></a>
</div>
</div>
</div>
<?php
}
public function print_js() {
?>
<script>jQuery( function( $ ) {
$( 'div.notice.aal-install-elementor' ).on( 'click', 'button.notice-dismiss', function( event ) {
event.preventDefault();
$.post( ajaxurl, {
action: 'aal_install_elementor_set_admin_notice_viewed'
} );
} );
} );</script>
<?php
}
public function __construct() {
add_action( 'admin_menu', array( &$this, 'create_admin_menu' ), 20 );
add_action( 'admin_head', array( &$this, 'admin_header' ) );
add_action( 'admin_notices', array( &$this, 'admin_notices' ) );
add_action( 'wp_ajax_aal_install_elementor_set_admin_notice_viewed', array( &$this, 'ajax_aal_install_elementor_set_admin_notice_viewed' ) );
}
private function _is_elementor_installed() {
$file_path = 'elementor/elementor.php';
$installed_plugins = get_plugins();
return isset( $installed_plugins[ $file_path ] );
}
/**
* @return AAL_Activity_Log_List_Table
*/
public function get_list_table() {
if ( is_null( $this->_list_table ) )
$this->_list_table = new AAL_Activity_Log_List_Table( array( 'screen' => $this->_screens['main'] ) );
return $this->_list_table;
}
}
| {'content_hash': 'de822045f6e09568a9f60dc79b171b27', 'timestamp': '', 'source': 'github', 'line_count': 240, 'max_line_length': 269, 'avg_line_length': 30.766666666666666, 'alnum_prop': 0.6248645720476707, 'repo_name': '20steps/alexa', 'id': '4463db28240666440a63a6928b971a05d360bba0', 'size': '7384', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/wp-content/plugins/aryo-activity-log/classes/class-aal-admin-ui.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4889348'}, {'name': 'CoffeeScript', 'bytes': '8023'}, {'name': 'Gherkin', 'bytes': '4336'}, {'name': 'HTML', 'bytes': '357026'}, {'name': 'JavaScript', 'bytes': '9076289'}, {'name': 'PHP', 'bytes': '33450039'}, {'name': 'Perl', 'bytes': '365'}, {'name': 'Ruby', 'bytes': '3054'}, {'name': 'Shell', 'bytes': '30158'}, {'name': 'TypeScript', 'bytes': '35051'}, {'name': 'VCL', 'bytes': '22958'}, {'name': 'XSLT', 'bytes': '5437'}]} |
'use strict';
var Platform = require('Platform');
var React = require('React');
var ReactNative = require('ReactNative');
var StyleSheet = require('StyleSheet');
var UIManager = require('UIManager');
var View = require('View');
var _portalRef: any;
// Unique identifiers for modals.
var lastUsedTag = 0;
/*
* Note: Only intended for Android at the moment. Just use Modal in your iOS
* code.
*
* A container that renders all the modals on top of everything else in the application.
*
* Portal makes it possible for application code to pass modal views all the way up to
* the root element created in `renderApplication`.
*
* Never use `<Portal>` in your code. There is only one Portal instance rendered
* by the top-level `renderApplication`.
*/
var Portal = React.createClass({
statics: {
/**
* Use this to create a new unique tag for your component that renders
* modals. A good place to allocate a tag is in `componentWillMount`
* of your component.
* See `showModal` and `closeModal`.
*/
allocateTag: function(): string {
return '__modal_' + (++lastUsedTag);
},
/**
* Render a new modal.
* @param tag A unique tag identifying the React component to render.
* This tag can be later used in `closeModal`.
* @param component A React component to be rendered.
*/
showModal: function(tag: string, component: any) {
if (!_portalRef) {
console.error('Calling showModal but no Portal has been rendered.');
return;
}
_portalRef._showModal(tag, component);
},
/**
* Remove a modal from the collection of modals to be rendered.
* @param tag A unique tag identifying the React component to remove.
* Must exactly match the tag previously passed to `showModal`.
*/
closeModal: function(tag: string) {
if (!_portalRef) {
console.error('Calling closeModal but no Portal has been rendered.');
return;
}
_portalRef._closeModal(tag);
},
/**
* Get an array of all the open modals, as identified by their tag string.
*/
getOpenModals: function(): Array<string> {
if (!_portalRef) {
console.error('Calling getOpenModals but no Portal has been rendered.');
return [];
}
return _portalRef._getOpenModals();
},
notifyAccessibilityService: function() {
if (!_portalRef) {
console.error('Calling closeModal but no Portal has been rendered.');
return;
}
_portalRef._notifyAccessibilityService();
},
},
getInitialState: function() {
return {modals: {}};
},
_showModal: function(tag: string, component: any) {
// We are about to open first modal, so Portal will appear.
// Let's disable accessibility for background view on Android.
if (this._getOpenModals().length === 0) {
this.props.onModalVisibilityChanged(true);
}
// This way state is chained through multiple calls to
// _showModal, _closeModal correctly.
this.setState((state) => {
var modals = state.modals;
modals[tag] = component;
return {modals};
});
},
_closeModal: function(tag: string) {
if (!this.state.modals.hasOwnProperty(tag)) {
return;
}
// We are about to close last modal, so Portal will disappear.
// Let's enable accessibility for application view on Android.
if (this._getOpenModals().length === 1) {
this.props.onModalVisibilityChanged(false);
}
// This way state is chained through multiple calls to
// _showModal, _closeModal correctly.
this.setState((state) => {
var modals = state.modals;
delete modals[tag];
return {modals};
});
},
_getOpenModals: function(): Array<string> {
return Object.keys(this.state.modals);
},
_notifyAccessibilityService: function() {
if (Platform.OS === 'android') {
// We need to send accessibility event in a new batch, as otherwise
// TextViews have no text set at the moment of populating event.
setTimeout(() => {
if (this._getOpenModals().length > 0) {
UIManager.sendAccessibilityEvent(
ReactNative.findNodeHandle(this),
UIManager.AccessibilityEventTypes.typeWindowStateChanged);
}
}, 0);
}
},
render: function() {
_portalRef = this;
if (!this.state.modals) {
return null;
}
var modals = [];
for (var tag in this.state.modals) {
modals.push(this.state.modals[tag]);
}
if (modals.length === 0) {
return null;
}
return (
<View
style={styles.modalsContainer}
importantForAccessibility="yes">
{modals}
</View>
);
}
});
var styles = StyleSheet.create({
modalsContainer: {
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
},
});
module.exports = Portal;
| {'content_hash': '5a92be168861391921726cbee8a2a5b8', 'timestamp': '', 'source': 'github', 'line_count': 174, 'max_line_length': 88, 'avg_line_length': 28.25287356321839, 'alnum_prop': 0.6255085435313262, 'repo_name': 'dubert/react-native', 'id': 'cfe278f15f6f23a62d66fe33b1552e2f6a4b26d9', 'size': '5262', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Libraries/Portal/Portal.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '15255'}, {'name': 'Awk', 'bytes': '121'}, {'name': 'Batchfile', 'bytes': '301'}, {'name': 'C', 'bytes': '65184'}, {'name': 'C++', 'bytes': '417371'}, {'name': 'CSS', 'bytes': '21505'}, {'name': 'HTML', 'bytes': '27404'}, {'name': 'IDL', 'bytes': '617'}, {'name': 'Java', 'bytes': '1720784'}, {'name': 'JavaScript', 'bytes': '1729776'}, {'name': 'Makefile', 'bytes': '4924'}, {'name': 'Objective-C', 'bytes': '1208460'}, {'name': 'Objective-C++', 'bytes': '8138'}, {'name': 'Prolog', 'bytes': '311'}, {'name': 'Python', 'bytes': '32195'}, {'name': 'Ruby', 'bytes': '4456'}, {'name': 'Shell', 'bytes': '23475'}]} |
using Org.Apache.REEF.Tang.Formats;
using Org.Apache.REEF.Tang.Util;
namespace Org.Apache.REEF.Tang.Tests.ScenarioTest
{
public class HttpHandlerConfiguration : ConfigurationModuleBuilder
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Not Applicable")]
public static readonly OptionalParameter<IHttpHandler> P = new OptionalParameter<IHttpHandler>();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Not Applicable")]
public static readonly ConfigurationModule CONF = new HttpHandlerConfiguration().Merge(HttpRuntimeConfiguration.CONF)
.BindSetEntry<HttpEventHandlers, IHttpHandler>(GenericType<HttpEventHandlers>.Class, HttpHandlerConfiguration.P)
.Build();
}
} | {'content_hash': '4cd6212ef45b53cc6797e7b5f92f12bd', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 165, 'avg_line_length': 50.72222222222222, 'alnum_prop': 0.7842278203723987, 'repo_name': 'yunseong/reef', 'id': 'b9fb14ffdd7d5568005114b2fc17130ec404e7c0', 'size': '1723', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'lang/cs/Org.Apache.REEF.Tang.Tests/ScenarioTest/HttpHandlerConfiguration.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2297'}, {'name': 'C', 'bytes': '2790'}, {'name': 'C#', 'bytes': '3555256'}, {'name': 'C++', 'bytes': '167088'}, {'name': 'CSS', 'bytes': '905'}, {'name': 'Java', 'bytes': '5250459'}, {'name': 'JavaScript', 'bytes': '4094'}, {'name': 'Objective-C', 'bytes': '965'}, {'name': 'PowerShell', 'bytes': '6426'}, {'name': 'Protocol Buffer', 'bytes': '35097'}, {'name': 'Python', 'bytes': '14622'}, {'name': 'Shell', 'bytes': '20728'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.