text
stringlengths
2
1.04M
meta
dict
module Spec module Runner class ExampleGroupRunner def initialize(options) @options = options end def load_files(files) # It's important that loading files (or choosing not to) stays the # responsibility of the ExampleGroupRunner. Some implementations (like) # the one using DRb may choose *not* to load files, but instead tell # someone else to do it over the wire. files.each do |file| load file end end def run prepare success = true example_groups.each do |example_group| success = success & example_group.run end return success ensure finish end protected def prepare reporter.start(number_of_examples) example_groups.reverse! if reverse end def finish reporter.end reporter.dump end def reporter @options.reporter end def reverse @options.reverse end def example_groups @options.example_groups end def number_of_examples @options.number_of_examples end end # TODO: BT - Deprecate BehaviourRunner? BehaviourRunner = ExampleGroupRunner end end
{ "content_hash": "fd2f200abd1e276f2011e4b70c437751", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 79, "avg_line_length": 21.74576271186441, "alnum_prop": 0.5923616523772408, "repo_name": "shanti/olio", "id": "47922400a9d1bc3291757f3a437783f24dc8abb2", "size": "2071", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "webapp/rails/trunk/vendor/plugins/rspec/lib/spec/runner/example_group_runner.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2669517" }, { "name": "JavaScript", "bytes": "1058343" }, { "name": "PHP", "bytes": "1001174" }, { "name": "Perl", "bytes": "252989" }, { "name": "Ruby", "bytes": "2400328" }, { "name": "Shell", "bytes": "57800" } ], "symlink_target": "" }
'use strict'; // Missing bits var q = Array() var t = new Object() // Array literal test var a = Array(); var ab = []; // Array constructions var b = new Array(); var bb = []; // Literals var c = Object(); var cb = []; // Number constructions var d = new Number(3) // JSON constructions var e = new JSON({}); // Leading decimals var g = .25; console.log(q,t,a,ab,b,bb,c,cb,d,e,g);
{ "content_hash": "37ccbbf7a3a6e85036282442d7a0f96b", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 38, "avg_line_length": 13.892857142857142, "alnum_prop": 0.6066838046272494, "repo_name": "goatslacker/atom-fixmyjs", "id": "d15ecfcc3ef8fb987b52fc693e39985e2b31e2b2", "size": "389", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1910" } ], "symlink_target": "" }
worker_processes Integer(ENV["UNICORN_WORKERS"] || ENV["WEB_CONCURRENCY"] || 3) timeout Integer(ENV["UNICORN_TIMEOUT"] || 25) preload_app true before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
{ "content_hash": "fc04ab59ac4425081d5df01bca4f5c2a", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 91, "avg_line_length": 26.916666666666668, "alnum_prop": 0.7337461300309598, "repo_name": "geminisbs/copycopter-server", "id": "0794a4ab5409cebe2a339d0392837388d6a7218d", "size": "666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/unicorn.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24160" }, { "name": "CoffeeScript", "bytes": "1761" }, { "name": "JavaScript", "bytes": "3781" }, { "name": "Ruby", "bytes": "86608" } ], "symlink_target": "" }
/** * This package contains implementations of the {@link com.gs.collections.api.collection.MutableCollection} interface. * <p> * This package contains the following implementations: * <ul> * <li> * {@link com.gs.collections.impl.collection.mutable.CollectionAdapter} - a MutableCollection interface wrapper around a {@link java.util.Collection} interface instance. * </li> * </ul> */ package com.gs.collections.impl.collection.mutable;
{ "content_hash": "36f10cbac1d062fbb1fb91d3d2c70d54", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 178, "avg_line_length": 36.07692307692308, "alnum_prop": 0.7142857142857143, "repo_name": "gabby2212/gs-collections", "id": "325b27c3e117351d9dca73f82be07ea6b050f311", "size": "1066", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "collections/src/main/java/com/gs/collections/impl/collection/mutable/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "11910874" }, { "name": "Scala", "bytes": "163387" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <автоматически создаваемое> // Этот код создан программой. // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </автоматически создаваемое> //------------------------------------------------------------------------------ namespace WebApplication1.Taskes { public partial class ATaskHard { /// <summary> /// form1 элемент управления. /// </summary> /// <remarks> /// Автоматически создаваемое поле. /// Для изменения переместите объявление поля из файла конструктора в файл кода программной части. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// MainPanel элемент управления. /// </summary> /// <remarks> /// Автоматически создаваемое поле. /// Для изменения переместите объявление поля из файла конструктора в файл кода программной части. /// </remarks> protected global::System.Web.UI.WebControls.Panel MainPanel; /// <summary> /// InputWord элемент управления. /// </summary> /// <remarks> /// Автоматически создаваемое поле. /// Для изменения переместите объявление поля из файла конструктора в файл кода программной части. /// </remarks> protected global::System.Web.UI.WebControls.TextBox InputWord; } }
{ "content_hash": "4ce047cd7259a416144fc93df848fe19", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 106, "avg_line_length": 37.214285714285715, "alnum_prop": 0.5515035188739603, "repo_name": "GKSG/AppASPSite", "id": "87720566e1dd620d675ed28be06c6733371b5d4c", "size": "2108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MainApp/EasyUKRaine/EasyUKRaine/kuchmynda/Taskes/Anagram/ATaskHard.aspx.designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "49641" }, { "name": "C#", "bytes": "259830" }, { "name": "CSS", "bytes": "6304" }, { "name": "HTML", "bytes": "5350" } ], "symlink_target": "" }
/** * Notification list. */ var list; /** * Expose `Notification`. */ exports.Notification = Notification; // list $(function(){ list = $('<ul id="notifications">'); list.appendTo('body'); }) /** * Return a new `Notification` with the given * (optional) `title` and `msg`. * * @param {String} title or msg * @param {String} msg * @return {Dialog} * @api public */ exports.notify = function(title, msg){ switch (arguments.length) { case 2: return new Notification({ title: title, message: msg }) .show() .hide(4000); case 1: return new Notification({ message: title }) .show() .hide(4000); } }; /** * Construct a notification function for `type`. * * @param {String} type * @return {Function} * @api private */ function type(type) { return function(title, msg){ return exports.notify.apply(this, arguments) .type(type); } } /** * Notification methods. */ exports.info = exports.notify; exports.warn = type('warn'); exports.error = type('error'); /** * Initialize a new `Notification`. * * Options: * * - `title` dialog title * - `message` a message to display * * @param {Object} options * @api public */ function Notification(options) { ui.Emitter.call(this); options = options || {}; this.template = html; this.el = $(this.template); this.render(options); if (Notification.effect) this.effect(Notification.effect); }; /** * Inherit from `Emitter.prototype`. */ Notification.prototype = new ui.Emitter; /** * Render with the given `options`. * * @param {Object} options * @api public */ Notification.prototype.render = function(options){ var el = this.el , title = options.title , msg = options.message , self = this; el.find('.close').click(function(){ self.hide(); return false; }); el.click(function(e){ e.preventDefault(); self.emit('click', e); }); el.find('h1').text(title); if (!title) el.find('h1').remove(); // message if ('string' == typeof msg) { el.find('p').text(msg); } else if (msg) { el.find('p').replaceWith(msg.el || msg); } setTimeout(function(){ el.removeClass('hide'); }, 0); }; /** * Enable the dialog close link. * * @return {Notification} for chaining * @api public */ Notification.prototype.closable = function(){ this.el.addClass('closable'); return this; }; /** * Set the effect to `type`. * * @param {String} type * @return {Notification} for chaining * @api public */ Notification.prototype.effect = function(type){ this._effect = type; this.el.addClass(type); return this; }; /** * Show the notification. * * @return {Notification} for chaining * @api public */ Notification.prototype.show = function(){ this.el.appendTo(list); return this; }; /** * Set the notification `type`. * * @param {String} type * @return {Notification} for chaining * @api public */ Notification.prototype.type = function(type){ this._type = type; this.el.addClass(type); return this; }; /** * Make it stick (clear hide timer), and make it closable. * * @return {Notification} for chaining * @api public */ Notification.prototype.sticky = function(){ return this.hide(0).closable(); }; /** * Hide the dialog with optional delay of `ms`, * otherwise the notification is removed immediately. * * @return {Number} ms * @return {Notification} for chaining * @api public */ Notification.prototype.hide = function(ms){ var self = this; // duration if ('number' == typeof ms) { clearTimeout(this.timer); if (!ms) return this; this.timer = setTimeout(function(){ self.hide(); }, ms); return this; } // hide / remove this.el.addClass('hide'); if (this._effect) { setTimeout(function(self){ self.remove(); }, 500, this); } else { self.remove(); } return this; }; /** * Hide the notification without potential animation. * * @return {Dialog} for chaining * @api public */ Notification.prototype.remove = function(){ this.el.remove(); return this; };
{ "content_hash": "f03cd2b07895ecb81f10374efb510b9d", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 61, "avg_line_length": 17.120833333333334, "alnum_prop": 0.6176685324896568, "repo_name": "mmakunas/uikit", "id": "5f007c53423eb97a8518746f2aca7973db9a2217", "size": "4109", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "lib/components/notification/notification.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!doctype html> <html> <title>npm-rebuild</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="../../static/style.css"> <link rel="canonical" href="https://www.npmjs.org/doc/api/npm-rebuild.html"> <script async=true src="../../static/toc.js"></script> <body> <div id="wrapper"> <h1><a href="../api/npm-rebuild.html">npm-rebuild</a></h1> <p>Rebuild a package</p> <h2 id="synopsis">SYNOPSIS</h2> <pre><code>npm.commands.rebuild([packages,] callback) </code></pre><h2 id="description">DESCRIPTION</h2> <p>This command runs the <code>npm build</code> command on each of the matched packages. This is useful when you install a new version of node, and must recompile all your C++ addons with the new binary. If no &#39;packages&#39; parameter is specify, every package will be rebuilt.</p> <h2 id="configuration">CONFIGURATION</h2> <p>See <code>npm help build</code></p> </div> <table border=0 cellspacing=0 cellpadding=0 id=npmlogo> <tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18>&nbsp;</td></tr> <tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td colspan=6 style="width:60px;height:10px;background:#fff">&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td></tr> <tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2>&nbsp;</td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff" rowspan=2>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff">&nbsp;</td></tr> <tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6>&nbsp;</td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td></tr> <tr><td colspan=5 style="width:50px;height:10px;background:#fff">&nbsp;</td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4>&nbsp;</td><td style="width:90px;height:10px;background:#fff" colspan=9>&nbsp;</td></tr> </table> <p id="footer">npm-rebuild &mdash; npm@2.15.12</p>
{ "content_hash": "7ee35bef9443fb7a80f5f0d9c0740a8c", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 807, "avg_line_length": 90.32352941176471, "alnum_prop": 0.714750895473787, "repo_name": "deep0892/jitendrachatbot", "id": "162b0177ac313ad26fa7e1ec81f868a50984b834", "size": "3071", "binary": false, "copies": "11", "ref": "refs/heads/Live", "path": "node_modules/npm-shrinkwrap/node_modules/npm/html/doc/api/npm-rebuild.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "525" }, { "name": "CSS", "bytes": "325809" }, { "name": "CoffeeScript", "bytes": "889285" }, { "name": "HTML", "bytes": "396795" }, { "name": "JavaScript", "bytes": "1640054" }, { "name": "Shell", "bytes": "1463" } ], "symlink_target": "" }
using base::win::RegKey; using installer::ProductState; namespace { const wchar_t kStageBinaryPatching[] = L"binary_patching"; const wchar_t kStageBuilding[] = L"building"; const wchar_t kStageConfiguringAutoLaunch[] = L"configuring_auto_launch"; const wchar_t kStageCopyingPreferencesFile[] = L"copying_prefs"; const wchar_t kStageCreatingShortcuts[] = L"creating_shortcuts"; const wchar_t kStageEnsemblePatching[] = L"ensemble_patching"; const wchar_t kStageExecuting[] = L"executing"; const wchar_t kStageFinishing[] = L"finishing"; const wchar_t kStagePreconditions[] = L"preconditions"; const wchar_t kStageRefreshingPolicy[] = L"refreshing_policy"; const wchar_t kStageRegisteringChrome[] = L"registering_chrome"; const wchar_t kStageRemovingOldVersions[] = L"removing_old_ver"; const wchar_t kStageRollingback[] = L"rollingback"; const wchar_t kStageUncompressing[] = L"uncompressing"; const wchar_t kStageUnpacking[] = L"unpacking"; const wchar_t kStageUpdatingChannels[] = L"updating_channels"; const wchar_t kStageCreatingVisualManifest[] = L"creating_visual_manifest"; const wchar_t kStageUninstallingBinaries[] = L"uninstalling_binaries"; const wchar_t kStageUninstallingChromeFrame[] = L"uninstalling_chrome_frame"; const wchar_t* const kStages[] = { NULL, kStagePreconditions, kStageUncompressing, kStageEnsemblePatching, kStageBinaryPatching, kStageUnpacking, kStageBuilding, kStageExecuting, kStageRollingback, kStageRefreshingPolicy, kStageUpdatingChannels, kStageCopyingPreferencesFile, kStageCreatingShortcuts, kStageRegisteringChrome, kStageRemovingOldVersions, kStageFinishing, kStageConfiguringAutoLaunch, kStageCreatingVisualManifest, nullptr, // Deprecated with InstallerStage(18) in util_constants.h. kStageUninstallingBinaries, kStageUninstallingChromeFrame, }; static_assert(installer::NUM_STAGES == arraysize(kStages), "kStages disagrees with Stage; they must match!"); // Creates a zero-sized non-decorated foreground window that doesn't appear // in the taskbar. This is used as a parent window for calls to ShellExecuteEx // in order for the UAC dialog to appear in the foreground and for focus // to be returned to this process once the UAC task is dismissed. Returns // NULL on failure, a handle to the UAC window on success. HWND CreateUACForegroundWindow() { HWND foreground_window = ::CreateWindowEx(WS_EX_TOOLWINDOW, L"STATIC", NULL, WS_POPUP | WS_VISIBLE, 0, 0, 0, 0, NULL, NULL, ::GetModuleHandle(NULL), NULL); if (foreground_window) { HMONITOR monitor = ::MonitorFromWindow(foreground_window, MONITOR_DEFAULTTONEAREST); if (monitor) { MONITORINFO mi = {0}; mi.cbSize = sizeof(mi); ::GetMonitorInfo(monitor, &mi); RECT screen_rect = mi.rcWork; int x_offset = (screen_rect.right - screen_rect.left) / 2; int y_offset = (screen_rect.bottom - screen_rect.top) / 2; ::MoveWindow(foreground_window, screen_rect.left + x_offset, screen_rect.top + y_offset, 0, 0, FALSE); } else { NOTREACHED() << "Unable to get default monitor"; } ::SetForegroundWindow(foreground_window); } return foreground_window; } } // namespace base::string16 InstallUtil::GetActiveSetupPath(BrowserDistribution* dist) { static const wchar_t kInstalledComponentsPath[] = L"Software\\Microsoft\\Active Setup\\Installed Components\\"; return kInstalledComponentsPath + dist->GetActiveSetupGuid(); } void InstallUtil::TriggerActiveSetupCommand() { base::string16 active_setup_reg( GetActiveSetupPath(BrowserDistribution::GetDistribution())); base::win::RegKey active_setup_key( HKEY_LOCAL_MACHINE, active_setup_reg.c_str(), KEY_QUERY_VALUE); base::string16 cmd_str; LONG read_status = active_setup_key.ReadValue(L"StubPath", &cmd_str); if (read_status != ERROR_SUCCESS) { LOG(ERROR) << active_setup_reg << ", " << read_status; // This should never fail if Chrome is registered at system-level, but if it // does there is not much else to be done. return; } base::CommandLine cmd(base::CommandLine::FromString(cmd_str)); // Force creation of shortcuts as the First Run beacon might land between now // and the time setup.exe checks for it. cmd.AppendSwitch(installer::switches::kForceConfigureUserSettings); base::Process process = base::LaunchProcess(cmd.GetCommandLineString(), base::LaunchOptions()); if (!process.IsValid()) PLOG(ERROR) << cmd.GetCommandLineString(); } bool InstallUtil::ExecuteExeAsAdmin(const base::CommandLine& cmd, DWORD* exit_code) { base::FilePath::StringType program(cmd.GetProgram().value()); DCHECK(!program.empty()); DCHECK_NE(program[0], L'\"'); base::CommandLine::StringType params(cmd.GetCommandLineString()); if (params[0] == '"') { DCHECK_EQ('"', params[program.length() + 1]); DCHECK_EQ(program, params.substr(1, program.length())); params = params.substr(program.length() + 2); } else { DCHECK_EQ(program, params.substr(0, program.length())); params = params.substr(program.length()); } base::TrimWhitespace(params, base::TRIM_ALL, &params); HWND uac_foreground_window = CreateUACForegroundWindow(); SHELLEXECUTEINFO info = {0}; info.cbSize = sizeof(SHELLEXECUTEINFO); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.hwnd = uac_foreground_window; info.lpVerb = L"runas"; info.lpFile = program.c_str(); info.lpParameters = params.c_str(); info.nShow = SW_SHOW; bool success = false; if (::ShellExecuteEx(&info) == TRUE) { ::WaitForSingleObject(info.hProcess, INFINITE); DWORD ret_val = 0; if (::GetExitCodeProcess(info.hProcess, &ret_val)) { success = true; if (exit_code) *exit_code = ret_val; } } if (uac_foreground_window) { DestroyWindow(uac_foreground_window); } return success; } base::CommandLine InstallUtil::GetChromeUninstallCmd( bool system_install, BrowserDistribution::Type distribution_type) { ProductState state; if (state.Initialize(system_install, distribution_type)) { return state.uninstall_command(); } return base::CommandLine(base::CommandLine::NO_PROGRAM); } void InstallUtil::GetChromeVersion(BrowserDistribution* dist, bool system_install, Version* version) { DCHECK(dist); RegKey key; HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; LONG result = key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_QUERY_VALUE | KEY_WOW64_32KEY); base::string16 version_str; if (result == ERROR_SUCCESS) result = key.ReadValue(google_update::kRegVersionField, &version_str); *version = Version(); if (result == ERROR_SUCCESS && !version_str.empty()) { VLOG(1) << "Existing " << dist->GetDisplayName() << " version found " << version_str; *version = Version(base::UTF16ToASCII(version_str)); } else { DCHECK_EQ(ERROR_FILE_NOT_FOUND, result); VLOG(1) << "No existing " << dist->GetDisplayName() << " install found."; } } void InstallUtil::GetCriticalUpdateVersion(BrowserDistribution* dist, bool system_install, Version* version) { DCHECK(dist); RegKey key; HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; LONG result = key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_QUERY_VALUE | KEY_WOW64_32KEY); base::string16 version_str; if (result == ERROR_SUCCESS) result = key.ReadValue(google_update::kRegCriticalVersionField, &version_str); *version = Version(); if (result == ERROR_SUCCESS && !version_str.empty()) { VLOG(1) << "Critical Update version for " << dist->GetDisplayName() << " found " << version_str; *version = Version(base::UTF16ToASCII(version_str)); } else { DCHECK_EQ(ERROR_FILE_NOT_FOUND, result); VLOG(1) << "No existing " << dist->GetDisplayName() << " install found."; } } bool InstallUtil::IsOSSupported() { // We do not support Win2K or older, or XP without service pack 2. VLOG(1) << base::SysInfo::OperatingSystemName() << ' ' << base::SysInfo::OperatingSystemVersion(); base::win::Version version = base::win::GetVersion(); return (version > base::win::VERSION_XP) || ((version == base::win::VERSION_XP) && (base::win::OSInfo::GetInstance()->service_pack().major >= 2)); } void InstallUtil::AddInstallerResultItems( bool system_install, const base::string16& state_key, installer::InstallStatus status, int string_resource_id, const base::string16* const launch_cmd, WorkItemList* install_list) { DCHECK(install_list); const HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; DWORD installer_result = (GetInstallReturnCode(status) == 0) ? 0 : 1; install_list->AddCreateRegKeyWorkItem(root, state_key, KEY_WOW64_32KEY); install_list->AddSetRegValueWorkItem(root, state_key, KEY_WOW64_32KEY, installer::kInstallerResult, installer_result, true); install_list->AddSetRegValueWorkItem(root, state_key, KEY_WOW64_32KEY, installer::kInstallerError, static_cast<DWORD>(status), true); if (string_resource_id != 0) { base::string16 msg = installer::GetLocalizedString(string_resource_id); install_list->AddSetRegValueWorkItem(root, state_key, KEY_WOW64_32KEY, installer::kInstallerResultUIString, msg, true); } if (launch_cmd != NULL && !launch_cmd->empty()) { install_list->AddSetRegValueWorkItem( root, state_key, KEY_WOW64_32KEY, installer::kInstallerSuccessLaunchCmdLine, *launch_cmd, true); } } void InstallUtil::UpdateInstallerStage(bool system_install, const base::string16& state_key_path, installer::InstallerStage stage) { DCHECK_LE(static_cast<installer::InstallerStage>(0), stage); DCHECK_GT(installer::NUM_STAGES, stage); const HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; RegKey state_key; LONG result = state_key.Open(root, state_key_path.c_str(), KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_32KEY); if (result == ERROR_SUCCESS) { if (stage == installer::NO_STAGE) { result = state_key.DeleteValue(installer::kInstallerExtraCode1); LOG_IF(ERROR, result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) << "Failed deleting installer stage from " << state_key_path << "; result: " << result; } else { const DWORD extra_code_1 = static_cast<DWORD>(stage); result = state_key.WriteValue(installer::kInstallerExtraCode1, extra_code_1); LOG_IF(ERROR, result != ERROR_SUCCESS) << "Failed writing installer stage to " << state_key_path << "; result: " << result; } // TODO(grt): Remove code below here once we're convinced that our use of // Google Update's new InstallerExtraCode1 value is good. installer::ChannelInfo channel_info; // This will return false if the "ap" value isn't present, which is fine. channel_info.Initialize(state_key); if (channel_info.SetStage(kStages[stage]) && !channel_info.Write(&state_key)) { LOG(ERROR) << "Failed writing installer stage to " << state_key_path; } } else { LOG(ERROR) << "Failed opening " << state_key_path << " to update installer stage; result: " << result; } } bool InstallUtil::IsPerUserInstall(const base::FilePath& exe_path) { scoped_ptr<base::Environment> env(base::Environment::Create()); static const char kEnvProgramFilesPath[] = "CHROME_PROBED_PROGRAM_FILES_PATH"; std::string env_program_files_path; // Check environment variable to find program files path. base::FilePath program_files_path; if (env->GetVar(kEnvProgramFilesPath, &env_program_files_path) && !env_program_files_path.empty()) { program_files_path = base::FilePath(base::UTF8ToWide(env_program_files_path)); } else { const int kProgramFilesKey = #if defined(_WIN64) // TODO(wfh): Revise this when Chrome is/can be installed in the 64-bit // program files directory. base::DIR_PROGRAM_FILESX86; #else base::DIR_PROGRAM_FILES; #endif if (!PathService::Get(kProgramFilesKey, &program_files_path)) { NOTREACHED(); return true; } env->SetVar(kEnvProgramFilesPath, base::WideToUTF8(program_files_path.value())); } // Return true if the program files path is not a case-insensitive prefix of // the exe path. if (exe_path.value().size() < program_files_path.value().size()) return true; DWORD prefix_len = base::saturated_cast<DWORD>(program_files_path.value().size()); return ::CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, exe_path.value().data(), prefix_len, program_files_path.value().data(), prefix_len) != CSTR_EQUAL; } bool InstallUtil::IsMultiInstall(BrowserDistribution* dist, bool system_install) { DCHECK(dist); ProductState state; return state.Initialize(system_install, dist) && state.is_multi_install(); } bool CheckIsChromeSxSProcess() { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); CHECK(command_line); if (command_line->HasSwitch(installer::switches::kChromeSxS)) return true; // Also return true if we are running from Chrome SxS installed path. base::FilePath exe_dir; PathService::Get(base::DIR_EXE, &exe_dir); base::string16 chrome_sxs_dir(installer::kGoogleChromeInstallSubDir2); chrome_sxs_dir.append(installer::kSxSSuffix); // This is SxS if current EXE is in or under (possibly multiple levels under) // |chrome_sxs_dir|\|installer::kInstallBinaryDir| std::vector<base::FilePath::StringType> components; exe_dir.GetComponents(&components); // We need at least 1 element in the array for the behavior of the following // loop to be defined. This should always be true, since we're splitting the // path to our executable and one of the components will be the drive letter. DCHECK(!components.empty()); typedef std::vector<base::FilePath::StringType>::const_reverse_iterator ComponentsIterator; for (ComponentsIterator current = components.rbegin(), parent = current + 1; parent != components.rend(); current = parent++) { if (base::FilePath::CompareEqualIgnoreCase( *current, installer::kInstallBinaryDir) && base::FilePath::CompareEqualIgnoreCase(*parent, chrome_sxs_dir)) { return true; } } return false; } bool InstallUtil::IsChromeSxSProcess() { static bool sxs = CheckIsChromeSxSProcess(); return sxs; } // static bool InstallUtil::IsFirstRunSentinelPresent() { // TODO(msw): Consolidate with first_run::internal::IsFirstRunSentinelPresent. base::FilePath user_data_dir; return !PathService::Get(chrome::DIR_USER_DATA, &user_data_dir) || base::PathExists(user_data_dir.Append(chrome::kFirstRunSentinel)); } // static bool InstallUtil::GetEULASentinelFilePath(base::FilePath* path) { base::FilePath user_data_dir; if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) return false; *path = user_data_dir.Append(installer::kEULASentinelFile); return true; } // This method tries to delete a registry key and logs an error message // in case of failure. It returns true if deletion is successful (or the key did // not exist), otherwise false. bool InstallUtil::DeleteRegistryKey(HKEY root_key, const base::string16& key_path, REGSAM wow64_access) { VLOG(1) << "Deleting registry key " << key_path; RegKey target_key; LONG result = target_key.Open(root_key, key_path.c_str(), KEY_READ | KEY_WRITE | wow64_access); if (result == ERROR_FILE_NOT_FOUND) return true; if (result == ERROR_SUCCESS) result = target_key.DeleteKey(L""); if (result != ERROR_SUCCESS) { LOG(ERROR) << "Failed to delete registry key: " << key_path << " error: " << result; return false; } return true; } // This method tries to delete a registry value and logs an error message // in case of failure. It returns true if deletion is successful (or the key did // not exist), otherwise false. bool InstallUtil::DeleteRegistryValue(HKEY reg_root, const base::string16& key_path, REGSAM wow64_access, const base::string16& value_name) { RegKey key; LONG result = key.Open(reg_root, key_path.c_str(), KEY_SET_VALUE | wow64_access); if (result == ERROR_SUCCESS) result = key.DeleteValue(value_name.c_str()); if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) { LOG(ERROR) << "Failed to delete registry value: " << value_name << " error: " << result; return false; } return true; } // static InstallUtil::ConditionalDeleteResult InstallUtil::DeleteRegistryKeyIf( HKEY root_key, const base::string16& key_to_delete_path, const base::string16& key_to_test_path, const REGSAM wow64_access, const wchar_t* value_name, const RegistryValuePredicate& predicate) { DCHECK(root_key); ConditionalDeleteResult delete_result = NOT_FOUND; RegKey key; base::string16 actual_value; if (key.Open(root_key, key_to_test_path.c_str(), KEY_QUERY_VALUE | wow64_access) == ERROR_SUCCESS && key.ReadValue(value_name, &actual_value) == ERROR_SUCCESS && predicate.Evaluate(actual_value)) { key.Close(); delete_result = DeleteRegistryKey(root_key, key_to_delete_path, wow64_access) ? DELETED : DELETE_FAILED; } return delete_result; } // static InstallUtil::ConditionalDeleteResult InstallUtil::DeleteRegistryValueIf( HKEY root_key, const wchar_t* key_path, REGSAM wow64_access, const wchar_t* value_name, const RegistryValuePredicate& predicate) { DCHECK(root_key); DCHECK(key_path); ConditionalDeleteResult delete_result = NOT_FOUND; RegKey key; base::string16 actual_value; if (key.Open(root_key, key_path, KEY_QUERY_VALUE | KEY_SET_VALUE | wow64_access) == ERROR_SUCCESS && key.ReadValue(value_name, &actual_value) == ERROR_SUCCESS && predicate.Evaluate(actual_value)) { LONG result = key.DeleteValue(value_name); if (result != ERROR_SUCCESS) { LOG(ERROR) << "Failed to delete registry value: " << (value_name ? value_name : L"(Default)") << " error: " << result; delete_result = DELETE_FAILED; } delete_result = DELETED; } return delete_result; } bool InstallUtil::ValueEquals::Evaluate(const base::string16& value) const { return value == value_to_match_; } // static int InstallUtil::GetInstallReturnCode(installer::InstallStatus status) { switch (status) { case installer::FIRST_INSTALL_SUCCESS: case installer::INSTALL_REPAIRED: case installer::NEW_VERSION_UPDATED: case installer::IN_USE_UPDATED: case installer::UNUSED_BINARIES_UNINSTALLED: return 0; default: return status; } } // static void InstallUtil::ComposeCommandLine(const base::string16& program, const base::string16& arguments, base::CommandLine* command_line) { *command_line = base::CommandLine::FromString(L"\"" + program + L"\" " + arguments); } // static base::string16 InstallUtil::GetCurrentDate() { static const wchar_t kDateFormat[] = L"yyyyMMdd"; wchar_t date_str[arraysize(kDateFormat)] = {0}; int len = GetDateFormatW(LOCALE_INVARIANT, 0, NULL, kDateFormat, date_str, arraysize(date_str)); if (len) { --len; // Subtract terminating \0. } else { PLOG(DFATAL) << "GetDateFormat"; } return base::string16(date_str, len); } // Open |path| with minimal access to obtain information about it, returning // true and populating |file| on success. // static bool InstallUtil::ProgramCompare::OpenForInfo(const base::FilePath& path, base::File* file) { DCHECK(file); file->Initialize(path, base::File::FLAG_OPEN); return file->IsValid(); } // Populate |info| for |file|, returning true on success. // static bool InstallUtil::ProgramCompare::GetInfo(const base::File& file, BY_HANDLE_FILE_INFORMATION* info) { DCHECK(file.IsValid()); return GetFileInformationByHandle(file.GetPlatformFile(), info) != 0; } InstallUtil::ProgramCompare::ProgramCompare(const base::FilePath& path_to_match) : path_to_match_(path_to_match), file_info_() { DCHECK(!path_to_match_.empty()); if (!OpenForInfo(path_to_match_, &file_)) { PLOG(WARNING) << "Failed opening " << path_to_match_.value() << "; falling back to path string comparisons."; } else if (!GetInfo(file_, &file_info_)) { PLOG(WARNING) << "Failed getting information for " << path_to_match_.value() << "; falling back to path string comparisons."; file_.Close(); } } InstallUtil::ProgramCompare::~ProgramCompare() { } bool InstallUtil::ProgramCompare::Evaluate(const base::string16& value) const { // Suss out the exe portion of the value, which is expected to be a command // line kinda (or exactly) like: // "c:\foo\bar\chrome.exe" -- "%1" base::FilePath program(base::CommandLine::FromString(value).GetProgram()); if (program.empty()) { LOG(WARNING) << "Failed to parse an executable name from command line: \"" << value << "\""; return false; } return EvaluatePath(program); } bool InstallUtil::ProgramCompare::EvaluatePath( const base::FilePath& path) const { // Try the simple thing first: do the paths happen to match? if (base::FilePath::CompareEqualIgnoreCase(path_to_match_.value(), path.value())) return true; // If the paths don't match and we couldn't open the expected file, we've done // our best. if (!file_.IsValid()) return false; // Open the program and see if it references the expected file. base::File file; BY_HANDLE_FILE_INFORMATION info = {}; return (OpenForInfo(path, &file) && GetInfo(file, &info) && info.dwVolumeSerialNumber == file_info_.dwVolumeSerialNumber && info.nFileIndexHigh == file_info_.nFileIndexHigh && info.nFileIndexLow == file_info_.nFileIndexLow); }
{ "content_hash": "4b8eb5bb403adc198fd1d73b463bc519", "timestamp": "", "source": "github", "line_count": 640, "max_line_length": 80, "avg_line_length": 37.6609375, "alnum_prop": 0.6298800979131228, "repo_name": "joone/chromium-crosswalk", "id": "6eb1b66adab2adf30aa3893a603ad17785444798", "size": "25470", "binary": false, "copies": "7", "ref": "refs/heads/2016.04.css-round-display-edtior-draft-1", "path": "chrome/installer/util/install_util.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
@extends('admin.layouts.modal') @section('content') <ul class="nav nav-tabs"> <li class="active"><a href="#tab-general" data-toggle="tab"> {{ Lang::get("admin/modal.general") }}</a></li> </ul> <form class="form-horizontal" id="fupload" enctype="multipart/form-data" method="post" action="@if(isset($video)){{ URL::to('admin/video/'.$video->id.'/edit') }} @else {{ URL::to('admin/video/create') }} @endif" autocomplete="off"> <input type="hidden" name="_token" value="{{{ csrf_token() }}}" /> <div class="tab-content"> <div class="tab-pane active" id="tab-general"> <div class="tab-pane active" id="tab-general"> <div class="form-group {{{ $errors->has('language_id') ? 'error' : '' }}}"> <div class="col-md-12"> <label class="control-label" for="language_id">{{ Lang::get("admin/admin.language") }}</label> <select style="width: 100%" name="language_id" id="language_id" class="form-control"> @foreach($languages as $item) <option value="{{$item->id}}" @if(!empty($language)) @if($item->id==$language) selected="selected" @endif @endif >{{$item->name}}</option> @endforeach </select> </div> </div> <div class="form-group {{{ $errors->has('name') ? 'has-error' : '' }}}"> <div class="col-md-12"> <label class="control-label" for="name"> {{ Lang::get("admin/modal.title") }}</label> <input class="form-control" type="text" name="name" id="name" value="{{{ Input::old('name', isset($video) ? $video->name : null) }}}" /> {!!$errors->first('name', '<span class="help-block">:message </span>')!!} </div> </div> <div class="form-group {{{ $errors->has('photo_album_id') ? 'has-error' : '' }}}"> <div class="col-md-12"> <label class="control-label" for="video_album_id">{{ Lang::get("admin/video.album") }}</label> <select style="width: 100%" name="video_album_id" id="video_album_id" class="form-control"> @foreach($videoalbums as $item) <option value="{{$item->id}}" @if(!empty($videoalbum)) @if($item->id==$videoalbum) selected="selected" @endif @endif >{{$item->name}}</option> @endforeach </select> </div> </div> <div class="form-group {{{ $errors->has('album_cover') ? 'has-error' : '' }}}"> <div class="col-lg-12"> <label class="control-label" for="album_cover">{{{ Lang::get('admin/photo.album_cover') }}}</label> <label class="radio"> {!! Form::radio('album_cover', 1, (Input::old('album_cover') == '1' || (isset($video) && $video->video_album_cover == '1')) ? true : false, array('id'=>'showtitle', 'class'=>'radio')) !!} {{{ Lang::get('admin/admin.yes') }}} </label> <label class="radio"> {!! Form::radio('album_cover', 0, (Input::old('album_cover') == '0' || (isset($video) && $video->video_album_cover == '0') || !isset($video)) ? true : false, array('id'=>'showtitle', 'class'=>'radio')) !!} {{{ Lang::get('admin/admin.no') }}} </label> </div> </div> <div class="form-group {{{ $errors->has('content') ? 'has-error' : '' }}}"> <div class="col-md-12"> <label class="control-label" for="description">{{ Lang::get("admin/photo.description") }}</label> <textarea class="form-control full-width wysihtml5" name="description" rows="10">{{{ Input::old('content', isset($video) ? $video->description : null) }}}</textarea> {!! $errors->first('description', '<label class="control-label">:message</label>')!!} </div> </div> <div class="form-group"> <div class="col-md-12"> <label class="control-label" for="youtube"> {{ Lang::get("admin/video.video_youtube") }}</label> <input class="form-control" type="text" name="youtube" id="youtube" value="{{{ Input::old('youtube', isset($video) ? $video->youtube : null) }}}" /> </div> </div> </div> </div> <div class="form-group"> <div class="col-md-12"> <button type="reset" class="btn btn-sm btn-warning close_popup"> <span class="glyphicon glyphicon-ban-circle"></span> {{ Lang::get("admin/modal.cancel") }} </button> <button type="reset" class="btn btn-sm btn-default"> <span class="glyphicon glyphicon-remove-circle"></span> {{ Lang::get("admin/modal.reset") }} </button> <button type="submit" class="btn btn-sm btn-success"> <span class="glyphicon glyphicon-ok-circle"></span> @if (isset($video)) {{ Lang::get("admin/modal.edit") }} @else {{Lang::get("admin/modal.create") }} @endif </button> </div> </div> </div> </form> @stop
{ "content_hash": "87130fdc631425a8bec4c38f8b51c396", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 132, "avg_line_length": 41.05, "alnum_prop": 0.5377588306942753, "repo_name": "mclxly/www.lx", "id": "61a61dcf719bad7a2a82d9643b77ff6ac5084ed8", "size": "4926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/admin/video/create_edit.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "701217" }, { "name": "HTML", "bytes": "288058" }, { "name": "JavaScript", "bytes": "1944249" }, { "name": "PHP", "bytes": "306733" } ], "symlink_target": "" }
/* eslint-disable import/no-extraneous-dependencies */ import enzyme from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import { JSDOM } from 'jsdom' enzyme.configure({ adapter: new Adapter() }) // ----------------------------------------------------------------------------- const exposedProperties = ['window', 'navigator', 'document'] const dom = new JSDOM('') global.document = dom.window.document global.window = dom.window Object.keys(dom.window).forEach(property => { if (typeof global[property] === 'undefined') { if (property === 'localStorage') return if (property === 'sessionStorage') return exposedProperties.push(property) global[property] = dom.window[property] } }) global.navigator = { userAgent: 'node.js', }
{ "content_hash": "1026666c1f40429d9811c48d59934318", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 80, "avg_line_length": 27.321428571428573, "alnum_prop": 0.6274509803921569, "repo_name": "kreativgebiet/kickup-react", "id": "4c2010e0d3bf9241556a422b3357cce43a6d0960", "size": "765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "internals/test/setupTests.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "40298" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Mycotaxon 13(2): 419 (1981) #### Original name Codinaea illinoensis Hewings & J.L. Crane ### Remarks null
{ "content_hash": "a7759874fafd059885a59251c0ff6a10", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 41, "avg_line_length": 13, "alnum_prop": 0.6982248520710059, "repo_name": "mdoering/backbone", "id": "14f8e0ba25ebf04c9a835b08545624c228094854", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Chaetosphaeriales/Chaetosphaeriaceae/Dictyochaeta/Codinaea illinoensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
A simple UIColor library to get UIColor object from RGB hex string/value, CMYK hex string/value or CMYK base component values. You can also retrieve back RGB hex string/value, CMYK hex string/value. [![Awesome iOS][awesome-ios-image]][awesome-ios-url] [![Swift Version][swift-image]][swift-url] [![Objective C][objc-image]][objc-url] [![License][license-image]][license-url] [![DOI](https://zenodo.org/badge/26798948.svg)](https://zenodo.org/badge/latestdoi/26798948) [![Build Status](https://travis-ci.org/burhanuddin353/TFTColor.svg?branch=master)](https://travis-ci.org/burhanuddin353/TFTColor) <img src="https://github.com/burhanuddin353/TFTColor/blob/master/Example.png" width="375"> You can support me here https://linktr.ee/burhanuddin353 ## Features - [x] Convert RGB Hex String/Value to UIColor - [x] Convert CMYK Hex String/Value to UIColor - [x] Get RGB Hex String/Value from UIColor - [x] Get CMYK Hex String/Value from UIColor - [x] Initialize CMYK from its base components * The beautiful part of this library is that you can input Hex values with `#`, `0x` or `0X` and the it will take care of this. * Also you can input hex value of any length and this will be handled. * The library also takes care of non-hex characters. #### Supporting Formats for RGB Hex Strings: 1. **#B** 2. **#BB** 3. **#RGB** 4. **#GGBB** 5. **#RGGBB** 6. **#RRGGBB** #### Supporting Formats for CMYK Hex Strings: 1. **#K** 2. **#KK** 3. **#YKK** 4. **#CMYK** 5. **#MYYKK** 6. **#MMYYKK** 7. **#CMMYYKK** 8. **#CCMMYYKK** ## Requirements - iOS 8.0+ - Xcode 7.3+ ## Installation #### CocoaPods You can use [CocoaPods](http://cocoapods.org/) to install `TFTColor` by adding it to your `Podfile`: ```ruby platform :ios, '9.0' use_frameworks! target 'YourApp' do pod 'TFTColor' end ``` Then, run the following command: ``` ruby $ pod install ``` #### Manually **Swift** 1. Download and drop ```TFTColor.swift``` in your project. **Objective-C** 1. Download and drop ```TFTColor.h``` & ```TFTColor.m``` in your project. 2. Congratulations! ## Usage example **Swift** ```swift import TFTColor // UIColor from RGB Hex String UIColor(rgbHexString: "FF34AE", alpha: 1.0) UIColor(rgbHexString: "#ea", alpha: 1.0) // UIColor from RGB Hex Value UIColor(rgbHexValue: 0xFF34AE alpha: 1.0) // RGB Hex String from UIColor let redColor = UIColor.redColor redColor.rgbHexString //"FF0000" // RGB Hex Value from UIColor redColor.rgbHexValue //0xFF0000 // UIColor from CMYK component values // Creates and returns a color object using the specified opacity and CMYK component values. // The components of the color object, specified as a value from 0.0 to 1.0. UIColor(cyan:0.5, magenta: 0.5, yellow: 0.5, black: 0.5, alpha: 1.0) // UIColor from CMYK Hex String UIColor(cmykHexString: "FF34AE34", alpha:1.0) UIColor(cmykHexString: "#ea", alpha:1.0) // UIColor from CMYK Hex Value UIColor(cmykHexValue: 0xFF34AE34 alpha:1.0) // CMYK Hex String from UIColor redColor.cmykHexString //"00646400" // CMYK Hex Value from UIColor redColor.cmykHexValue //0x00646400 ``` **Objective-C** ```objc // UIColor from RGB Hex String [UIColor colorWithRGBHexString:@"FF34AE" alpha:1.0f]; [UIColor colorWithRGBHexString:@"#ea" alpha:1.0f]; // UIColor from RGB Hex Value [UIColor colorWithRGBHexValue:0xFF34AE alpha:1.0f]; // RGB Hex String from UIColor [UIColor rgbHexStringForColor:[UIColor redColor]]; //@"FF0000" // RGB Hex Value from UIColor [UIColor rgbHexValueForColor:[UIColor redColor]]; //0xFF0000 // UIColor from CMYK component values // Creates and returns a color object using the specified opacity and CMYK component values. // The components of the color object, specified as a value from 0.0 to 1.0. [UIColor colorWithCyan:0.5f magenta:0.5 yellow:0.5f black:0.5f alpha:1.0f]; // UIColor from CMYK Hex String [UIColor colorWithCMYKHexString:@"FF34AE34" alpha:1.0f]; [UIColor colorWithCMYKHexString:@"#EA" alpha:1.0f]; // UIColor from CMYK Hex Value [UIColor colorWithCMYKHexValue:0xFF34AE34 alpha:1.0f]; // CMYK Hex String from UIColor [UIColor cmykHexStringForColor:[UIColor redColor]]; //"00646400" // CMYK Hex Value from UIColor [UIColor cmykHexValueForColor:[UIColor redColor]]; //0x00646400 ``` ## Contribute We would love for you to contribute to **TFTColor**, check the ``LICENSE`` file for more info. ## Meta Burhanuddin Sunelwala – [@burhanuddin353](https://twitter.com/burhanuddin353) – burhanuddin353@gmail.com Distributed under the **The MIT License (MIT)** license. See ``LICENSE`` for more information. [https://github.com/burhanuddin353/TFTColor](https://github.com/burhanuddin353/TFTColor) [swift-image]: https://img.shields.io/badge/swift-3.0-orange.svg [swift-url]: https://swift.org/ [objc-image]: https://img.shields.io/badge/Objective-C-purple.svg [objc-url]: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html [license-image]: https://img.shields.io/badge/License-MIT-blue.svg [license-url]: https://github.com/burhanuddin353/TFTColor/blob/master/LICENSE [travis-image]: https://img.shields.io/travis/dbader/node-datadog-metrics/master.svg?style=flat-square [travis-url]: https://travis-ci.org/dbader/node-datadog-metrics [codebeat-image]: https://codebeat.co/badges/c19b47ea-2f9d-45df-8458-b2d952fe9dad [codebeat-url]: https://codebeat.co/projects/github-com-vsouza-awesomeios-com [awesome-ios-image]: https://img.shields.io/badge/Awesome-iOS-blue.svg [awesome-ios-url]: https://github.com/vsouza/awesome-ios
{ "content_hash": "fa02b5e5f6f55e84cae4da8b5c785352", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 139, "avg_line_length": 30.966480446927374, "alnum_prop": 0.732816164531842, "repo_name": "burhanuddin353/TFTColor", "id": "0b2c8991006cbaf668d97c1b88e9672ad66a295d", "size": "5558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "12656" }, { "name": "Ruby", "bytes": "705" }, { "name": "Swift", "bytes": "13966" } ], "symlink_target": "" }
package org.gradoop.flink.model.impl.operators.statistics; import org.apache.flink.api.java.DataSet; import org.gradoop.common.model.impl.id.GradoopId; import org.gradoop.flink.model.api.epgm.LogicalGraph; import org.gradoop.flink.model.api.operators.UnaryGraphToValueOperator; import org.gradoop.flink.model.impl.operators.statistics.functions.SumCounts; import org.gradoop.flink.model.impl.tuples.WithCount; /** * Computes the vertex degree for each vertex. */ public class VertexDegrees implements UnaryGraphToValueOperator<DataSet<WithCount<GradoopId>>> { @Override public DataSet<WithCount<GradoopId>> execute(LogicalGraph graph) { return new OutgoingVertexDegrees() .execute(graph) .join(new IncomingVertexDegrees().execute(graph)) .where(0).equalTo(0) .with(new SumCounts<>()); } }
{ "content_hash": "df9a043b16f8e0a6bfe346010fc68450", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 96, "avg_line_length": 34.541666666666664, "alnum_prop": 0.773220747889023, "repo_name": "s1ck/gradoop", "id": "90ce643a98c8eaa4ff6e87444800631234679e67", "size": "1467", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gradoop-flink/src/main/java/org/gradoop/flink/model/impl/operators/statistics/VertexDegrees.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3911258" }, { "name": "Shell", "bytes": "4071" } ], "symlink_target": "" }
package net.dxs.mobilesafe.utils; import java.util.List; import net.dxs.mobilesafe.app.App; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.Context; /** * 服务状态工具类 * * @author lijian-pc * @date 2016-5-9 下午2:59:51 */ public class ServiceStatusUtils { /** * 判断一个服务是否处于开启状态 * * @param context * 上下文 * @param serviceClassname * 服务的完整的类名称 * @return */ public static boolean isServiceRunning(Context context, String serviceClassname) { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> serviceInfos = am.getRunningServices(100); for (RunningServiceInfo serviceInfo : serviceInfos) { String servicename = serviceInfo.service.getClassName(); if (serviceClassname.equals(servicename)) { return true; } } return false; } /** * 判断一个服务是否处于开启状态 * * @param clazz * 服务类 * @return */ public static boolean isServiceRunning(Class<?> clazz) { ActivityManager am = (ActivityManager) App.getContext() .getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> serviceInfos = am.getRunningServices(100); for (RunningServiceInfo serviceInfo : serviceInfos) { String servicename = serviceInfo.service.getClassName(); if (clazz.getName().equals(servicename)) { return true; } } return false; } }
{ "content_hash": "d9f89ef2577e5846a157bbf53067dd46", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 69, "avg_line_length": 24.81967213114754, "alnum_prop": 0.6776750330250991, "repo_name": "54dxs/mobilesafe", "id": "642e206ca1ec199a974620ba279be4d1edc55dac", "size": "1618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ms/src/net/dxs/mobilesafe/utils/ServiceStatusUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "45452" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Collections.ObjectModel; using Sitecore.Data; namespace Synthesis.Templates { public interface ITemplateInfo { ID TemplateId { get; } string Name { get; } IList<ITemplateFieldInfo> Fields { get; } string HelpText { get; } string FullPath { get; } IList<ITemplateFieldInfo> OwnFields { get; } /// <summary> /// Gets immediate ancestor base templates /// </summary> ReadOnlyCollection<ITemplateInfo> BaseTemplates { get; } /// <summary> /// Gets all base templates (including base templates of base templates back up to the standard template) /// </summary> ReadOnlyCollection<ITemplateInfo> AllNonstandardBaseTemplates { get; } } }
{ "content_hash": "23bfd7cc467c24203f498098bf22cabc", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 107, "avg_line_length": 27.346153846153847, "alnum_prop": 0.7271448663853727, "repo_name": "kamsar/Synthesis", "id": "9f67d1976d5e4b38b06101f1b23accac843cc6cf", "size": "711", "binary": false, "copies": "2", "ref": "refs/heads/Sitecore-8.1", "path": "Source/Synthesis/Templates/ITemplateInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "117" }, { "name": "C#", "bytes": "394882" }, { "name": "PowerShell", "bytes": "1619" } ], "symlink_target": "" }
package com.messagemedia.service; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for MessageErrorListType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MessageErrorListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="error" type="{http://xml.m4u.com.au/2009}MessageErrorType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MessageErrorListType", propOrder = { "error" }) public class MessageErrorListType { @XmlElement(required = true) protected List<MessageErrorType> error; /** * Gets the value of the error property. * * <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 error property. * * <p> * For example, to add a new item, do as follows: * <pre> * getError().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MessageErrorType } * * */ public List<MessageErrorType> getError() { if (error == null) { error = new ArrayList<MessageErrorType>(); } return this.error; } }
{ "content_hash": "01a727748c24421fb7543175397ce77c", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 111, "avg_line_length": 27.17391304347826, "alnum_prop": 0.6421333333333333, "repo_name": "messagemedia/messagemedia-java", "id": "8d4618f93cbdba72bb297368e87ab7fb7d9aeca3", "size": "1875", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/messagemedia/service/MessageErrorListType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "261" }, { "name": "Java", "bytes": "236394" } ], "symlink_target": "" }
DataStore::DataStore(QString name) { filename = name; state = load(); } DataStore::~DataStore() { // save(); } bool DataStore::load() { QFile loadFile(filename); if (!loadFile.open(QIODevice::ReadOnly)) { qWarning("Couldn't open save file."); return false; } QByteArray saveData = qUncompress(loadFile.readAll()); QJsonDocument loadDoc(QJsonDocument::fromJson(saveData)); json = loadDoc.object(); return true; } bool DataStore::save() { QFile saveFile(filename); if (!saveFile.open(QIODevice::WriteOnly)) { qWarning("Couldn't open save file."); return false; } QJsonDocument saveDoc(json); saveFile.write(qCompress(saveDoc.toJson(), 9)); return true; } void DataStore::clear() { json = QJsonObject(); } QStringList DataStore::keys() { return json.keys(); } QJsonValue DataStore::read(QString key) { return json.value(key); } void DataStore::write(QString key, double value) { json[key] = value; } void DataStore::write(QString key, QJsonArray value) { json[key] = value; } void DataStore::write(QString key, QJsonObject value) { json[key] = value; } void DataStore::write(QString key, QString value) { json[key] = value; } void DataStore::write(QString key, int value) { json[key] = value; } void DataStore::write(QString key, QVariant value) { json.insert(key, QJsonValue::fromVariant(value)); } void DataStore::append(QString key, QString subkey, QString value) { QJsonObject subObj; subObj[subkey] = value; json[key].toArray().append(subObj); }
{ "content_hash": "bff6d31f711dea6f3a9a9940b73baadb", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 68, "avg_line_length": 21.972602739726028, "alnum_prop": 0.6577306733167082, "repo_name": "jeyboy/palyo2", "id": "76192701f3881444cf5efeb0ffc936db6926fa1e", "size": "1629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "misc/data_store.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "74163" }, { "name": "C++", "bytes": "1087149" }, { "name": "Objective-C", "bytes": "6293" }, { "name": "Prolog", "bytes": "413" } ], "symlink_target": "" }
require_relative "../json_compat" require_relative "../mixin/versioned_api" class Chef class Cookbook class ManifestV0 extend Chef::Mixin::VersionedAPI minimum_api_version 0 COOKBOOK_SEGMENTS = %w{ resources providers recipes definitions libraries attributes files templates root_files }.freeze class << self def from_hash(hash) response = Mash.new(hash) response[:all_files] = COOKBOOK_SEGMENTS.inject([]) do |memo, segment| next memo if hash[segment].nil? || hash[segment].empty? hash[segment].each do |file| file["name"] = "#{segment}/#{file["name"]}" memo << file end response.delete(segment) memo end response end def to_h(manifest) result = manifest.manifest.dup result.delete("all_files") files = manifest.by_parent_directory files.keys.each_with_object(result) do |parent, memo| if COOKBOOK_SEGMENTS.include?(parent) memo[parent] ||= [] files[parent].each do |file| file["name"] = file["name"].split("/")[1] file.delete("full_path") memo[parent] << file end end end # Ensure all segments are set to [] if they don't exist. # See https://github.com/chef/chef/issues/6044 COOKBOOK_SEGMENTS.each do |segment| result[segment] ||= [] end result.merge({ "frozen?" => manifest.frozen_version?, "chef_type" => "cookbook_version" }) end alias_method :to_hash, :to_h end end end end
{ "content_hash": "960e65a3ce199b0fcb6cf82041a2998c", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 126, "avg_line_length": 29.775862068965516, "alnum_prop": 0.5437174290677476, "repo_name": "gene1wood/chef", "id": "b2b39f32f3ce1399c398180f3e7571711a9d03e4", "size": "2401", "binary": false, "copies": "9", "ref": "refs/heads/main", "path": "lib/chef/cookbook/manifest_v0.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1454" }, { "name": "HTML", "bytes": "76265" }, { "name": "Makefile", "bytes": "2652" }, { "name": "PowerShell", "bytes": "21983" }, { "name": "Python", "bytes": "13362" }, { "name": "Raku", "bytes": "128" }, { "name": "Ruby", "bytes": "11095253" }, { "name": "Shell", "bytes": "40296" } ], "symlink_target": "" }
<!DOCTYPE html> <link rel="author" title="Mats Palmgren" href="mailto:mats@mozilla.com"> <link rel="help" href="https://www.w3.org/TR/css-break-3/"> <link rel="match" href="block-001-wm-vlr-ref.html"> <meta name="flags" content="paged"> <meta name="fuzzy" content="maxDifference=0-60;totalPixels=0-200"> <html> <style> @page { size: 5in 3in; margin: 0.5in; } html,body { color:black; background-color:white; font:20px/1 monospace; padding:0; margin:0; writing-mode: vertical-lr; } html { block-size: 40vw; } .b { inline-size: 50vh; block-size: 210vw; box-sizing: border-box; border: 5px solid black; border-block-start-color: blue; border-inline-start-color: lime; margin-inline-start: 20px; margin-block-end: -20px; } </style> <body> <div class="b"></div> </body> </html>
{ "content_hash": "b1ca0738eec9a0d9f13cd4e661e52826", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 82, "avg_line_length": 23.558823529411764, "alnum_prop": 0.6779026217228464, "repo_name": "ric2b/Vivaldi-browser", "id": "6cd5ea07c7b2a132cef7d26abd4204cb157b5eae", "size": "801", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "chromium/third_party/blink/web_tests/external/wpt/css/css-break/block-001-wm-vlr-print.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Phyllosticta minutella Bubák & Dearn. ### Remarks null
{ "content_hash": "e3dfe1bfc3aa9820201b46f61dbb3326", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 37, "avg_line_length": 10.923076923076923, "alnum_prop": 0.7112676056338029, "repo_name": "mdoering/backbone", "id": "9685996c64ca0d2abce8e469499279456f8e94f6", "size": "205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Botryosphaeriales/Botryosphaeriaceae/Phyllosticta/Phyllosticta minutella/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * @var array $brands * @var Producer $brand */ ?> <?php if ($brands): ?> <div class="row"> <div class="col-sm-12"> <div id="brand-carousel" class="carousel slide" data-ride="carousel"> <div class="carousel-inner" role="listbox"> <?php foreach ($brands as $i => $brand): ?> <div class="item <?= $i == 0 ? 'active' : '' ?>"> <div class="scrollElement__item" data-target="#carousel"> <?php $this->render('_item', ['brand' => $brand]) ?> </div> </div> <?php endforeach; ?> </div> <a class="left carousel-control" href="#brand-carousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> </a> <a class="right carousel-control" href="#brand-carousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> </a> </div> </div> </div> <?php endif; ?>
{ "content_hash": "e8c29f3900a3959b77a79b81ba1bf902", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 105, "avg_line_length": 42.206896551724135, "alnum_prop": 0.45179738562091504, "repo_name": "u4aew/tdtaliru", "id": "ae6d549537503f72ad637f90f16e22991ae4018b", "size": "1224", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "uploads/themes/default/views/store/widgets/ProducersWidget/default.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "3012" }, { "name": "Batchfile", "bytes": "378" }, { "name": "CSS", "bytes": "383803" }, { "name": "HTML", "bytes": "53" }, { "name": "JavaScript", "bytes": "413142" }, { "name": "Nginx", "bytes": "2365" }, { "name": "PHP", "bytes": "5478493" }, { "name": "Shell", "bytes": "873" } ], "symlink_target": "" }
module CNU::Gozer require "#{File.dirname(__FILE__)}/san_types/three_par.rb" require "#{File.dirname(__FILE__)}/san_types/equal_logic.rb" class SanCmdRunner class BadTypeException < Exception; end attr_accessor :san def initialize(type) if type == '3par' @san = SanTypes::ThreePar.new elsif type == 'equallogic' @san = SanTypes::EqualLogic.new else raise SanBadTypeException, "Don't know how to work on #{san.type}" end end def self.add_volume(san, *args) self.new(san).add_volume(*args) end def add_volume(*args) @san.run(:add_volume, *args) end def self.add_host(san, *args) self.new(san).add_host(*args) end def add_host(*args) @san.run(:add_host, *args) end def self.export_volume(san, *args) self.new(san).export_volume(*args) end def export_volume(*args) @san.run(:export_volume, *args) end def self.unexport_volume(san, *args) self.new(san).unexport_volume(*args) end def unexport_volume(*args) @san.run(:unexport_volume, *args) end def self.create_rw_snapshot(san, *args) self.new(san).create_rw_snapshot(*args) end def create_rw_snapshot(*args) @san.run(:create_rw_snap, *args) end def self.create_ro_snapshot(san, *args) self.new(san).create_ro_snapshot(*args) end def create_ro_snapshot(*args) @san.run(:create_ro_snap, *args) end end end
{ "content_hash": "4768dfb5f95f2e9b2177edd45261d09c", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 74, "avg_line_length": 21.295774647887324, "alnum_prop": 0.6038359788359788, "repo_name": "slaught/enki_cloud", "id": "8eb9d4a814629ba43a6e4a166b02c4994933a07d", "size": "1512", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ui/lib/cnu/gozer/san_cmd_runner.rb", "mode": "33188", "license": "mit", "language": [ { "name": "D", "bytes": "269" }, { "name": "JavaScript", "bytes": "363862" }, { "name": "Perl", "bytes": "329111" }, { "name": "Ruby", "bytes": "631195" }, { "name": "Shell", "bytes": "3209" } ], "symlink_target": "" }
package org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd; import com.google.common.base.Preconditions; import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveOperationType; import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject; import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject.HivePrivObjectActionType; import org.apache.hadoop.hive.ql.security.authorization.plugin.HivePrivilegeObject.HivePrivilegeObjectType; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Mapping of operation to its required input and output privileges */ public class Operation2Privilege { public enum IOType { INPUT, OUTPUT } private static class PrivRequirement { private final SQLPrivTypeGrant[] reqPrivs; // The following fields specify the criteria on objects for this priv to be required private final IOType ioType; private final HivePrivObjectActionType actionType; private final HivePrivilegeObjectType objectType; private PrivRequirement(SQLPrivTypeGrant[] privs, IOType ioType) { this(privs, ioType, null); } private PrivRequirement(SQLPrivTypeGrant[] privs, IOType ioType, HivePrivObjectActionType actionType) { this(privs, ioType, actionType, null); } private PrivRequirement(SQLPrivTypeGrant[] privs, HivePrivilegeObjectType objectType) { this(privs, null, null, objectType); } private PrivRequirement(SQLPrivTypeGrant[] privs, IOType ioType, HivePrivObjectActionType actionType, HivePrivilegeObjectType objectType) { this.reqPrivs = privs; this.ioType = ioType; this.actionType = actionType; this.objectType = objectType; } /** * Utility function that takes a input and output privilege objects * @param inGrant * @param outGrant * @return */ static List<PrivRequirement> newIOPrivRequirement(SQLPrivTypeGrant[] inGrants, SQLPrivTypeGrant[] outGrants) { List<PrivRequirement> privReqs = new ArrayList<PrivRequirement>(); privReqs.add(new PrivRequirement(inGrants, IOType.INPUT)); privReqs.add(new PrivRequirement(outGrants, IOType.OUTPUT)); return privReqs; } /** * Utility function that converts PrivRequirement array into list * @param privs * @return */ static List<PrivRequirement> newPrivRequirementList(PrivRequirement... privs) { return new ArrayList<PrivRequirement>(Arrays.asList(privs)); } private SQLPrivTypeGrant[] getReqPrivs() { return reqPrivs; } private IOType getIOType() { return ioType; } private HivePrivObjectActionType getActionType() { return actionType; } public HivePrivilegeObjectType getObjectType() { return objectType; } } private static Map<HiveOperationType, List<PrivRequirement>> op2Priv; private static List<HiveOperationType> adminPrivOps; private static SQLPrivTypeGrant[] OWNER_PRIV_AR = arr(SQLPrivTypeGrant.OWNER_PRIV); private static SQLPrivTypeGrant[] SEL_NOGRANT_AR = arr(SQLPrivTypeGrant.SELECT_NOGRANT); private static SQLPrivTypeGrant[] SEL_GRANT_AR = arr(SQLPrivTypeGrant.SELECT_WGRANT); private static SQLPrivTypeGrant[] ADMIN_PRIV_AR = arr(SQLPrivTypeGrant.ADMIN_PRIV); private static SQLPrivTypeGrant[] INS_NOGRANT_AR = arr(SQLPrivTypeGrant.INSERT_NOGRANT); private static SQLPrivTypeGrant[] DEL_NOGRANT_AR = arr(SQLPrivTypeGrant.DELETE_NOGRANT); private static SQLPrivTypeGrant[] UPD_NOGRANT_AR = arr(SQLPrivTypeGrant.UPDATE_NOGRANT); private static SQLPrivTypeGrant[] INS_SEL_DEL_NOGRANT_AR = arr(SQLPrivTypeGrant.INSERT_NOGRANT, SQLPrivTypeGrant.DELETE_NOGRANT, SQLPrivTypeGrant.SELECT_NOGRANT); static { adminPrivOps = new ArrayList<HiveOperationType>(); op2Priv = new HashMap<HiveOperationType, List<PrivRequirement>>(); op2Priv.put(HiveOperationType.EXPLAIN, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, SEL_NOGRANT_AR)); //?? op2Priv.put(HiveOperationType.CREATEDATABASE, PrivRequirement.newPrivRequirementList( new PrivRequirement(INS_SEL_DEL_NOGRANT_AR, HivePrivilegeObjectType.DFS_URI), new PrivRequirement(INS_SEL_DEL_NOGRANT_AR, HivePrivilegeObjectType.LOCAL_URI))); op2Priv.put(HiveOperationType.DROPDATABASE, PrivRequirement.newIOPrivRequirement(null, OWNER_PRIV_AR)); // this should be database usage privilege once it is supported op2Priv.put(HiveOperationType.SWITCHDATABASE, PrivRequirement.newIOPrivRequirement(null, null)); // lock operations not controlled for now op2Priv.put(HiveOperationType.LOCKDB, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.UNLOCKDB, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DROPTABLE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, null)); op2Priv.put(HiveOperationType.DESCTABLE, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); op2Priv.put(HiveOperationType.SHOWPARTITIONS, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); op2Priv.put(HiveOperationType.DESCFUNCTION, PrivRequirement.newIOPrivRequirement(null, null)); // meta store check command - equivalent to add partition command // no input objects are passed to it currently, but keeping admin priv // requirement on inputs just in case some input object like file // uri is added later op2Priv.put(HiveOperationType.MSCK, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, INS_NOGRANT_AR)); //alter table commands require table ownership // There should not be output object, but just in case the table is incorrectly added // to output instead of input, adding owner requirement on output will catch that as well op2Priv.put(HiveOperationType.ALTERTABLE_ADDCOLS, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_REPLACECOLS, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_RENAMECOL, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_RENAMEPART, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_RENAME, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_UPDATETABLESTATS, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_UPDATEPARTSTATS, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_TOUCH, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_ARCHIVE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_UNARCHIVE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_PROPERTIES, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_OWNER, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_SERIALIZER, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_PARTCOLTYPE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERPARTITION_SERIALIZER, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_SERDEPROPERTIES, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERPARTITION_SERDEPROPERTIES, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_CLUSTER_SORT, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_BUCKETNUM, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERPARTITION_BUCKETNUM, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_PROTECTMODE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERPARTITION_PROTECTMODE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_FILEFORMAT, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERPARTITION_FILEFORMAT, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_LOCATION, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, INS_SEL_DEL_NOGRANT_AR)); op2Priv.put(HiveOperationType.ALTERPARTITION_LOCATION, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, INS_SEL_DEL_NOGRANT_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_MERGEFILES, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERPARTITION_MERGEFILES, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_SKEWED, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTBLPART_SKEWED_LOCATION, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, INS_SEL_DEL_NOGRANT_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_COMPACT, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_UPDATECOLUMNS, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.TRUNCATETABLE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_DROPCONSTRAINT, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERTABLE_ADDCONSTRAINT, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); // require view ownership for alter/drop view op2Priv.put(HiveOperationType.ALTERVIEW_PROPERTIES, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERVIEW_RENAME, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERVIEW_AS, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.DROPVIEW, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ALTER_MATERIALIZED_VIEW_REWRITE, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.DROP_MATERIALIZED_VIEW, PrivRequirement.newIOPrivRequirement(OWNER_PRIV_AR, OWNER_PRIV_AR)); op2Priv.put(HiveOperationType.ANALYZE_TABLE, PrivRequirement.newIOPrivRequirement(arr(SQLPrivTypeGrant.SELECT_NOGRANT, SQLPrivTypeGrant.INSERT_NOGRANT), null)); op2Priv.put(HiveOperationType.CACHE_METADATA, PrivRequirement.newIOPrivRequirement(arr(SQLPrivTypeGrant.SELECT_NOGRANT, SQLPrivTypeGrant.INSERT_NOGRANT), null)); op2Priv.put(HiveOperationType.SHOWDATABASES, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOWTABLES, PrivRequirement.newIOPrivRequirement(null, null)); // operations that require insert/delete privileges op2Priv.put(HiveOperationType.ALTERTABLE_DROPPARTS, PrivRequirement.newIOPrivRequirement(DEL_NOGRANT_AR, null)); // in alter-table-add-partition, the table is output, and location is input op2Priv.put(HiveOperationType.ALTERTABLE_ADDPARTS, PrivRequirement.newIOPrivRequirement(INS_SEL_DEL_NOGRANT_AR, INS_NOGRANT_AR)); // select with grant for exporting contents op2Priv.put(HiveOperationType.EXPORT, PrivRequirement.newIOPrivRequirement(SEL_GRANT_AR, INS_SEL_DEL_NOGRANT_AR)); // For import statement, require uri rwx+owner privileges on input uri, and // necessary privileges on the output table and database // NOTE : privileges are only checked if the object of that type is marked as part of ReadEntity or WriteEntity // So, if a table is present, Import will mark a table as a WriteEntity, and we'll authorize for that, and if not present, // Import will mark the parent db as a WriteEntity, thus ensuring that we check for table creation privileges. op2Priv.put(HiveOperationType.IMPORT, PrivRequirement.newPrivRequirementList( new PrivRequirement(INS_SEL_DEL_NOGRANT_AR, IOType.INPUT), new PrivRequirement(arr(SQLPrivTypeGrant.INSERT_NOGRANT, SQLPrivTypeGrant.DELETE_NOGRANT), IOType.OUTPUT, null, HivePrivilegeObjectType.TABLE_OR_VIEW), new PrivRequirement(OWNER_PRIV_AR, IOType.OUTPUT, null, HivePrivilegeObjectType.DATABASE))); // Setting REPL DUMP and REPL LOAD as all requiring ADMIN privileges. // We might wind up loosening this in the future, but right now, we do not want // to do individual object based checks on every object possible, and thus, asking // for a broad privilege such as this is the best route forward. REPL STATUS // should use privileges similar to DESCRIBE DB/TABLE, and so, it asks for no // output privileges, and asks for select-no-grant on input. op2Priv.put(HiveOperationType.REPLDUMP, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.REPLLOAD, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.REPLSTATUS, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); adminPrivOps.add(HiveOperationType.REPLDUMP); adminPrivOps.add(HiveOperationType.REPLLOAD); adminPrivOps.add(HiveOperationType.KILL_QUERY); adminPrivOps.add(HiveOperationType.CREATE_RESOURCEPLAN); adminPrivOps.add(HiveOperationType.ALTER_RESOURCEPLAN); adminPrivOps.add(HiveOperationType.DROP_RESOURCEPLAN); adminPrivOps.add(HiveOperationType.SHOW_RESOURCEPLAN); adminPrivOps.add(HiveOperationType.CREATE_TRIGGER); adminPrivOps.add(HiveOperationType.ALTER_TRIGGER); adminPrivOps.add(HiveOperationType.DROP_TRIGGER); adminPrivOps.add(HiveOperationType.CREATE_POOL); adminPrivOps.add(HiveOperationType.ALTER_POOL); adminPrivOps.add(HiveOperationType.DROP_POOL); adminPrivOps.add(HiveOperationType.CREATE_MAPPING); adminPrivOps.add(HiveOperationType.ALTER_MAPPING); adminPrivOps.add(HiveOperationType.DROP_MAPPING); adminPrivOps.add(HiveOperationType.CREATEFUNCTION); adminPrivOps.add(HiveOperationType.DROPFUNCTION); adminPrivOps.add(HiveOperationType.CREATE_SCHEDULED_QUERY); adminPrivOps.add(HiveOperationType.ALTER_SCHEDULED_QUERY); adminPrivOps.add(HiveOperationType.DROP_SCHEDULED_QUERY); // operations require select priv op2Priv.put(HiveOperationType.SHOWCOLUMNS, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); op2Priv.put(HiveOperationType.SHOW_TABLESTATUS, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); op2Priv.put(HiveOperationType.SHOW_TBLPROPERTIES, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); op2Priv.put(HiveOperationType.CREATETABLE_AS_SELECT, PrivRequirement.newPrivRequirementList( new PrivRequirement(SEL_NOGRANT_AR, IOType.INPUT), new PrivRequirement(INS_SEL_DEL_NOGRANT_AR, HivePrivilegeObjectType.DFS_URI), new PrivRequirement(OWNER_PRIV_AR, HivePrivilegeObjectType.DATABASE))); // QUERY,LOAD op can contain an insert & overwrite, // require delete privilege if this is an insert-overwrite op2Priv.put(HiveOperationType.QUERY, arr( new PrivRequirement(SEL_NOGRANT_AR, IOType.INPUT), new PrivRequirement(INS_NOGRANT_AR, IOType.OUTPUT, HivePrivObjectActionType.INSERT), new PrivRequirement( arr(SQLPrivTypeGrant.INSERT_NOGRANT, SQLPrivTypeGrant.DELETE_NOGRANT), IOType.OUTPUT, HivePrivObjectActionType.INSERT_OVERWRITE), new PrivRequirement(DEL_NOGRANT_AR, IOType.OUTPUT, HivePrivObjectActionType.DELETE), new PrivRequirement(UPD_NOGRANT_AR, IOType.OUTPUT, HivePrivObjectActionType.UPDATE), new PrivRequirement(INS_NOGRANT_AR, IOType.OUTPUT, HivePrivObjectActionType.OTHER) ) ); op2Priv.put(HiveOperationType.LOAD, PrivRequirement.newIOPrivRequirement(INS_SEL_DEL_NOGRANT_AR, arr(SQLPrivTypeGrant.INSERT_NOGRANT, SQLPrivTypeGrant.DELETE_NOGRANT))); // show create table is more sensitive information, includes table properties etc // for now require select WITH GRANT op2Priv.put(HiveOperationType.SHOW_CREATETABLE, PrivRequirement.newIOPrivRequirement(SEL_GRANT_AR, null)); op2Priv.put(HiveOperationType.SHOW_CREATEDATABASE, PrivRequirement.newIOPrivRequirement(SEL_GRANT_AR, null)); // for now allow only create-view with 'select with grant' // the owner will also have select with grant privileges on new view op2Priv.put(HiveOperationType.CREATEVIEW, PrivRequirement.newPrivRequirementList( new PrivRequirement(SEL_GRANT_AR, IOType.INPUT), new PrivRequirement(OWNER_PRIV_AR, HivePrivilegeObjectType.DATABASE))); op2Priv.put(HiveOperationType.CREATE_MATERIALIZED_VIEW, PrivRequirement.newPrivRequirementList( new PrivRequirement(SEL_GRANT_AR, IOType.INPUT), new PrivRequirement(OWNER_PRIV_AR, HivePrivilegeObjectType.DATABASE))); op2Priv.put(HiveOperationType.SHOWFUNCTIONS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOWLOCKS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.CREATEFUNCTION, PrivRequirement.newIOPrivRequirement(null, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.DROPFUNCTION, PrivRequirement.newIOPrivRequirement(null, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.RELOADFUNCTION, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.CREATEMACRO, PrivRequirement.newIOPrivRequirement(null, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.DROPMACRO, PrivRequirement.newIOPrivRequirement(null, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.SHOW_COMPACTIONS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOW_TRANSACTIONS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOWCONF, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOWVIEWS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOWMATERIALIZEDVIEWS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.LOCKTABLE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.UNLOCKTABLE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.CREATE_SCHEDULED_QUERY, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.ALTER_SCHEDULED_QUERY, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DROP_SCHEDULED_QUERY, PrivRequirement.newIOPrivRequirement(null, null)); // require db ownership, if there is a file require SELECT , INSERT, and DELETE op2Priv.put(HiveOperationType.CREATETABLE, PrivRequirement.newPrivRequirementList( new PrivRequirement(INS_SEL_DEL_NOGRANT_AR, IOType.INPUT), new PrivRequirement(OWNER_PRIV_AR, HivePrivilegeObjectType.DATABASE))); op2Priv.put(HiveOperationType.ALTERDATABASE, PrivRequirement.newIOPrivRequirement(null, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERDATABASE_OWNER, PrivRequirement.newIOPrivRequirement(null, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.ALTERDATABASE_LOCATION, PrivRequirement.newIOPrivRequirement(null, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.DESCDATABASE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DFS, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.RESET, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.COMPILE, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.ADD, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.DELETE, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, ADMIN_PRIV_AR)); // set command is currently not authorized through the API op2Priv.put(HiveOperationType.SET, PrivRequirement.newIOPrivRequirement(null, null)); // The following actions are authorized through SQLStdHiveAccessController, // and it is not using this privilege mapping, but it might make sense to move it here op2Priv.put(HiveOperationType.CREATEROLE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DROPROLE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GRANT_PRIVILEGE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.REVOKE_PRIVILEGE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOW_GRANT, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GRANT_ROLE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.REVOKE_ROLE, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOW_ROLES, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOW_ROLE_GRANT, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOW_ROLE_PRINCIPALS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GET_CATALOGS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GET_SCHEMAS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GET_TABLES, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GET_FUNCTIONS, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GET_TABLETYPES, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GET_TYPEINFO, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.GET_COLUMNS, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); op2Priv.put(HiveOperationType.START_TRANSACTION, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.COMMIT, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.ROLLBACK, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SET_AUTOCOMMIT, PrivRequirement.newIOPrivRequirement(null, null)); // For alter table exchange partition, we need select & delete on input & insert on output op2Priv.put( HiveOperationType.ALTERTABLE_EXCHANGEPARTITION, PrivRequirement.newIOPrivRequirement( arr(SQLPrivTypeGrant.SELECT_NOGRANT, SQLPrivTypeGrant.DELETE_NOGRANT), INS_NOGRANT_AR)); op2Priv.put(HiveOperationType.ABORT_TRANSACTIONS, PrivRequirement.newIOPrivRequirement(null, null)); // Handled via adminPrivOps (see above). op2Priv.put(HiveOperationType.KILL_QUERY, PrivRequirement.newIOPrivRequirement(null, null)); // llap cluster info does not need admin privilege, since it is read only assigning privilege same as // describe/explain/show commands op2Priv.put(HiveOperationType.LLAP_CLUSTER_INFO, PrivRequirement.newIOPrivRequirement(SEL_NOGRANT_AR, null)); // llap cache purge requires admin privilege as it mutates state (cache) on the cluster op2Priv.put(HiveOperationType.LLAP_CACHE_PURGE, PrivRequirement.newIOPrivRequirement(ADMIN_PRIV_AR, ADMIN_PRIV_AR)); op2Priv.put(HiveOperationType.CREATE_RESOURCEPLAN, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.ALTER_RESOURCEPLAN, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DROP_RESOURCEPLAN, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.SHOW_RESOURCEPLAN, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.CREATE_TRIGGER, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.ALTER_TRIGGER, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DROP_TRIGGER, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.CREATE_POOL, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.ALTER_POOL, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DROP_POOL, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.CREATE_MAPPING, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.ALTER_MAPPING, PrivRequirement.newIOPrivRequirement(null, null)); op2Priv.put(HiveOperationType.DROP_MAPPING, PrivRequirement.newIOPrivRequirement(null, null)); } /** * Convenience method so that creation of this array in PrivRequirement constructor * is not too verbose * * @param grantList * @return grantList */ private static SQLPrivTypeGrant[] arr(SQLPrivTypeGrant... grantList) { return grantList; } /** * Convenience method so that creation of list of PrivRequirement is not too verbose * @param privReqList * @return */ private static List<PrivRequirement> arr(PrivRequirement... privReqList){ return Arrays.asList(privReqList); } /** * Get the privileges required for this operation (hiveOpType) on hive object (hObj) when its * IOType is ioType. Looks at the action type in hObj to find privileges that are applicable * to that action. * * @param hiveOpType * @param hObj * @param ioType * @return */ public static RequiredPrivileges getRequiredPrivs(HiveOperationType hiveOpType, HivePrivilegeObject hObj, IOType ioType) { List<PrivRequirement> opPrivs = op2Priv.get(hiveOpType); Preconditions.checkNotNull(opPrivs, "Privileges for " + hiveOpType + " are null"); RequiredPrivileges reqPrivs = new RequiredPrivileges(); // Find the PrivRequirements that match on IOType, ActionType, and HivePrivilegeObjectType add // the privilege required to reqPrivs for (PrivRequirement opPriv : opPrivs) { if (opPriv.getIOType() != null && opPriv.getIOType() != ioType) { continue; } if (opPriv.getActionType() != null && opPriv.getActionType() != hObj.getActionType()) { continue; } if (opPriv.getObjectType() != null && opPriv.getObjectType() != hObj.getType()) { continue; } reqPrivs.addAll(opPriv.getReqPrivs()); } return reqPrivs; } /** * Some operations are tagged as requiring admin privileges, ignoring any object that * might be checked on it. This check is run in those cases. * * @param hiveOpType * @return */ public static boolean isAdminPrivOperation(HiveOperationType hiveOpType) { return adminPrivOps.contains(hiveOpType); } // for unit tests public static Set<HiveOperationType> getOperationTypes() { return op2Priv.keySet(); } }
{ "content_hash": "34362fc2c489d23b38b1e274511179a8", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 126, "avg_line_length": 56.903420523138834, "alnum_prop": 0.7707294650118454, "repo_name": "vineetgarg02/hive", "id": "9005fa24096aec0c802b62b7482c408fc5021f25", "size": "29086", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ql/src/java/org/apache/hadoop/hive/ql/security/authorization/plugin/sqlstd/Operation2Privilege.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "54376" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "45308" }, { "name": "CSS", "bytes": "5157" }, { "name": "GAP", "bytes": "179697" }, { "name": "HTML", "bytes": "58711" }, { "name": "HiveQL", "bytes": "7606577" }, { "name": "Java", "bytes": "53149057" }, { "name": "JavaScript", "bytes": "43855" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "5261" }, { "name": "PLpgSQL", "bytes": "302587" }, { "name": "Perl", "bytes": "319842" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "408662" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "409" }, { "name": "Shell", "bytes": "299497" }, { "name": "TSQL", "bytes": "2560286" }, { "name": "Thrift", "bytes": "144733" }, { "name": "XSLT", "bytes": "20199" }, { "name": "q", "bytes": "320552" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-directive-isolate-jquery</title> <script src="../../components/jquery-undefined/jquery.js"></script> <script src="../../../angular.js"></script> <script src="script.js"></script> </head> <body ng-app="docsIsolateScopeDirective"> <div ng-controller="Controller"> <my-customer info="naomi"></my-customer> <hr> <my-customer info="igor"></my-customer> </div> </body> </html>
{ "content_hash": "5c6b0623d762b39482e62a42866122c5", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 69, "avg_line_length": 22.136363636363637, "alnum_prop": 0.6447638603696099, "repo_name": "jonahpelfrey/Badgerloop_Competition_Dashboard", "id": "fe543b2179f5b4c26f4ec732982f33f82422cae6", "size": "487", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "log/client/js/angular/docs/examples/example-directive-isolate/index-jquery.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "72559" }, { "name": "HTML", "bytes": "3713227" }, { "name": "JavaScript", "bytes": "506485" }, { "name": "Python", "bytes": "6157" } ], "symlink_target": "" }
<?php namespace Payum\Payex\Action\Api; use Payum\Core\Action\ActionInterface; use Payum\Core\ApiAwareInterface; use Payum\Core\Bridge\Spl\ArrayObject; use Payum\Core\Exception\RequestNotSupportedException; use Payum\Core\Exception\UnsupportedApiException; use Payum\Payex\Api\RecurringApi; use Payum\Payex\Request\Api\CheckRecurringPayment; class CheckRecurringPaymentAction implements ActionInterface, ApiAwareInterface { /** * @var RecurringApi */ protected $api; /** * {@inheritDoc} */ public function setApi($api) { if (false == $api instanceof RecurringApi) { throw new UnsupportedApiException('Expected api must be instance of RecurringApi.'); } $this->api = $api; } /** * {@inheritDoc} */ public function execute($request) { /** @var $request CheckRecurringPayment */ RequestNotSupportedException::assertSupports($this, $request); $model = ArrayObject::ensureArrayObject($request->getModel()); $model->validatedKeysSet(array( 'agreementRef', )); $result = $this->api->check((array) $model); $model->replace($result); } /** * {@inheritDoc} */ public function supports($request) { return $request instanceof CheckRecurringPayment && $request->getModel() instanceof \ArrayAccess ; } }
{ "content_hash": "3ea8b93d92c578211d755cd11098517d", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 96, "avg_line_length": 24, "alnum_prop": 0.63125, "repo_name": "fullpipe/Payum", "id": "c40376eedf2c7a6ce63cdaf0c8b47dccd35bc6c8", "size": "1440", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/Payum/Payex/Action/Api/CheckRecurringPaymentAction.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4453" }, { "name": "PHP", "bytes": "1338541" } ], "symlink_target": "" }
/*********************************************************************************************************************************** Restore Protocol Handler ***********************************************************************************************************************************/ #include "build.auto.h" #include "command/restore/file.h" #include "command/restore/protocol.h" #include "common/debug.h" #include "common/io/io.h" #include "common/log.h" #include "common/memContext.h" #include "config/config.h" #include "storage/helper.h" /**********************************************************************************************************************************/ void restoreFileProtocol(PackRead *const param, ProtocolServer *const server) { FUNCTION_LOG_BEGIN(logLevelDebug); FUNCTION_LOG_PARAM(PACK_READ, param); FUNCTION_LOG_PARAM(PROTOCOL_SERVER, server); FUNCTION_LOG_END(); ASSERT(param != NULL); ASSERT(server != NULL); MEM_CONTEXT_TEMP_BEGIN() { // Restore file const String *const repoFile = pckReadStrP(param); const unsigned int repoIdx = pckReadU32P(param); const CompressType repoFileCompressType = (CompressType)pckReadU32P(param); const time_t copyTimeBegin = pckReadTimeP(param); const bool delta = pckReadBoolP(param); const bool deltaForce = pckReadBoolP(param); const String *const cipherPass = pckReadStrP(param); // Build the file list List *fileList = lstNewP(sizeof(RestoreFile)); while (!pckReadNullP(param)) { RestoreFile file = {.name = pckReadStrP(param)}; file.checksum = pckReadStrP(param); file.size = pckReadU64P(param); file.timeModified = pckReadTimeP(param); file.mode = pckReadModeP(param); file.zero = pckReadBoolP(param); file.user = pckReadStrP(param); file.group = pckReadStrP(param); if (pckReadBoolP(param)) { file.offset = pckReadU64P(param); file.limit = varNewUInt64(pckReadU64P(param)); } file.manifestFile = pckReadStrP(param); lstAdd(fileList, &file); } // Restore files const List *const result = restoreFile( repoFile, repoIdx, repoFileCompressType, copyTimeBegin, delta, deltaForce, cipherPass, fileList); // Return result PackWrite *const resultPack = protocolPackNew(); for (unsigned int resultIdx = 0; resultIdx < lstSize(result); resultIdx++) { const RestoreFileResult *const fileResult = lstGet(result, resultIdx); pckWriteStrP(resultPack, fileResult->manifestFile); pckWriteU32P(resultPack, fileResult->result); } protocolServerDataPut(server, resultPack); protocolServerDataEndPut(server); } MEM_CONTEXT_TEMP_END(); FUNCTION_LOG_RETURN_VOID(); }
{ "content_hash": "713be1d518625adab3518ec8999a6e9c", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 132, "avg_line_length": 35.73809523809524, "alnum_prop": 0.5469686875416389, "repo_name": "pgbackrest/pgbackrest", "id": "8846177f640a2d1b758c5c399c7b17d3ea552bf8", "size": "3002", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/command/restore/protocol.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7935427" }, { "name": "Dockerfile", "bytes": "1467" }, { "name": "M4", "bytes": "8197" }, { "name": "Makefile", "bytes": "9789" }, { "name": "Meson", "bytes": "20192" }, { "name": "Perl", "bytes": "876207" }, { "name": "Shell", "bytes": "15358" } ], "symlink_target": "" }
package com.perm.kate.api; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.TreeMap; import java.util.Map.Entry; public class Params { //TreeMap нужен был чтобы сортировать параметры по имени, сейчас это уже не важно, главно подписывать и передавать параметры в одном и тотм же порядке private TreeMap<String, String> args = new TreeMap<String, String>(); String method_name; public Params(String method_name){ this.method_name=method_name; } public boolean contains(String name){ return args.containsKey(name); } public void put(String param_name, String param_value) { if(param_value==null || param_value.length()==0) return; args.put(param_name, param_value); } public void put(String param_name, Long param_value) { if(param_value==null) return; args.put(param_name, Long.toString(param_value)); } public void put(String param_name, Integer param_value) { if(param_value==null) return; args.put(param_name, Integer.toString(param_value)); } public void putDouble(String param_name, double param_value) { args.put(param_name, Double.toString(param_value)); } public String getParamsString() { String params=""; try { for(Entry<String, String> entry:args.entrySet()){ if(params.length()!=0) params+="&"; params+=(entry.getKey()+"="+URLEncoder.encode(entry.getValue(), "utf-8")); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return params; } }
{ "content_hash": "6ea6df46f0b784178d4a1ddc890d3b01", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 154, "avg_line_length": 31.649122807017545, "alnum_prop": 0.5898004434589801, "repo_name": "romanbrandhall/MyApp", "id": "ea92ea8e1c99019dc48ca7b97f5bffe7c9362f82", "size": "1920", "binary": false, "copies": "2", "ref": "refs/heads/roman", "path": "AndroidVkSdk/src/com/perm/kate/api/Params.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "258933" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" android:layout_margin="8dp" android:layout_above="@+id/adViewContainer"> <Button android:id="@+id/displayInterstitial" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/displayInterstitial" /> <Button android:id="@+id/houseAds" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/houseAds" /> </LinearLayout> <include layout="@layout/ad_view_container" /> </RelativeLayout>
{ "content_hash": "4d67a7beba099402a3cada9ae4b56489", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 120, "avg_line_length": 56.142857142857146, "alnum_prop": 0.7595419847328244, "repo_name": "wskplho/jdroid", "id": "703602a1fff81f5108896521488d204fe7337f85", "size": "786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jdroid-android-sample/src/main/res/layout/ads_fragment.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "22672" }, { "name": "HTML", "bytes": "4607" }, { "name": "Java", "bytes": "1668601" }, { "name": "Shell", "bytes": "20202" } ], "symlink_target": "" }
/********************************************************************************************************* * BRTOS * Brazilian Real-Time Operating System * Acronymous of Basic Real-Time Operating System * * * Open Source RTOS under MIT License * * * * OS Tasks * * * Author: Gustavo Weber Denardin * Revision: 1.0 * Date: 20/03/2009 * *********************************************************************************************************/ #include "hardware.h" void System_Time(void); void Task_2(void); void Task_3(void); void Task_Serial(void); void Transmite_Uptime(void); void Transmite_Duty_Cycle(void); void Transmite_RAM_Ocupada(void); void Transmite_Task_Stacks(void); void Transmite_CPU_Load(void); void Reason_of_Reset(void);
{ "content_hash": "978d7286cde953e3b8bab17c1dcd7895", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 106, "avg_line_length": 28.441176470588236, "alnum_prop": 0.40020682523267836, "repo_name": "brtos/examples", "id": "1ebc3880ee9a8ca5ea8c0d35ba7d18d333a2e0fc", "size": "967", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platforms/atmelstudio_gcc_avr/includes/tasks.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3871" }, { "name": "C", "bytes": "1514659" }, { "name": "C++", "bytes": "257839" }, { "name": "Makefile", "bytes": "33463" }, { "name": "Objective-C", "bytes": "2877" }, { "name": "Shell", "bytes": "426" } ], "symlink_target": "" }
// Code generated by injection-gen. DO NOT EDIT. package interceptor import ( context "context" json "encoding/json" fmt "fmt" v1alpha1 "github.com/tektoncd/triggers/pkg/apis/triggers/v1alpha1" versioned "github.com/tektoncd/triggers/pkg/client/clientset/versioned" triggersv1alpha1 "github.com/tektoncd/triggers/pkg/client/listers/triggers/v1alpha1" zap "go.uber.org/zap" v1 "k8s.io/api/core/v1" equality "k8s.io/apimachinery/pkg/api/equality" errors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" types "k8s.io/apimachinery/pkg/types" sets "k8s.io/apimachinery/pkg/util/sets" record "k8s.io/client-go/tools/record" controller "knative.dev/pkg/controller" kmp "knative.dev/pkg/kmp" logging "knative.dev/pkg/logging" reconciler "knative.dev/pkg/reconciler" ) // Interface defines the strongly typed interfaces to be implemented by a // controller reconciling v1alpha1.Interceptor. type Interface interface { // ReconcileKind implements custom logic to reconcile v1alpha1.Interceptor. Any changes // to the objects .Status or .Finalizers will be propagated to the stored // object. It is recommended that implementors do not call any update calls // for the Kind inside of ReconcileKind, it is the responsibility of the calling // controller to propagate those properties. The resource passed to ReconcileKind // will always have an empty deletion timestamp. ReconcileKind(ctx context.Context, o *v1alpha1.Interceptor) reconciler.Event } // Finalizer defines the strongly typed interfaces to be implemented by a // controller finalizing v1alpha1.Interceptor. type Finalizer interface { // FinalizeKind implements custom logic to finalize v1alpha1.Interceptor. Any changes // to the objects .Status or .Finalizers will be ignored. Returning a nil or // Normal type reconciler.Event will allow the finalizer to be deleted on // the resource. The resource passed to FinalizeKind will always have a set // deletion timestamp. FinalizeKind(ctx context.Context, o *v1alpha1.Interceptor) reconciler.Event } // ReadOnlyInterface defines the strongly typed interfaces to be implemented by a // controller reconciling v1alpha1.Interceptor if they want to process resources for which // they are not the leader. type ReadOnlyInterface interface { // ObserveKind implements logic to observe v1alpha1.Interceptor. // This method should not write to the API. ObserveKind(ctx context.Context, o *v1alpha1.Interceptor) reconciler.Event } type doReconcile func(ctx context.Context, o *v1alpha1.Interceptor) reconciler.Event // reconcilerImpl implements controller.Reconciler for v1alpha1.Interceptor resources. type reconcilerImpl struct { // LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware. reconciler.LeaderAwareFuncs // Client is used to write back status updates. Client versioned.Interface // Listers index properties about resources. Lister triggersv1alpha1.InterceptorLister // Recorder is an event recorder for recording Event resources to the // Kubernetes API. Recorder record.EventRecorder // configStore allows for decorating a context with config maps. // +optional configStore reconciler.ConfigStore // reconciler is the implementation of the business logic of the resource. reconciler Interface // finalizerName is the name of the finalizer to reconcile. finalizerName string // skipStatusUpdates configures whether or not this reconciler automatically updates // the status of the reconciled resource. skipStatusUpdates bool } // Check that our Reconciler implements controller.Reconciler. var _ controller.Reconciler = (*reconcilerImpl)(nil) // Check that our generated Reconciler is always LeaderAware. var _ reconciler.LeaderAware = (*reconcilerImpl)(nil) func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client versioned.Interface, lister triggersv1alpha1.InterceptorLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { // Check the options function input. It should be 0 or 1. if len(options) > 1 { logger.Fatal("Up to one options struct is supported, found: ", len(options)) } // Fail fast when users inadvertently implement the other LeaderAware interface. // For the typed reconcilers, Promote shouldn't take any arguments. if _, ok := r.(reconciler.LeaderAware); ok { logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) } rec := &reconcilerImpl{ LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { all, err := lister.List(labels.Everything()) if err != nil { return err } for _, elt := range all { // TODO: Consider letting users specify a filter in options. enq(bkt, types.NamespacedName{ Namespace: elt.GetNamespace(), Name: elt.GetName(), }) } return nil }, }, Client: client, Lister: lister, Recorder: recorder, reconciler: r, finalizerName: defaultFinalizerName, } for _, opts := range options { if opts.ConfigStore != nil { rec.configStore = opts.ConfigStore } if opts.FinalizerName != "" { rec.finalizerName = opts.FinalizerName } if opts.SkipStatusUpdates { rec.skipStatusUpdates = true } if opts.DemoteFunc != nil { rec.DemoteFunc = opts.DemoteFunc } } return rec } // Reconcile implements controller.Reconciler func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { logger := logging.FromContext(ctx) // Initialize the reconciler state. This will convert the namespace/name // string into a distinct namespace and name, determine if this instance of // the reconciler is the leader, and any additional interfaces implemented // by the reconciler. Returns an error is the resource key is invalid. s, err := newState(key, r) if err != nil { logger.Error("Invalid resource key: ", key) return nil } // If we are not the leader, and we don't implement either ReadOnly // observer interfaces, then take a fast-path out. if s.isNotLeaderNorObserver() { return controller.NewSkipKey(key) } // If configStore is set, attach the frozen configuration to the context. if r.configStore != nil { ctx = r.configStore.ToContext(ctx) } // Add the recorder to context. ctx = controller.WithEventRecorder(ctx, r.Recorder) // Get the resource with this namespace/name. getter := r.Lister.Interceptors(s.namespace) original, err := getter.Get(s.name) if errors.IsNotFound(err) { // The resource may no longer exist, in which case we stop processing and call // the ObserveDeletion handler if appropriate. logger.Debugf("Resource %q no longer exists", key) if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { return del.ObserveDeletion(ctx, types.NamespacedName{ Namespace: s.namespace, Name: s.name, }) } return nil } else if err != nil { return err } // Don't modify the informers copy. resource := original.DeepCopy() var reconcileEvent reconciler.Event name, do := s.reconcileMethodFor(resource) // Append the target method to the logger. logger = logger.With(zap.String("targetMethod", name)) switch name { case reconciler.DoReconcileKind: // Set and update the finalizer on resource if r.reconciler // implements Finalizer. if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { return fmt.Errorf("failed to set finalizers: %w", err) } // Reconcile this copy of the resource and then write back any status // updates regardless of whether the reconciliation errored out. reconcileEvent = do(ctx, resource) case reconciler.DoFinalizeKind: // For finalizing reconcilers, if this resource being marked for deletion // and reconciled cleanly (nil or normal event), remove the finalizer. reconcileEvent = do(ctx, resource) if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { return fmt.Errorf("failed to clear finalizers: %w", err) } case reconciler.DoObserveKind: // Observe any changes to this resource, since we are not the leader. reconcileEvent = do(ctx, resource) } // Synchronize the status. switch { case r.skipStatusUpdates: // This reconciler implementation is configured to skip resource updates. // This may mean this reconciler does not observe spec, but reconciles external changes. case equality.Semantic.DeepEqual(original.Status, resource.Status): // If we didn't change anything then don't call updateStatus. // This is important because the copy we loaded from the injectionInformer's // cache may be stale and we don't want to overwrite a prior update // to status with this stale state. case !s.isLeader: // High-availability reconcilers may have many replicas watching the resource, but only // the elected leader is expected to write modifications. logger.Warn("Saw status changes when we aren't the leader!") default: if err = r.updateStatus(ctx, original, resource); err != nil { logger.Warnw("Failed to update resource status", zap.Error(err)) r.Recorder.Eventf(resource, v1.EventTypeWarning, "UpdateFailed", "Failed to update status for %q: %v", resource.Name, err) return err } } // Report the reconciler event, if any. if reconcileEvent != nil { var event *reconciler.ReconcilerEvent if reconciler.EventAs(reconcileEvent, &event) { logger.Infow("Returned an event", zap.Any("event", reconcileEvent)) r.Recorder.Event(resource, event.EventType, event.Reason, event.Error()) // the event was wrapped inside an error, consider the reconciliation as failed if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { return reconcileEvent } return nil } if controller.IsSkipKey(reconcileEvent) { // This is a wrapped error, don't emit an event. } else if ok, _ := controller.IsRequeueKey(reconcileEvent); ok { // This is a wrapped error, don't emit an event. } else { logger.Errorw("Returned an error", zap.Error(reconcileEvent)) r.Recorder.Event(resource, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) } return reconcileEvent } return nil } func (r *reconcilerImpl) updateStatus(ctx context.Context, existing *v1alpha1.Interceptor, desired *v1alpha1.Interceptor) error { existing = existing.DeepCopy() return reconciler.RetryUpdateConflicts(func(attempts int) (err error) { // The first iteration tries to use the injectionInformer's state, subsequent attempts fetch the latest state via API. if attempts > 0 { getter := r.Client.TriggersV1alpha1().Interceptors(desired.Namespace) existing, err = getter.Get(ctx, desired.Name, metav1.GetOptions{}) if err != nil { return err } } // If there's nothing to update, just return. if equality.Semantic.DeepEqual(existing.Status, desired.Status) { return nil } if diff, err := kmp.SafeDiff(existing.Status, desired.Status); err == nil && diff != "" { logging.FromContext(ctx).Debug("Updating status with: ", diff) } existing.Status = desired.Status updater := r.Client.TriggersV1alpha1().Interceptors(existing.Namespace) _, err = updater.UpdateStatus(ctx, existing, metav1.UpdateOptions{}) return err }) } // updateFinalizersFiltered will update the Finalizers of the resource. // TODO: this method could be generic and sync all finalizers. For now it only // updates defaultFinalizerName or its override. func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1alpha1.Interceptor, desiredFinalizers sets.String) (*v1alpha1.Interceptor, error) { // Don't modify the informers copy. existing := resource.DeepCopy() var finalizers []string // If there's nothing to update, just return. existingFinalizers := sets.NewString(existing.Finalizers...) if desiredFinalizers.Has(r.finalizerName) { if existingFinalizers.Has(r.finalizerName) { // Nothing to do. return resource, nil } // Add the finalizer. finalizers = append(existing.Finalizers, r.finalizerName) } else { if !existingFinalizers.Has(r.finalizerName) { // Nothing to do. return resource, nil } // Remove the finalizer. existingFinalizers.Delete(r.finalizerName) finalizers = existingFinalizers.List() } mergePatch := map[string]interface{}{ "metadata": map[string]interface{}{ "finalizers": finalizers, "resourceVersion": existing.ResourceVersion, }, } patch, err := json.Marshal(mergePatch) if err != nil { return resource, err } patcher := r.Client.TriggersV1alpha1().Interceptors(resource.Namespace) resourceName := resource.Name updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) if err != nil { r.Recorder.Eventf(existing, v1.EventTypeWarning, "FinalizerUpdateFailed", "Failed to update finalizers for %q: %v", resourceName, err) } else { r.Recorder.Eventf(updated, v1.EventTypeNormal, "FinalizerUpdate", "Updated %q finalizers", resource.GetName()) } return updated, err } func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1alpha1.Interceptor) (*v1alpha1.Interceptor, error) { if _, ok := r.reconciler.(Finalizer); !ok { return resource, nil } finalizers := sets.NewString(resource.Finalizers...) // If this resource is not being deleted, mark the finalizer. if resource.GetDeletionTimestamp().IsZero() { finalizers.Insert(r.finalizerName) } // Synchronize the finalizers filtered by r.finalizerName. return r.updateFinalizersFiltered(ctx, resource, finalizers) } func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1alpha1.Interceptor, reconcileEvent reconciler.Event) (*v1alpha1.Interceptor, error) { if _, ok := r.reconciler.(Finalizer); !ok { return resource, nil } if resource.GetDeletionTimestamp().IsZero() { return resource, nil } finalizers := sets.NewString(resource.Finalizers...) if reconcileEvent != nil { var event *reconciler.ReconcilerEvent if reconciler.EventAs(reconcileEvent, &event) { if event.EventType == v1.EventTypeNormal { finalizers.Delete(r.finalizerName) } } } else { finalizers.Delete(r.finalizerName) } // Synchronize the finalizers filtered by r.finalizerName. return r.updateFinalizersFiltered(ctx, resource, finalizers) }
{ "content_hash": "fcb36dd048559f7d5624190d0f01388d", "timestamp": "", "source": "github", "line_count": 415, "max_line_length": 236, "avg_line_length": 35.0578313253012, "alnum_prop": 0.7442435906247852, "repo_name": "tektoncd/triggers", "id": "6a5677aeabf6343776110de0315d74b80d2a8366", "size": "15113", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/client/injection/reconciler/triggers/v1alpha1/interceptor/reconciler.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1081483" }, { "name": "Makefile", "bytes": "5967" }, { "name": "Shell", "bytes": "42793" }, { "name": "Smarty", "bytes": "3940" } ], "symlink_target": "" }
package org.projectodd.vdx.core; public interface Printer { Printer DEFAULT_PRINTER = new Printer() {}; default void printlnErr(String msg) { System.err.println(msg); } default void println(String msg) { System.out.println(msg); } }
{ "content_hash": "b3ac93818e267c56f2ea778a61886439", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 47, "avg_line_length": 17.1875, "alnum_prop": 0.6363636363636364, "repo_name": "projectodd/vdx", "id": "fa9b8ae0c6b4a73a8bac41c87e6af248226fc616", "size": "896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/projectodd/vdx/core/Printer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "25766" }, { "name": "Java", "bytes": "131804" }, { "name": "Ruby", "bytes": "4168" }, { "name": "Shell", "bytes": "914" } ], "symlink_target": "" }
======== Glossary ======== .. glossary:: filtered term A query term consisting of an explicit filter name and an argument, like ``regexp:hi|hello`` or ``callers:frob`` index A folder containing one or more source trees indexed for search and prepared to serve as HTML. Indices are created by the :program:`dxr-index.py` command. instance See :term:`index`. term A space-delimited part of a query text term A query term without an explicit filter name, interpreted as raw text for a substring search
{ "content_hash": "52e7fcf0ac83cc7ede4ad6fd3fe4b96a", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 77, "avg_line_length": 24.833333333333332, "alnum_prop": 0.6308724832214765, "repo_name": "nrc/dxr", "id": "e1f40c1a6aa74954ba9ac072a211efe8930616f9", "size": "596", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/source/glossary.rst", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "719" }, { "name": "C++", "bytes": "63422" }, { "name": "CSS", "bytes": "23016" }, { "name": "HTML", "bytes": "43487" }, { "name": "JavaScript", "bytes": "47312" }, { "name": "Makefile", "bytes": "6445" }, { "name": "Python", "bytes": "313502" }, { "name": "Shell", "bytes": "2921" } ], "symlink_target": "" }
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 for-comment"> <h3>Comment</h3> <hr/> <div id="comment-list"> <?php foreach($post_comment as $data){ $member_image = ($data['member_image'] ? $data['member_image'] : 'no-img-profil.png'); ?> <div class="post-item" style="margin-top: 15px;"> <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1 nopadding"> <img class="img-circle post-img" src="<?php echo base_url().'uploadfiles/member-images/'.$member_image; ?>"> </div> <div class="col-lg-11 col-md-11 col-sm-11 col-xs-11"> <a href="<?php echo base_url().'member/profile/'.md5($data['member_id']); ?>" class="url-color"><h4><?php echo $data['member_name']; ?></h4></a> <span class="long-time" title="<?php echo $data['comment_created']; ?>"><?php echo $data['long_time']; ?></span> <hr/> <p> <?php echo $data['comment_description']; ?> </p> </div> <div class="clearfix"> </div> </div> <?php } ?> <div id="new_member_post_comment"></div> </div> <div class="write-comment"> <textarea class="form-control" onkeyup="textAreaAdjust(this)" style="overflow:hidden" name="new_post_comment" id="new_post_comment" placeholder="Write a comment . . ."></textarea> <input type="hidden"> </div> </div> <script type="text/javascript"> $('#new_post_comment').on('keydown', function(e){ if(!e.shiftKey && e.which == 13){ $.post(base_url + "social/add_new_comment", { new_post_comment: $(this).val(), post_id: '<?php echo $post_id; ?>' }, function(data,status){ data = $.parseJSON(data); if(data.status == 1){ emit_new_notif($.parseJSON(data.data_notif), $.parseJSON(data.data_count_notif)); document.getElementById('new_post_comment').style.height = "inherit"; document.getElementById('comment-content').style.height = "inherit"; $("#new_member_post_comment").append(data.data_html); $('#new_post_comment').val(''); } }); } }); function textAreaAdjust(o) { o.style.height = "1px"; document.getElementById('comment-content').style.height = "1px"; o.style.height = (25+o.scrollHeight)+"px"; document.getElementById('comment-content').style.height = (document.getElementById('comment-content').scrollHeight)+"px"; } </script> <button title="Close (Esc)" type="button" class="mfp-close">×</button>
{ "content_hash": "1a173f7a9dc239bd5ecaf8f1dac2256c", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 181, "avg_line_length": 39.101694915254235, "alnum_prop": 0.6302557433896836, "repo_name": "aldenaoktavian/futsalsocial", "id": "bec7daae785f6caac88ae44bf07dfed9c20ee70c", "size": "2308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "social/application/views/comment.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "765" }, { "name": "CSS", "bytes": "1467979" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "HTML", "bytes": "186784" }, { "name": "JavaScript", "bytes": "8477120" }, { "name": "PHP", "bytes": "4301586" }, { "name": "PLpgSQL", "bytes": "158136" }, { "name": "PowerShell", "bytes": "468" }, { "name": "Shell", "bytes": "444" } ], "symlink_target": "" }
#if !__has_feature(objc_arc) #error "This source file must be compiled with ARC enabled!" #endif #import "SBJsonWriter.h" #import "SBJsonStreamWriter.h" #import "SBJsonStreamWriterAccumulator.h" @interface SBJsonWriter () @property (copy) NSString *error; @end @implementation SBJsonWriter @synthesize sortKeys; @synthesize humanReadable; @synthesize error; @synthesize maxDepth; @synthesize sortKeysComparator; - (id)init { self = [super init]; if (self) { self.maxDepth = 32u; } return self; } - (NSString*)stringWithObject:(id)value { NSData *data = [self dataWithObject:value]; if (data) return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return nil; } - (NSData*)dataWithObject:(id)object { self.error = nil; SBJsonStreamWriterAccumulator *accumulator = [[SBJsonStreamWriterAccumulator alloc] init]; SBJsonStreamWriter *streamWriter = [[SBJsonStreamWriter alloc] init]; streamWriter.sortKeys = self.sortKeys; streamWriter.maxDepth = self.maxDepth; streamWriter.sortKeysComparator = self.sortKeysComparator; streamWriter.humanReadable = self.humanReadable; streamWriter.delegate = accumulator; BOOL ok = NO; if ([object isKindOfClass:[NSDictionary class]]) ok = [streamWriter writeObject:object]; else if ([object isKindOfClass:[NSArray class]]) ok = [streamWriter writeArray:object]; else if ([object respondsToSelector:@selector(proxyForJson)]) return [self dataWithObject:[object proxyForJson]]; else { self.error = @"Not valid type for JSON"; return nil; } if (ok) return accumulator.data; self.error = streamWriter.error; return nil; } @end
{ "content_hash": "cf7201930441d1490f6787a00ee50116", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 94, "avg_line_length": 22.17105263157895, "alnum_prop": 0.7264094955489614, "repo_name": "KingfishDevelopment/iOS-Contributors", "id": "34e4db49120f35eff4215eac732a23ef7023d921", "size": "3198", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "src/SBJson/SBJsonWriter.m", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "3485" } ], "symlink_target": "" }
{% extends "layout.html" %} {% block page_title %} Claim type {% endblock %} {% block content %} <main id="content" role="main"> <div class="phase-banner"> <p> <strong class="phase-tag">BETA</strong> <span>This is a new service – your <a href="#">feedback</a> will help us to improve it.</span> </p> </div> <form class="form" method="post"> <h1 class="form-title heading-large">What are you claiming for?</h1> <fieldset class="form-group"> <!-- <legend class="form-label-bold" for="claim">What are you claiming for?</legend> --> <label class="block-label" for="radio-inline-1"> <input id="radio-inline-1" type="radio" name="claimtype" value="Travel"> Travel </label> <label class="block-label" for="radio-inline-2"> <input id="radio-inline-2" type="radio" name="claimtype" value="Oneoff"> Equipment or adaptation </label> <label class="block-label" for="radio-inline-3"> <input id="radio-inline-3" type="radio" name="claimtype" value="Support"> Support work </label> </fieldset> <div class="form-group"> <input type="submit" class="button" value="Continue"> </div> </main> {% endblock %}
{ "content_hash": "efe672ea8d1bd50141924b20d2a4abca", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 102, "avg_line_length": 27.085106382978722, "alnum_prop": 0.5868028279654359, "repo_name": "dwpdigitaltech/accesstowork-phase2", "id": "97cf8fe7d8024caef77f571f84e2f00c61a078c0", "size": "1275", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/views/payments-v1/claim-type.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "65259" }, { "name": "HTML", "bytes": "1233520" }, { "name": "JavaScript", "bytes": "73028" }, { "name": "Shell", "bytes": "1495" } ], "symlink_target": "" }
'use strict'; var io = require('socket.io'), AgentManagerEventEnum = require('siebogjs-common').enums.AgentManagerEventEnum, MessageTypeEnum = require('siebogjs-common').enums.MessageTypeEnum; module.exports = function (server, messageManager) { var ws = io(server); ws.of('console') .on('connection', function (socket) { messageManager.handleMessage(MessageTypeEnum.GET_RUNNING_AGENTS, function (msg) { socket.emit('running', msg); }); messageManager.on(MessageTypeEnum.LOG, function (msg) { socket.emit('log', msg); }); messageManager.on(AgentManagerEventEnum.NEW_AGENT, function (aid) { socket.emit('newAgent', aid); }); messageManager.on(AgentManagerEventEnum.REMOVED_AGENT, function (aid) { socket.emit('removeAgent', aid); }); }); };
{ "content_hash": "7be4a2f02d2734e96dd3ce8b420bd13c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 93, "avg_line_length": 30.322580645161292, "alnum_prop": 0.5904255319148937, "repo_name": "SiebogJS/RestWS", "id": "83e9c12c2b621d862d3eea9dd6038bca70519d25", "size": "940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/ws.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4446" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE Test SYSTEM "test.dtd"> <!-- Author: Alexander D. Shipilov Version: $Revision: 1.3 $ --> <Test ID="idiv0401" date-of-creation="2005-01-20" timeout="1" > <Author value="Alexander D. Shipilov"/> <Description> Tests idiv java virtual machine instruction. Value2 contains min value. Covered assertions assert_instr26a099 assert_instr26a100 assert_instr26a101 assert_instr26a102 assert_instr26a103 </Description> <Source name="idiv0401p.j"/> <Runner ID="Runtime"> <Param name="toRun" value="org.apache.harmony.vts.test.vm.jvms.instructions.arithm.idiv.idiv04.idiv0401.idiv0401p"/> </Runner> </Test>
{ "content_hash": "441f9649d1afe4bf6e13075f5928adf5", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 120, "avg_line_length": 32.78048780487805, "alnum_prop": 0.7217261904761905, "repo_name": "freeVM/freeVM", "id": "454bfade6796eddc32384d1b428b0d8d77353417", "size": "1344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "enhanced/buildtest/tests/vts/vm/src/test/vm/jvms/instructions/arithm/idiv/idiv04/idiv0401/idiv0401.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "116828" }, { "name": "C", "bytes": "17860389" }, { "name": "C++", "bytes": "19007206" }, { "name": "CSS", "bytes": "217777" }, { "name": "Java", "bytes": "152108632" }, { "name": "Objective-C", "bytes": "106412" }, { "name": "Objective-J", "bytes": "11029421" }, { "name": "Perl", "bytes": "305690" }, { "name": "Scilab", "bytes": "34" }, { "name": "Shell", "bytes": "153821" }, { "name": "XSLT", "bytes": "152859" } ], "symlink_target": "" }
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.belongs_to :consumer t.string :email t.string :external_id t.string :name t.timestamps end end end
{ "content_hash": "b47e5742f60f5592f2725220e51c5162", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 43, "avg_line_length": 20.454545454545453, "alnum_prop": 0.6355555555555555, "repo_name": "flxw/codeocean", "id": "bfec23fabfcbe4fff15daab4efa23ed567f51d89", "size": "225", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "db/migrate/20140701122345_create_users.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "3588" }, { "name": "HTML", "bytes": "63810" }, { "name": "Java", "bytes": "1550" }, { "name": "JavaScript", "bytes": "44865" }, { "name": "Makefile", "bytes": "314" }, { "name": "Nginx", "bytes": "1197" }, { "name": "Python", "bytes": "531" }, { "name": "Ruby", "bytes": "339017" } ], "symlink_target": "" }
 #pragma once #include <aws/docdb/DocDB_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/docdb/model/ResponseMetadata.h> #include <aws/docdb/model/GlobalCluster.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Xml { class XmlDocument; } // namespace Xml } // namespace Utils namespace DocDB { namespace Model { class AWS_DOCDB_API DescribeGlobalClustersResult { public: DescribeGlobalClustersResult(); DescribeGlobalClustersResult(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); DescribeGlobalClustersResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result); /** * <p/> */ inline const Aws::String& GetMarker() const{ return m_marker; } /** * <p/> */ inline void SetMarker(const Aws::String& value) { m_marker = value; } /** * <p/> */ inline void SetMarker(Aws::String&& value) { m_marker = std::move(value); } /** * <p/> */ inline void SetMarker(const char* value) { m_marker.assign(value); } /** * <p/> */ inline DescribeGlobalClustersResult& WithMarker(const Aws::String& value) { SetMarker(value); return *this;} /** * <p/> */ inline DescribeGlobalClustersResult& WithMarker(Aws::String&& value) { SetMarker(std::move(value)); return *this;} /** * <p/> */ inline DescribeGlobalClustersResult& WithMarker(const char* value) { SetMarker(value); return *this;} /** * <p/> */ inline const Aws::Vector<GlobalCluster>& GetGlobalClusters() const{ return m_globalClusters; } /** * <p/> */ inline void SetGlobalClusters(const Aws::Vector<GlobalCluster>& value) { m_globalClusters = value; } /** * <p/> */ inline void SetGlobalClusters(Aws::Vector<GlobalCluster>&& value) { m_globalClusters = std::move(value); } /** * <p/> */ inline DescribeGlobalClustersResult& WithGlobalClusters(const Aws::Vector<GlobalCluster>& value) { SetGlobalClusters(value); return *this;} /** * <p/> */ inline DescribeGlobalClustersResult& WithGlobalClusters(Aws::Vector<GlobalCluster>&& value) { SetGlobalClusters(std::move(value)); return *this;} /** * <p/> */ inline DescribeGlobalClustersResult& AddGlobalClusters(const GlobalCluster& value) { m_globalClusters.push_back(value); return *this; } /** * <p/> */ inline DescribeGlobalClustersResult& AddGlobalClusters(GlobalCluster&& value) { m_globalClusters.push_back(std::move(value)); return *this; } inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; } inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; } inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); } inline DescribeGlobalClustersResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;} inline DescribeGlobalClustersResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;} private: Aws::String m_marker; Aws::Vector<GlobalCluster> m_globalClusters; ResponseMetadata m_responseMetadata; }; } // namespace Model } // namespace DocDB } // namespace Aws
{ "content_hash": "a74f31931c03cc714ba892bdcb35a5c4", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 149, "avg_line_length": 26.60902255639098, "alnum_prop": 0.6722237920316474, "repo_name": "awslabs/aws-sdk-cpp", "id": "9eaf632923fd4d6f45b9c2b3d69273855a8297b4", "size": "3658", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-cpp-sdk-docdb/include/aws/docdb/model/DescribeGlobalClustersResult.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7596" }, { "name": "C++", "bytes": "61740540" }, { "name": "CMake", "bytes": "337520" }, { "name": "Java", "bytes": "223122" }, { "name": "Python", "bytes": "47357" } ], "symlink_target": "" }
Deface::Override.new(:virtual_path => 'spree/layouts/admin' , :insert_bottom => "[data-hook='admin_tabs'], #admin_tabs[data-hook]", :text => "<%= tab :subscriptions %>", :name => "subscriptions_admin_tab", :disabled => false)
{ "content_hash": "65339b34017071b36b440735ed48991c", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 90, "avg_line_length": 62, "alnum_prop": 0.4806451612903226, "repo_name": "sheenobu/spree_recurring", "id": "ddb2396765446719c721a5eaf414c469016eeb4f", "size": "310", "binary": false, "copies": "1", "ref": "refs/heads/1.2-dev", "path": "app/overrides/subscriptions_admin_tab.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "198" }, { "name": "JavaScript", "bytes": "205" }, { "name": "Ruby", "bytes": "21921" } ], "symlink_target": "" }
<!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_152-release) on Mon Dec 04 23:07:54 MST 2017 --> <title>ListSortingHelper</title> <meta name="date" content="2017-12-04"> <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="ListSortingHelper"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9,"i2":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/ImageHelper.html" title="class in com.cmput301f17t11.cupofjava.Controllers"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/OfflineStateHandler.html" title="class in com.cmput301f17t11.cupofjava.Controllers"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/cmput301f17t11/cupofjava/Controllers/ListSortingHelper.html" target="_top">Frames</a></li> <li><a href="ListSortingHelper.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.cmput301f17t11.cupofjava.Controllers</div> <h2 title="Class ListSortingHelper" class="title">Class ListSortingHelper</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.cmput301f17t11.cupofjava.Controllers.ListSortingHelper</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">ListSortingHelper</span> extends java.lang.Object</pre> <div class="block">This helper class has static methods that accepts arraylists, and returns the array list sorted in different ways. An example is a reverse chronological ordering of HabitEvents</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/ListSortingHelper.html#ListSortingHelper--">ListSortingHelper</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/ListSortingHelper.html#alphabeticalTitleSort-java.util.ArrayList-">alphabeticalTitleSort</a></span>(java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;habitEvents)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/ListSortingHelper.html#chronologicalSort-java.util.ArrayList-">chronologicalSort</a></span>(java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;habitEvents)</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>static java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/ListSortingHelper.html#reverseChronological-java.util.ArrayList-">reverseChronological</a></span>(java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;habitEvents)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ListSortingHelper--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ListSortingHelper</h4> <pre>public&nbsp;ListSortingHelper()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="chronologicalSort-java.util.ArrayList-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>chronologicalSort</h4> <pre>public static&nbsp;java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;chronologicalSort(java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;habitEvents)</pre> </li> </ul> <a name="reverseChronological-java.util.ArrayList-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>reverseChronological</h4> <pre>public static&nbsp;java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;reverseChronological(java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;habitEvents)</pre> </li> </ul> <a name="alphabeticalTitleSort-java.util.ArrayList-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>alphabeticalTitleSort</h4> <pre>public static&nbsp;java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;alphabeticalTitleSort(java.util.ArrayList&lt;<a href="../../../../com/cmput301f17t11/cupofjava/Models/HabitEvent.html" title="class in com.cmput301f17t11.cupofjava.Models">HabitEvent</a>&gt;&nbsp;habitEvents)</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> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/ImageHelper.html" title="class in com.cmput301f17t11.cupofjava.Controllers"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/cmput301f17t11/cupofjava/Controllers/OfflineStateHandler.html" title="class in com.cmput301f17t11.cupofjava.Controllers"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/cmput301f17t11/cupofjava/Controllers/ListSortingHelper.html" target="_top">Frames</a></li> <li><a href="ListSortingHelper.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "3b4845cc769eb1a4d7d186245ea72a5e", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 421, "avg_line_length": 43.013422818791945, "alnum_prop": 0.6715556249024809, "repo_name": "CMPUT301F17T11/CupOfJava", "id": "81e28327e1de0381593b27ab83f273016866aa78", "size": "12818", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/com/cmput301f17t11/cupofjava/Controllers/ListSortingHelper.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "231799" } ], "symlink_target": "" }
from __future__ import absolute_import import celery import kombu import os import platform as _platform from celery import datastructures from celery import platforms from celery.utils.text import pretty from celery.utils.imports import qualname from .defaults import find SETTINGS_INFO = """%s %s""" BUGREPORT_INFO = """ software -> celery:%(celery_v)s kombu:%(kombu_v)s py:%(py_v)s platform -> system:%(system)s arch:%(arch)s imp:%(py_i)s loader -> %(loader)s settings -> transport:%(transport)s results:%(results)s %(human_settings)s """ class Settings(datastructures.ConfigurationView): @property def CELERY_RESULT_BACKEND(self): """Resolves deprecated alias ``CELERY_BACKEND``.""" return self.first("CELERY_RESULT_BACKEND", "CELERY_BACKEND") @property def BROKER_TRANSPORT(self): """Resolves compat aliases :setting:`BROKER_BACKEND` and :setting:`CARROT_BACKEND`.""" return self.first("BROKER_TRANSPORT", "BROKER_BACKEND", "CARROT_BACKEND") @property def BROKER_BACKEND(self): """Deprecated compat alias to :attr:`BROKER_TRANSPORT`.""" return self.BROKER_TRANSPORT @property def BROKER_HOST(self): return (os.environ.get("CELERY_BROKER_URL") or self.first("BROKER_URL", "BROKER_HOST")) def without_defaults(self): # the last stash is the default settings, so just skip that return Settings({}, self._order[:-1]) def find_value_for_key(self, name, namespace="celery"): return self.get_by_parts(*self.find_option(name, namespace)[:-1]) def find_option(self, name, namespace="celery"): return find(name, namespace) def get_by_parts(self, *parts): return self["_".join(filter(None, parts))] def humanize(self): return "\n".join(SETTINGS_INFO % (key + ':', pretty(value, width=50)) for key, value in self.without_defaults().iteritems()) class AppPickler(object): """Default application pickler/unpickler.""" def __call__(self, cls, *args): kwargs = self.build_kwargs(*args) app = self.construct(cls, **kwargs) self.prepare(app, **kwargs) return app def prepare(self, app, **kwargs): app.conf.update(kwargs["changes"]) def build_kwargs(self, *args): return self.build_standard_kwargs(*args) def build_standard_kwargs(self, main, changes, loader, backend, amqp, events, log, control, accept_magic_kwargs): return dict(main=main, loader=loader, backend=backend, amqp=amqp, changes=changes, events=events, log=log, control=control, set_as_current=False, accept_magic_kwargs=accept_magic_kwargs) def construct(self, cls, **kwargs): return cls(**kwargs) def _unpickle_app(cls, pickler, *args): return pickler()(cls, *args) def bugreport(app): return BUGREPORT_INFO % {"system": _platform.system(), "arch": _platform.architecture(), "py_i": platforms.pyimplementation(), "celery_v": celery.__version__, "kombu_v": kombu.__version__, "py_v": _platform.python_version(), "transport": app.conf.BROKER_TRANSPORT, "results": app.conf.CELERY_RESULT_BACKEND, "human_settings": app.conf.humanize(), "loader": qualname(app.loader.__class__)}
{ "content_hash": "544a5574adb90c9955a6252d202f8b47", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 77, "avg_line_length": 32.763636363636365, "alnum_prop": 0.5979467258601554, "repo_name": "couchbaselabs/celery", "id": "00a97a82ff33929bd5be6c71c091aef6fd479d1a", "size": "3604", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "celery/app/utils.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php namespace Opis\View\Test; use Opis\View\ViewRenderer; use Opis\View\IEngine; class ViewsTest extends \PHPUnit\Framework\TestCase { /** @var \Opis\View\ViewRenderer */ protected $renderer; public function setUp() { $this->renderer = new ViewRenderer(); } public function testResolve() { $this->renderer->handle('foo', function () { return 'bar'; }); $this->assertEquals('bar', $this->renderer->resolveViewName('foo')); } public function testResolveMissing() { $this->assertEquals(null, $this->renderer->resolveViewName('missing')); } public function testResolveMultiple() { $this->renderer->handle('foo', function () { return 'bar'; }); $this->renderer->handle('foo', function () { return 'baz'; }); $this->renderer->handle('foo', function () { return 'qux'; }); $this->assertEquals('qux', $this->renderer->resolveViewName('foo')); } public function testResolvePriority() { $this->renderer->handle('foo', function () { return 'bar'; }, 1); $this->renderer->handle('foo', function () { return 'baz'; }); $this->assertEquals('bar', $this->renderer->resolveViewName('foo')); } public function testEngine() { $this->renderer->getEngineResolver()->register(function () { return new ViewEngine1(); }); $this->renderer->handle('foo', function () { return 'bar'; }); $this->assertEquals('BAR', $this->renderer->renderView('foo')); } public function testEnginePriority1() { $this->renderer->getEngineResolver()->register(function () { return new ViewEngine1(); }); $this->renderer->getEngineResolver()->register(function () { return new ViewEngine2(); }); $this->renderer->handle('foo', function () { return 'bar'; }); $this->assertEquals('BAR!', $this->renderer->renderView('foo')); } public function testEnginePriority2() { $this->renderer->getEngineResolver()->register(function () { return new ViewEngine1(); }, 1); $this->renderer->getEngineResolver()->register(function () { return new ViewEngine2(); }); $this->renderer->handle('foo', function () { return 'bar'; }); $this->assertEquals('BAR', $this->renderer->renderView('foo')); } public function testRenderMethod1() { $this->assertEquals('foo', $this->renderer->render('foo')); } }
{ "content_hash": "8a6a3cebf8db29ae4969ded4a0b20a52", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 79, "avg_line_length": 24.105263157894736, "alnum_prop": 0.5393013100436681, "repo_name": "opis/view", "id": "18ced22d0770e86042f4519d3d23ea66418715fa", "size": "3500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/ViewsTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "26219" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <!-- adopted from `github.com/madrobby/zepto` and modified --> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>jQTouch’s touch unit tests</title> <link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css" type="text/css" media="screen"> <script type="text/javascript" src="http://code.jquery.com/qunit/qunit-git.js"></script> <script src="../../../build/lib/jquery/jquery-1.7.js"></script> <script src="../../../build/src/jqt.js"></script> <script src="../../../build/src/jqtouch-jquery.js"></script> </head> <body> <h1 id="qunit-header">jQTouch's touch unit tests</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <style> #test { position: absolute; left: 0; top: 0; width: 100px; height: 50px; } </style> <script src="test-touch.js"></script> </body> </html>
{ "content_hash": "68a67efcbacb11db4826d6e4a8e4b3f4", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 106, "avg_line_length": 29.742857142857144, "alnum_prop": 0.6176753121998079, "repo_name": "illucent/jQTouch", "id": "96edd3cbe5cafcb8e84347fda6535b9a0cd44633", "size": "1043", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "test/unit/touch/jquery-jqtouch.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "37" }, { "name": "CSS", "bytes": "99607" }, { "name": "CoffeeScript", "bytes": "38704" }, { "name": "HTML", "bytes": "107901" }, { "name": "JavaScript", "bytes": "62456" }, { "name": "PHP", "bytes": "1090" }, { "name": "Ruby", "bytes": "589" } ], "symlink_target": "" }
<!-- HTML header for doxygen 1.8.13--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>MTB CAT1 Peripheral driver library: Clock Trim (ILO, PILO)</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen_style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><a href="http://www.cypress.com/"><img alt="Logo" src="IFXCYP_one-line.png"/></a></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">MTB CAT1 Peripheral driver library</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('group__group__sysclk__trim.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#groups">API Reference</a> </div> <div class="headertitle"> <div class="title">Clock Trim (ILO, PILO)<div class="ingroups"><a class="el" href="group__group__sysclk.html">SysClk (System Clock)</a></div></div> </div> </div><!--header--> <div class="contents"> <a name="details" id="details"></a><h2 class="groupheader">General Description</h2> <p>These functions perform a single trim operation on the ILO or PILO. </p> <p>Each function's parameter is the actual frequency of the clock. To measure the frequency, use the functions described in the <a class="el" href="group__group__sysclk__calclk.html">Clock Measurement</a> API.</p> <p>To trim the clock as close as possible to the target frequency, multiple calls to the trim function may be needed. A typical usage example is to:</p><ol type="1"> <li>Call the clock measurement functions to get the actual frequency of the clock</li> <li>Call the trim function, passing in the measured frequency</li> <li>Repeat the above until the trim function reports that the clock is trimmed to within limits. </li> </ol> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="groups"></a> API Reference</h2></td></tr> <tr class="memitem:group__group__sysclk__trim__funcs"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__group__sysclk__trim__funcs.html">Functions</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part <div id="nav-path" class="navpath"> <ul> <li class="footer"> Generated for <b>MTB CAT1 Peripheral driver library</b> by <b>Cypress Semiconductor Corporation</b>. All rights reserved. </li> </ul> </div> --> </body> </html>
{ "content_hash": "0c15f4cc18253cce3c6b37b5935456ec", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 240, "avg_line_length": 43.69827586206897, "alnum_prop": 0.6808048924837246, "repo_name": "Infineon/mtb-pdl-cat1", "id": "fa196b97f4d654d6ca41ff6a8461c27e2ebcaf2c", "size": "5069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/pdl_api_reference_manual/html/group__group__sysclk__trim.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "16538" }, { "name": "C", "bytes": "45610434" }, { "name": "Tcl", "bytes": "58782" } ], "symlink_target": "" }
<?php namespace common\models; use Yii; use yii\db\ActiveRecord; use common\base\BaseActiveRecord; /** * 文章数据操作类 */ class Article extends BaseActiveRecord { private static $_instance; public static function tableName(){ return 'ligao_article'; } public static function getInstance(){ if(!(self::$_instance instanceof self)){ self::$_instance = new self; } return self::$_instance; } /** * 添加文章 * [addArticle description] */ public static function addArticle($postdata=null){ if($postdata == null){ return false; } $map['title'] = $postdata['title']; } } ?>
{ "content_hash": "47793b461bd10f95f0eae2b9e6e6bf2b", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 52, "avg_line_length": 13.306122448979592, "alnum_prop": 0.6104294478527608, "repo_name": "gaoxuxu123/phpblog", "id": "740042c27a93bcbc36d0dcaa18d08546dc4d06d6", "size": "674", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/models/Article.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "611215" }, { "name": "HTML", "bytes": "520680" }, { "name": "JavaScript", "bytes": "2199317" }, { "name": "PHP", "bytes": "193148" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <workflow-app xmlns="uri:oozie:workflow:0.1" name="test-wf"> <start to="a1234567890123456789012345678901234567890123456789x"/> <end name="a1234567890123456789012345678901234567890123456789x"/> </workflow-app>
{ "content_hash": "b0dde59f4b25223d7850a3e6b55d40fc", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 74, "avg_line_length": 48.23809523809524, "alnum_prop": 0.7680157946692991, "repo_name": "terrancesnyder/oozie-hadoop2", "id": "a8e939f475d7122835089ed93eb3e29d3a808f1e", "size": "1013", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/test/resources/wf-schema-action-name-too-long.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "26164" }, { "name": "Java", "bytes": "6812525" }, { "name": "JavaScript", "bytes": "136888" }, { "name": "Shell", "bytes": "43020" }, { "name": "XSLT", "bytes": "1366" } ], "symlink_target": "" }
FROM debian:sid MAINTAINER Christian Koep <christian.koep@fom-net.de> ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && apt-get install -y \ keepass2 \ xdotool \ --no-install-recommends \ && rm -rf /var/lib/apt/lists/* ENTRYPOINT ["/usr/bin/keepass2"]
{ "content_hash": "23873271d998c3b25247dbec5ced276f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 53, "avg_line_length": 22.166666666666668, "alnum_prop": 0.7255639097744361, "repo_name": "saneax/dockerfiles", "id": "dfe59b8df63fae0f4652236474807e85a67d2054", "size": "879", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "keepass2/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "323" }, { "name": "Nginx", "bytes": "3121" }, { "name": "Python", "bytes": "7607" }, { "name": "Shell", "bytes": "24323" } ], "symlink_target": "" }
package com.scheible.risingempire.game.core; import com.scheible.risingempire.game.common.command.Command; import com.scheible.risingempire.game.core.fleet.Fleet; import com.scheible.risingempire.game.core.star.Colony; import com.scheible.risingempire.game.core.star.Star; import com.scheible.risingempire.game.common.view.View; import com.scheible.risingempire.game.ai.Ai; import com.scheible.risingempire.game.ai.FleetSendingAi; import com.scheible.risingempire.game.core.event.Event; import com.scheible.risingempire.game.core.event.RandomMessageEvent; import com.scheible.risingempire.game.core.fleet.Fleets; import com.scheible.risingempire.game.core.star.Star.Prototype; import com.scheible.risingempire.game.core.star.Stars; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; /** * * @author sj */ public class Universe { private final static List<Prototype> STAR_PROTOTYPES = Arrays.asList(new Prototype("Tesh", 100,80), new Prototype("Dolz", 280,100), new Prototype("Alaozar", 460,60), new Prototype("Nagar", 640,40), new Prototype("Praecipua", 200, 200), new Prototype("Kled", 540, 180), new Prototype("Balin", 380, 240), new Prototype("Trigon", 700, 200), new Prototype("Uxnai", 100, 340), new Prototype("Draconis", 260, 340), new Prototype("Sagan", 580, 300), new Prototype("Hut", 440, 380), new Prototype("Burin", 160, 480), new Prototype("Proctor", 320, 460), new Prototype("Pesci", 720, 400), new Prototype("Seki", 500, 480), new Prototype("Tycho", 660, 520)); private int fleedId = 100; private int turn = 0; private final List<Leader> leaders = new ArrayList<>(); private final Map<Leader, Ai> aiLeaders = new HashMap<>(); private final Stars stars = new Stars(); private final Fleets fleets = new Fleets(); private final Map<Leader, List<Command>> leaderCommands = new HashMap<>(); private final List<Event> events = new ArrayList<>(); public Universe() { for(Prototype prototype : STAR_PROTOTYPES) { stars.add(new Star(prototype.getName(), prototype.getLocation(), Optional.empty())); } } public void register(Leader leader) { register(leader, false); } public void addAi(Leader leader) { register(leader, true); } private void register(Leader leader, boolean isAi) { if(leaders.contains(leader)) { throw new IllegalStateException("Leader is already registered!"); } Star removedStar = getRandomUncolonizedStar(); stars.remove(removedStar); Star home = new Star(leader.getHomeStar(), removedStar.getLocation(), Optional.of(new Colony(leader, 40))); stars.add(home); fleets.add(new Fleet(fleedId++, leader, home)); leaders.add(leader); if(isAi) { aiLeaders.put(leader, new FleetSendingAi()); } } private Star getRandomUncolonizedStar() { Random random = new Random(); Star result = null; while(result == null) { Star star = stars.get(random.nextInt(stars.size())); if(!star.getColony().isPresent()) { result = star; } } return result; } public List<Leader> getLeaders() { return leaders; } public boolean isAi(Leader leader) { return aiLeaders.containsKey(leader); } public Map<Leader, Boolean> getTurnFinishInfo() { Map<Leader, Boolean> result = new HashMap<>(); for(Leader leader : leaders) { if(!aiLeaders.keySet().contains(leader)) { result.put(leader, leaderCommands.containsKey(leader)); } else { result.put(leader, true); } } return result; } public boolean process(Leader leader, List<Command> commands) { leaderCommands.put(leader, commands); Map<Leader, View> views = getViews(); boolean turnFinished = leaderCommands.size() == leaders.size() - aiLeaders.size(); if(turnFinished) { events.clear(); for(Leader aiLeader : aiLeaders.keySet()) { leaderCommands.put(aiLeader, aiLeaders.get(aiLeader).think(aiLeader, views.get(aiLeader))); } for (Leader currentLeader : leaderCommands.keySet()) { for (Fleet fleet : fleets) { fleet.turn(stars, leaderCommands.get(currentLeader)); } } leaderCommands.clear(); turn++; // NOTE Dummy event for now... but should cheer you up! ;-) if(turn % 7 == 0) { for(Leader currentLeader : leaders) { events.add(new RandomMessageEvent(currentLeader, "Your empire is the best since " + turn + " turns!")); } } return true; } return false; } public Map<Leader, View> getViews() { return ViewGenerator.create(leaders, stars, fleets, events); } public int getTurn() { return turn; } }
{ "content_hash": "e60172666df858ea67d85603f28e1f32", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 109, "avg_line_length": 28.70414201183432, "alnum_prop": 0.6722325293753865, "repo_name": "janScheible/rising-empire", "id": "8477e6f855312b1f7ff9587f9b5503ba79c00fa4", "size": "4851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/scheible/risingempire/game/core/Universe.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3299" }, { "name": "Java", "bytes": "52987" }, { "name": "JavaScript", "bytes": "204147" }, { "name": "TypeScript", "bytes": "20033" } ], "symlink_target": "" }
package com.example.wangyeming.getuidemo.utils; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.util.Log; import java.util.List; /** * Created by wangyeming on 15-6-10. */ public class AppUtil { /** * 获取当前应用包名 * @param context * @return */ public static String getPackageName(Context context) { return context.getPackageName(); } /** * 获取显示在最顶端的activity名称 * @param context * @return */ public static String getTopActivityName(Context context) { String topActivityClassName = null; ActivityManager activityManager = (ActivityManager) (context.getSystemService(android.content.Context.ACTIVITY_SERVICE)); List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1); if (runningTaskInfos != null) { ComponentName f = runningTaskInfos.get(0).topActivity; topActivityClassName = f.getClassName(); } return topActivityClassName; } /** * 判断当前应用是否运行在用户前台 * @param context * @return */ public static boolean isRunningForeground(Context context) { String packageName = getPackageName(context); String topActivityClassName = getTopActivityName(context); Log.d("wym", "packageName=" + packageName + ",topActivityClassName=" + topActivityClassName); if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(packageName)) { Log.d("wym", "---> isRunningForeGround"); return true; } else { Log.d("wym", "---> isRunningBackGround"); return false; } } }
{ "content_hash": "b2ee9e868f1ab38352406cf50022d1b4", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 114, "avg_line_length": 30.53448275862069, "alnum_prop": 0.6453980801806889, "repo_name": "wangyeming/GeTuiDemo", "id": "41bcab1ef627c99a8b0ad3b78d7e7a147244b617", "size": "1839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/example/wangyeming/getuidemo/utils/AppUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "16455" } ], "symlink_target": "" }
package funcs import ( "github.com/Cepave/open-falcon-backend/common/model" ) func AgentMetrics() []*model.MetricValue { return []*model.MetricValue{GaugeValue("agent.alive", 1)} } func AgentMetricsThirty() []*model.MetricValue { return []*model.MetricValue{GaugeValue("agent.alive.30sec", 1)} }
{ "content_hash": "d1da0e8653faac4e95f2c4c95d49cf52", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 64, "avg_line_length": 23.23076923076923, "alnum_prop": 0.7350993377483444, "repo_name": "Cepave/open-falcon-backend", "id": "d7e307b18184814ffb5fc03eaab5d7f65aa1306c", "size": "302", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "modules/agent/funcs/agent.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "API Blueprint", "bytes": "11657" }, { "name": "Batchfile", "bytes": "621" }, { "name": "CSS", "bytes": "176820" }, { "name": "Go", "bytes": "2866772" }, { "name": "HTML", "bytes": "926212" }, { "name": "JavaScript", "bytes": "72432" }, { "name": "Makefile", "bytes": "5770" }, { "name": "Python", "bytes": "6305" }, { "name": "Ruby", "bytes": "4077" }, { "name": "Shell", "bytes": "64668" } ], "symlink_target": "" }
package com.wenyu.Data; public class IMConfiguration { public final static String sAppKey ="f7d9257d9ad2b4edaeb39c81";//"00b6413a92d4c1c84ad99e0a"; public static boolean sSoundNotice = true; public static boolean sVibrateNotice = true; }
{ "content_hash": "cf940ec0e5d75b588ced1a74e651717f", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 95, "avg_line_length": 34.857142857142854, "alnum_prop": 0.7991803278688525, "repo_name": "xingfeng2010/kai-ji-wang", "id": "e9728a447878bfc8816ab9324357b3b1eeef54c2", "size": "244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/wenyu/Data/IMConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1282037" } ], "symlink_target": "" }
@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,300italic,400italic,600italic); @import url(http://fonts.googleapis.com/css?family=Kaushan+Script); /*! * AdminLTE v1.2 * Author: AlmsaeedStudio.com * License: Open source - MIT * Please visit http://opensource.org/licenses/MIT for more information !*/ /* Core: General style ---------------------------- */ html, body { overflow-x: hidden!important; font-family: 'Source Sans Pro', sans-serif; -webkit-font-smoothing: antialiased; min-height: 100%; background: #f9f9f9; } a { color: #3c8dbc; } a:hover, a:active, a:focus { outline: none; text-decoration: none; color: #72afd2; } /* Layouts */ .wrapper { min-height: 100%; } .wrapper:before, .wrapper:after { display: table; content: " "; } .wrapper:after { clear: both; } /* Header */ body > .header { position: absolute; top: 0; left: 0; right: 0; z-index: 1030; } /* Define 2 column template */ .right-side, .left-side { min-height: 100%; display: block; } /*right side - contins main content*/ .right-side { background-color: #f9f9f9; margin-left: 220px; } /*left side - contains sidebar*/ .left-side { position: absolute; width: 220px; top: 0; } @media screen and (min-width: 992px) { .left-side { top: 50px; } /*Right side strech mode*/ .right-side.strech { margin-left: 0; } .right-side.strech > .content-header { margin-top: 0px; } /* Left side collapse */ .left-side.collapse-left { left: -220px; } } /*Give content full width on xs screens*/ @media screen and (max-width: 992px) { .right-side { margin-left: 0; } } /* By default the layout is not fixed but if you add the class .fixed to the body element the sidebar and the navbar will automatically become poisitioned fixed */ body.fixed > .header, body.fixed .left-side, body.fixed .navbar { position: fixed; } body.fixed > .header { top: 0; right: 0; left: 0; } body.fixed .navbar { left: 0; right: 0; } body.fixed .wrapper { margin-top: 50px; } /* Content */ .content { padding: 20px 15px; background: #f9f9f9; } /* Utility */ /* H1 - H6 font */ h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 { font-family: 'Source Sans Pro', sans-serif; } /* Page Header */ .page-header { margin: 10px 0 20px 0; font-size: 22px; } .page-header > small { color: #666; display: block; margin-top: 5px; } /* All images should be responsive */ img { max-width: 100%important; } .sort-highlight { background: #f4f4f4; border: 1px dashed #ddd; margin-bottom: 10px; } /* 10px padding and margins */ .pad { padding: 10px; } .margin { margin: 10px; } /* Display inline */ .inline { display: inline; width: auto; } /* Background colors */ .bg-red, .bg-yellow, .bg-aqua, .bg-blue, .bg-light-blue, .bg-green, .bg-navy, .bg-teal, .bg-olive, .bg-lime, .bg-orange, .bg-fuchsia, .bg-purple, .bg-maroon, .bg-black { color: #f9f9f9 !important; } .bg-gray { background-color: #eaeaec !important; } .bg-black { background-color: #222222 !important; } .bg-red { background-color: #f56954 !important; } .bg-yellow { background-color: #f39c12 !important; } .bg-aqua { background-color: #00c0ef !important; } .bg-blue { background-color: #0073b7 !important; } .bg-light-blue { background-color: #3c8dbc !important; } .bg-green { background-color: #00a65a !important; } .bg-navy { background-color: #001f3f !important; } .bg-teal { background-color: #39cccc !important; } .bg-olive { background-color: #3d9970 !important; } .bg-lime { background-color: #01ff70 !important; } .bg-orange { background-color: #ff851b !important; } .bg-fuchsia { background-color: #f012be !important; } .bg-purple { background-color: #932ab6 !important; } .bg-maroon { background-color: #85144b !important; } /* Text colors */ .text-red { color: #f56954 !important; } .text-yellow { color: #f39c12 !important; } .text-aqua { color: #00c0ef !important; } .text-blue { color: #0073b7 !important; } .text-light-blue { color: #3c8dbc !important; } .text-green { color: #00a65a !important; } .text-navy { color: #001f3f !important; } .text-teal { color: #39cccc !important; } .text-olive { color: #3d9970 !important; } .text-lime { color: #01ff70 !important; } .text-orange { color: #ff851b !important; } .text-fuchsia { color: #f012be !important; } .text-purple { color: #932ab6 !important; } .text-maroon { color: #85144b !important; } /*Hide elements by display none only*/ .hide { display: none !important; } /* Remove borders */ .no-border { border: 0px !important; } /* Remove padding */ .no-padding { padding: 0px !important; } /* Remove margins */ .no-margin { margin: 0px !important; } /* Remove box shadow */ .no-shadow { box-shadow: none!important; } /* Don't display when printing */ @media print { .no-print { display: none; } .left-side, .header, .content-header { display: none; } .right-side { margin: 0; } } /* Remove border radius */ .flat { -webkit-border-radius: 0 !important; -moz-border-radius: 0 !important; border-radius: 0 !important; } /* Change the color of the striped tables */ .table-striped > tbody > tr:nth-child(odd) > td, .table-striped > tbody > tr:nth-child(odd) > th { background-color: #f3f4f5; } /* .text-center in tables */ table.text-center td, table.text-center th { text-align: center; } /* _fix for sparkline tooltip */ .jqstooltip { padding: 5px!important; width: auto!important; height: auto!important; } /* Components: navbar, logo and content header ------------------------------------------------- */ body > .header { position: relative; max-height: 100px; z-index: 1030; } body > .header .navbar { height: 50px; margin-bottom: 0; margin-left: 220px; } body > .header .navbar .sidebar-toggle { float: left; padding: 9px 5px; margin-top: 8px; margin-right: 0; margin-bottom: 8px; margin-left: 5px; background-color: transparent; background-image: none; border: 1px solid transparent; -webkit-border-radius: 0 !important; -moz-border-radius: 0 !important; border-radius: 0 !important; } body > .header .navbar .sidebar-toggle:hover .icon-bar { background: #f6f6f6; } body > .header .navbar .sidebar-toggle .icon-bar { display: block; width: 22px; height: 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } body > .header .navbar .sidebar-toggle .icon-bar + .icon-bar { margin-top: 4px; } body > .header .navbar .nav > li.user > a { font-weight: bold; } body > .header .navbar .nav > li.user > a > .fa, body > .header .navbar .nav > li.user > a > .glyphicon, body > .header .navbar .nav > li.user > a > .ion { margin-right: 5px; } body > .header .navbar .nav > li > a > .label { -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; position: absolute; top: 7px; right: 2px; font-size: 10px; font-weight: normal; width: 15px; height: 15px; line-height: 1.0em; text-align: center; padding: 2px; } body > .header .navbar .nav > li > a:hover > .label { top: 3px; } body > .header .logo { float: left; font-size: 20px; line-height: 50px; text-align: center; padding: 0 10px; width: 220px; font-family: 'Kaushan Script', cursive; font-weight: 500; height: 50px; display: block; } body > .header .logo .icon { margin-right: 10px; } .right-side > .content-header { position: relative; padding: 15px 15px 10px 20px; } .right-side > .content-header > h1 { margin: 0; font-size: 24px; } .right-side > .content-header > h1 > small { font-size: 15px; display: inline-block; padding-left: 4px; font-weight: 300; } .right-side > .content-header > .breadcrumb { float: right; background: transparent; margin-top: 0px; margin-bottom: 0; font-size: 12px; padding: 7px 5px; position: absolute; top: 15px; right: 10px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; } .right-side > .content-header > .breadcrumb > li > a { color: #444; text-decoration: none; } .right-side > .content-header > .breadcrumb > li > a > .fa, .right-side > .content-header > .breadcrumb > li > a > .glyphicon, .right-side > .content-header > .breadcrumb > li > a > .ion { margin-right: 5px; } .right-side > .content-header > .breadcrumb > li + li:before { content: '>\00a0'; } @media screen and (max-width: 767px) { .right-side > .content-header > .breadcrumb { position: relative; margin-top: 5px; top: 0; right: 0; float: none; background: #efefef; } } @media (max-width: 767px) { .navbar .navbar-nav > li { float: left; } .navbar-nav { margin: 0; float: left; } .navbar-nav > li > a { padding-top: 15px; padding-bottom: 15px; line-height: 20px; } .navbar .navbar-right { float: right; } } @media screen and (max-width: 560px) { body > .header { position: relative; } body > .header .logo, body > .header .navbar { width: 100%; float: none; position: relative!important; } body > .header .navbar { margin: 0; } body.fixed > .header { position: fixed; } body.fixed > .wrapper, body.fixed .sidebar-offcanvas { margin-top: 100px!important; } } /* Component: Sidebar -------------------------- */ .sidebar { margin-bottom: 5px; } .sidebar .sidebar-form input:focus { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; border-color: transparent!important; } .sidebar .sidebar-menu { list-style: none; margin: 0; padding: 0; } .sidebar .sidebar-menu > li { margin: 0; padding: 0; } .sidebar .sidebar-menu > li > a { padding: 12px 5px 12px 15px; display: block; } .sidebar .sidebar-menu > li > a > .fa, .sidebar .sidebar-menu > li > a > .glyphicon, .sidebar .sidebar-menu > li > a > .ion { width: 20px; } .sidebar .sidebar-menu .treeview-menu { display: none; list-style: none; padding: 0; margin: 0; } .sidebar .sidebar-menu .treeview-menu > li { margin: 0; } .sidebar .sidebar-menu .treeview-menu > li > a { padding: 5px 5px 5px 15px; display: block; font-size: 14px; margin: 0px 0px; } .sidebar .sidebar-menu .treeview-menu > li > a > .fa, .sidebar .sidebar-menu .treeview-menu > li > a > .glyphicon, .sidebar .sidebar-menu .treeview-menu > li > a > .ion { width: 20px; } .user-panel { padding: 10px; } .user-panel:before, .user-panel:after { display: table; content: " "; } .user-panel:after { clear: both; } .user-panel > .image > img { width: 45px; height: 45px; } .user-panel > .info { font-weight: 600; padding: 5px 5px 5px 15px; font-size: 14px; line-height: 1; } .user-panel > .info > p { margin-bottom: 9px; } .user-panel > .info > a { text-decoration: none; padding-right: 5px; margin-top: 3px; font-size: 11px; font-weight: normal; } .user-panel > .info > a > .fa, .user-panel > .info > a > .ion, .user-panel > .info > a > .glyphicon { margin-right: 3px; } /* * Off Canvas * -------------------------------------------------- * Gives us the push menu effect */ @media screen and (max-width: 992px) { .relative { position: relative; } .row-offcanvas-right .sidebar-offcanvas { right: -220px; } .row-offcanvas-left .sidebar-offcanvas { left: -220px; } .row-offcanvas-right.active { right: 220px; } .row-offcanvas-left.active { left: 220px; } .sidebar-offcanvas { left: 0; } body.fixed .sidebar-offcanvas { margin-top: 50px; left: -220px; } body.fixed .row-offcanvas-left.active .navbar { left: 220px !important; right: 0; } body.fixed .row-offcanvas-left.active .sidebar-offcanvas { left: 0px; } } /* Dropdown menus ---------------------------- */ /*Dropdowns in general*/ .dropdown-menu { -webkit-box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.1); box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.1); z-index: 2300; } .dropdown-menu > li > a > .glyphicon, .dropdown-menu > li > a > .fa, .dropdown-menu > li > a > .ion { margin-right: 10px; } .dropdown-menu > li > a:hover { background-color: #3c8dbc; color: #f9f9f9; } /*Drodown in navbars*/ .skin-blue .navbar .dropdown-menu > li > a { color: #444444; } /* Navbar custom dropdown menu ------------------------------------ */ .navbar-nav > .notifications-menu > .dropdown-menu, .navbar-nav > .messages-menu > .dropdown-menu, .navbar-nav > .tasks-menu > .dropdown-menu { width: 280px; padding: 0 0 0 0!important; margin: 0!important; top: 100%; border: 1px solid #dfdfdf; -webkit-border-radius: 4px !important; -moz-border-radius: 4px !important; border-radius: 4px !important; } .navbar-nav > .notifications-menu > .dropdown-menu > li.header, .navbar-nav > .messages-menu > .dropdown-menu > li.header, .navbar-nav > .tasks-menu > .dropdown-menu > li.header { -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 0; -webkit-border-bottom-left-radius: 0; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -moz-border-radius-bottomright: 0; -moz-border-radius-bottomleft: 0; border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; background-color: #ffffff; padding: 7px 10px; border-bottom: 1px solid #f4f4f4; color: #444444; font-size: 14px; } .navbar-nav > .notifications-menu > .dropdown-menu > li.header:after, .navbar-nav > .messages-menu > .dropdown-menu > li.header:after, .navbar-nav > .tasks-menu > .dropdown-menu > li.header:after { bottom: 100%; left: 92%; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(255, 255, 255, 0); border-bottom-color: #ffffff; border-width: 7px; margin-left: -7px; } .navbar-nav > .notifications-menu > .dropdown-menu > li.footer > a, .navbar-nav > .messages-menu > .dropdown-menu > li.footer > a, .navbar-nav > .tasks-menu > .dropdown-menu > li.footer > a { -webkit-border-top-left-radius: 0px; -webkit-border-top-right-radius: 0px; -webkit-border-bottom-right-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-topleft: 0px; -moz-border-radius-topright: 0px; -moz-border-radius-bottomright: 4px; -moz-border-radius-bottomleft: 4px; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; font-size: 12px; background-color: #f4f4f4; padding: 7px 10px; border-bottom: 1px solid #eeeeee; color: #444444; text-align: center; } .navbar-nav > .notifications-menu > .dropdown-menu > li.footer > a:hover, .navbar-nav > .messages-menu > .dropdown-menu > li.footer > a:hover, .navbar-nav > .tasks-menu > .dropdown-menu > li.footer > a:hover { background: #f4f4f4; text-decoration: none; font-weight: normal; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu, .navbar-nav > .messages-menu > .dropdown-menu > li .menu, .navbar-nav > .tasks-menu > .dropdown-menu > li .menu { margin: 0; padding: 0; list-style: none; overflow-x: hidden; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a, .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a, .navbar-nav > .tasks-menu > .dropdown-menu > li .menu > li > a { display: block; white-space: nowrap; /* Prevent text from breaking */ border-bottom: 1px solid #f4f4f4; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a:hover, .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a:hover, .navbar-nav > .tasks-menu > .dropdown-menu > li .menu > li > a:hover { background: #f6f6f6; text-decoration: none; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a { font-size: 12px; color: #444444; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .glyphicon, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .fa, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .ion { font-size: 20px; width: 50px; text-align: center; padding: 15px 0px; margin-right: 5px; /* Default background and font colors */ background: #00c0ef; color: #f9f9f9; /* Fallback for browsers that doesn't support rgba */ color: rgba(255, 255, 255, 0.7); } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .glyphicon.danger, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .fa.danger, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .ion.danger { background: #f56954; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .glyphicon.warning, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .fa.warning, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .ion.warning { background: #f39c12; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .glyphicon.success, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .fa.success, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .ion.success { background: #00a65a; } .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .glyphicon.info, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .fa.info, .navbar-nav > .notifications-menu > .dropdown-menu > li .menu > li > a > .ion.info { background: #00c0ef; } .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a { margin: 0px; line-height: 20px; padding: 10px 5px 10px 5px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a > div > img { margin: auto 10px auto auto; width: 40px; height: 40px; border: 1px solid #dddddd; } .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a > h4 { padding: 0; margin: 0 0 0 45px; color: #444444; font-size: 15px; } .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a > h4 > small { color: #999999; font-size: 10px; float: right; } .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a > p { margin: 0 0 0 45px; font-size: 12px; color: #888888; } .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a:before, .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a:after { display: table; content: " "; } .navbar-nav > .messages-menu > .dropdown-menu > li .menu > li > a:after { clear: both; } .navbar-nav > .tasks-menu > .dropdown-menu > li .menu > li > a { padding: 10px; } .navbar-nav > .tasks-menu > .dropdown-menu > li .menu > li > a > h3 { font-size: 14px; padding: 0; margin: 0 0 10px 0; color: #666666; } .navbar-nav > .tasks-menu > .dropdown-menu > li .menu > li > a > .progress { padding: 0; margin: 0; } .navbar-nav > .user-menu > .dropdown-menu { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; padding: 1px 0 0 0; border-top-width: 0; width: 280px; } .navbar-nav > .user-menu > .dropdown-menu:after { bottom: 100%; right: 10px; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(255, 255, 255, 0); border-bottom-color: #ffffff; border-width: 10px; margin-left: -10px; } .navbar-nav > .user-menu > .dropdown-menu > li.user-header { height: 175px; padding: 10px; background: #3c8dbc; text-align: center; } .navbar-nav > .user-menu > .dropdown-menu > li.user-header > img { z-index: 5; height: 90px; width: 90px; border: 8px solid; border-color: transparent; border-color: rgba(255, 255, 255, 0.2); } .navbar-nav > .user-menu > .dropdown-menu > li.user-header > p { z-index: 5; color: #f9f9f9; color: rgba(255, 255, 255, 0.8); font-size: 17px; text-shadow: 2px 2px 3px #333333; margin-top: 10px; } .navbar-nav > .user-menu > .dropdown-menu > li.user-header > p > small { display: block; font-size: 12px; } .navbar-nav > .user-menu > .dropdown-menu > li.user-body { padding: 15px; border-bottom: 1px solid #f4f4f4; border-top: 1px solid #dddddd; } .navbar-nav > .user-menu > .dropdown-menu > li.user-body:before, .navbar-nav > .user-menu > .dropdown-menu > li.user-body:after { display: table; content: " "; } .navbar-nav > .user-menu > .dropdown-menu > li.user-body:after { clear: both; } .navbar-nav > .user-menu > .dropdown-menu > li.user-body > div > a { color: #0073b7; } .navbar-nav > .user-menu > .dropdown-menu > li.user-footer { background-color: #f9f9f9; padding: 10px; } .navbar-nav > .user-menu > .dropdown-menu > li.user-footer:before, .navbar-nav > .user-menu > .dropdown-menu > li.user-footer:after { display: table; content: " "; } .navbar-nav > .user-menu > .dropdown-menu > li.user-footer:after { clear: both; } .navbar-nav > .user-menu > .dropdown-menu > li.user-footer .btn-default { color: #666666; } /* Add fade animation to dropdown menus */ .open > .dropdown-menu { animation-name: fadeAnimation; animation-duration: .7s; animation-iteration-count: 1; animation-timing-function: ease; animation-fill-mode: forwards; -webkit-animation-name: fadeAnimation; -webkit-animation-duration: .7s; -webkit-animation-iteration-count: 1; -webkit-animation-timing-function: ease; -webkit-animation-fill-mode: forwards; -moz-animation-name: fadeAnimation; -moz-animation-duration: .7s; -moz-animation-iteration-count: 1; -moz-animation-timing-function: ease; -moz-animation-fill-mode: forwards; } @keyframes fadeAnimation { from { opacity: 0; top: 120%; } to { opacity: 1; top: 100%; } } @-webkit-keyframes fadeAnimation { from { opacity: 0; top: 120%; } to { opacity: 1; top: 100%; } } /* Fix dropdown menu for small screens to display correctly on small screens */ @media screen and (max-width: 767px) { .navbar-nav > .notifications-menu > .dropdown-menu, .navbar-nav > .user-menu > .dropdown-menu, .navbar-nav > .tasks-menu > .dropdown-menu, .navbar-nav > .messages-menu > .dropdown-menu { position: absolute; top: 100%; right: 0; left: auto; border-right: 1px solid #dddddd; border-bottom: 1px solid #dddddd; border-left: 1px solid #dddddd; background: #ffffff; } } /* Fix menu positions on xs screens to appear correctly and fully */ @media screen and (max-width: 480px) { .navbar-nav > .notifications-menu > .dropdown-menu > li.header, .navbar-nav > .tasks-menu > .dropdown-menu > li.header, .navbar-nav > .messages-menu > .dropdown-menu > li.header { /* Remove arrow from the top */ } .navbar-nav > .notifications-menu > .dropdown-menu > li.header:after, .navbar-nav > .tasks-menu > .dropdown-menu > li.header:after, .navbar-nav > .messages-menu > .dropdown-menu > li.header:after { border-width: 0px!important; } .navbar-nav > .tasks-menu > .dropdown-menu { position: absolute; right: -120px; left: auto; } .navbar-nav > .notifications-menu > .dropdown-menu { position: absolute; right: -170px; left: auto; } .navbar-nav > .messages-menu > .dropdown-menu { position: absolute; right: -210px; left: auto; } } /* All form elements including input, select, textarea etc. ----------------------------------------------------------------- */ .form-control { -webkit-border-radius: 0px !important; -moz-border-radius: 0px !important; border-radius: 0px !important; box-shadow: none; } .form-control:focus { border-color: #3c8dbc !important; box-shadow: none; } .form-group.has-success label { color: #00a65a; } .form-group.has-success .form-control { border-color: #00a65a !important; box-shadow: none; } .form-group.has-warning label { color: #f39c12; } .form-group.has-warning .form-control { border-color: #f39c12 !important; box-shadow: none; } .form-group.has-error label { color: #f56954; } .form-group.has-error .form-control { border-color: #f56954 !important; box-shadow: none; } /* Input group */ .input-group .input-group-addon { border-radius: 0; background-color: #f4f4f4; } /* button groups */ .btn-group-vertical .btn.btn-flat:first-of-type, .btn-group-vertical .btn.btn-flat:last-of-type { border-radius: 0; } /* Checkbox and radio inputs */ .checkbox, .radio { padding-left: 0; } /* Compenent: Progress bars -------------------------------- */ /* size variation */ .progress.sm { height: 10px; } .progress.xs { height: 7px; } /* Vertical bars */ .progress.vertical { position: relative; width: 30px; height: 200px; display: inline-block; margin-right: 10px; } .progress.vertical > .progress-bar { width: 100%!important; position: absolute; bottom: 0; } .progress.vertical.sm { width: 20px; } .progress.vertical.xs { width: 10px; } /* Remove margins from progress bars when put in a table */ .table tr > td .progress { margin: 0; } .progress-bar-light-blue, .progress-bar-primary { background-color: #3c8dbc; } .progress-striped .progress-bar-light-blue, .progress-striped .progress-bar-primary { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-green, .progress-bar-success { background-color: #00a65a; } .progress-striped .progress-bar-green, .progress-striped .progress-bar-success { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-aqua, .progress-bar-info { background-color: #00c0ef; } .progress-striped .progress-bar-aqua, .progress-striped .progress-bar-info { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-yellow, .progress-bar-warning { background-color: #f39c12; } .progress-striped .progress-bar-yellow, .progress-striped .progress-bar-warning { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-red, .progress-bar-danger { background-color: #f56954; } .progress-striped .progress-bar-red, .progress-striped .progress-bar-danger { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } /* Component: Small boxes */ .small-box { position: relative; display: block; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; margin-bottom: 15px; } .small-box > .inner { padding: 10px; } .small-box > .small-box-footer { position: relative; text-align: center; padding: 3px 0; color: #fff; color: rgba(255, 255, 255, 0.8); display: block; z-index: 10; background: rgba(0, 0, 0, 0.1); text-decoration: none; } .small-box > .small-box-footer:hover { color: #fff; background: rgba(0, 0, 0, 0.15); } .small-box h3 { font-size: 38px; font-weight: bold; margin: 0 0 10px 0; white-space: nowrap; padding: 0; } .small-box p { font-size: 15px; } .small-box p > small { display: block; color: #f9f9f9; font-size: 13px; margin-top: 5px; } .small-box h3, .small-box p { z-index: 5px; } .small-box .icon { position: absolute; top: auto; bottom: 5px; right: 5px; z-index: 0; font-size: 90px; color: rgba(0, 0, 0, 0.15); } .small-box:hover { text-decoration: none; color: #f9f9f9; } .small-box:hover .icon { animation-name: tansformAnimation; animation-duration: .5s; animation-iteration-count: 1; animation-timing-function: ease; animation-fill-mode: forwards; -webkit-animation-name: tansformAnimation; -webkit-animation-duration: .5s; -webkit-animation-iteration-count: 1; -webkit-animation-timing-function: ease; -webkit-animation-fill-mode: forwards; -moz-animation-name: tansformAnimation; -moz-animation-duration: .5s; -moz-animation-iteration-count: 1; -moz-animation-timing-function: ease; -moz-animation-fill-mode: forwards; } @keyframes tansformAnimation { from { font-size: 90px; } to { font-size: 100px; } } @-webkit-keyframes tansformAnimation { from { font-size: 90px; } to { font-size: 100px; } } @media screen and (max-width: 480px) { .small-box { text-align: center; } .small-box .icon { display: none; } .small-box p { font-size: 12px; } } /* component: Boxes ------------------------- */ .box { position: relative; background: #ffffff; border-top: 2px solid #c1c1c1; margin-bottom: 20px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; width: 100%; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1); } .box.box-primary { border-top-color: #3c8dbc; } .box.box-info { border-top-color: #00c0ef; } .box.box-danger { border-top-color: #f56954; } .box.box-warning { border-top-color: #f39c12; } .box.box-success { border-top-color: #00a65a; } .box.height-control .box-body { max-height: 300px; overflow: auto; } .box .box-header { position: relative; -webkit-border-top-left-radius: 3px; -webkit-border-top-right-radius: 3px; -webkit-border-bottom-right-radius: 0; -webkit-border-bottom-left-radius: 0; -moz-border-radius-topleft: 3px; -moz-border-radius-topright: 3px; -moz-border-radius-bottomright: 0; -moz-border-radius-bottomleft: 0; border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; border-bottom: 0px solid #f4f4f4; color: #444; padding-bottom: 10px; } .box .box-header:before, .box .box-header:after { display: table; content: " "; } .box .box-header:after { clear: both; } .box .box-header > .fa, .box .box-header > .glyphicon, .box .box-header > .ion, .box .box-header .box-title { display: inline-block; padding: 10px 0px 10px 10px; margin: 0; font-size: 20px; font-weight: 400; float: left; cursor: default; } .box .box-header a { color: #444; } .box .box-header > .box-tools { padding: 5px 10px 5px 5px; } .box .box-body { padding: 10px; -webkit-border-top-left-radius: 0; -webkit-border-top-right-radius: 0; -webkit-border-bottom-right-radius: 3px; -webkit-border-bottom-left-radius: 3px; -moz-border-radius-topleft: 0; -moz-border-radius-topright: 0; -moz-border-radius-bottomright: 3px; -moz-border-radius-bottomleft: 3px; border-top-left-radius: 0; border-top-right-radius: 0; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .box .box-body > table, .box .box-body > .table { margin-bottom: 0; } .box .box-body.chart-responsive { width: 100%; overflow: hidden; } .box .box-body > .chart { position: relative; overflow: hidden; width: 100%; } .box .box-body > .chart svg, .box .box-body > .chart canvas { width: 100%!important; } .box .box-body .fc { margin-top: 5px; } .box .box-body .fc-header-title h2 { font-size: 15px; line-height: 1.6em; color: #666; margin-left: 10px; } .box .box-body .fc-header-right { padding-right: 10px; } .box .box-body .fc-header-left { padding-left: 10px; } .box .box-body .fc-widget-header { background: #fafafa; box-shadow: inset 0px -3px 1px rgba(0, 0, 0, 0.02); } .box .box-body .fc-grid { width: 100%; border: 0; } .box .box-body .fc-widget-header:first-of-type, .box .box-body .fc-widget-content:first-of-type { border-left: 0; border-right: 0; } .box .box-body .fc-widget-header:last-of-type, .box .box-body .fc-widget-content:last-of-type { border-right: 0; } .box .box-body .table { margin-bottom: 0; } .box .box-body .full-width-chart { margin: -19px; } .box .box-body.no-padding .full-width-chart { margin: -9px; } .box .box-footer { border-top: 1px solid #f4f4f4; -webkit-border-top-left-radius: 0; -webkit-border-top-right-radius: 0; -webkit-border-bottom-right-radius: 3px; -webkit-border-bottom-left-radius: 3px; -moz-border-radius-topleft: 0; -moz-border-radius-topright: 0; -moz-border-radius-bottomright: 3px; -moz-border-radius-bottomleft: 3px; border-top-left-radius: 0; border-top-right-radius: 0; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 10px; background-color: #ffffff; } .box.box-solid { border-top: 0px; } .box.box-solid > .box-header { padding-bottom: 0px!important; } .box.box-solid > .box-header .btn.btn-default { background: transparent; } .box.box-solid.box-primary > .box-header { color: #fff; background: #3c8dbc; background-color: #3c8dbc; } .box.box-solid.box-primary > .box-header a { color: #444; } .box.box-solid.box-info > .box-header { color: #fff; background: #00c0ef; background-color: #00c0ef; } .box.box-solid.box-info > .box-header a { color: #444; } .box.box-solid.box-danger > .box-header { color: #fff; background: #f56954; background-color: #f56954; } .box.box-solid.box-danger > .box-header a { color: #444; } .box.box-solid.box-warning > .box-header { color: #fff; background: #f39c12; background-color: #f39c12; } .box.box-solid.box-warning > .box-header a { color: #444; } .box.box-solid.box-success > .box-header { color: #fff; background: #00a65a; background-color: #00a65a; } .box.box-solid.box-success > .box-header a { color: #444; } .box.box-solid > .box-header > .box-tools > .btn { border: 0; box-shadow: none; } .box.box-solid.collapsed-box .box-header { -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .box.box-solid[class*='bg'] > .box-header { color: #fff; } .box .box-group > .box { margin-bottom: 5px; } .box .knob-label { text-align: center; color: #333; font-weight: 100; font-size: 12px; margin-bottom: 0.3em; } .box .todo-list { margin: 0; padding: 0px 0px; list-style: none; } .box .todo-list > li { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; padding: 10px; background: #f3f4f5; margin-bottom: 2px; border-left: 2px solid #e6e7e8; color: #444; } .box .todo-list > li:last-of-type { margin-bottom: 0; } .box .todo-list > li.danger { border-left-color: #f56954; } .box .todo-list > li.warning { border-left-color: #f39c12; } .box .todo-list > li.info { border-left-color: #00c0ef; } .box .todo-list > li.success { border-left-color: #00a65a; } .box .todo-list > li.primary { border-left-color: #3c8dbc; } .box .todo-list > li > input[type='checkbox'] { margin: 0 10px 0 5px; } .box .todo-list > li .text { display: inline-block; margin-left: 5px; font-weight: 600; } .box .todo-list > li .label { margin-left: 10px; font-size: 9px; } .box .todo-list > li .tools { display: none; float: right; color: #f56954; } .box .todo-list > li .tools > .fa, .box .todo-list > li .tools > .glyphicon, .box .todo-list > li .tools > .ion { margin-right: 5px; cursor: pointer; } .box .todo-list > li:hover .tools { display: inline-block; } .box .todo-list > li.done { color: #999; } .box .todo-list > li.done .text { text-decoration: line-through; font-weight: 500; } .box .todo-list > li.done .label { background: #eaeaec !important; } .box .todo-list .handle { display: inline-block; cursor: move; margin: 0 5px; } .box .chat { padding: 5px 20px 5px 10px; } .box .chat .item { margin-bottom: 10px; } .box .chat .item:before, .box .chat .item:after { display: table; content: " "; } .box .chat .item:after { clear: both; } .box .chat .item > img { width: 40px; height: 40px; border: 2px solid transparent; -webkit-border-radius: 50% !important; -moz-border-radius: 50% !important; border-radius: 50% !important; } .box .chat .item > img.online { border: 2px solid #00a65a; } .box .chat .item > img.offline { border: 2px solid #f56954; } .box .chat .item > .message { margin-left: 55px; margin-top: -40px; } .box .chat .item > .message > .name { display: block; font-weight: 600; } .box .chat .item > .attachment { -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background: #f0f0f0; margin-left: 65px; margin-right: 15px; padding: 10px; } .box .chat .item > .attachment > h4 { margin: 0 0 5px 0; font-weight: 600; font-size: 14px; } .box .chat .item > .attachment > p, .box .chat .item > .attachment > .filename { font-weight: 600; font-size: 13px; font-style: italic; margin: 0; } .box .chat .item > .attachment:before, .box .chat .item > .attachment:after { display: table; content: " "; } .box .chat .item > .attachment:after { clear: both; } .box > .overlay, .box > .loading-img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .box > .overlay { z-index: 1010; background: rgba(255, 255, 255, 0.7); } .box > .overlay.dark { background: rgba(0, 0, 0, 0.5); } .box > .loading-img { z-index: 1020; background: transparent url('../img/ajax-loader1.gif') 50% 50% no-repeat; } /* Component: timeline -------------------- */ .timeline { margin: 0 0 30px 0; padding: 0; list-style: none; } .timeline:before { content: ''; position: absolute; top: 0px; bottom: 0; width: 5px; background: #ddd; left: 45px; border: 1px solid #eee; margin: 0; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; } .timeline > li { position: relative; margin-right: 10px; margin-bottom: 15px; } .timeline > li:before, .timeline > li:after { display: table; content: " "; } .timeline > li:after { clear: both; } .timeline > li > .timeline-item { margin-top: 10px; border: 0px solid #dfdfdf; background: #fff; color: #555; margin-left: 60px; margin-right: 15px; padding: 5px; position: relative; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1); } .timeline > li > .timeline-item > .time { color: #999; float: right; margin: 2px 0 0 0; } .timeline > li > .timeline-item > .timeline-header { margin: 0; color: #555; border-bottom: 1px solid #f4f4f4; padding: 5px; font-size: 16px; line-height: 1.1; } .timeline > li > .timeline-item > .timeline-header > a { font-weight: 600; } .timeline > li > .timeline-item > .timeline-body, .timeline > li > .timeline-item > .timeline-footer { padding: 10px; } .timeline > li.time-label > span { font-weight: 600; padding: 5px; display: inline-block; background-color: #fff; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5); -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .timeline > li > .fa, .timeline > li > .glyphicon, .timeline > li > .ion { box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); width: 30px; height: 30px; font-size: 15px; line-height: 30px; position: absolute; color: #666; background: #eee; border-radius: 50%; text-align: center; left: 18px; top: 0; } /* Component: Buttons ------------------------- */ .btn { font-weight: 500; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; border: 1px solid transparent; -webkit-box-shadow: inset 0px -2px 0px 0px rgba(0, 0, 0, 0.09); -moz-box-shadow: inset 0px -2px 0px 0px rgba(0, 0, 0, 0.09); box-shadow: inset 0px -1px 0px 0px rgba(0, 0, 0, 0.09); } .btn.btn-default { background-color: #fafafa; color: #666; border-color: #ddd; border-bottom-color: #ddd; } .btn.btn-default:hover, .btn.btn-default:active, .btn.btn-default.hover { background-color: #f4f4f4!important; } .btn.btn-default.btn-flat { border-bottom-color: #d9dadc; } .btn.btn-primary { background-color: #3c8dbc; border-color: #367fa9; } .btn.btn-primary:hover, .btn.btn-primary:active, .btn.btn-primary.hover { background-color: #367fa9; } .btn.btn-success { background-color: #00a65a; border-color: #008d4c; } .btn.btn-success:hover, .btn.btn-success:active, .btn.btn-success.hover { background-color: #008d4c; } .btn.btn-info { background-color: #00c0ef; border-color: #00acd6; } .btn.btn-info:hover, .btn.btn-info:active, .btn.btn-info.hover { background-color: #00acd6; } .btn.btn-danger { background-color: #f56954; border-color: #f4543c; } .btn.btn-danger:hover, .btn.btn-danger:active, .btn.btn-danger.hover { background-color: #f4543c; } .btn.btn-warning { background-color: #f39c12; border-color: #e08e0b; } .btn.btn-warning:hover, .btn.btn-warning:active, .btn.btn-warning.hover { background-color: #e08e0b; } .btn.btn-flat { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; border-width: 1px; } .btn:active { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); -moz-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn:focus { outline: none; } .btn.btn-file { position: relative; width: 120px; height: 35px; overflow: hidden; } .btn.btn-file > input[type='file'] { display: block !important; width: 100% !important; height: 35px !important; opacity: 0 !important; position: absolute; top: -10px; cursor: pointer; } .btn.btn-app { position: relative; padding: 15px 5px; margin: 0 0 10px 10px; min-width: 80px; height: 60px; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; text-align: center; color: #666; border: 1px solid #ddd; background-color: #fafafa; font-size: 12px; } .btn.btn-app > .fa, .btn.btn-app > .glyphicon, .btn.btn-app > .ion { font-size: 20px; display: block; } .btn.btn-app:hover { background: #f4f4f4; color: #444; border-color: #aaa; } .btn.btn-app:active, .btn.btn-app:focus { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); -moz-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn.btn-app > .badge { position: absolute; top: -3px; right: -10px; font-size: 10px; font-weight: 400; } .btn.btn-social-old { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; opacity: 0.9; padding: 0; } .btn.btn-social-old > .fa { padding: 10px 0; width: 40px; } .btn.btn-social-old > .fa + span { border-left: 1px solid rgba(255, 255, 255, 0.3); } .btn.btn-social-old span { padding: 10px; } .btn.btn-social-old:hover { opacity: 1; } .btn.btn-circle { width: 30px; height: 30px; line-height: 30px; padding: 0; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; } /* Component: callout ------------------------ */ .callout { margin: 0 0 20px 0; padding: 15px 30px 15px 15px; border-left: 5px solid #eee; } .callout h4 { margin-top: 0; } .callout p:last-child { margin-bottom: 0; } .callout code, .callout .highlight { background-color: #fff; } .callout.callout-danger { background-color: #fcf2f2; border-color: #dFb5b4; } .callout.callout-warning { background-color: #fefbed; border-color: #f1e7bc; } .callout.callout-info { background-color: #f0f7fd; border-color: #d0e3f0; } .callout.callout-danger h4 { color: #B94A48; } .callout.callout-warning h4 { color: #C09853; } .callout.callout-info h4 { color: #3A87AD; } /* Component: alert ------------------------ */ .alert { padding-left: 30px; margin-left: 15px; position: relative; } .alert > .fa, .alert > .glyphicon { position: absolute; left: -15px; top: -15px; width: 35px; height: 35px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; line-height: 35px; text-align: center; background: inherit; border: inherit; } /* Component: Navs */ /* NAV PILLS */ .nav.nav-pills > li > a { border-top: 3px solid transparent; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; color: #444; } .nav.nav-pills > li > a > .fa, .nav.nav-pills > li > a > .glyphicon, .nav.nav-pills > li > a > .ion { margin-right: 5px; } .nav.nav-pills > li.active > a, .nav.nav-pills > li.active > a:hover { background-color: #f6f6f6; border-top-color: #3c8dbc; color: #444; } .nav.nav-pills > li.active > a { font-weight: 600; } .nav.nav-pills > li > a:hover { background-color: #f6f6f6; } .nav.nav-pills.nav-stacked > li > a { border-top: 0; border-left: 3px solid transparent; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; color: #444; } .nav.nav-pills.nav-stacked > li.active > a, .nav.nav-pills.nav-stacked > li.active > a:hover { background-color: #f6f6f6; border-left-color: #3c8dbc; color: #444; } .nav.nav-pills.nav-stacked > li.header { border-bottom: 1px solid #ddd; color: #777; margin-bottom: 10px; padding: 5px 10px; text-transform: uppercase; } /* NAV TABS */ .nav-tabs-custom { margin-bottom: 20px; background: #fff; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1); } .nav-tabs-custom > .nav-tabs { margin: 0; border-bottom-color: #f4f4f4; } .nav-tabs-custom > .nav-tabs > li { border-top: 3px solid transparent; margin-bottom: -2px; margin-right: 5px; } .nav-tabs-custom > .nav-tabs > li > a { -webkit-border-radius: 0 !important; -moz-border-radius: 0 !important; border-radius: 0 !important; } .nav-tabs-custom > .nav-tabs > li > a, .nav-tabs-custom > .nav-tabs > li > a:hover { background: transparent; margin: 0; } .nav-tabs-custom > .nav-tabs > li:not(.active) > a:hover, .nav-tabs-custom > .nav-tabs > li:not(.active) > a:focus, .nav-tabs-custom > .nav-tabs > li:not(.active) > a:active { border-color: transparent; } .nav-tabs-custom > .nav-tabs > li.active { border-top-color: #3c8dbc; } .nav-tabs-custom > .nav-tabs > li.active > a, .nav-tabs-custom > .nav-tabs > li.active:hover > a { background-color: #fff; } .nav-tabs-custom > .nav-tabs > li.active > a { border-top: 0; border-left-color: #f4f4f4; border-right-color: #f4f4f4; } .nav-tabs-custom > .nav-tabs > li:first-of-type { margin-left: 0px; } .nav-tabs-custom > .nav-tabs > li:first-of-type.active > a { border-left-width: 0; } .nav-tabs-custom > .nav-tabs.pull-right { float: none!important; } .nav-tabs-custom > .nav-tabs.pull-right > li { float: right; } .nav-tabs-custom > .nav-tabs.pull-right > li:first-of-type { margin-right: 0px; } .nav-tabs-custom > .nav-tabs.pull-right > li:first-of-type.active > a { border-left-width: 1px; border-right-width: 0px; } .nav-tabs-custom > .nav-tabs > li.header { font-weight: 400; line-height: 35px; padding: 0 10px; font-size: 20px; color: #444; cursor: default; } .nav-tabs-custom > .nav-tabs > li.header > .fa, .nav-tabs-custom > .nav-tabs > li.header > .glyphicon, .nav-tabs-custom > .nav-tabs > li.header > .ion { margin-right: 10px; } .nav-tabs-custom > .tab-content { background: #fff; padding: 10px; } /* PAGINATION */ .pagination > li > a { background: #fafafa; color: #666; -webkit-box-shadow: inset 0px -2px 0px 0px rgba(0, 0, 0, 0.09); -moz-box-shadow: inset 0px -2px 0px 0px rgba(0, 0, 0, 0.09); box-shadow: inset 0px -1px 0px 0px rgba(0, 0, 0, 0.09); } .pagination > li:first-of-type a, .pagination > li:last-of-type a { -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } /* Component: Mailbox */ .mailbox .table-mailbox { border-left: 1px solid #ddd; border-right: 1px solid #ddd; border-bottom: 1px solid #ddd; } .mailbox .table-mailbox tr.unread > td { background-color: rgba(0, 0, 0, 0.05); color: #000; font-weight: 600; } .mailbox .table-mailbox tr > td > .fa.fa-star, .mailbox .table-mailbox tr > td > .fa.fa-star-o, .mailbox .table-mailbox tr > td > .glyphicon.glyphicon-star, .mailbox .table-mailbox tr > td > .glyphicon.glyphicon-star-empty { color: #f39c12; cursor: pointer; } .mailbox .table-mailbox tr > td.small-col { width: 30px; } .mailbox .table-mailbox tr > td.name { width: 150px; font-weight: 600; } .mailbox .table-mailbox tr > td.time { text-align: right; width: 100px; } .mailbox .table-mailbox tr > td { white-space: nowrap; } .mailbox .table-mailbox tr > td > a { color: #444; } @media screen and (max-width: 767px) { .mailbox .nav-stacked > li:not(.header) { float: left; width: 50%; } .mailbox .nav-stacked > li:not(.header).header { border: 0!important; } .mailbox .search-form { margin-top: 10px; } } /* Page: locked screen */ /* ADD THIS CLASS TO THE <HTML> TAG */ .lockscreen { background: url(../img/blur-background09.jpg) repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } /* Remove the background from the body element */ .lockscreen > body { background: transparent; } /* We will put the dynamically generated digital clock here */ .lockscreen .headline { color: #fff; text-shadow: 1px 3px 5px rgba(0, 0, 0, 0.5); font-weight: 300; -webkit-font-smoothing: antialiased !important; opacity: 0.8; margin: 10px 0 30px 0; font-size: 90px; } @media screen and (max-width: 480px) { .lockscreen .headline { font-size: 60px; margin-bottom: 40px; } } /* User name [optional] */ .lockscreen .lockscreen-name { text-align: center; font-weight: 600; font-size: 16px; } /* Will contain the image and the sign in form */ .lockscreen-item { padding: 0; background: #fff; position: relative; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; margin: 10px auto; width: 290px; } .lockscreen-item:before, .lockscreen-item:after { display: table; content: " "; } .lockscreen-item:after { clear: both; } /* User image */ .lockscreen-item > .lockscreen-image { position: absolute; left: -10px; top: -30px; background: #fff; padding: 10px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; z-index: 10; } .lockscreen-item > .lockscreen-image > img { width: 70px; height: 70px; -webkit-border-radius: 50%; -moz-border-radius: 50%; border-radius: 50%; } /* Contains the password input and the login button */ .lockscreen-item > .lockscreen-credentials { margin-left: 80px; } .lockscreen-item > .lockscreen-credentials input { border: 0 !important; } .lockscreen-item > .lockscreen-credentials .btn { background-color: #fff; border: 0; } /* Extra to give the user an option to navigate the website [optional]*/ .lockscreen-link { margin-top: 30px; text-align: center; } /* Page: register and login */ .form-box { width: 360px; margin: 90px auto 0 auto; } .form-box .header { -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 0; -webkit-border-bottom-left-radius: 0; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -moz-border-radius-bottomright: 0; -moz-border-radius-bottomleft: 0; border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; background: #3d9970; box-shadow: inset 0px -3px 0px rgba(0, 0, 0, 0.2); padding: 20px 10px; text-align: center; font-size: 26px; font-weight: 300; color: #fff; } .form-box .body, .form-box .footer { padding: 10px 20px; background: #fff; color: #444; } .form-box .body > .form-group, .form-box .footer > .form-group { margin-top: 20px; } .form-box .body > .form-group > input, .form-box .footer > .form-group > input { border: #fff; } .form-box .body > .btn, .form-box .footer > .btn { margin-bottom: 10px; } .form-box .footer { -webkit-border-top-left-radius: 0; -webkit-border-top-right-radius: 0; -webkit-border-bottom-right-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-topleft: 0; -moz-border-radius-topright: 0; -moz-border-radius-bottomright: 4px; -moz-border-radius-bottomleft: 4px; border-top-left-radius: 0; border-top-right-radius: 0; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; } @media (max-width: 767px) { .form-box { width: 90%; } } /* Page: 404 and 500 error pages ------------------------------------ */ .error-page { width: 600px; margin: 20px auto 0 auto; } @media screen and (max-width: 767px) { .error-page { width: 100%; } } .error-page > .headline { float: left; font-size: 100px; font-weight: 300; } @media screen and (max-width: 767px) { .error-page > .headline { float: none; text-align: center; } } .error-page > .error-content { margin-left: 190px; display: block; } @media screen and (max-width: 767px) { .error-page > .error-content { margin-left: 0; } } .error-page > .error-content > h3 { font-weight: 300; font-size: 25px; } @media screen and (max-width: 767px) { .error-page > .error-content > h3 { text-align: center; } } .error-page:before, .error-page:after { display: table; content: " "; } .error-page:after { clear: both; } /* Page: Invoice */ .invoice { position: relative; width: 90%; margin: 10px auto; background: #fff; border: 1px solid #f4f4f4; } .invoice-title { margin-top: 0; } /* Enhancement for printing */ @media print { .invoice { width: 100%; border: 0; margin: 0; padding: 0; } .invoice-col { float: left; width: 33.3333333%; } .table-responsive { overflow: auto; } .table-responsive > .table tr th, .table-responsive > .table tr td { white-space: normal!important; } } /* Skins ----- */ /* Skin Blue --------- */ /* skin-blue navbar */ .skin-blue .navbar { background-color: #3c8dbc; } .skin-blue .navbar .nav a { color: rgba(255, 255, 255, 0.8); } .skin-blue .navbar .nav > li > a:hover, .skin-blue .navbar .nav > li > a:active, .skin-blue .navbar .nav > li > a:focus, .skin-blue .navbar .nav .open > a, .skin-blue .navbar .nav .open > a:hover, .skin-blue .navbar .nav .open > a:focus { background: rgba(0, 0, 0, 0.1); color: #f6f6f6; } .skin-blue .navbar .navbar-right > .nav { margin-right: 10px; } .skin-blue .navbar .sidebar-toggle .icon-bar { background: rgba(255, 255, 255, 0.8); } .skin-blue .navbar .sidebar-toggle:hover .icon-bar { background: #f6f6f6 !important; } /* skin-blue logo */ .skin-blue .logo { background-color: #367fa9; color: #f9f9f9; } .skin-blue .logo > a { color: #f9f9f9; } .skin-blue .logo:hover { background: #357ca5; } /* skin-blue content header */ .skin-blue .right-side > .content-header { background: #fbfbfb; box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1); } /* Skin-blue user panel */ .skin-blue .user-panel > .image > img { border: 1px solid #dfdfdf; } .skin-blue .user-panel > .info, .skin-blue .user-panel > .info > a { color: #555555; } /* skin-blue sidebar */ .skin-blue .sidebar { border-bottom: 1px solid #fff; } .skin-blue .sidebar > .sidebar-menu > li { border-top: 1px solid #fff; border-bottom: 1px solid #dbdbdb; } .skin-blue .sidebar > .sidebar-menu > li:first-of-type { border-top: 1px solid #dbdbdb; } .skin-blue .sidebar > .sidebar-menu > li:first-of-type > a { border-top: 1px solid #fff; } .skin-blue .sidebar > .sidebar-menu > li > a { margin-right: 1px; } .skin-blue .sidebar > .sidebar-menu > li > a:hover, .skin-blue .sidebar > .sidebar-menu > li.active > a { color: #222; background: #f9f9f9; } .skin-blue .sidebar > .sidebar-menu > li > .treeview-menu { margin: 0 1px; background: #f9f9f9; } .skin-blue .left-side { background: #f4f4f4; -webkit-box-shadow: inset -3px 0px 8px -4px rgba(0, 0, 0, 0.1); -moz-box-shadow: inset -3px 0px 8px -4px rgba(0, 0, 0, 0.1); box-shadow: inset -3px 0px 8px -4px rgba(0, 0, 0, 0.07); } .skin-blue .sidebar a { color: #555555; } .skin-blue .sidebar a:hover { text-decoration: none; } .skin-blue .treeview-menu > li > a { color: #777; } .skin-blue .treeview-menu > li.active > a, .skin-blue .treeview-menu > li > a:hover { color: #111; } .skin-blue .sidebar-form { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; border: 1px solid #dbdbdb; margin: 10px 10px; } .skin-blue .sidebar-form input[type="text"], .skin-blue .sidebar-form .btn { box-shadow: none; background-color: #fafafa; border: 1px solid #fafafa; height: 35px; } .skin-blue .sidebar-form input[type="text"] { color: #666; -webkit-border-top-left-radius: 2px !important; -webkit-border-top-right-radius: 0 !important; -webkit-border-bottom-right-radius: 0 !important; -webkit-border-bottom-left-radius: 2px !important; -moz-border-radius-topleft: 2px !important; -moz-border-radius-topright: 0 !important; -moz-border-radius-bottomright: 0 !important; -moz-border-radius-bottomleft: 2px !important; border-top-left-radius: 2px !important; border-top-right-radius: 0 !important; border-bottom-right-radius: 0 !important; border-bottom-left-radius: 2px !important; } .skin-blue .sidebar-form input[type="text"]:focus, .skin-blue .sidebar-form input[type="text"]:focus + .input-group-btn .btn { background-color: #fff; color: #666; } .skin-blue .sidebar-form input[type="text"]:focus + .input-group-btn .btn { border-left-color: #fff; } .skin-blue .sidebar-form .btn { color: #999; -webkit-border-top-left-radius: 0 !important; -webkit-border-top-right-radius: 2px !important; -webkit-border-bottom-right-radius: 2px !important; -webkit-border-bottom-left-radius: 0 !important; -moz-border-radius-topleft: 0 !important; -moz-border-radius-topright: 2px !important; -moz-border-radius-bottomright: 2px !important; -moz-border-radius-bottomleft: 0 !important; border-top-left-radius: 0 !important; border-top-right-radius: 2px !important; border-bottom-right-radius: 2px !important; border-bottom-left-radius: 0 !important; } /* Skin Black -------- */ /* skin-black navbar */ .skin-black .navbar { background-color: #ffffff; border-bottom: 1px solid #eee; } .skin-black .navbar .nav a { color: #333333; } .skin-black .navbar .nav > li > a:hover, .skin-black .navbar .nav > li > a:active, .skin-black .navbar .nav > li > a:focus, .skin-black .navbar .nav .open > a, .skin-black .navbar .nav .open > a:hover, .skin-black .navbar .nav .open > a:focus { background: #ffffff; color: #999999; } .skin-black .navbar .navbar-right > .nav { margin-right: 10px; } .skin-black .navbar .sidebar-toggle .icon-bar { background: #333333; } .skin-black .navbar .sidebar-toggle:hover .icon-bar { background: #999999 !important; } /* skin-black logo */ .skin-black .logo { background-color: #333333; color: #f9f9f9; } .skin-black .logo > a { color: #f9f9f9; } .skin-black .logo:hover { background: #303030; } /* skin-black content header */ .skin-black .right-side > .content-header { background: transparent; box-shadow: none; } /* Skin-red user panel */ .skin-black .user-panel > .image > img { border: 1px solid #444; } .skin-black .user-panel > .info, .skin-black .user-panel > .info > a { color: #eee; } /* skin-black sidebar */ .skin-black .sidebar { border-bottom: 1px solid #333; } .skin-black .sidebar > .sidebar-menu > li { border-top: 1px solid #333; border-bottom: 0px solid #444; } .skin-black .sidebar > .sidebar-menu > li:first-of-type { border-top: 1px solid #444; } .skin-black .sidebar > .sidebar-menu > li:first-of-type > a { border-top: 0px solid #333; } .skin-black .sidebar > .sidebar-menu > li > a { margin-right: 1px; } .skin-black .sidebar > .sidebar-menu > li > a:hover, .skin-black .sidebar > .sidebar-menu > li.active > a { color: #f6f6f6; background: #444; } .skin-black .sidebar > .sidebar-menu > li > .treeview-menu { margin: 0 1px; background: #444; } .skin-black .left-side { background: #333; } .skin-black .sidebar a { color: #eee; } .skin-black .sidebar a:hover { text-decoration: none; } .skin-black .treeview-menu > li > a { color: #ccc; } .skin-black .treeview-menu > li.active > a, .skin-black .treeview-menu > li > a:hover { color: #fff; } .skin-black .sidebar-form { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; border: 0px solid #555; margin: 10px 10px; } .skin-black .sidebar-form input[type="text"], .skin-black .sidebar-form .btn { box-shadow: none; background-color: rgba(255, 255, 255, 0.1); border: 0 solid rgba(255, 255, 255, 0.1); height: 35px; outline: none; } .skin-black .sidebar-form input[type="text"] { color: #666; -webkit-border-top-left-radius: 2px !important; -webkit-border-top-right-radius: 0 !important; -webkit-border-bottom-right-radius: 0 !important; -webkit-border-bottom-left-radius: 2px !important; -moz-border-radius-topleft: 2px !important; -moz-border-radius-topright: 0 !important; -moz-border-radius-bottomright: 0 !important; -moz-border-radius-bottomleft: 2px !important; border-top-left-radius: 2px !important; border-top-right-radius: 0 !important; border-bottom-right-radius: 0 !important; border-bottom-left-radius: 2px !important; } .skin-black .sidebar-form input[type="text"]:focus, .skin-black .sidebar-form input[type="text"]:focus + .input-group-btn .btn { background-color: #444; border: 0; } .skin-black .sidebar-form input[type="text"]:focus + .input-group-btn .btn { border-left: 0; } .skin-black .sidebar-form .btn { color: #999; -webkit-border-top-left-radius: 0 !important; -webkit-border-top-right-radius: 2px !important; -webkit-border-bottom-right-radius: 2px !important; -webkit-border-bottom-left-radius: 0 !important; -moz-border-radius-topleft: 0 !important; -moz-border-radius-topright: 2px !important; -moz-border-radius-bottomright: 2px !important; -moz-border-radius-bottomleft: 0 !important; border-top-left-radius: 0 !important; border-top-right-radius: 2px !important; border-bottom-right-radius: 2px !important; border-bottom-left-radius: 0 !important; border-left: 0; } /*! * iCheck v1.0.1, http://git.io/arlzeA * ================================= * Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization * * (c) 2013 Damir Sultanov, http://fronteed.com * MIT Licensed */ /* iCheck plugin Minimal skin, black ----------------------------------- */ .icheckbox_minimal, .iradio_minimal { display: inline-block; *display: inline; vertical-align: middle; margin: 0; padding: 0; width: 18px; height: 18px; background: rgba(255, 255, 255, 0.7) url(iCheck/minimal/minimal.png) no-repeat; border: none; cursor: pointer; } .icheckbox_minimal { background-position: 0 0; } .icheckbox_minimal.hover { background-position: -20px 0; } .icheckbox_minimal.checked { background-position: -40px 0; } .icheckbox_minimal.disabled { background-position: -60px 0; cursor: default; } .icheckbox_minimal.checked.disabled { background-position: -80px 0; } .iradio_minimal { background-position: -100px 0; } .iradio_minimal.hover { background-position: -120px 0; } .iradio_minimal.checked { background-position: -140px 0; } .iradio_minimal.disabled { background-position: -160px 0; cursor: default; } .iradio_minimal.checked.disabled { background-position: -180px 0; } /* Retina support */ @media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (-moz-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (min-device-pixel-ratio: 1.5) { .icheckbox_minimal, .iradio_minimal { background-image: url('iCheck/minimal/minimal@2x.png'); -webkit-background-size: 200px 20px; background-size: 200px 20px; } } .pace .pace-progress { background: #00c0ef; position: fixed; z-index: 2000; top: 0; left: 0; height: 2px; -webkit-transition: width 1s; -moz-transition: width 1s; -o-transition: width 1s; transition: width 1s; } .pace-inactive { display: none; } /* * Social Buttons for Bootstrap * * Copyright 2013-2014 Panayiotis Lipiridis * Licensed under the MIT License * * https://github.com/lipis/bootstrap-social * * Note: this file has been altered to work correctly with AdminLTE */ .btn-social { position: relative; padding-left: 44px !important; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .btn-social :first-child { position: absolute; left: 0; top: 0; bottom: 0; width: 32px !important; line-height: 34px !important; font-size: 1.6em!important; text-align: center; border-right: 1px solid rgba(0, 0, 0, 0.2); } .btn-social.btn-lg { padding-left: 60px !important; } .btn-social.btn-lg :first-child { line-height: 45px; width: 45px; font-size: 1.8em; } .btn-social.btn-sm { padding-left: 38px !important; } .btn-social.btn-sm :first-child { line-height: 28px; width: 28px; font-size: 1.4em; } .btn-social.btn-xs { padding-left: 30px !important; } .btn-social.btn-xs :first-child { line-height: 20px; width: 20px; font-size: 1.2em; } .btn-social-icon { position: relative; padding-left: 44px !important; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; height: 34px; width: 34px; padding: 0; } .btn-social-icon :first-child { position: absolute; left: 0; top: 0; bottom: 0; width: 32px !important; line-height: 34px !important; font-size: 1.6em!important; text-align: center; border-right: 1px solid rgba(0, 0, 0, 0.2); } .btn-social-icon.btn-lg { padding-left: 60px !important; } .btn-social-icon.btn-lg :first-child { line-height: 45px; width: 45px; font-size: 1.8em; } .btn-social-icon.btn-sm { padding-left: 38px !important; } .btn-social-icon.btn-sm :first-child { line-height: 28px; width: 28px; font-size: 1.4em; } .btn-social-icon.btn-xs { padding-left: 30px !important; } .btn-social-icon.btn-xs :first-child { line-height: 20px; width: 20px; font-size: 1.2em; } .btn-social-icon :first-child { border: none; text-align: center; width: 100%!important; } .btn-social-icon.btn-lg { height: 45px; width: 45px; padding-left: 0; padding-right: 0; } .btn-social-icon.btn-sm { height: 30px; width: 30px; padding-left: 0; padding-right: 0; } .btn-social-icon.btn-xs { height: 22px; width: 22px; padding-left: 0; padding-right: 0; } .btn-bitbucket { color: #ffffff; background-color: #205081; border-color: rgba(0, 0, 0, 0.2); } .btn-bitbucket:hover, .btn-bitbucket:focus, .btn-bitbucket:active, .btn-bitbucket.active, .open .dropdown-toggle.btn-bitbucket { color: #ffffff; background-color: #183c60; border-color: rgba(0, 0, 0, 0.2); } .btn-bitbucket:active, .btn-bitbucket.active, .open .dropdown-toggle.btn-bitbucket { background-image: none; } .btn-bitbucket.disabled, .btn-bitbucket[disabled], fieldset[disabled] .btn-bitbucket, .btn-bitbucket.disabled:hover, .btn-bitbucket[disabled]:hover, fieldset[disabled] .btn-bitbucket:hover, .btn-bitbucket.disabled:focus, .btn-bitbucket[disabled]:focus, fieldset[disabled] .btn-bitbucket:focus, .btn-bitbucket.disabled:active, .btn-bitbucket[disabled]:active, fieldset[disabled] .btn-bitbucket:active, .btn-bitbucket.disabled.active, .btn-bitbucket[disabled].active, fieldset[disabled] .btn-bitbucket.active { background-color: #205081; border-color: rgba(0, 0, 0, 0.2); } .btn-bitbucket .badge { color: #205081; background-color: #ffffff; } .btn-dropbox { color: #ffffff; background-color: #1087dd; border-color: rgba(0, 0, 0, 0.2); } .btn-dropbox:hover, .btn-dropbox:focus, .btn-dropbox:active, .btn-dropbox.active, .open .dropdown-toggle.btn-dropbox { color: #ffffff; background-color: #0d70b7; border-color: rgba(0, 0, 0, 0.2); } .btn-dropbox:active, .btn-dropbox.active, .open .dropdown-toggle.btn-dropbox { background-image: none; } .btn-dropbox.disabled, .btn-dropbox[disabled], fieldset[disabled] .btn-dropbox, .btn-dropbox.disabled:hover, .btn-dropbox[disabled]:hover, fieldset[disabled] .btn-dropbox:hover, .btn-dropbox.disabled:focus, .btn-dropbox[disabled]:focus, fieldset[disabled] .btn-dropbox:focus, .btn-dropbox.disabled:active, .btn-dropbox[disabled]:active, fieldset[disabled] .btn-dropbox:active, .btn-dropbox.disabled.active, .btn-dropbox[disabled].active, fieldset[disabled] .btn-dropbox.active { background-color: #1087dd; border-color: rgba(0, 0, 0, 0.2); } .btn-dropbox .badge { color: #1087dd; background-color: #ffffff; } .btn-facebook { color: #ffffff; background-color: #3b5998; border-color: rgba(0, 0, 0, 0.2); } .btn-facebook:hover, .btn-facebook:focus, .btn-facebook:active, .btn-facebook.active, .open .dropdown-toggle.btn-facebook { color: #ffffff; background-color: #30487b; border-color: rgba(0, 0, 0, 0.2); } .btn-facebook:active, .btn-facebook.active, .open .dropdown-toggle.btn-facebook { background-image: none; } .btn-facebook.disabled, .btn-facebook[disabled], fieldset[disabled] .btn-facebook, .btn-facebook.disabled:hover, .btn-facebook[disabled]:hover, fieldset[disabled] .btn-facebook:hover, .btn-facebook.disabled:focus, .btn-facebook[disabled]:focus, fieldset[disabled] .btn-facebook:focus, .btn-facebook.disabled:active, .btn-facebook[disabled]:active, fieldset[disabled] .btn-facebook:active, .btn-facebook.disabled.active, .btn-facebook[disabled].active, fieldset[disabled] .btn-facebook.active { background-color: #3b5998; border-color: rgba(0, 0, 0, 0.2); } .btn-facebook .badge { color: #3b5998; background-color: #ffffff; } .btn-flickr { color: #ffffff; background-color: #ff0084; border-color: rgba(0, 0, 0, 0.2); } .btn-flickr:hover, .btn-flickr:focus, .btn-flickr:active, .btn-flickr.active, .open .dropdown-toggle.btn-flickr { color: #ffffff; background-color: #d6006f; border-color: rgba(0, 0, 0, 0.2); } .btn-flickr:active, .btn-flickr.active, .open .dropdown-toggle.btn-flickr { background-image: none; } .btn-flickr.disabled, .btn-flickr[disabled], fieldset[disabled] .btn-flickr, .btn-flickr.disabled:hover, .btn-flickr[disabled]:hover, fieldset[disabled] .btn-flickr:hover, .btn-flickr.disabled:focus, .btn-flickr[disabled]:focus, fieldset[disabled] .btn-flickr:focus, .btn-flickr.disabled:active, .btn-flickr[disabled]:active, fieldset[disabled] .btn-flickr:active, .btn-flickr.disabled.active, .btn-flickr[disabled].active, fieldset[disabled] .btn-flickr.active { background-color: #ff0084; border-color: rgba(0, 0, 0, 0.2); } .btn-flickr .badge { color: #ff0084; background-color: #ffffff; } .btn-foursquare { color: #ffffff; background-color: #0072b1; border-color: rgba(0, 0, 0, 0.2); } .btn-foursquare:hover, .btn-foursquare:focus, .btn-foursquare:active, .btn-foursquare.active, .open .dropdown-toggle.btn-foursquare { color: #ffffff; background-color: #005888; border-color: rgba(0, 0, 0, 0.2); } .btn-foursquare:active, .btn-foursquare.active, .open .dropdown-toggle.btn-foursquare { background-image: none; } .btn-foursquare.disabled, .btn-foursquare[disabled], fieldset[disabled] .btn-foursquare, .btn-foursquare.disabled:hover, .btn-foursquare[disabled]:hover, fieldset[disabled] .btn-foursquare:hover, .btn-foursquare.disabled:focus, .btn-foursquare[disabled]:focus, fieldset[disabled] .btn-foursquare:focus, .btn-foursquare.disabled:active, .btn-foursquare[disabled]:active, fieldset[disabled] .btn-foursquare:active, .btn-foursquare.disabled.active, .btn-foursquare[disabled].active, fieldset[disabled] .btn-foursquare.active { background-color: #0072b1; border-color: rgba(0, 0, 0, 0.2); } .btn-foursquare .badge { color: #0072b1; background-color: #ffffff; } .btn-github { color: #ffffff; background-color: #444444; border-color: rgba(0, 0, 0, 0.2); } .btn-github:hover, .btn-github:focus, .btn-github:active, .btn-github.active, .open .dropdown-toggle.btn-github { color: #ffffff; background-color: #303030; border-color: rgba(0, 0, 0, 0.2); } .btn-github:active, .btn-github.active, .open .dropdown-toggle.btn-github { background-image: none; } .btn-github.disabled, .btn-github[disabled], fieldset[disabled] .btn-github, .btn-github.disabled:hover, .btn-github[disabled]:hover, fieldset[disabled] .btn-github:hover, .btn-github.disabled:focus, .btn-github[disabled]:focus, fieldset[disabled] .btn-github:focus, .btn-github.disabled:active, .btn-github[disabled]:active, fieldset[disabled] .btn-github:active, .btn-github.disabled.active, .btn-github[disabled].active, fieldset[disabled] .btn-github.active { background-color: #444444; border-color: rgba(0, 0, 0, 0.2); } .btn-github .badge { color: #444444; background-color: #ffffff; } .btn-google-plus { color: #ffffff; background-color: #dd4b39; border-color: rgba(0, 0, 0, 0.2); } .btn-google-plus:hover, .btn-google-plus:focus, .btn-google-plus:active, .btn-google-plus.active, .open .dropdown-toggle.btn-google-plus { color: #ffffff; background-color: #ca3523; border-color: rgba(0, 0, 0, 0.2); } .btn-google-plus:active, .btn-google-plus.active, .open .dropdown-toggle.btn-google-plus { background-image: none; } .btn-google-plus.disabled, .btn-google-plus[disabled], fieldset[disabled] .btn-google-plus, .btn-google-plus.disabled:hover, .btn-google-plus[disabled]:hover, fieldset[disabled] .btn-google-plus:hover, .btn-google-plus.disabled:focus, .btn-google-plus[disabled]:focus, fieldset[disabled] .btn-google-plus:focus, .btn-google-plus.disabled:active, .btn-google-plus[disabled]:active, fieldset[disabled] .btn-google-plus:active, .btn-google-plus.disabled.active, .btn-google-plus[disabled].active, fieldset[disabled] .btn-google-plus.active { background-color: #dd4b39; border-color: rgba(0, 0, 0, 0.2); } .btn-google-plus .badge { color: #dd4b39; background-color: #ffffff; } .btn-instagram { color: #ffffff; background-color: #3f729b; border-color: rgba(0, 0, 0, 0.2); } .btn-instagram:hover, .btn-instagram:focus, .btn-instagram:active, .btn-instagram.active, .open .dropdown-toggle.btn-instagram { color: #ffffff; background-color: #335d7e; border-color: rgba(0, 0, 0, 0.2); } .btn-instagram:active, .btn-instagram.active, .open .dropdown-toggle.btn-instagram { background-image: none; } .btn-instagram.disabled, .btn-instagram[disabled], fieldset[disabled] .btn-instagram, .btn-instagram.disabled:hover, .btn-instagram[disabled]:hover, fieldset[disabled] .btn-instagram:hover, .btn-instagram.disabled:focus, .btn-instagram[disabled]:focus, fieldset[disabled] .btn-instagram:focus, .btn-instagram.disabled:active, .btn-instagram[disabled]:active, fieldset[disabled] .btn-instagram:active, .btn-instagram.disabled.active, .btn-instagram[disabled].active, fieldset[disabled] .btn-instagram.active { background-color: #3f729b; border-color: rgba(0, 0, 0, 0.2); } .btn-instagram .badge { color: #3f729b; background-color: #ffffff; } .btn-linkedin { color: #ffffff; background-color: #007bb6; border-color: rgba(0, 0, 0, 0.2); } .btn-linkedin:hover, .btn-linkedin:focus, .btn-linkedin:active, .btn-linkedin.active, .open .dropdown-toggle.btn-linkedin { color: #ffffff; background-color: #005f8d; border-color: rgba(0, 0, 0, 0.2); } .btn-linkedin:active, .btn-linkedin.active, .open .dropdown-toggle.btn-linkedin { background-image: none; } .btn-linkedin.disabled, .btn-linkedin[disabled], fieldset[disabled] .btn-linkedin, .btn-linkedin.disabled:hover, .btn-linkedin[disabled]:hover, fieldset[disabled] .btn-linkedin:hover, .btn-linkedin.disabled:focus, .btn-linkedin[disabled]:focus, fieldset[disabled] .btn-linkedin:focus, .btn-linkedin.disabled:active, .btn-linkedin[disabled]:active, fieldset[disabled] .btn-linkedin:active, .btn-linkedin.disabled.active, .btn-linkedin[disabled].active, fieldset[disabled] .btn-linkedin.active { background-color: #007bb6; border-color: rgba(0, 0, 0, 0.2); } .btn-linkedin .badge { color: #007bb6; background-color: #ffffff; } .btn-tumblr { color: #ffffff; background-color: #2c4762; border-color: rgba(0, 0, 0, 0.2); } .btn-tumblr:hover, .btn-tumblr:focus, .btn-tumblr:active, .btn-tumblr.active, .open .dropdown-toggle.btn-tumblr { color: #ffffff; background-color: #1f3346; border-color: rgba(0, 0, 0, 0.2); } .btn-tumblr:active, .btn-tumblr.active, .open .dropdown-toggle.btn-tumblr { background-image: none; } .btn-tumblr.disabled, .btn-tumblr[disabled], fieldset[disabled] .btn-tumblr, .btn-tumblr.disabled:hover, .btn-tumblr[disabled]:hover, fieldset[disabled] .btn-tumblr:hover, .btn-tumblr.disabled:focus, .btn-tumblr[disabled]:focus, fieldset[disabled] .btn-tumblr:focus, .btn-tumblr.disabled:active, .btn-tumblr[disabled]:active, fieldset[disabled] .btn-tumblr:active, .btn-tumblr.disabled.active, .btn-tumblr[disabled].active, fieldset[disabled] .btn-tumblr.active { background-color: #2c4762; border-color: rgba(0, 0, 0, 0.2); } .btn-tumblr .badge { color: #2c4762; background-color: #ffffff; } .btn-twitter { color: #ffffff; background-color: #55acee; border-color: rgba(0, 0, 0, 0.2); } .btn-twitter:hover, .btn-twitter:focus, .btn-twitter:active, .btn-twitter.active, .open .dropdown-toggle.btn-twitter { color: #ffffff; background-color: #309aea; border-color: rgba(0, 0, 0, 0.2); } .btn-twitter:active, .btn-twitter.active, .open .dropdown-toggle.btn-twitter { background-image: none; } .btn-twitter.disabled, .btn-twitter[disabled], fieldset[disabled] .btn-twitter, .btn-twitter.disabled:hover, .btn-twitter[disabled]:hover, fieldset[disabled] .btn-twitter:hover, .btn-twitter.disabled:focus, .btn-twitter[disabled]:focus, fieldset[disabled] .btn-twitter:focus, .btn-twitter.disabled:active, .btn-twitter[disabled]:active, fieldset[disabled] .btn-twitter:active, .btn-twitter.disabled.active, .btn-twitter[disabled].active, fieldset[disabled] .btn-twitter.active { background-color: #55acee; border-color: rgba(0, 0, 0, 0.2); } .btn-twitter .badge { color: #55acee; background-color: #ffffff; } .btn-vk { color: #ffffff; background-color: #587ea3; border-color: rgba(0, 0, 0, 0.2); } .btn-vk:hover, .btn-vk:focus, .btn-vk:active, .btn-vk.active, .open .dropdown-toggle.btn-vk { color: #ffffff; background-color: #4a6a89; border-color: rgba(0, 0, 0, 0.2); } .btn-vk:active, .btn-vk.active, .open .dropdown-toggle.btn-vk { background-image: none; } .btn-vk.disabled, .btn-vk[disabled], fieldset[disabled] .btn-vk, .btn-vk.disabled:hover, .btn-vk[disabled]:hover, fieldset[disabled] .btn-vk:hover, .btn-vk.disabled:focus, .btn-vk[disabled]:focus, fieldset[disabled] .btn-vk:focus, .btn-vk.disabled:active, .btn-vk[disabled]:active, fieldset[disabled] .btn-vk:active, .btn-vk.disabled.active, .btn-vk[disabled].active, fieldset[disabled] .btn-vk.active { background-color: #587ea3; border-color: rgba(0, 0, 0, 0.2); } .btn-vk .badge { color: #587ea3; background-color: #ffffff; } .error{ color:#990000;}
{ "content_hash": "08dbaebb6b348f288138168f99cf1272", "timestamp": "", "source": "github", "line_count": 3407, "max_line_length": 304, "avg_line_length": 24.296448488406224, "alnum_prop": 0.6625915098214501, "repo_name": "Raysail/lean", "id": "2ecd3d94a9de25b9029f8d006683b5f989a66ee8", "size": "82778", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "design/admin/css/Admin.css", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "476" }, { "name": "CSS", "bytes": "954019" }, { "name": "HTML", "bytes": "50033" }, { "name": "JavaScript", "bytes": "1619475" }, { "name": "PHP", "bytes": "4086356" } ], "symlink_target": "" }
"use strict"; function TourGuide(iface) { this._iface = iface; this._create_tour(); } TourGuide.prototype._create_tour = function() { var self = this; this._tour = new Tour({ storage: false, onStart: function() { $('.nav > li').addClass('disabled-nav'); }, onEnd: function() { self._iface.deactivate_active_panel(); // Ensure that nav is no longer disabled (which it may be if used // ended tour early). $('.nav > li').removeClass('disabled-nav'); }, steps: [ { element: '.query-name:first', placement: 'bottom', title: 'Queries', content: "<strong>Query</strong> sequences are nucleotide or amino acid seqquences for which you are searching (e.g., the nucleotide sequence corresponding to a certain organism's gene).", }, { element: '.subject-name:first', placement: 'bottom', title: 'Subjects', content: "Each query sequence will have hits to one or more <strong>subject</strong> sequences from BLAST's database (e.g., listings of all genes in all organisms that BLAST knows about).", }, { element: '.subject:first svg', placement: 'top', title: 'Alignments', content: "For each query-subject pairing, you will have one or more <strong>alignments</strong>, in which BLAST deemed a portion of the query sequence to align to a portion of the subject sequence. For this query-subject combination, you see two alignments.", }, { element: '.subject:first svg', placement: 'top', title: 'Viewing alignments', content: "Mouse over an alignment to see details such as its position, score, and reading frame. Click on an alignment to select it. After selecting, you can view or export the alignment by clicking the associated buttons.", }, { element: '.subject:first svg', placement: 'top', title: 'Zooming and panning', content: "To zoom and pan the query sequence, move your mouse cursor near the Query (top) axis, then scroll up using your mouse wheel. After zooming in, click the left mouse button and drag left or right to pan. To zoom back out, scroll the mouse wheel down. You can zoom and pan the subject sequence by performing the same manipulations with your mouse cursor near the Subject (bottom) axis.", }, { element: '.export-image:first', placement: 'left', title: 'Exporting images', content: 'Click the <strong>Export image</strong> button to export your alignment image to SVG (vector) or high-resolution PNG (bitmap) formats. SVGs can be easily edited in applications such as Inkscape or Adobe Illustrator, allowing you to delete certain alignments, change axis labels, and make whatever other modifications you please.', }, { element: '#load-results', placement: 'bottom', title: 'Loading your own data', onShown: function() { var load_nav = $('#load-results'); load_nav.removeClass('disabled-nav'); self._iface.activate_panel(load_nav); // This does not persist across different tour steps, so no need to // manually save original value and reset it. $('.tour-tour').css('position', 'fixed'); }, onPrev: function() { var load_nav = $('#load-results'); load_nav.addClass('disabled-nav'); self._iface.deactivate_active_panel(); }, content: 'Click <strong>Load results</strong> to load your own data. You can load BLAST results stored at a central location (e.g., from a repository containing all of your lab\'s BLAST results), or ones that are stored on your own computer.' }, { element: '#display-params', placement: 'left', title: 'Filtering data', onShown: function() { $('.tour-tour').css('position', 'fixed'); }, content: 'You can limit the number of results shown to make generating graphs faster, show only queries or subjects that have certain text in their names, or hide alignments whose E values, scores, or lengths are below defined values. You can also change the colour used for generating images.' }, { orphan: true, title: 'Enjoy!', content: 'If you have any issues with or suggestions for Kablammo, please let us know. Otherwise, have fun!' }, ] }); } TourGuide.prototype.start = function() { this._tour.init(); this._tour.start(); // When testing, can skip to certain step. //this._tour.goTo(5); }
{ "content_hash": "14719ca06a2959cba8865dea7f5d7a08", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 402, "avg_line_length": 42.669724770642205, "alnum_prop": 0.6355622446785637, "repo_name": "smith1511/AzureBlast", "id": "6d859c4879f38456b6e62d0426c4d0e4310fb514", "size": "4651", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "AzureBlast.Web/Areas/Kablammo/Scripts/tour_guide.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "116" }, { "name": "C#", "bytes": "205325" }, { "name": "CSS", "bytes": "20193" }, { "name": "JavaScript", "bytes": "284508" }, { "name": "Python", "bytes": "4554" }, { "name": "Shell", "bytes": "3887" } ], "symlink_target": "" }
<?php namespace Zend\Mail\Header; use Zend\Mail\Header; /** * @category Zend * @package Zend_Mail * @subpackage Header * @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 ContentType implements Header { /** * Header encoding * * @var string */ protected $encoding = 'ASCII'; /** * @var string */ protected $type; /** * @var array */ protected $parameters = array(); /** * Factory: create Content-Type header object from string * * @param string $headerLine * @return ContentType */ public static function fromString($headerLine) { $headerLine = iconv_mime_decode($headerLine, ICONV_MIME_DECODE_CONTINUE_ON_ERROR); list($name, $value) = explode(': ', $headerLine, 2); // check to ensure proper header type for this factory if (strtolower($name) !== 'content-type') { throw new Exception\InvalidArgumentException('Invalid header line for Content-Type string'); } $value = str_replace("\r\n ", " ", $value); $values = preg_split('#\s*;\s*#', $value); $type = array_shift($values); $header = new static(); $header->setType($type); if (count($values)) { foreach ($values as $keyValuePair) { list($key, $value) = explode('=', $keyValuePair); $value = trim($value, "\"\' \t\n\r\0\x0B"); $header->addParameter($key, $value); } } return $header; } /** * Get header name * * @return string */ public function getFieldName() { return 'Content-Type'; } /** * Get header value * * @return string */ public function getFieldValue() { $prepared = $this->type; if (empty($this->parameters)) { return $prepared; } $values = array($prepared); foreach ($this->parameters as $attribute => $value) { $values[] = sprintf('%s="%s"', $attribute, $value); } $value = implode(";\r\n ", $values); return $value; } /** * Set header encoding * * @param string $encoding * @return ContentType */ public function setEncoding($encoding) { $this->encoding = $encoding; return $this; } /** * Get header encoding * * @return string */ public function getEncoding() { return $this->encoding; } /** * Serialize header to string * * @return string */ public function toString() { return 'Content-Type: ' . $this->getFieldValue() . "\r\n"; } /** * Set the content type * * @param string $type * @return ContentType */ public function setType($type) { if (!preg_match('/^[a-z_-]+\/[a-z_-]+$/i', $type)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a value in the format "type/subtype"; received "%s"', __METHOD__, (string) $type )); } $this->type = $type; return $this; } /** * Retrieve the content type * * @return void */ public function getType() { return $this->type; } /** * Add a parameter pair * * @param string $name * @param string $value * @return ContentType */ public function addParameter($name, $value) { $name = strtolower($name); $this->parameters[$name] = (string) $value; return $this; } /** * Get all parameters * * @return array */ public function getParameters() { return $this->parameters; } /** * Get a parameter by name * * @param string $name * @return null|string */ public function getParameter($name) { $name = strtolower($name); if (isset($this->parameters[$name])) { return $this->parameters[$name]; } return null; } /** * Remove a named parameter * * @param string $name * @return bool */ public function removeParameter($name) { $name = strtolower($name); if (isset($this->parameters[$name])) { unset($this->parameters[$name]); return true; } return false; } }
{ "content_hash": "2365049fdb5fe1455a3812df80ca5b37", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 104, "avg_line_length": 21.88262910798122, "alnum_prop": 0.5024672816992062, "repo_name": "dineshkummarc/zf2", "id": "4f94e00fd5c2479be7afa6e7a8e7caa2f60f7a8f", "size": "5353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/Zend/Mail/Header/ContentType.php", "mode": "33261", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
namespace solar { class file_system; //this builder handles files that contain configuration options for building side-by-side files. // //ex. button.tga has dds compression configuration in button.peon. class build_config_file_builder : public builder { private: file_system& _file_system; std::string _src_extension; std::string _config_target_extension; mutable std::unique_ptr<checksum> _checksum; public: build_config_file_builder(file_system& file_system); build_config_file_builder(file_system& file_system, json_object& object); virtual std::string to_string() const override; virtual std::unique_ptr<builder> clone(json_object& object) override; virtual std::string get_src_extension() override; virtual std::string get_dst_folder() override; virtual bool build_file(peon& peon, const std::string& src_path, build_file_is_forced is_forced) override; private: checksum get_checksum() const; bool build_config_target_file(peon& peon, const std::string& src_path, const char* reason); }; }
{ "content_hash": "ba18b090b20be21b7b82294f32e2b7e6", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 108, "avg_line_length": 32.4375, "alnum_prop": 0.7418111753371869, "repo_name": "jseward/peon", "id": "4341c2a2e5a4c700b3a340c290d091fef0437ed8", "size": "1074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/peon/builders/build_config_file_builder.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "570" }, { "name": "C++", "bytes": "46375" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@android:color/transparent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:background="@android:color/white" android:orientation="vertical" android:padding="@dimen/editWindowPadding"> <TextView android:id="@+id/tvSceneObjectName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginBottom="16dp" android:layout_weight="1" android:gravity="center" android:text="Large" android:textAppearance="?android:attr/textAppearanceLarge"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="2" android:orientation="horizontal" android:weightSum="1"> <TextView android:id="@+id/tvScale" android:layout_width="@dimen/editObjectTextSize" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="@string/tv_scale" android:textAppearance="?android:attr/textAppearanceLarge"/> <Button android:id="@+id/bScaleUp" android:layout_width="41dp" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:layout_weight="0.02" android:background="@drawable/scale_up_button"/> <Button android:id="@+id/bScaleDown" android:layout_width="41dp" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:layout_marginStart="16dp" android:layout_weight="0.02" android:background="@drawable/scale_down_button"/> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="2" android:orientation="horizontal"> <TextView android:id="@+id/tvYaw" android:layout_width="@dimen/editObjectTextSize" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="@string/tv_yaw" android:textAppearance="?android:attr/textAppearanceLarge"/> <SeekBar android:id="@+id/sbYaw" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:indeterminate="false"/> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="2" android:orientation="horizontal"> <TextView android:id="@+id/tvPitch" android:layout_width="@dimen/editObjectTextSize" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="@string/tv_pitch" android:textAppearance="?android:attr/textAppearanceLarge"/> <SeekBar android:id="@+id/sbPitch" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:indeterminate="false"/> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="2" android:orientation="horizontal"> <TextView android:id="@+id/tvRoll" android:layout_width="@dimen/editObjectTextSize" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="@string/tv_roll" android:textAppearance="?android:attr/textAppearanceLarge"/> <SeekBar android:id="@+id/sbRoll" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:indeterminate="false"/> </LinearLayout> <Button android:id="@+id/bRemoveFromScene" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/removeFromScene" /> </LinearLayout> <Button android:id="@+id/bDone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right|top" android:layout_margin="1dp" android:text="X"/> </FrameLayout>
{ "content_hash": "380bfa48fbfa6f4025b72edf9067d0c3", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 76, "avg_line_length": 37.53061224489796, "alnum_prop": 0.5657059996374841, "repo_name": "Samsung/GearVRf", "id": "66ecfbb3ee1c41a4d62a398877eca3ec80a88005", "size": "5517", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "GVRf/tools/gvr-scene-editor/app/src/main/res/layout/edit_object_layout.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1168974" }, { "name": "C++", "bytes": "7061283" }, { "name": "CMake", "bytes": "5001" }, { "name": "CSS", "bytes": "1394" }, { "name": "GLSL", "bytes": "77438" }, { "name": "HTML", "bytes": "4555" }, { "name": "Java", "bytes": "5384972" }, { "name": "JavaScript", "bytes": "868539" }, { "name": "Makefile", "bytes": "17080" }, { "name": "Objective-C", "bytes": "4040" }, { "name": "Python", "bytes": "28941" }, { "name": "Shell", "bytes": "5361" } ], "symlink_target": "" }
import { Injectable } from '@angular/core'; import { DataForEmailUnsubscribe } from 'app/api/models/data-for-email-unsubscribe'; import { NotificationSettingsService } from 'app/api/services/notification-settings.service'; import { ErrorHandlerService } from 'app/core/error-handler.service'; import { BehaviorSubject, Observable, of } from 'rxjs'; import { tap } from 'rxjs/operators'; // In production the data is pre-rendered in the host page declare const data: DataForEmailUnsubscribe; export type UnsubscribeStep = 'form' | 'done'; /** * Holds the DataForEmailUnsubscribe instance and manages its state */ @Injectable() export class UnsubscribeState { data$ = new BehaviorSubject<DataForEmailUnsubscribe>(null); processing$ = new BehaviorSubject(false); step$ = new BehaviorSubject<UnsubscribeStep>('form'); private key: string; constructor( private errorHandler: ErrorHandlerService, private notificationSettingsService: NotificationSettingsService) { } /** * Initializes the data */ initialize(key: string): Observable<DataForEmailUnsubscribe> { this.key = key; if (data) { this.data$.next(data); return of(data); } else { // We're on development. Fetch the data. return this.notificationSettingsService.getDataForEmailUnsubscribe({ key }).pipe( tap(d => this.data$.next(d)) ); } } get data(): DataForEmailUnsubscribe { return this.data$.value; } /** * Performs the e-mail unsubscription */ unsubscribe() { if (this.processing$.value) { return; } this.processing$.next(true); this.notificationSettingsService.emailUnsubscribe({ key: this.key }) .subscribe( () => { this.processing$.next(false); this.step$.next('done'); }, e => { this.processing$.next(false); this.errorHandler.handleHttpError(e); }); } /** * Navigates to the given URL */ exit() { location.assign(this.data.homeUrl); } }
{ "content_hash": "dc372229a8fe15487d23d323201464c4", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 93, "avg_line_length": 26.723684210526315, "alnum_prop": 0.6637124569177745, "repo_name": "cyclosproject/cyclos4-ui", "id": "bee4adb0851009f63819a51eddcca5ffab9ea8e5", "size": "2031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/unsubscribe/unsubscribe-state.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4329" }, { "name": "HTML", "bytes": "764844" }, { "name": "JavaScript", "bytes": "788" }, { "name": "SCSS", "bytes": "159779" }, { "name": "TypeScript", "bytes": "1809903" } ], "symlink_target": "" }
package org.apache.lenya.cms.site; /** * A node in the site structure. */ public interface SiteNode { /** * @return The site structure this node belongs to. */ SiteStructure getStructure(); /** * @return The path. */ String getPath(); /** * @return The parent node. * @throws SiteException If the node has no parent. */ SiteNode getParent() throws SiteException; /** * @return If this is a top level node. Top level nodes have no parents. */ boolean isTopLevel(); /** * @return The languages of this node. */ String[] getLanguages(); /** * @param language The language. * @return The link for the language. * @throws SiteException if no link is contained for the language. */ Link getLink(String language) throws SiteException; /** * @return The UUID of this node. */ String getUuid(); /** * Checks if a link for a certain language is contained. * @param language The language. * @return A boolean value. */ boolean hasLink(String language); /** * @return The name, i.e. the last path element. */ String getName(); /** * @return if the node is visible in the navigation. */ boolean isVisible(); /** * Sets the node visibility in the navigation. * @param visibleInNav if the node should be visible. */ void setVisible(boolean visibleInNav); /** * Deletes this node. */ void delete(); /** * @return The children of this node. */ SiteNode[] getChildren(); /** * @return if the node has an external link. */ boolean hasLink(); /** * @return The external link. */ String getHref(); /** * @return The suffix. */ String getSuffix(); }
{ "content_hash": "c90fb8fbd16c25e344e44c850edfef63", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 76, "avg_line_length": 19.86315789473684, "alnum_prop": 0.5633280339162692, "repo_name": "apache/lenya", "id": "af9936c337f3c133dc0d6fcbe926f5617e0af8b2", "size": "2702", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "org.apache.lenya.core.publication.api/src/main/java/org/apache/lenya/cms/site/SiteNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8295" }, { "name": "CSS", "bytes": "30572" }, { "name": "HTML", "bytes": "28814" }, { "name": "Java", "bytes": "2328029" }, { "name": "JavaScript", "bytes": "84684" }, { "name": "NSIS", "bytes": "4675" }, { "name": "Shell", "bytes": "23705" }, { "name": "XSLT", "bytes": "598838" } ], "symlink_target": "" }
(function (angular) { angular.module('authentication', []) .factory('AuthenticationService', AuthenticationService); AuthenticationService.$inject = ['$http', '$window']; function AuthenticationService($http, $window) { var service = { saveToken: saveToken, getToken: getToken, isLoggedIn: isLoggedIn, currentUser: currentUser, register: register, login: login, logout: logout }; return service; function saveToken(token) { $window.localStorage['mean-token'] = token; } function getToken() { return $window.localStorage['mean-token']; } function isLoggedIn() { var token = getToken(); var payload; if(token){ payload = token.split('.')[1]; payload = $window.atob(payload); payload = JSON.parse(payload); return payload.exp > Date.now() / 1000; } else { return false; } } function currentUser() { if(isLoggedIn()){ var token = getToken(); var payload = token.split('.')[1]; payload = $window.atob(payload); payload = JSON.parse(payload); return { id: payload._id, email : payload.email, ime : payload.ime, prezime: payload.prezime }; } } function register(user) { return $http({ // without anything here, put * in app.post() url : 'http://localhost:8181/api/accounts/signup', method : "POST", data : $.param(user), responseType : "application/json", headers : { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function mySuccess(response) { // saveToken(response.data.token); alert("register service " + response.data.message); }, function myError(response) { alert(response.statusText); }); } function login(user) { return $http({ // without anything here, put * in app.post() url : 'http://localhost:8181/api/accounts/login', method : "POST", data : $.param(user), responseType : "application/json", headers : { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function mySuccess(response) { alert(response.data.message); saveToken(response.data.token); }, function myError(response) { alert(response.statusText); }); } function logout() { $window.localStorage.removeItem('mean-token'); } }; })(angular);
{ "content_hash": "f69d396444a9989cb8e464c20c95381f", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 65, "avg_line_length": 26.252525252525253, "alnum_prop": 0.5606002308580224, "repo_name": "predragfalcic/napredne_web_tehnologije", "id": "de03caaa113bf9f1421a3be7f2c104da5bf00f07", "size": "2599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/public/services/auth_service.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "980" }, { "name": "HTML", "bytes": "10451" }, { "name": "JavaScript", "bytes": "33747" } ], "symlink_target": "" }
package com.wounit.rules; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.lang.reflect.Field; import java.net.URL; import org.junit.Ignore; import org.junit.Test; import com.webobjects.eoaccess.EOModel; import com.webobjects.eoaccess.EOModelGroup; import com.webobjects.foundation.NSArray; import com.webobjects.foundation.NSBundle; import com.webobjects.foundation.NSDictionary; import com.wounit.exceptions.WOUnitException; import er.extensions.foundation.ERXProperties; /** * @author <a href="mailto:hprange@gmail.com">Henrique Prange</a> */ public class TestTemporaryEditingContext extends AbstractEditingContextTest { private static final String JAVA_MEMORY_ADAPTOR_BUNDLE_NAME = "JavaMemoryAdaptor"; @Override protected TemporaryEditingContext createEditingContext(String... modelNames) { return new TemporaryEditingContext(modelNames); } @Test @Ignore("Don't know how to clean the mess in the adaptor context after the test") public void doNotClearTheDatabaseContextIfNoModelsLoaded() throws Throwable { EOModelGroup modelGroup = EOModelGroup.defaultGroup(); NSArray<EOModel> models = modelGroup.models(); EOModel model = null; for (int i = 0; i < models.size(); i++) { model = models.get(i); modelGroup.removeModel(model); } TemporaryEditingContext editingContext = new TemporaryEditingContext(); editingContext.before(); editingContext.after(); } @Test @Ignore("Don't know how to clean the mess in the adaptor context after the test") public void exceptionIfAdaptorContextIsNotMemoryAdaptor() throws Throwable { TemporaryEditingContext editingContext = new TemporaryEditingContext(TEST_MODEL_NAME); NSArray<EOModel> models = EOModelGroup.defaultGroup().models(); for (EOModel model : models) { model.setAdaptorName("JDBC"); } editingContext.before(); thrown.expect(IllegalStateException.class); thrown.expectMessage(is("Expected er.memoryadaptor.ERMemoryAdaptorContext, but got com.webobjects.jdbcadaptor.JDBCContext. Please, use the TemporaryEditingContext constructor to load all the required models for testing.")); editingContext.after(); } @Test public void exceptionIfJavaMemoryAdaptorBundleNotFound() throws Exception { Field field = NSBundle.class.getDeclaredField("BundlesNamesTable"); field.setAccessible(true); @SuppressWarnings("unchecked") NSDictionary<String, NSBundle> bundles = (NSDictionary<String, NSBundle>) field.get(null); NSBundle bundleToRestore = bundles.remove(JAVA_MEMORY_ADAPTOR_BUNDLE_NAME); thrown.expect(WOUnitException.class); thrown.expectMessage("The JavaMemoryAdaptor bundle is not loaded. Are you sure the JavaMemoryAdaptor framework is in the test classpath?"); try { new TemporaryEditingContext(); } catch (Exception exception) { bundles.takeValueForKey(bundleToRestore, JAVA_MEMORY_ADAPTOR_BUNDLE_NAME); throw exception; } } @Test public void ignoreMissingModelWhileRestoringAdaptorConfiguration() throws Exception { AbstractEditingContextRule editingContext = initEditingContext(TEST_MODEL_NAME); editingContext.before(); EOModelGroup modelGroup = EOModelGroup.defaultGroup(); modelGroup.removeModel(modelGroup.modelNamed(TEST_MODEL_NAME)); editingContext.after(); } @Test public void restoreOriginalAdaptorConfigurationAfterTestExecution() throws Throwable { URL url = getClass().getResource("/" + TEST_MODEL_NAME + ".eomodeld"); EOModel model = EOModelGroup.defaultGroup().addModelWithPathURL(url); model.setAdaptorName("JDBC"); AbstractEditingContextRule editingContext = initEditingContext(); editingContext.before(); editingContext.after(); assertThat(EOModelGroup.defaultGroup().modelNamed(TEST_MODEL_NAME).adaptorName(), is("JDBC")); } @Test public void useMemoryAdaptorForAllModels() throws Exception { new TemporaryEditingContext(TEST_MODEL_NAME); String result = EOModelGroup.defaultGroup().modelNamed(TEST_MODEL_NAME).adaptorName(); assertThat(result, is("Memory")); } @Test public void useMemoryPrototypesForAllModels() throws Exception { new TemporaryEditingContext(); String result = ERXProperties.stringForKey("dbEOPrototypesEntityGLOBAL"); assertThat(result, is("EOMemoryPrototypes")); } }
{ "content_hash": "bf64dcbe7b9f1b25b56bd58e64c741ff", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 224, "avg_line_length": 30.321678321678323, "alnum_prop": 0.7709870848708487, "repo_name": "hprange/wounit", "id": "7cb25830391975b9a7ad86c02735255236adeca7", "size": "4950", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/wounit/rules/TestTemporaryEditingContext.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "259488" } ], "symlink_target": "" }
/** * A demo based on the Movie dataset from the Web Data Management book. * */ package org.sindice.siren.demo.movie;
{ "content_hash": "d60a10c130f58a9e29ddee7ca8fc548c", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 71, "avg_line_length": 17.571428571428573, "alnum_prop": 0.6991869918699187, "repo_name": "rdelbru/SIREn", "id": "d01167a9b6eaeb32714a5ad961833a5880f482ee", "size": "862", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "siren-demo/src/main/java/org/sindice/siren/demo/movie/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2689806" }, { "name": "Shell", "bytes": "1396" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- content security for android --> <!-- look here: http://stackoverflow.com/questions/30212306/no-content-security-policy-meta-tag-found-error-in-my-phonegap-application --> <meta http-equiv="Content-Security-Policy" content="default-src * data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; script-src * 'unsafe-inline';"> <title>NewsCanary</title> <link href="aboutPageStyle.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="js/jquery-2.2.3.min.js"></script> <script type="text/javascript" src="js/functions.js"></script> <!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.--> <script>var __adobewebfontsappname__="dreamweaver"</script><script src="http://use.edgefonts.net/montserrat:n4:default;source-sans-pro:n2:default.js" type="text/javascript"></script> </head> <body> <!-- Header content --> <header> <div class="profileLogo"> <p class="logoPlaceholder"><!-- <img src="logoImage.png" alt="sample logo"> --><span>NewsCanary</span></p> </div> <div class="profilePhoto"> <!-- Profile photo --> <img src="images/News-Briefs.png" alt="news globe" class="globe"> </div> <!-- Identity details --> <section class="profileHeader"> <h3>Welcome to NewsCanary for all your latest news and weather updates.</h3> <hr> <p><br />Please <a href="login.html">Log In</a> Here<br /> <br />Not already a member?<br /> <br /><a href="register.html"> Sign Up Here!</a></p> </section> </header> <footer> <hr> <p class="footerDisclaimer">2016 Copyrights - <span>All Rights Reserved</span></p> </footer> </body> </html>
{ "content_hash": "e016988b38946de7969b16572213ab9f", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 196, "avg_line_length": 41.5531914893617, "alnum_prop": 0.6497695852534562, "repo_name": "suethomas1/newscanaryupdate2", "id": "b3ba3550f31d882b9a695515a9ae4c9d7558e59c", "size": "1953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "19319" }, { "name": "HTML", "bytes": "27145" }, { "name": "JavaScript", "bytes": "813" } ], "symlink_target": "" }
"""Wrapper for signalfd(2) system call. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import errno import logging import os import ctypes from ctypes import ( c_int, c_void_p, c_uint32, c_uint64, c_uint8, c_int32, ) from ctypes.util import find_library import enum from ._sigsetops import ( SigSet, sigaddset, sigfillset, ) _LOGGER = logging.getLogger(__name__) ############################################################################### # Map the C interface _LIBC_PATH = find_library('c') _LIBC = ctypes.CDLL(_LIBC_PATH, use_errno=True) if getattr(_LIBC, 'signalfd', None) is None: raise ImportError('Unsupported libc version found: %s' % _LIBC_PATH) ############################################################################### # int signalfd(int fd, const sigset_t *mask, int flags); _SIGNALFD_DECL = ctypes.CFUNCTYPE(c_int, c_int, c_void_p, c_int, use_errno=True) _SIGNALFD = _SIGNALFD_DECL(('signalfd', _LIBC)) def signalfd(sigset, flags=0, prev_fd=-1): """create/update a signal file descriptor. """ if isinstance(sigset, SigSet): new_set = sigset elif sigset == 'all': new_set = SigSet() sigfillset(new_set) else: new_set = SigSet() for signum in sigset: sigaddset(new_set, signum) new_set_p = ctypes.pointer(new_set) fileno = _SIGNALFD(prev_fd, new_set_p, flags) if fileno < 0: err = ctypes.get_errno() raise OSError(err, os.strerror(err), 'signalfd(%r, %r, %r)' % (prev_fd, new_set, flags)) return fileno ############################################################################### # Constants copied from sys/signalfd.h # # See man signalfd(2) for more details. # class SFDFlags(enum.IntEnum): """Flags supported by SignalFD. """ #: Set the O_NONBLOCK file status flag on the new open file description. #: Using this flag saves extra calls to fcntl(2) to achieve the same #: result. NONBLOCK = 0o4000 #: Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See #: the description of the O_CLOEXEC flag in open(2) for reasons why this #: may be useful. CLOEXEC = 0o2000000 #: Set the O_NONBLOCK file status flag on the new open file description. Using #: this flag saves extra calls to fcntl(2) to achieve the same result. #: (since Linux 2.6.27) SFD_NONBLOCK = SFDFlags.NONBLOCK #: Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the #: description of the O_CLOEXEC flag in open(2) for reasons why this may be #: useful. #: (since Linux 2.6.27) SFD_CLOEXEC = SFDFlags.CLOEXEC ############################################################################### # The signalfd_siginfo structure # class SFDSigInfo(ctypes.Structure): """The signalfd_siginfo structure. The format of the signalfd_siginfo structure(s) returned by read(2)s from a signalfd file descriptor is as follows: struct signalfd_siginfo { uint32_t ssi_signo; /* Signal number */ int32_t ssi_errno; /* Error number (unused) */ int32_t ssi_code; /* Signal code */ uint32_t ssi_pid; /* PID of sender */ uint32_t ssi_uid; /* Real UID of sender */ int32_t ssi_fd; /* File descriptor (SIGIO) */ uint32_t ssi_tid; /* Kernel timer ID (POSIX timers) uint32_t ssi_band; /* Band event (SIGIO) */ uint32_t ssi_overrun; /* POSIX timer overrun count */ uint32_t ssi_trapno; /* Trap number that caused signal */ int32_t ssi_status; /* Exit status or signal (SIGCHLD) */ int32_t ssi_int; /* Integer sent by sigqueue(2) */ uint64_t ssi_ptr; /* Pointer sent by sigqueue(2) */ uint64_t ssi_utime; /* User CPU time consumed (SIGCHLD) */ uint64_t ssi_stime; /* System CPU time consumed (SIGCHLD) */ uint64_t ssi_addr; /* Address that generated signal (for hardware-generated signals) */ uint8_t pad[X]; /* Pad size to 128 bytes (allow for additional fields in the future) */ }; """ # pylint: disable=bad-whitespace _FIELDS = [ ('ssi_signo', c_uint32), #: Signal number ('ssi_errno', c_int32), #: Error number (unused) ('ssi_code', c_int32), #: Signal code ('ssi_pid', c_uint32), #: PID of sender ('ssi_uid', c_uint32), #: Real UID of sender ('ssi_fd', c_int32), #: File descriptor (SIGIO) ('ssi_tid', c_uint32), #: Kernel timer ID (POSIX timers) ('ssi_band', c_uint32), #: Band event (SIGIO) ('ssi_overrun', c_uint32), #: POSIX timer overrun count ('ssi_trapno', c_uint32), #: Trap number that caused signal ('ssi_status', c_int32), #: Exit status or signal (SIGCHLD) ('ssi_int', c_int32), #: Integer sent by sigqueue(2) ('ssi_ptr', c_uint64), #: Pointer sent by sigqueue(2) ('ssi_utime', c_uint64), #: User CPU time consumed (SIGCHLD) ('ssi_stime', c_uint64), #: System CPU time consumed (SIGCHLD) ('ssi_addr', c_uint64), #: Address that generated signal ] __PADWORDS = 128 - sum([ctypes.sizeof(field[1]) for field in _FIELDS]) _fields_ = _FIELDS + [ ('_pad', c_uint8 * __PADWORDS), # Pad size to 128 bytes (allow for # additional fields in the future) ] def signalfd_read(sfd): """Read signalfd_siginfo data from a signalfd filedescriptor. """ try: data = os.read(sfd, ctypes.sizeof(SFDSigInfo)) except OSError as err: # Ignore signal interruptions if err.errno != errno.EINTR: raise return None return SFDSigInfo.from_buffer_copy(data) ############################################################################### __all__ = [ 'SFD_NONBLOCK', 'SFD_CLOEXEC', 'signalfd', 'signalfd_read', ]
{ "content_hash": "0f8d592dd0b474d31488104bd9a7a9f3", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 79, "avg_line_length": 33.62765957446808, "alnum_prop": 0.5472951597595698, "repo_name": "Morgan-Stanley/treadmill", "id": "bb5d65dda49a3b80cacdeb8777c33f059b2d2a10", "size": "6322", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/python/treadmill/syscall/signalfd.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PowerShell", "bytes": "3750" }, { "name": "Python", "bytes": "3372983" }, { "name": "Ruby", "bytes": "3712" }, { "name": "Shell", "bytes": "51646" } ], "symlink_target": "" }
package cn.com.warlock.test; import java.io.Serializable; import cn.com.warlock.kafka.handler.MessageHandler; import cn.com.warlock.kafka.message.DefaultMessage; public class Demo2MessageHandler implements MessageHandler { @Override public void p1Process(DefaultMessage message) { //TODO 第一阶段处理,譬如一些需要及时 } @Override public void p2Process(DefaultMessage message) { //第二阶段处理一些耗时操作,如:最终入库 Serializable body = message.getBody(); System.out.println("Demo2MessageHandler process message:" + body); try { Thread.sleep(500); } catch (Exception e) { } } @Override public boolean onProcessError(DefaultMessage message) { //如果业务自己处理消费错误的消息,再这里实现并return false; return false; } }
{ "content_hash": "f240485463cab23ab17567b43e288542", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 74, "avg_line_length": 24.8125, "alnum_prop": 0.672544080604534, "repo_name": "warlock-china/azeroth", "id": "9f55dcf9b794b53e177c20fac272abc6495335f6", "size": "906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azeroth-kafka/src/test/java/cn/com/warlock/test/Demo2MessageHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "986724" } ], "symlink_target": "" }
package types import ( "errors" "strconv" "github.com/boltdb/bolt" "github.com/jakebailey/botzik/db/helpers" ) // Counter errors var ( ErrCounterExists = errors.New("Counter already exists") ) var ( valueKey = []byte("_value") ) // Counter wraps a bucket as a counter. type Counter struct { b *bolt.Bucket } // AsCounter converts a bucket to a Counter. func AsCounter(b *bolt.Bucket) Counter { return Counter{b} } // Init initializes a counter. func (c Counter) Init() error { return helpers.PutWrap(c.b, valueKey, []byte("0")) } // Get gets the value of a counter. func (c Counter) Get() (int64, error) { return strconv.ParseInt(string(c.b.Get(valueKey)), 10, 64) } // Set sets the value of a counter. func (c Counter) Set(x int64) error { return helpers.PutWrap(c.b, valueKey, []byte(strconv.FormatInt(x, 10))) } // Increment increments the value of a counter by i and returns the resulting value. // Negative numbers are valid. func (c Counter) Increment(i int64) (int64, error) { value, err := c.Get() if err != nil { return value, err } newValue := value + i return newValue, c.Set(newValue) }
{ "content_hash": "9f79722304402b4031477704bf0f6434", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 84, "avg_line_length": 20.87037037037037, "alnum_prop": 0.6912156166814551, "repo_name": "jakebailey/botzik", "id": "576f7b8ea6490bc7a705707aa4d9945949ae0b01", "size": "1127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/types/counter.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "47464" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <id>incluir-ou-alterar-itens-na-lista-de-ex-tarifario-vigente-no-regime-de-autopecas-nao-produzidas</id> <dbId>1073</dbId> <nome>Incluir ou alterar itens na lista de Ex-tarifário vigente no Regime de Autopeças não-produzidas</nome> <sigla></sigla> <descricao>&lt;p style="text-align:justify"&gt;Inclusão de novos itens ou alteração da Lista de Autopeças Não Produzidas, que elenca as autopeças sem produção nacional equivalente com redução da alíquota do Imposto de Importação na condição de Ex-tarifário.&lt;/p&gt;</descricao> <contato></contato> <gratuito>true</gratuito> <porcentagem-manual>false</porcentagem-manual> <servico-digital>true</servico-digital> <link-servico-digital>http://mpdg-hom-ps.lecom.com.br/processos/iniciar</link-servico-digital> <solicitantes> <solicitante id="917"> <tipo>Empresas privadas do setor automotivo.</tipo> <requisitos></requisitos> </solicitante> </solicitantes> <tempo-total-estimado> <nao-estimado-ainda/> <descricao></descricao> </tempo-total-estimado> <validade-documento> <descricao></descricao> </validade-documento> <etapas> <etapa id="2288"> <titulo>Solicitar alteração da lista</titulo> <descricao>&lt;p style="text-align:justify"&gt;Apresentação de pleito de inclusão de novos itens, alteração de redação ou revogação de itens da Lista de Autopeças Não Produzidas, conforme &lt;a href="http://www.mdic.gov.br/index.php/competitividade-industrial/setor-automotivo/regime-de-autopecas-nao-produzidas" target="_blank"&gt;formulário padrão&lt;/a&gt;.&lt;/p&gt; &lt;p style="text-align:justify"&gt;Cada pleito deverá apresentar o conjunto completo da documentação especificada abaixo.&lt;/p&gt;</descricao> <documentos> <default> <item id="1655">Código NCM – Nomenclatura Comum do Mercosul baseada no Sistema Harmonizado de Designação e de Codificação de Mercadorias</item> <item id="1656">Descrição detalhada da autopeça, suas características, sua aplicação e composição dos insumos e materiais que compõem o produto;</item> <item id="1657">Proposta de redação específica para o Ex-tarifário que caracterize suficientemente o produto;</item> <item id="1658">Catálogo original (com tradução técnica, quando em língua estrangeira), sem impedimentos ou restrições de confidencialidade, de modo que possa ser divulgado em consulta pública;</item> <item id="1659">Layout, croqui, desenhos esquemáticos, fotos representativas ou quaisquer outros meios de identificação visual do item, sem impedimentos ou restrições de confidencialidade, de modo que possam ser divulgados em consulta pública; e</item> <item id="1660">Outras informações relevantes, tais quais: * Se a autopeça solicitada representa a introdução de nova tecnologia ou se o item já é utilizado no processo produtivo; * Previsão anual de importação, em valores US$ FOB; e * Material adicional ou literatura técnica.</item> </default> </documentos> <custos> <default/> </custos> <canais-de-prestacao> <default> <canal-de-prestacao id="2366" tipo="postal"> <descricao>&lt;p&gt;&lt;b&gt;Ministério da Indústria, Comércio Exterior e Serviços &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Secretaria de Desenvolvimento e Competitividade Industrial - SDCI &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Departamento das Indústrias para a Mobilidade e Logística- DEMOB &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Coordenação-Geral das Indústrias do Complexo Automotivo - CGCA &lt;/b&gt;&lt;/p&gt; Esplanada dos Ministérios, Bloco “J”, 5º andar, Brasília/DF, CEP 70.053-900</descricao> </canal-de-prestacao> <canal-de-prestacao id="2367" tipo="presencial"> <descricao>&lt;b&gt;Ministério da Indústria, Comércio Exterior e Serviços&lt;/b&gt; - Setor de Protocolo; Esplanada dos Ministérios, Bloco “J”, andar térreo, Brasília/DF, CEP 70.053-900</descricao> </canal-de-prestacao> </default> </canais-de-prestacao> </etapa> <etapa id="2289"> <titulo>Acompanhar Consulta Pública</titulo> <descricao>&lt;p style="text-align:justify"&gt;Atendidos os requisitos mínimos de conteúdo e forma, colocam-se os pleitos em Consulta Pública pelo prazo de 30 (trinta) dias corridos, para que fabricantes nacionais de produtos equivalentes ou associações possam apresentar contestação aos pleitos.&lt;/p&gt; &lt;p style="text-align:justify"&gt;&lt;a href="https://goo.gl/5cbv1n" target="_blank"&gt;Formulário padrão para manifestação de produção nacional&lt;/a&gt;.&lt;/p&gt;</descricao> <documentos> <default/> </documentos> <custos> <default/> </custos> <canais-de-prestacao> <default> <canal-de-prestacao id="2368" tipo="web"> <descricao>http://www.mdic.gov.br/index.php/component/content/article/105-assuntos/competitividade-industrial/2459-consultas-publicas-regime-de-autopecas-nao-produzidas/</descricao> </canal-de-prestacao> </default> </canais-de-prestacao> </etapa> <etapa id="2290"> <titulo>Apresentar defesa do pleito (caso haja contestação na Consulta Pública)</titulo> <descricao>&lt;p style="text-align:justify"&gt;Caso alguma empresa manifeste capacidade de produção nacional durante a Consulta Pública, comunica-se à empresa pleiteante que existe a contestação, e solicita-se que, não concordando com a manifestação, apresente argumentos que desqualifiquem a produção nacional como equivalente ao bem importado. Será realizada então nova análise, podendo, inclusive, envolver a realização de reuniões entre as partes.&lt;/p&gt;</descricao> <documentos> <default/> </documentos> <custos> <default/> </custos> <canais-de-prestacao> <default> <canal-de-prestacao id="2369" tipo="postal"> <descricao>&lt;p&gt;&lt;b&gt;Ministério da Indústria, Comércio Exterior e Serviços &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Secretaria de Desenvolvimento e Competitividade Industrial - SDCI &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Departamento das Indústrias para a Mobilidade e Logística- DEMOB &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Coordenação-Geral das Indústrias do Complexo Automotivo - CGCA &lt;/b&gt;&lt;/p&gt; Esplanada dos Ministérios, Bloco “J”, 5º andar, Brasília/DF, CEP 70.053-900</descricao> </canal-de-prestacao> <canal-de-prestacao id="2370" tipo="presencial"> <descricao>&lt;b&gt;Ministério da Indústria, Comércio Exterior e Serviços&lt;/b&gt; - Setor de Protocolo; Esplanada dos Ministérios, Bloco “J”, andar térreo, Brasília/DF, CEP 70.053-900</descricao> </canal-de-prestacao> </default> </canais-de-prestacao> </etapa> <etapa id="2291"> <titulo>Apresentar recurso final à decisão (caso haja indeferimento pelo GECEX)</titulo> <descricao>&lt;p style="text-align:justify"&gt;Os pleitos são analisados pelo Comitê Técnico de Análise e encaminhados ao GECEX, a quem compete o deferimento ou não dos pleitos apresentados.&lt;/p&gt; &lt;p style="text-align:justify"&gt;Na hipótese do GECEX indeferir o pleito, ainda é permitido um último recurso da empresa pleiteante, agora perante a SE/CAMEX. Sendo apresentado novos argumentos pertinentes para uma nova avaliação dos membros do GECEX, o pleito volta a ser discutido.&lt;/p&gt;</descricao> <documentos> <default/> </documentos> <custos> <default/> </custos> <canais-de-prestacao> <default> <canal-de-prestacao id="2371" tipo="presencial"> <descricao>&lt;b&gt;Ministério da Indústria, Comércio Exterior e Serviços&lt;/b&gt; - Setor de Protocolo; Esplanada dos Ministérios, Bloco “J”, andar térreo, Brasília/DF, CEP 70.053-900</descricao> </canal-de-prestacao> <canal-de-prestacao id="2372" tipo="postal"> <descricao>&lt;p&gt;&lt;b&gt;Ministério da Indústria, Comércio Exterior e Serviços &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Secretaria Executiva da Câmara de Comércio Exterior (CAMEX) &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Departamento das Indústrias para a Mobilidade e Logística- DEMOB &lt;/b&gt;&lt;/p&gt; &lt;p&gt;&lt;b&gt;Coordenação-Geral das Indústrias do Complexo Automotivo - CGCA &lt;/b&gt;&lt;/p&gt; Esplanada dos Ministérios, Bloco “J”, Sala T-3, Térreo, Brasília/DF, CEP 70.053-900</descricao> </canal-de-prestacao> </default> </canais-de-prestacao> </etapa> <etapa id="2292"> <titulo>Verificar resultado em Resolução da CAMEX</titulo> <descricao>&lt;p style="text-align:justify"&gt;Se o pleito for definitivamente indeferido, o pleiteante é comunicado quanto ao fim do processo. Caso seja deferido, a concessão do ex-tarifários será declarada por Portaria da Camex.&lt;/p&gt;</descricao> <documentos> <default/> </documentos> <custos> <default/> </custos> <canais-de-prestacao> <default> <canal-de-prestacao id="2373" tipo="web"> <descricao>http://www.camex.gov.br/resolucoes-camex</descricao> </canal-de-prestacao> </default> </canais-de-prestacao> </etapa> </etapas> <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/3162" dbId="37530"> <nomeOrgao>Ministério da Indústria, Comércio Exterior e Serviços (MDIC)</nomeOrgao> </orgao> <segmentos-da-sociedade> <item idSegmento="3" idServicoSegmento="2543">Empresas</item> </segmentos-da-sociedade> <areas-de-interesse> <item>Comércio e Serviços</item> <item>Comercio externo</item> </areas-de-interesse> <palavras-chave> <item id="2751">benefício fiscal</item> <item id="2752">camex</item> <item id="2753">autopeças</item> </palavras-chave> </servico>
{ "content_hash": "f29aa16298e1cefcd8c6212b64ece9cd", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 485, "avg_line_length": 68.23456790123457, "alnum_prop": 0.6428442192871359, "repo_name": "servicosgovbr/cartas-de-homologacao", "id": "d5e1d70e4707e14c4addb20674e5978b4eb357d9", "size": "11279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cartas-servico/v3/servicos/incluir-ou-alterar-itens-na-lista-de-ex-tarifario-vigente-no-regime-de-autopecas-nao-produzidas.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "906" } ], "symlink_target": "" }
package org.scijava.event; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation identifying an event handler method. This annotation allows a * class to subscribe to multiple types of events by implementing multiple event * handling methods and annotating each with @{@link EventHandler}. * <p> * Note to developers: This annotation serves exactly the same purpose as * EventBus's {@link org.bushe.swing.event.annotation.EventSubscriber} * annotation, recapitulating a subset of the same functionality. We do this to * avoid third party code depending directly on EventBus. That is, we do not * wish to require SciJava developers to {@code import org.bushe.swing.event.*} * or similar. In this way, EventBus is isolated as only a transitive dependency * of downstream code, rather than a direct dependency. Unfortunately, because * Java annotation interfaces cannot utilize inheritance, we have to * recapitulate the functionality rather than extend it (as we are able to do * with {@link EventSubscriber}). * </p> * * @author Curtis Rueden * @see EventService */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface EventHandler { /** * Unique subscription key. If multiple {@code @EventHandler} annotations * exist with the same key, only the first to be subscribed will be respected; * the others will be silently ignored. If no key is specified, the event * handler is always subscribed. * <p> * This feature exists to enable better extensibility of event handling: if * code exists that handles an event in an undesirable way, that logic can be * completely intercepted and overridden by writing more code that handles the * event in a better way, specifying the same key as the original. * </p> */ String key() default ""; }
{ "content_hash": "f4f281506b35601d53ad345a3b949244", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 80, "avg_line_length": 40.3125, "alnum_prop": 0.7602067183462532, "repo_name": "scijava/scijava-common", "id": "ad94bda55a706c6150f2a1e03a6b0ca24b413203", "size": "3376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/scijava/event/EventHandler.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "3336521" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <!-- SQL XML created by WWW SQL Designer, https://github.com/ondras/wwwsqldesigner/ --> <!-- Active URL: https://ondras.zarovi.cz/sql/demo/ --> <sql> <datatypes db="mysql"> <group label="Numeric" color="rgb(238,238,170)"> <type label="Integer" length="0" sql="INTEGER" quote=""/> <type label="TINYINT" length="0" sql="TINYINT" quote=""/> <type label="SMALLINT" length="0" sql="SMALLINT" quote=""/> <type label="MEDIUMINT" length="0" sql="MEDIUMINT" quote=""/> <type label="INT" length="0" sql="INT" quote=""/> <type label="BIGINT" length="0" sql="BIGINT" quote=""/> <type label="Decimal" length="1" sql="DECIMAL" re="DEC" quote=""/> <type label="Single precision" length="0" sql="FLOAT" quote=""/> <type label="Double precision" length="0" sql="DOUBLE" re="DOUBLE" quote=""/> </group> <group label="Character" color="rgb(255,200,200)"> <type label="Char" length="1" sql="CHAR" quote="'"/> <type label="Varchar" length="1" sql="VARCHAR" quote="'"/> <type label="Text" length="0" sql="MEDIUMTEXT" re="TEXT" quote="'"/> <type label="Binary" length="1" sql="BINARY" quote="'"/> <type label="Varbinary" length="1" sql="VARBINARY" quote="'"/> <type label="BLOB" length="0" sql="BLOB" re="BLOB" quote="'"/> </group> <group label="Date &amp; Time" color="rgb(200,255,200)"> <type label="Date" length="0" sql="DATE" quote="'"/> <type label="Time" length="0" sql="TIME" quote="'"/> <type label="Datetime" length="0" sql="DATETIME" quote="'"/> <type label="Year" length="0" sql="YEAR" quote=""/> <type label="Timestamp" length="0" sql="TIMESTAMP" quote="'"/> </group> <group label="Miscellaneous" color="rgb(200,200,255)"> <type label="ENUM" length="1" sql="ENUM" quote=""/> <type label="SET" length="1" sql="SET" quote=""/> <type label="Bit" length="0" sql="bit" quote=""/> </group> </datatypes><table x="788" y="122" name="users"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="first_name" null="1" autoincrement="0"> <datatype>VARCHAR</datatype> <default>NULL</default></row> <row name="last_name" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="email" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="password" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="585" y="144" name="products"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="name" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="description" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="price" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="stock" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="image" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="featured" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="category_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="categories" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="360" y="202" name="categories"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="name" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="featured" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="539" y="401" name="settings"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="phone" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="address" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="email" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="copyright" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="web_title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="site_name_first" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="site_name_second" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="site_tagline" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="homepage_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="homepages" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="902" y="290" name="sliders"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="bg_img" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="tagline" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="description" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="button_text" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="button_link" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="homepage_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="homepages" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="366" y="384" name="nav_links"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="link" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="dropdown" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="365" y="521" name="footers"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="365" y="612" name="footer_links"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="link" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="footer_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="footers" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="904" y="531" name="promos"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="bg_img" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="tagline" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="link" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="homepage_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="homepages" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="732" y="394" name="homepages"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="name" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="sliders" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="promos" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="featured" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="banner" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="testimonials" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="newsletter" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default></row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="1037" y="281" name="testimonials"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="picture" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="name" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="comment" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="job_title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="company" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="homepage_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="homepages" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="956" y="123" name="newsletter_emails"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="email" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="1048" y="501" name="newsletters"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="description" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="button_text" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="homepage_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="homepages" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> <table x="1067" y="653" name="banners"> <row name="id" null="1" autoincrement="1"> <datatype>INTEGER</datatype> <default>NULL</default></row> <row name="symbol" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="title" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="description" null="1" autoincrement="0"> <datatype>MEDIUMTEXT</datatype> <default>NULL</default></row> <row name="homepage_id" null="1" autoincrement="0"> <datatype>INTEGER</datatype> <default>NULL</default><relation table="homepages" row="id" /> </row> <key type="PRIMARY" name=""> <part>id</part> </key> </table> </sql>
{ "content_hash": "3486ab260f76a885d6083a9600e5e6e0", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 87, "avg_line_length": 34.49856733524355, "alnum_prop": 0.6879568106312293, "repo_name": "coleby210/Zunecommerce", "id": "90b72008648f6a927475a8e90a6a37dcf037c6ed", "size": "12040", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "schema.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "131614" }, { "name": "HTML", "bytes": "31373" }, { "name": "JavaScript", "bytes": "206070" }, { "name": "Ruby", "bytes": "55172" } ], "symlink_target": "" }
pub use super::raw::types::{ ImVec2, ImVec4, ImGuiStyle, ImGuiIO, ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextFilterTextRange, ImGuiTextBuffer, ImGuiStorage, ImGuiStoragePair, ImGuiTextEditCallbackData, ImGuiSizeConstraintCallbackData, ImColor, ImGuiListClipper, ImDrawCmd, ImDrawVert, ImDrawChannel, ImDrawList, ImDrawData, ImFontConfig, ImFontAtlas, ImFont, ImFontGlyph, ImVector, };
{ "content_hash": "d75c9b729d912a197c78a4674913ece2", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 33, "avg_line_length": 15.846153846153847, "alnum_prop": 0.7961165048543689, "repo_name": "ExPixel/rust-imgui", "id": "fcad2aabf4dba5af035db0438d228787f90b283d", "size": "412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/imgui/structs.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Rust", "bytes": "115132" } ], "symlink_target": "" }
namespace Google.Analytics.Admin.V1Alpha.Snippets { // [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAccount_async] using Google.Analytics.Admin.V1Alpha; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets { /// <summary>Snippet for UpdateAccountAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task UpdateAccountRequestObjectAsync() { // Create client AnalyticsAdminServiceClient analyticsAdminServiceClient = await AnalyticsAdminServiceClient.CreateAsync(); // Initialize request argument(s) UpdateAccountRequest request = new UpdateAccountRequest { Account = new Account(), UpdateMask = new FieldMask(), }; // Make the request Account response = await analyticsAdminServiceClient.UpdateAccountAsync(request); } } // [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAccount_async] }
{ "content_hash": "18648bc58131ebcfbd20a0b6ee9f1ad0", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 118, "avg_line_length": 43.03333333333333, "alnum_prop": 0.6777691711851278, "repo_name": "jskeet/google-cloud-dotnet", "id": "741fc4b9c88eee8afa5b85bec99be78fef668818", "size": "1913", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "apis/Google.Analytics.Admin.V1Alpha/Google.Analytics.Admin.V1Alpha.GeneratedSnippets/AnalyticsAdminServiceClient.UpdateAccountRequestObjectAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "268415427" }, { "name": "CSS", "bytes": "1346" }, { "name": "Dockerfile", "bytes": "3173" }, { "name": "HTML", "bytes": "3823" }, { "name": "JavaScript", "bytes": "226" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65260" }, { "name": "sed", "bytes": "1030" } ], "symlink_target": "" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <cstdlib> #ifdef _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include "testrunnerswitcher.h" #include "micromock.h" #include "micromockcharstararenullterminatedstrings.h" #include "agenttime.h" static MICROMOCK_MUTEX_HANDLE g_testByTest; time_t my_time64(time_t * _Time) { (void)_Time; return (int64_t)-1; } struct tm* my_gmtime64(time_t* _Time) { (void)_Time; return NULL; } struct tm* my_localtime64(time_t * _Time) { (void)_Time; return NULL; } time_t my_mktime64(struct tm* _Time) { (void)_Time; return (int64_t)-1; } static MICROMOCK_GLOBAL_SEMAPHORE_HANDLE g_dllByDll; BEGIN_TEST_SUITE(agenttime_unittests) TEST_SUITE_INITIALIZE(TestClassInitialize) { INITIALIZE_MEMORY_DEBUG(g_dllByDll); g_testByTest = MicroMockCreateMutex(); ASSERT_IS_NOT_NULL(g_testByTest); } TEST_SUITE_CLEANUP(TestClassCleanup) { MicroMockDestroyMutex(g_testByTest); DEINITIALIZE_MEMORY_DEBUG(g_dllByDll); } TEST_FUNCTION_INITIALIZE(TestMethodInitialize) { if (!MicroMockAcquireMutex(g_testByTest)) { ASSERT_FAIL("our mutex is ABANDONED. Failure in test framework"); } } TEST_FUNCTION_CLEANUP(TestMethodCleanup) { if (!MicroMockReleaseMutex(g_testByTest)) { ASSERT_FAIL("failure in test framework at ReleaseMutex"); } } TEST_FUNCTION(get_time_succeed) { ///act time_t t; auto result = get_time(&t); ///assert ASSERT_ARE_EQUAL(int, (int)result, (int)t); } TEST_FUNCTION(get_gmtime_success) { ///act time_t now; struct tm* p; now = get_time(NULL); p = get_gmtime(&now); ///assert ASSERT_IS_NOT_NULL(p); } TEST_FUNCTION(get_difftime_success) { time_t now, sometimeAfterNow; now = get_time(NULL); sometimeAfterNow = now + 42; /*whatever this is*/ double diff; ///act diff = get_difftime(sometimeAfterNow, now); ///assert ASSERT_ARE_EQUAL(double, difftime(sometimeAfterNow, now), diff); } END_TEST_SUITE(agenttime_unittests)
{ "content_hash": "b15a8078645e1af76b61f661ade16101", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 101, "avg_line_length": 22.264957264957264, "alnum_prop": 0.5616122840690979, "repo_name": "5e8a91/Azure_C_Library_new", "id": "3da37372ec83a97ab4ceffb7757e1a6a7e4a4348", "size": "2605", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "c/common/tests/agenttime_unittests/agenttime_unittests.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "106644" }, { "name": "C", "bytes": "3072123" }, { "name": "C#", "bytes": "1349579" }, { "name": "C++", "bytes": "4662537" }, { "name": "CMake", "bytes": "64949" }, { "name": "CSS", "bytes": "492583" }, { "name": "HTML", "bytes": "481" }, { "name": "Java", "bytes": "1201397" }, { "name": "JavaScript", "bytes": "4429805" }, { "name": "Makefile", "bytes": "7082" }, { "name": "Objective-C", "bytes": "2177" }, { "name": "PowerShell", "bytes": "18836" }, { "name": "Shell", "bytes": "21705" } ], "symlink_target": "" }
package com.taobao.weex.ui.component; import com.taobao.weex.WXSDKInstanceTest; import com.taobao.weex.dom.TestDomObject; import com.taobao.weex.ui.SimpleComponentHolder; import com.taobao.weex.ui.component.list.WXListComponent; import java.lang.reflect.InvocationTargetException; import static org.junit.Assert.*; /** * Created by sospartan on 8/29/16. */ public class WXHeaderTest { public static WXHeader create(WXVContainer parent) throws IllegalAccessException, InstantiationException, InvocationTargetException { return (WXHeader) new SimpleComponentHolder(WXHeader.class).createInstance(WXSDKInstanceTest.createInstance(), new TestDomObject(), parent); } }
{ "content_hash": "7290ff75aa6053ba7209e965445307a0", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 144, "avg_line_length": 30.954545454545453, "alnum_prop": 0.8076358296622613, "repo_name": "MrRaindrop/incubator-weex", "id": "213119bc970ab128f4cd44e666e2178519352b5c", "size": "1490", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "android/sdk/src/test/java/com/taobao/weex/ui/component/WXHeaderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1100" }, { "name": "C", "bytes": "54245" }, { "name": "CSS", "bytes": "62128" }, { "name": "HTML", "bytes": "8388" }, { "name": "Java", "bytes": "4921258" }, { "name": "JavaScript", "bytes": "15169815" }, { "name": "Objective-C", "bytes": "1609681" }, { "name": "Objective-C++", "bytes": "48153" }, { "name": "Ruby", "bytes": "5268" }, { "name": "Shell", "bytes": "24917" }, { "name": "Vue", "bytes": "113516" } ], "symlink_target": "" }
// #docregion /** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. */ (function(global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 'rxjs': 'node_modules/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }, }; var ngPackageNames = [ 'common', 'compiler', 'core', 'forms', 'http', 'platform-browser', 'platform-browser-dynamic', 'router', 'router-deprecated', 'upgrade', ]; // Individual files (~300 requests): function packIndex(pkgName) { packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' }; } // Bundled (~40 requests): function packUmd(pkgName) { packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' }; } // Most environments should use UMD; some (Karma) need the individual index files var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; // Add package entries for angular packages ngPackageNames.forEach(setPackageConfig); var config = { map: map, packages: packages }; System.config(config); })(this);
{ "content_hash": "fc107483089aaf2c95cf822bbd855fb5", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 104, "avg_line_length": 27.9, "alnum_prop": 0.5967741935483871, "repo_name": "patou/angular-fr", "id": "901b8f01d012bc25ec1623e508808fcca8cab6e9", "size": "1674", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "public/docs/_examples/quickstart/ts/systemjs.config.1.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "129107" }, { "name": "Dart", "bytes": "135209" }, { "name": "HTML", "bytes": "1796719" }, { "name": "JavaScript", "bytes": "136645" }, { "name": "Shell", "bytes": "8687" }, { "name": "TypeScript", "bytes": "596298" } ], "symlink_target": "" }
/** * Module dependencies. */ var mongoose = require('mongoose'); var home = require('home'); /** * Expose */ module.exports = function (app, passport) { app.get('/', home.index); app.get('/about', home.about); app.get('/contact', home.contact); app.get('/privacy', home.privacy); app.get('/terms', home.terms); /** * Error handling */ app.use(function (err, req, res, next) { // treat as 404 if (err.message && (~err.message.indexOf('not found') || (~err.message.indexOf('Cast to ObjectId failed')))) { return next(); } console.error(err.stack); // error page res.status(500).render('500', { error: err.stack }); }); // assume 404 since no middleware responded app.use(function (req, res, next) { res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }); }); };
{ "content_hash": "62149aeec4f6f4340458d132fce6eebb", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 62, "avg_line_length": 20.09090909090909, "alnum_prop": 0.5769230769230769, "repo_name": "garyburge/node-express-mongoose-bootstrap-passport", "id": "b303cc1b3c453e2b2ec7ec5cfd1cd85dc230f4fc", "size": "884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/routes.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "290" }, { "name": "JavaScript", "bytes": "12816" } ], "symlink_target": "" }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\modules\admin\models\Brands */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="brands-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'description')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'keyword')->textInput(['maxlength' => true]) ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
{ "content_hash": "5c3cf641b96e85d6e03f6fa076582b90", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 159, "avg_line_length": 27, "alnum_prop": 0.5925925925925926, "repo_name": "AndreyGP/ekom.loc", "id": "f501f6556ccd7556865da3dfa9a2e96d5b2d1ad0", "size": "750", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/admin/views/brands/_form.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "4318" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "788681" }, { "name": "HTML", "bytes": "4206081" }, { "name": "JavaScript", "bytes": "116586" }, { "name": "Makefile", "bytes": "2393" }, { "name": "PHP", "bytes": "366633" }, { "name": "Ruby", "bytes": "6337" } ], "symlink_target": "" }
package de.thk.ct.endpoint.pi4j.osgi.resources; /** * Listener that is used to listen for changes on a * {@link AbstractDeviceResource}. Every sensor and actuator in this application * should use this listener. * * @author Martin Vantroba * */ public interface DeviceResourceListener { /** * Callback method that is called when a sensor's or an actuator's state has * changed. * * @param value * new value */ void onChanged(String value); }
{ "content_hash": "502b3fc22f7604ab443630028bb7fe79", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 80, "avg_line_length": 23.714285714285715, "alnum_prop": 0.6606425702811245, "repo_name": "mvantroba/CoRE-Things", "id": "349f9c5c0a22019cb2a71e4b8d123b6fb4978487", "size": "498", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ct-endpoint-parent/ct-endpoint-pi4j-osgi/src/main/java/de/thk/ct/endpoint/pi4j/osgi/resources/DeviceResourceListener.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2123" }, { "name": "Java", "bytes": "252406" } ], "symlink_target": "" }
""" Samsara ~~~~~~~ Samsara service package """ from setuptools import setup, find_packages setup( name='samsara_sdk', version='', url='https://github.com/samsara/samsara', author='Samsara Developers', author_email='samsara.systems+info@gmail.com', description="A Python Client for Samsaza's Ingestion-API", long_description=""" # Install and use to install use: pip install samsara_sdk to use please refer to the documentation at this website: http://samsara-analytics.io/docs/clients/python-client/ """, packages=find_packages(), include_package_data=True, platforms='any', keywords=['analytics', 'client', 'samsara'], tests_require=find_packages(include=['*-dev']) )
{ "content_hash": "3445bee51c93edd788f4b9accd20a5f3", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 62, "avg_line_length": 20.243243243243242, "alnum_prop": 0.6662216288384513, "repo_name": "samsara/samsara", "id": "5b7dddedc2a604043b20fc11c9cff3a1bf056c01", "size": "773", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "clients/python/setup.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "342475" }, { "name": "Go", "bytes": "58894" }, { "name": "HCL", "bytes": "39101" }, { "name": "Java", "bytes": "24749" }, { "name": "Lua", "bytes": "16152" }, { "name": "Objective-C", "bytes": "104" }, { "name": "Python", "bytes": "13974" }, { "name": "Ruby", "bytes": "52737" }, { "name": "Shell", "bytes": "75841" }, { "name": "Swift", "bytes": "31918" } ], "symlink_target": "" }
Goals and Architecture Overview =============================== High Level Goals ---------------- Traditionally, language interpreters are written in a target platform language such as C/Posix, Java or C#. Each implementation provides a fundamental mapping between application source code and the target environment. One of the goals of the "all-encompassing" environments, such as the .NET framework and to some extent the Java virtual machine, is to provide standardized and higher level functionalities in order to support language implementers for writing language implementations. PyPy is experimenting with a more ambitious approach. We are using a subset of the high-level language Python, called :doc:`rpython`, in which we write languages as simple interpreters with few references to and dependencies on lower level details. The RPython toolchain produces a concrete virtual machine for the platform of our choice by inserting appropriate lower level aspects. The result can be customized by selecting other feature and platform configurations. Our goal is to provide a possible solution to the problem of language implementers: having to write ``l * o * p`` interpreters for ``l`` dynamic languages and ``p`` platforms with ``o`` crucial design decisions. PyPy aims at making it possible to change each of these variables independently such that: * ``l``: the language that we analyze can be evolved or entirely replaced; * ``o``: we can tweak and optimize the translation process to produce platform specific code based on different models and trade-offs; * ``p``: we can write new translator back-ends to target different physical and virtual platforms. By contrast, a standardized target environment - say .NET - enforces ``p=1`` as far as it's concerned. This helps making ``o`` a bit smaller by providing a higher-level base to build upon. Still, we believe that enforcing the use of one common environment is not necessary. PyPy's goal is to give weight to this claim - at least as far as language implementation is concerned - showing an approach to the ``l * o * p`` problem that does not rely on standardization. The most ambitious part of this goal is to :doc:`generate Just-In-Time Compilers <jit/index>` in a language-independent way, instead of only translating the source interpreter into an interpreter for the target platform. This is an area of language implementation that is commonly considered very challenging because of the involved complexity. Architecture ------------ The job of the RPython toolchain is to translate :doc:`rpython` programs into an efficient version of that program for one of the various target platforms, generally one that is considerably lower-level than Python. The approach we have taken is to reduce the level of abstraction of the source RPython program in several steps, from the high level down to the level of the target platform, whatever that may be. Currently we support two broad flavours of target platforms: the ones that assume a C-like memory model with structures and pointers, and the ones that assume an object-oriented model with classes, instances and methods (as, for example, the Java and .NET virtual machines do). The RPython toolchain never sees the RPython source code or syntax trees, but rather starts with the *code objects* that define the behaviour of the function objects one gives it as input. It can be considered as "freezing" a pre-imported RPython program into an executable form suitable for the target platform. The steps of the translation process can be summarized as follows: * The code object of each source functions is converted to a :ref:`control flow graph <flow-model>` by the :ref:`flow graph builder<flow-graphs>`. * The control flow graphs are processed by the :ref:`Annotator <annotator>`, which performs whole-program type inference to annotate each variable of the control flow graph with the types it may take at run-time. * The information provided by the annotator is used by the :doc:`RTyper <rtyper>` to convert the high level operations of the control flow graphs into operations closer to the abstraction level of the target platform. * Optionally, `various transformations <optional-transformations>` can then be applied which, for example, perform optimizations such as inlining, add capabilities such as stackless-style concurrency, or insert code for the :doc:`garbage collector <garbage_collection>`. * Then, the graphs are converted to source code for the target platform and compiled into an executable. This process is described in much more detail in the :doc:`document about the RPython toolchain <translation>` and in the paper `Compiling dynamic language implementations`_. .. _Compiling dynamic language implementations: https://bitbucket.org/pypy/extradoc/raw/tip/eu-report/D05.1_Publish_on_translating_a_very-high-level_description.pdf Further reading --------------- * :doc:`getting-started`: a hands-on guide to getting involved with the PyPy source code. * `PyPy's approach to virtual machine construction`_: a paper presented to the Dynamic Languages Symposium attached to OOPSLA 2006. * :doc:`The translation document <translation>`: a detailed description of our translation process. * :doc:`JIT Generation in PyPy <jit/index>`, describing how we produce a Just-in-time Compiler from an interpreter. * A tutorial of how to use the :doc:`RPython toolchain <translation>` to `implement your own interpreter`_. .. _PyPy's approach to virtual machine construction: https://bitbucket.org/pypy/extradoc/raw/tip/talk/dls2006/pypy-vm-construction.pdf .. _implement your own interpreter: http://morepypy.blogspot.com/2011/04/tutorial-writing-interpreter-with-pypy.html
{ "content_hash": "dbce7cbcc70618dafc74fc845865be84", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 164, "avg_line_length": 47.80165289256198, "alnum_prop": 0.7764522821576764, "repo_name": "jptomo/rpython-lang-scheme", "id": "44434a8699de9c6125dc1b424bc04019a9656313", "size": "5784", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "rpython/doc/architecture.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "161293" }, { "name": "Batchfile", "bytes": "5289" }, { "name": "C", "bytes": "335765" }, { "name": "C++", "bytes": "12638" }, { "name": "Emacs Lisp", "bytes": "3149" }, { "name": "HCL", "bytes": "155" }, { "name": "Makefile", "bytes": "6988" }, { "name": "Objective-C", "bytes": "1907" }, { "name": "Python", "bytes": "16129160" }, { "name": "Scheme", "bytes": "3" }, { "name": "Shell", "bytes": "721" }, { "name": "VimL", "bytes": "1107" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ru"> <head> <title>org.apache.poi.hpbf.model.qcbits (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../../../org/apache/poi/hpbf/model/qcbits/package-summary.html" target="classFrame">org.apache.poi.hpbf.model.qcbits</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="QCBit.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">QCBit</a></li> <li><a href="QCPLCBit.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">QCPLCBit</a></li> <li><a href="QCPLCBit.Type0.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">QCPLCBit.Type0</a></li> <li><a href="QCPLCBit.Type12.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">QCPLCBit.Type12</a></li> <li><a href="QCPLCBit.Type4.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">QCPLCBit.Type4</a></li> <li><a href="QCPLCBit.Type8.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">QCPLCBit.Type8</a></li> <li><a href="QCTextBit.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">QCTextBit</a></li> <li><a href="UnknownQCBit.html" title="class in org.apache.poi.hpbf.model.qcbits" target="classFrame">UnknownQCBit</a></li> </ul> </div> </body> </html>
{ "content_hash": "c9cebc99f15c921fd15f793875464cd3", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 159, "avg_line_length": 65.79166666666667, "alnum_prop": 0.7061431285623813, "repo_name": "pedro93/ifarmaStudents", "id": "6f457dc4dde32bced1f79a42e2b40db88815e959", "size": "1579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "poi-3.10-FINAL/docs/apidocs/org/apache/poi/hpbf/model/qcbits/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25085" }, { "name": "Java", "bytes": "26983" } ], "symlink_target": "" }
package org.apache.asterix.installer.command; public abstract class CommandConfig { }
{ "content_hash": "d38e02ab29559fbb05e10f6bd39eb434", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 45, "avg_line_length": 14.833333333333334, "alnum_prop": 0.797752808988764, "repo_name": "waans11/incubator-asterixdb", "id": "4c07d4ec4ef4d83fed117ded1db2c117b2c4b493", "size": "896", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "asterixdb/asterix-installer/src/main/java/org/apache/asterix/installer/command/CommandConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "16145" }, { "name": "C", "bytes": "421" }, { "name": "CSS", "bytes": "17665" }, { "name": "Crystal", "bytes": "453" }, { "name": "FreeMarker", "bytes": "68104" }, { "name": "Gnuplot", "bytes": "89" }, { "name": "HTML", "bytes": "131935" }, { "name": "Java", "bytes": "20780094" }, { "name": "JavaScript", "bytes": "636055" }, { "name": "Python", "bytes": "281315" }, { "name": "Ruby", "bytes": "3078" }, { "name": "Scheme", "bytes": "1105" }, { "name": "Shell", "bytes": "232529" }, { "name": "Smarty", "bytes": "31412" }, { "name": "TeX", "bytes": "1059" } ], "symlink_target": "" }
<!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_72) on Thu Feb 18 20:48:47 EST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.red5.io.m4a.impl (Red5 :: IO 1.0.7-SNAPSHOT API)</title> <meta name="date" content="2016-02-18"> <link rel="stylesheet" type="text/css" href="../../../../../javadoc.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.red5.io.m4a.impl (Red5 :: IO 1.0.7-SNAPSHOT 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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.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><a href="../../../../../org/red5/io/m4a/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../org/red5/io/matroska/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/red5/io/m4a/impl/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.red5.io.m4a.impl</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/red5/io/m4a/impl/M4A.html" title="class in org.red5.io.m4a.impl">M4A</a></td> <td class="colLast"> <div class="block">A M4AImpl implements the M4A api</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/red5/io/m4a/impl/M4AReader.html" title="class in org.red5.io.m4a.impl">M4AReader</a></td> <td class="colLast"> <div class="block">A Reader is used to read the contents of a M4A file.</div> </td> </tr> </tbody> </table> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.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><a href="../../../../../org/red5/io/m4a/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../org/red5/io/matroska/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/red5/io/m4a/impl/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2005&#x2013;2016 <a href="https://github.com/Red5">Red5</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "2c1715e4a5d6f139d04d5c86c439dfee", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 138, "avg_line_length": 35.7828947368421, "alnum_prop": 0.6113256113256114, "repo_name": "Red5/red5.github.io", "id": "e294e3d2b88dabafed0b0935f32217778c0d734b", "size": "5439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/red5-io/org/red5/io/m4a/impl/package-summary.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "70129" }, { "name": "HTML", "bytes": "34446" }, { "name": "JavaScript", "bytes": "303467" } ], "symlink_target": "" }
import pandas as pd import json import numpy as np class NpEncoder(json.JSONEncoder): def default(self, obj): """ Converts the dictionary's values into a JSON serializable data type """ if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() else: return super(NpEncoder, self).default(obj) class ParsePsortExperimental: def __init__(self, max_entries): self.max_entries = max_entries def parse_psortdb(self): """ To parse database psortdb Experimental-PSORTdb-v4.00.tsv file and create JSON files conforming to datanator_pattern/observation_compiled.json Args: max_entries: int number of rows to parse. A JSON file will be created for each of the tsv file's first <max_entries> rows Return: () """ data=pd.read_csv('Experimental-PSORTdb-v4.00.tsv',delimiter="\t") data = data.where(pd.notnull(data), None) for i in range(self.max_entries): d={} #entity d["entity"]={} d["entity"]["type"]="protein" d["entity"]["name"]=str(data.iloc[i,6]).replace(".","") if data.iloc[i,7] != None: d["entity"]["synonyms"]=str(data.iloc[i,7]).split(",") else: d["entity"]["synonyms"]=[] #identifiers d["entity"]["identifiers"]=[] uniprot={} uniprot["name_space"]="uniprot_id" uniprot["value"]=data.iloc[i,0] ref_seq = {} ref_seq["name_space"]="Refseq_Accession" ref_seq["value"]=data.iloc[i,1] other_accession = {} other_accession["name_space"]="Other_Accession" other_accession["value"]=data.iloc[i,2] d["entity"]["identifiers"].append(uniprot) d["entity"]["identifiers"].append(ref_seq) d["entity"]["identifiers"].append(other_accession) #localizations d["value"]={} if data.iloc[i,3] != None: d["value"]["experimental_localization"] = str(data.iloc[i,3]).split(",") else: d["value"]["experimental_localization"] = [] if data.iloc[i,4] != None: d["value"]["secondary_localizaton"] = str(data.iloc[i,4]).split(",") else: d["value"]["secondary_localizaton"] = [] #genotype d["genotype"]={} d["genotype"]["taxon"]={} d["genotype"]["taxon"]["ncbi_taxonomy_id"]=data.iloc[i,9] d["genotype"]["taxon"]["name"]=data.iloc[i,10] #environment d["environment"]={} d["environment"]["GramStain"]=data.iloc[i,13] #source d["source"]={} d["source"]["namespace"]="ePSORTdb" d["source"]["value"]="Version "+str(data.iloc[i,17]) #name is the JSON file's name if (data.iloc[i,0]!=None): name = data.iloc[i,0] #SwissProt_ID else: name = data.iloc[i,2] #Other_Accession with open("Experimental_PSortdb/"+name+".json","w+") as f: json.dump(d,f,cls=NpEncoder,indent=4) p1=ParsePsortExperimental(10) p1.parse_psortdb()
{ "content_hash": "89a864012915a7994109dfd36592b5eb", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 95, "avg_line_length": 36.73737373737374, "alnum_prop": 0.49546329392356336, "repo_name": "KarrLab/kinetic_datanator", "id": "1de0421c470a38956bfbd2a47bd89371544e0123", "size": "3637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "datanator/data_source/protein_localization/parse_psortdb_experimental.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1217" }, { "name": "Dockerfile", "bytes": "171" }, { "name": "HTML", "bytes": "50579" }, { "name": "Python", "bytes": "980025" } ], "symlink_target": "" }
/* * Name mangling for public symbols is controlled by --with-mangling and * --with-jemalloc-prefix. With default settings the je_ prefix is stripped by * these macro definitions. */ #ifndef JEMALLOC_NO_RENAME # define je_malloc_conf je_malloc_conf # define je_malloc_message je_malloc_message # define je_malloc je_malloc # define je_calloc je_calloc # define je_posix_memalign je_posix_memalign # define je_aligned_alloc je_aligned_alloc # define je_realloc je_realloc # define je_free je_free # define je_mallocx je_mallocx # define je_rallocx je_rallocx # define je_xallocx je_xallocx # define je_sallocx je_sallocx # define je_dallocx je_dallocx # define je_nallocx je_nallocx # define je_mallctl je_mallctl # define je_mallctlnametomib je_mallctlnametomib # define je_mallctlbymib je_mallctlbymib # define je_malloc_stats_print je_malloc_stats_print # define je_malloc_usable_size je_malloc_usable_size # define je_memalign je_memalign # define je_valloc je_valloc # define je_allocm je_allocm # define je_dallocm je_dallocm # define je_nallocm je_nallocm # define je_rallocm je_rallocm # define je_sallocm je_sallocm #endif
{ "content_hash": "c61611042daab3de750d4d1d734417de", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 79, "avg_line_length": 35.21212121212121, "alnum_prop": 0.7581755593803786, "repo_name": "alexandermerritt/redis", "id": "bc1a1ef5b3ff704f889147c9b40aa518d829526a", "size": "1162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deps/jemalloc/include/jemalloc/jemalloc_rename.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "2069671" }, { "name": "Makefile", "bytes": "7893" }, { "name": "Ruby", "bytes": "59448" }, { "name": "Shell", "bytes": "14388" }, { "name": "Smarty", "bytes": "1047" }, { "name": "Tcl", "bytes": "428804" } ], "symlink_target": "" }
package io.vertx.test.codegen.testvariance; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public interface MethodWithVarAsCoParamAsCoParamInCoPos<@Analyze T> { MethodWithCoType<MethodWithCoType<T>> foo(); }
{ "content_hash": "868414a36680aff46df7aab0002fbd1c", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 69, "avg_line_length": 24, "alnum_prop": 0.7541666666666667, "repo_name": "vert-x3/vertx-codegen", "id": "da32678f7462a55c0226cbeb1667188c0aa2d2dc", "size": "240", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/io/vertx/test/codegen/testvariance/MethodWithVarAsCoParamAsCoParamInCoPos.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1506838" } ], "symlink_target": "" }
from decimal import * import getpass import math import os import os.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def determine_db_dir(): """Return the default location of the catchcoin data directory""" if platform.system() == "Darwin": return os.path.expanduser("~/Library/Application Support/Catchcoin/") elif platform.system() == "Windows": return os.path.join(os.environ['APPDATA'], "Catchcoin") return os.path.expanduser("~/.catchcoin") def read_catchcoin_config(dbdir): """Read the catchcoin.conf file from dbdir, returns dictionary of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: s = self.fp.readline() if s.find('#') != -1: s = s[0:s.find('#')].strip() +"\n" return s config_parser = SafeConfigParser() config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "catchcoin.conf")))) return dict(config_parser.items("all")) def connect_JSON(config): """Connect to a catchcoin JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 18332 if testnet else 8332 connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the catchcoind we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(catchcoind): info = catchcoind.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <= time.time(): try: passphrase = getpass.getpass("Wallet is locked; enter passphrase: ") catchcoind.walletpassphrase(passphrase, 5) except: sys.stderr.write("Wrong passphrase\n") info = catchcoind.getinfo() return int(info['unlocked_until']) > time.time() def list_available(catchcoind): address_summary = dict() address_to_account = dict() for info in catchcoind.listreceivedbyaddress(0): address_to_account[info["address"]] = info["account"] unspent = catchcoind.listunspent(0) for output in unspent: # listunspent doesn't give addresses, so: rawtx = catchcoind.getrawtransaction(output['txid'], 1) vout = rawtx["vout"][output['vout']] pk = vout["scriptPubKey"] # This code only deals with ordinary pay-to-catchcoin-address # or pay-to-script-hash outputs right now; anything exotic is ignored. if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash": continue address = pk["addresses"][0] if address in address_summary: address_summary[address]["total"] += vout["value"] address_summary[address]["outputs"].append(output) else: address_summary[address] = { "total" : vout["value"], "outputs" : [output], "account" : address_to_account.get(address, "") } return address_summary def select_coins(needed, inputs): # Feel free to improve this, this is good enough for my simple needs: outputs = [] have = Decimal("0.0") n = 0 while have < needed and n < len(inputs): outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]}) have += inputs[n]["amount"] n += 1 return (outputs, have-needed) def create_tx(catchcoind, fromaddresses, toaddress, amount, fee): all_coins = list_available(catchcoind) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total"] if total_available < needed: sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed)); sys.exit(1) # # Note: # Python's json/jsonrpc modules have inconsistent support for Decimal numbers. # Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode # Decimals, I'm casting amounts to float before sending them to catchcoind. # outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float(change_amount) else: outputs[change_address] = float(change_amount) rawtx = catchcoind.createrawtransaction(inputs, outputs) signed_rawtx = catchcoind.signrawtransaction(rawtx) if not signed_rawtx["complete"]: sys.stderr.write("signrawtransaction failed\n") sys.exit(1) txdata = signed_rawtx["hex"] return txdata def compute_amount_in(catchcoind, txinfo): result = Decimal("0.0") for vin in txinfo['vin']: in_info = catchcoind.getrawtransaction(vin['txid'], 1) vout = in_info['vout'][vin['vout']] result = result + vout['value'] return result def compute_amount_out(txinfo): result = Decimal("0.0") for vout in txinfo['vout']: result = result + vout['value'] return result def sanity_test_fee(catchcoind, txdata_hex, max_fee): class FeeError(RuntimeError): pass try: txinfo = catchcoind.decoderawtransaction(txdata_hex) total_in = compute_amount_in(catchcoind, txinfo) total_out = compute_amount_out(txinfo) if total_in-total_out > max_fee: raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out)) tx_size = len(txdata_hex)/2 kb = tx_size/1000 # integer division rounds down if kb > 1 and fee < BASE_FEE: raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes") if total_in < 0.01 and fee < BASE_FEE: raise FeeError("Rejecting no-fee, tiny-amount transaction") # Exercise for the reader: compute transaction priority, and # warn if this is a very-low-priority transaction except FeeError as err: sys.stderr.write((str(err)+"\n")) sys.exit(1) def main(): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--from", dest="fromaddresses", default=None, help="addresses to get catchcoins from") parser.add_option("--to", dest="to", default=None, help="address to get send catchcoins to") parser.add_option("--amount", dest="amount", default=None, help="amount to send") parser.add_option("--fee", dest="fee", default="0.0", help="fee to include") parser.add_option("--datadir", dest="datadir", default=determine_db_dir(), help="location of catchcoin.conf file with RPC username/password (default: %default)") parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the test network") parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true", help="Don't broadcast the transaction, just create and print the transaction data") (options, args) = parser.parse_args() check_json_precision() config = read_catchcoin_config(options.datadir) if options.testnet: config['testnet'] = True catchcoind = connect_JSON(config) if options.amount is None: address_summary = list_available(catchcoind) for address,info in address_summary.iteritems(): n_transactions = len(info['outputs']) if n_transactions > 1: print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions)) else: print("%s %.8f %s"%(address, info['total'], info['account'])) else: fee = Decimal(options.fee) amount = Decimal(options.amount) while unlock_wallet(catchcoind) == False: pass # Keep asking for passphrase until they get it right txdata = create_tx(catchcoind, options.fromaddresses.split(","), options.to, amount, fee) sanity_test_fee(catchcoind, txdata, amount*Decimal("0.01")) if options.dry_run: print(txdata) else: txid = catchcoind.sendrawtransaction(txdata) print(txid) if __name__ == '__main__': main()
{ "content_hash": "2ccfd6d13baa62be6f0d5dee5272be71", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 111, "avg_line_length": 38.69444444444444, "alnum_prop": 0.6185006665982976, "repo_name": "tinybike/catchcoin", "id": "cb2f2dd506a75607d0b38bfe97c9259e77600b79", "size": "10135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "contrib/spendfrom/spendfrom.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "301826" }, { "name": "C++", "bytes": "2879017" }, { "name": "CSS", "bytes": "1127" }, { "name": "Objective-C++", "bytes": "6266" }, { "name": "Python", "bytes": "95592" }, { "name": "Shell", "bytes": "40370" }, { "name": "TypeScript", "bytes": "10322619" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <CoverageParams> <TargetExecutable>C:/Program Files/dotnet/dotnet.exe</TargetExecutable> <TargetArguments>test --no-build -c Release</TargetArguments> <Filters> <IncludeFilters> <FilterEntry> <ModuleMask>Google.Cloud.BigQuery.DataExchange.V1Beta1</ModuleMask> </FilterEntry> </IncludeFilters> </Filters> <AttributeFilters> <AttributeFilterEntry>System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute</AttributeFilterEntry> <AttributeFilterEntry>System.Diagnostics.DebuggerNonUserCodeAttribute</AttributeFilterEntry> </AttributeFilters> <TargetWorkingDir>.</TargetWorkingDir> <Output>../../../coverage/Google.Cloud.BigQuery.DataExchange.V1Beta1.Snippets.dvcr</Output> </CoverageParams>
{ "content_hash": "1bf2b12828b75ef2d25df13c5823b046", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 113, "avg_line_length": 43.666666666666664, "alnum_prop": 0.767175572519084, "repo_name": "googleapis/google-cloud-dotnet", "id": "f9ff670f2b134532ad713fa26bf8052054eb14fc", "size": "788", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apis/Google.Cloud.BigQuery.DataExchange.V1Beta1/Google.Cloud.BigQuery.DataExchange.V1Beta1.Snippets/coverage.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "319820004" }, { "name": "Dockerfile", "bytes": "3415" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65881" } ], "symlink_target": "" }
const int IntroSequence::mini = 150; const int IntroSequence::maxi = 400; enum CONTROL_ID playercontrols[4] = {KEYBOARD_0, KEYBOARD_1, KEYBOARD_2, KEYBOARD_3}; IntroSequence::IntroSequence(GameSequence *previous, float zoom, float zoomspeed, int players, int level, int lives, bool dca, bool wall) : GameSequence(previous) { width = GameManager::display_width; height = GameManager::display_height; iLogo = al_load_bitmap("assets/intro/intro_logo.bmp"); iZoomMax = iZoom = (zoom); iZoomSpeed = (zoomspeed); iDoublebuffer = al_create_bitmap(width, maxi - mini); playerschoice = players; levelchoice = level; liveschoice = lives; dcachoice = dca; wallchoice = wall; assert(GameManager::num_joysticks_loaded >= 0 && GameManager::num_joysticks_loaded <= 4); // setup player_controls based on number of joysticks, if there are joysticks use them first, otherwise use keyboard int playercontrol; for (playercontrol = 0; playercontrol < GameManager::num_joysticks_loaded; playercontrol++) playercontrols[playercontrol] = static_cast<CONTROL_ID>(4 + playercontrol); for (playercontrol = GameManager::num_joysticks_loaded; playercontrol < NB_MAX_PLAYERS; playercontrol++) playercontrols[playercontrol] = static_cast<CONTROL_ID>(playercontrol - GameManager::num_joysticks_loaded); } IntroSequence::~IntroSequence() { if (iLogo) al_destroy_bitmap(iLogo); if (iDoublebuffer) al_destroy_bitmap(iDoublebuffer); } GameSequence *IntroSequence::doTick(ALLEGRO_BITMAP *screen_buffer, bool key_pressed[ALLEGRO_KEY_MAX], bool key_down[ALLEGRO_KEY_MAX], bool *exit_game, double dt) { iZoom = (iZoom - iZoomSpeed); if (iZoom < 1.0) { iZoom = 1; isRunning = false; } clear_bitmap(iDoublebuffer); DrawZoomedLogoInCenter(mini, maxi); // draw 2 horizontal lines hline(iDoublebuffer, 0, 0, width, al_map_rgb(255, 255, 255)); hline(iDoublebuffer, 0, IntroSequence::maxi - IntroSequence::mini - 1, width, al_map_rgb(255, 255, 255)); // blit to the screen blit(iDoublebuffer, screen_buffer, 0, 0, 0, mini, width, maxi - mini); if (key_pressed[ALLEGRO_KEY_ESCAPE] && canQuickExit) { quickExit = true; isRunning = false; } if (joystick_action_timer.is_running()) joystick_action_timer.tick(); bool startgame = false; bool exit = false; bool reload = false; if (!quickExit && !isRunning) { black = al_map_rgb(0, 0, 0); red = al_map_rgb(255, 0, 0); lightred = al_map_rgb(255, 75, 75); handle_key_presses(key_pressed, &reload, &startgame, &exit); char layout_str[1000]; auto font = GameManager::font; MenuHandler mh; mh.reset(); mh.selected_idx = menuselected; mh.maxi = maxi; mh.width = width; mh.max_visible_lines = 25; mh.addline("Start game"); mh.addline("Options:", false, 15); snprintf(menutext, sizeof(menutext), " Players - %d ", playerschoice); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Level - %d ", levelchoice + 1); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Lives - %d ", liveschoice); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Use DCA - %s ", ((dcachoice) ? "yes" : "no")); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Wall Collision - %s ", ((wallchoice) ? "yes" : "no")); mh.addline(menutext); mh.addline("Controls:", false, 15); snprintf(menutext, sizeof(menutext), " Player 1 - %s", get_control_id_as_string(playercontrols[0])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Player 2 - %s", get_control_id_as_string(playercontrols[1])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Player 3 - %s", get_control_id_as_string(playercontrols[2])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Player 4 - %s", get_control_id_as_string(playercontrols[3])); mh.addline(menutext); mh.addline("Controller layouts:", false, 15); menu_joy_kbd_idx = 10; menu_kbd_layout1_idx = 0; menu_kbd_layout2_idx = 0; menu_kbd_layout3_idx = 0; menu_kbd_layout4_idx = 0; menu_kbd_layout_end = 0; menu_joy_layout1_idx = 0; menu_joy_layout2_idx = 0; menu_joy_layout3_idx = 0; menu_joy_layout4_idx = 0; menu_joy_layout_end = 0; if (GameManager::num_joysticks_loaded > 0) { for (int i = 0; i < GameManager::num_joysticks_loaded; i++) { switch (i) { case 0: menu_joy_layout1_idx = menu_joy_kbd_idx; break; case 1: menu_joy_layout2_idx = menu_joy_kbd_idx; break; case 2: menu_joy_layout3_idx = menu_joy_kbd_idx; break; case 3: menu_joy_layout4_idx = menu_joy_kbd_idx; break; } snprintf(menutext, sizeof(menutext), " Joystick %d %s", (i + 1), al_get_joystick_name(GameManager::joysticks[i]->joy)); mh.addline(menutext, false, 10); snprintf(menutext, sizeof(menutext), " Left - %s", button_to_str(mapping_joy::btn_sets[i][0])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Right - %s", button_to_str(mapping_joy::btn_sets[i][1])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Thrust - %s", button_to_str(mapping_joy::btn_sets[i][2])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Shield - %s", button_to_str(mapping_joy::btn_sets[i][3])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Fire - %s", button_to_str(mapping_joy::btn_sets[i][4])); mh.addline(menutext); menu_joy_kbd_idx = menu_joy_kbd_idx + 5; menu_joy_layout_end = menu_joy_kbd_idx; } } for (int i = 0; i < 4; i++) { switch (i) { case 0: menu_kbd_layout1_idx = menu_joy_kbd_idx; break; case 1: menu_kbd_layout2_idx = menu_joy_kbd_idx; break; case 2: menu_kbd_layout3_idx = menu_joy_kbd_idx; break; case 3: menu_kbd_layout4_idx = menu_joy_kbd_idx; break; } snprintf(menutext, sizeof(menutext), " Keyboard %d", (i + 1)); mh.addline(menutext, false, 10); snprintf(menutext, sizeof(menutext), " Left - %s", key_to_str(mapping_key::key_sets[i][0])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Right - %s", key_to_str(mapping_key::key_sets[i][1])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Thrust - %s", key_to_str(mapping_key::key_sets[i][2])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Shield - %s", key_to_str(mapping_key::key_sets[i][3])); mh.addline(menutext); snprintf(menutext, sizeof(menutext), " Fire - %s", key_to_str(mapping_key::key_sets[i][4])); mh.addline(menutext); menu_joy_kbd_idx = menu_joy_kbd_idx + 5; menu_kbd_layout_end = menu_joy_kbd_idx; } snprintf(menutext, sizeof(menutext), "Resolution (%ix%i): ", width, height); mh.addline(menutext, false, 15); menu_resolution_idx = menu_joy_kbd_idx; menu_exit_idx = menu_resolution_idx + 1; menuitems = menu_exit_idx + 1; if (width == GameManager::native_width && height == GameManager::native_height) snprintf(menutext, sizeof(menutext), " Switch to Low - 1024x768 "); else snprintf(menutext, sizeof(menutext), " Switch to Native - %ix%i ", GameManager::native_width, GameManager::native_height); mh.addline(menutext); mh.addline("Exit", true, 15); mh.draw(screen_buffer, font); } *exit_game = exit; GameSequence *seq = nullptr; if (startgame) { iZoom = iZoomMax; seq = new BattleSequence(this, playerschoice, playerschoice, liveschoice, levelchoice, dcachoice, wallchoice, width, height, playercontrols); } else if (reload) seq = new IntroSequence(NULL, 10.0, 0.5, playerschoice, levelchoice, liveschoice, dcachoice, wallchoice); else seq = ReturnScreen(); return seq; } void IntroSequence::DrawZoomedLogoInCenter(int y1, int y2) { int logowidth = fixtoi(fixmul(itofix(al_get_bitmap_width(iLogo)), iZoom)); int logoheight = fixtoi(fixmul(itofix(al_get_bitmap_height(iLogo)), iZoom)); int targetwidth = width; int targetheight = y2 - y1; int xs, ys, ws, hs; int xd, yd, wd, hd; if (logowidth > targetwidth) { ws = fixtoi(fixdiv(itofix(targetwidth), iZoom)); xs = (al_get_bitmap_width(iLogo) - ws) / 2; xd = 0; wd = targetwidth; } else { xs = 0; ws = al_get_bitmap_width(iLogo); xd = (targetwidth - logowidth) / 2; wd = logowidth; } if (logoheight > targetheight) { hs = fixtoi(fixdiv(itofix(targetheight), iZoom)); ys = (al_get_bitmap_height(iLogo) - hs) / 2; yd = 0; hd = targetheight; } else { ys = 0; hs = al_get_bitmap_height(iLogo); yd = (targetheight - logoheight) / 2; hd = logoheight; } stretch_blit(iLogo, iDoublebuffer, xs, ys, ws, hs, xd, yd, wd, hd); } void IntroSequence::cycle_control(int playerno) { int num_keyboard_layouts = 4; int num_ctrls = static_cast<int>(NUM_CONTROLS); int end_control_index = std::min( num_ctrls, num_keyboard_layouts + GameManager::num_joysticks_loaded); int next_ctrl_idx = static_cast<int>(playercontrols[playerno]) + 1; playercontrols[playerno] = static_cast<CONTROL_ID>(next_ctrl_idx % end_control_index); } bool IntroSequence::do_js_action(JoyButton button) { auto joystick = GameManager::joysticks[0]; if (joystick == nullptr) return false; if (!is_pressed(joystick, button)) return false; bool js_ok = GameManager::num_joysticks_loaded > 0; bool timer_ok = joystick_action_timer.is_done(); if (js_ok && timer_ok) { joystick_action_timer.start(0.10, GameManager::FPS); return true; } return false; }; bool get_first_keyboard_button_pressed(bool key_pressed[ALLEGRO_KEY_MAX], int *keycode) { for (int i = 0; i < ALLEGRO_KEY_MAX; i++) { if (key_pressed[i]) { *keycode = i; return true; } } return false; } bool get_first_joystick_button_pressed(XC_STATE *joystick, JoyButton *button) { if (is_pressed(joystick, JoyButton::LEFT_STICK_X_LEFT)) { *button = JoyButton::LEFT_STICK_X_LEFT; return true; } if (is_pressed(joystick, JoyButton::LEFT_STICK_X_RIGHT)) { *button = JoyButton::LEFT_STICK_X_RIGHT; return true; } if (is_pressed(joystick, JoyButton::LEFT_STICK_Y_UP)) { *button = JoyButton::LEFT_STICK_Y_UP; return true; } if (is_pressed(joystick, JoyButton::LEFT_STICK_Y_DOWN)) { *button = JoyButton::LEFT_STICK_Y_DOWN; return true; } if (is_pressed(joystick, JoyButton::LEFT_TRIGGER)) { *button = JoyButton::LEFT_TRIGGER; return true; } if (is_pressed(joystick, JoyButton::RIGHT_STICK_X_LEFT)) { *button = JoyButton::RIGHT_STICK_X_LEFT; return true; } if (is_pressed(joystick, JoyButton::RIGHT_STICK_X_RIGHT)) { *button = JoyButton::RIGHT_STICK_X_RIGHT; return true; } if (is_pressed(joystick, JoyButton::RIGHT_STICK_Y_UP)) { *button = JoyButton::RIGHT_STICK_Y_UP; return true; } if (is_pressed(joystick, JoyButton::RIGHT_STICK_Y_DOWN)) { *button = JoyButton::RIGHT_STICK_Y_DOWN; return true; } if (is_pressed(joystick, JoyButton::RIGHT_TRIGGER)) { *button = JoyButton::RIGHT_TRIGGER; return true; } if (is_pressed(joystick, JoyButton::DPAD_X_LEFT)) { *button = JoyButton::DPAD_X_LEFT; return true; } if (is_pressed(joystick, JoyButton::DPAD_X_RIGHT)) { *button = JoyButton::DPAD_X_RIGHT; return true; } if (is_pressed(joystick, JoyButton::DPAD_Y_UP)) { *button = JoyButton::DPAD_Y_UP; return true; } if (is_pressed(joystick, JoyButton::DPAD_Y_DOWN)) { *button = JoyButton::DPAD_Y_DOWN; return true; } if (is_pressed(joystick, JoyButton::BUTTON_A)) { *button = JoyButton::BUTTON_A; return true; } if (is_pressed(joystick, JoyButton::BUTTON_B)) { *button = JoyButton::BUTTON_B; return true; } if (is_pressed(joystick, JoyButton::BUTTON_X)) { *button = JoyButton::BUTTON_X; return true; } if (is_pressed(joystick, JoyButton::BUTTON_Y)) { *button = JoyButton::BUTTON_Y; return true; } if (is_pressed(joystick, JoyButton::BUTTON_LEFT_STICK)) { *button = JoyButton::BUTTON_LEFT_STICK; return true; } if (is_pressed(joystick, JoyButton::BUTTON_RIGHT_STICK)) { *button = JoyButton::BUTTON_RIGHT_STICK; return true; } if (is_pressed(joystick, JoyButton::BUTTON_LEFT_SHOULDER)) { *button = JoyButton::BUTTON_LEFT_SHOULDER; return true; } if (is_pressed(joystick, JoyButton::BUTTON_RIGHT_SHOULDER)) { *button = JoyButton::BUTTON_RIGHT_SHOULDER; return true; } if (is_pressed(joystick, JoyButton::BUTTON_START)) { *button = JoyButton::BUTTON_START; return true; } if (is_pressed(joystick, JoyButton::BUTTON_BACK)) { *button = JoyButton::BUTTON_BACK; return true; } if (is_pressed(joystick, JoyButton::BUTTON_XBOX)) { *button = JoyButton::BUTTON_XBOX; return true; } return false; } void IntroSequence::handle_key_presses(bool key_pressed[ALLEGRO_KEY_MAX], bool *reload, bool *startgame, bool *exit) { if (selecting_new_keyboard_button) { int keycode; if (get_first_keyboard_button_pressed(key_pressed, &keycode)) { int keyboard_set = -1; int start_idx = -1; if (menuselected >= menu_kbd_layout1_idx) { keyboard_set = 0; start_idx = menu_kbd_layout1_idx; } if (menu_kbd_layout2_idx != 0 && menuselected >= menu_kbd_layout2_idx) { keyboard_set = 1; start_idx = menu_kbd_layout2_idx; } if (menu_kbd_layout3_idx != 0 && menuselected >= menu_kbd_layout3_idx) { keyboard_set = 2; start_idx = menu_kbd_layout3_idx; } if (menu_kbd_layout4_idx != 0 && menuselected >= menu_kbd_layout4_idx) { keyboard_set = 3; start_idx = menu_kbd_layout4_idx; } int key_idx = menuselected - start_idx; mapping_key::key_sets[keyboard_set][key_idx] = keycode; selecting_new_keyboard_button = false; return; } } else if (selecting_new_joystick_button) { JoyButton button; int joy_set = -1; int start_idx = -1; if (menuselected >= menu_joy_layout1_idx) { joy_set = 0; start_idx = menu_joy_layout1_idx; } if (menu_joy_layout2_idx != 0 && menuselected >= menu_joy_layout2_idx) { joy_set = 1; start_idx = menu_joy_layout2_idx; } if (menu_joy_layout3_idx != 0 && menuselected >= menu_joy_layout3_idx) { joy_set = 2; start_idx = menu_joy_layout3_idx; } if (menu_joy_layout4_idx != 0 && menuselected >= menu_joy_layout4_idx) { joy_set = 3; start_idx = menu_joy_layout4_idx; } int key_idx = menuselected - start_idx; if (joystick_action_timer.is_done() && get_first_joystick_button_pressed(GameManager::joysticks[joy_set], &button)) { mapping_joy::btn_sets[joy_set][key_idx] = button; selecting_new_joystick_button = false; do_js_action(button); // For resetting timer } } auto do_js_action = [&](JoyButton button) { auto joystick = GameManager::joysticks[0]; if (joystick == nullptr) return false; if (!is_pressed(joystick, button)) return false; bool js_ok = GameManager::num_joysticks_loaded > 0; bool timer_ok = joystick_action_timer.is_done(); if (js_ok && timer_ok) { joystick_action_timer.start(0.10, GameManager::FPS); return true; } return false; }; auto do_key_action = [&](int button) { if (!key_pressed[button]) return false; if (button != ALLEGRO_KEY_ESCAPE && (selecting_new_keyboard_button || selecting_new_joystick_button)) { return false; } return true; }; if (do_key_action(ALLEGRO_KEY_ESCAPE) || do_js_action(JoyButton::BUTTON_BACK)) { if (selecting_new_joystick_button || selecting_new_keyboard_button) { selecting_new_joystick_button = false; selecting_new_keyboard_button = false; } else { *exit = true; } } if (do_key_action(ALLEGRO_KEY_F2)) { playerschoice = 2; *startgame = true; } if (do_key_action(ALLEGRO_KEY_F3)) { playerschoice = 3; *startgame = true; } if (do_key_action(ALLEGRO_KEY_F4)) { playerschoice = 4; *startgame = true; } // menu control if (do_key_action(ALLEGRO_KEY_DOWN) || do_js_action(JoyButton::LEFT_STICK_Y_DOWN)) { if (menuselected < menuitems - 1) menuselected++; else menuselected = 0; } if (do_key_action(ALLEGRO_KEY_UP) || do_js_action(JoyButton::LEFT_STICK_Y_UP)) { if (menuselected > 0) menuselected--; else menuselected = menuitems - 1; } if (do_key_action(ALLEGRO_KEY_LEFT) || do_js_action(JoyButton::LEFT_STICK_X_LEFT)) { switch (menuselected) { case 1: if (playerschoice > 2) playerschoice--; break; case 2: if (levelchoice > 0) levelchoice--; break; case 3: if (liveschoice > 0) liveschoice--; break; case 4: dcachoice = !dcachoice; break; case 5: wallchoice = !wallchoice; break; } } if (do_key_action(ALLEGRO_KEY_RIGHT) || do_js_action(JoyButton::LEFT_STICK_X_RIGHT)) { switch (menuselected) { case 1: if (playerschoice < NB_MAX_PLAYERS) playerschoice++; break; case 2: if (levelchoice < NB_LEVELS - 1) levelchoice++; break; case 3: liveschoice++; break; case 4: dcachoice = !dcachoice; break; case 5: wallchoice = !wallchoice; break; } } if (do_key_action(ALLEGRO_KEY_ENTER) || do_js_action(JoyButton::BUTTON_A)) { switch (menuselected) { case 0: *startgame = true; break; case 1: playerschoice++; if (playerschoice > NB_MAX_PLAYERS) playerschoice = 2; break; case 2: levelchoice++; if (levelchoice == NB_LEVELS) levelchoice = 0; break; case 3: liveschoice++; if (liveschoice == NB_MAXLIVES) liveschoice = 0; break; case 4: dcachoice = !dcachoice; break; case 5: wallchoice = !wallchoice; break; case 6: cycle_control(0); break; case 7: cycle_control(1); break; case 8: cycle_control(2); break; case 9: cycle_control(3); break; } if (menuselected == menu_resolution_idx) { if (width == GameManager::native_width && height == GameManager::native_height) GameManager::ChangeScreenRes(1024, 768); else GameManager::ChangeScreenRes(GameManager::native_width, GameManager::native_height); *reload = true; } else if (menuselected == menu_exit_idx) { *exit = true; } else if (menuselected >= menu_kbd_layout1_idx && menuselected < menu_kbd_layout_end) { selecting_new_keyboard_button = true; } else if (menuselected >= menu_joy_layout1_idx && menuselected < menu_joy_layout_end) { selecting_new_joystick_button = true; } } }
{ "content_hash": "c77fea65e116e9c846fc7fdf9060db59", "timestamp": "", "source": "github", "line_count": 684, "max_line_length": 129, "avg_line_length": 30.637426900584796, "alnum_prop": 0.5742985302538652, "repo_name": "martinohanlon/mayhem-pi", "id": "b645a2abd57ce703ac2a03b6a391ad985cd270ea", "size": "21187", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "intro_sequence.cpp", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "18763" }, { "name": "C++", "bytes": "156023" }, { "name": "Makefile", "bytes": "3109" }, { "name": "Shell", "bytes": "358" } ], "symlink_target": "" }
<?php /** * @file * Definition of Drupal\system\Tests\File\ScanDirectoryTest. */ namespace Drupal\system\Tests\File; /** * Tests the file_scan_directory() function. */ class ScanDirectoryTest extends FileTestBase { /** * Modules to enable. * * @var array */ public static $modules = array('file_test'); public static function getInfo() { return array( 'name' => 'File scan directory', 'description' => 'Tests the file_scan_directory() function.', 'group' => 'File API', ); } function setUp() { parent::setUp(); $this->path = drupal_get_path('module', 'simpletest') . '/files'; } /** * Check the format of the returned values. */ function testReturn() { // Grab a listing of all the JavaSscript files and check that they're // passed to the callback. $all_files = file_scan_directory($this->path, '/^javascript-/'); ksort($all_files); $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.'); // Check the first file. $file = reset($all_files); $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the first returned file.'); $this->assertEqual($file->uri, $this->path . '/javascript-1.txt', 'First file name was set correctly.'); $this->assertEqual($file->filename, 'javascript-1.txt', 'First basename was set correctly'); $this->assertEqual($file->name, 'javascript-1', 'First name was set correctly.'); // Check the second file. $file = next($all_files); $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the second returned file.'); $this->assertEqual($file->uri, $this->path . '/javascript-2.script', 'Second file name was set correctly.'); $this->assertEqual($file->filename, 'javascript-2.script', 'Second basename was set correctly'); $this->assertEqual($file->name, 'javascript-2', 'Second name was set correctly.'); } /** * Check that the callback function is called correctly. */ function testOptionCallback() { drupal_load('module', 'file_test'); // When nothing is matched nothing should be passed to the callback. $all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array('callback' => 'file_test_file_scan_callback')); $this->assertEqual(0, count($all_files), 'No files were found.'); $results = file_test_file_scan_callback(); file_test_file_scan_callback_reset(); $this->assertEqual(0, count($results), 'No files were passed to the callback.'); // Grab a listing of all the JavaSscript files and check that they're // passed to the callback. $all_files = file_scan_directory($this->path, '/^javascript-/', array('callback' => 'file_test_file_scan_callback')); $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.'); $results = file_test_file_scan_callback(); file_test_file_scan_callback_reset(); $this->assertEqual(2, count($results), 'Files were passed to the callback.'); } /** * Check that the no-mask parameter is honored. */ function testOptionNoMask() { // Grab a listing of all the JavaSscript files. $all_files = file_scan_directory($this->path, '/^javascript-/'); $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.'); // Now use the nomast parameter to filter out the .script file. $filtered_files = file_scan_directory($this->path, '/^javascript-/', array('nomask' => '/.script$/')); $this->assertEqual(1, count($filtered_files), 'Filtered correctly.'); } /** * Check that key parameter sets the return value's key. */ function testOptionKey() { // "filename", for the path starting with $dir. $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script'); $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filepath'))); sort($actual); $this->assertEqual($expected, $actual, 'Returned the correct values for the filename key.'); // "basename", for the basename of the file. $expected = array('javascript-1.txt', 'javascript-2.script'); $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filename'))); sort($actual); $this->assertEqual($expected, $actual, 'Returned the correct values for the basename key.'); // "name" for the name of the file without an extension. $expected = array('javascript-1', 'javascript-2'); $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'name'))); sort($actual); $this->assertEqual($expected, $actual, 'Returned the correct values for the name key.'); // Invalid option that should default back to "filename". $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script'); $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'INVALID'))); sort($actual); $this->assertEqual($expected, $actual, 'An invalid key defaulted back to the default.'); } /** * Check that the recurse option decends into subdirectories. */ function testOptionRecurse() { $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => FALSE)); $this->assertTrue(empty($files), "Without recursion couldn't find javascript files."); $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => TRUE)); $this->assertEqual(2, count($files), 'With recursion we found the expected javascript files.'); } /** * Check that the min_depth options lets us ignore files in the starting * directory. */ function testOptionMinDepth() { $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 0)); $this->assertEqual(2, count($files), 'No minimum-depth gets files in current directory.'); $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 1)); $this->assertTrue(empty($files), 'Minimum-depth of 1 successfully excludes files from current directory.'); } }
{ "content_hash": "e9900a97e9a6beb5695b8e19298a7dc8", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 129, "avg_line_length": 42.17687074829932, "alnum_prop": 0.655483870967742, "repo_name": "augustash/d8.dev", "id": "b4a4885c207956cf4af2d32f20766b1183f770a3", "size": "6200", "binary": false, "copies": "10", "ref": "refs/heads/develop", "path": "core/modules/system/lib/Drupal/system/Tests/File/ScanDirectoryTest.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Mycotaxon 29: 199 (1987) #### Original name Cladia moniliformis Kantvilas & Elix ### Remarks null
{ "content_hash": "44539b7debc1f30750cd4dd8e168e23f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 36, "avg_line_length": 12.384615384615385, "alnum_prop": 0.7142857142857143, "repo_name": "mdoering/backbone", "id": "7c8c99f4194d98d58cf1bae45ee9e433eb7da3c3", "size": "221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Cladoniaceae/Cladia/Cladia moniliformis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Unit tests for the SyncApi. Note that a lot of the underlying // functionality is provided by the Syncable layer, which has its own // unit tests. We'll test SyncApi specific things in this harness. #include <cstddef> #include <map> #include "base/basictypes.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/files/scoped_temp_dir.h" #include "base/format_macros.h" #include "base/location.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/message_loop/message_loop_proxy.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/values_test_util.h" #include "base/values.h" #include "sync/engine/sync_scheduler.h" #include "sync/internal_api/public/base/model_type_test_util.h" #include "sync/internal_api/public/change_record.h" #include "sync/internal_api/public/engine/model_safe_worker.h" #include "sync/internal_api/public/engine/polling_constants.h" #include "sync/internal_api/public/http_post_provider_factory.h" #include "sync/internal_api/public/http_post_provider_interface.h" #include "sync/internal_api/public/read_node.h" #include "sync/internal_api/public/read_transaction.h" #include "sync/internal_api/public/test/test_entry_factory.h" #include "sync/internal_api/public/test/test_internal_components_factory.h" #include "sync/internal_api/public/test/test_user_share.h" #include "sync/internal_api/public/write_node.h" #include "sync/internal_api/public/write_transaction.h" #include "sync/internal_api/sync_encryption_handler_impl.h" #include "sync/internal_api/sync_manager_impl.h" #include "sync/internal_api/syncapi_internal.h" #include "sync/js/js_arg_list.h" #include "sync/js/js_backend.h" #include "sync/js/js_event_handler.h" #include "sync/js/js_reply_handler.h" #include "sync/js/js_test_util.h" #include "sync/notifier/fake_invalidation_handler.h" #include "sync/notifier/fake_invalidator.h" #include "sync/notifier/invalidation_handler.h" #include "sync/notifier/invalidator.h" #include "sync/protocol/bookmark_specifics.pb.h" #include "sync/protocol/encryption.pb.h" #include "sync/protocol/extension_specifics.pb.h" #include "sync/protocol/password_specifics.pb.h" #include "sync/protocol/preference_specifics.pb.h" #include "sync/protocol/proto_value_conversions.h" #include "sync/protocol/sync.pb.h" #include "sync/sessions/sync_session.h" #include "sync/syncable/directory.h" #include "sync/syncable/entry.h" #include "sync/syncable/mutable_entry.h" #include "sync/syncable/nigori_util.h" #include "sync/syncable/syncable_id.h" #include "sync/syncable/syncable_read_transaction.h" #include "sync/syncable/syncable_util.h" #include "sync/syncable/syncable_write_transaction.h" #include "sync/test/callback_counter.h" #include "sync/test/engine/fake_sync_scheduler.h" #include "sync/test/engine/test_id_factory.h" #include "sync/test/fake_encryptor.h" #include "sync/test/fake_extensions_activity_monitor.h" #include "sync/util/cryptographer.h" #include "sync/util/extensions_activity_monitor.h" #include "sync/util/test_unrecoverable_error_handler.h" #include "sync/util/time.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::ExpectDictStringValue; using testing::_; using testing::DoAll; using testing::InSequence; using testing::Return; using testing::SaveArg; using testing::StrictMock; namespace syncer { using sessions::SyncSessionSnapshot; using syncable::GET_BY_HANDLE; using syncable::IS_DEL; using syncable::IS_UNSYNCED; using syncable::NON_UNIQUE_NAME; using syncable::SPECIFICS; using syncable::kEncryptedString; namespace { const char kTestChromeVersion[] = "test chrome version"; void ExpectInt64Value(int64 expected_value, const base::DictionaryValue& value, const std::string& key) { std::string int64_str; EXPECT_TRUE(value.GetString(key, &int64_str)); int64 val = 0; EXPECT_TRUE(base::StringToInt64(int64_str, &val)); EXPECT_EQ(expected_value, val); } void ExpectTimeValue(const base::Time& expected_value, const base::DictionaryValue& value, const std::string& key) { std::string time_str; EXPECT_TRUE(value.GetString(key, &time_str)); EXPECT_EQ(GetTimeDebugString(expected_value), time_str); } // Makes a non-folder child of the root node. Returns the id of the // newly-created node. int64 MakeNode(UserShare* share, ModelType model_type, const std::string& client_tag) { WriteTransaction trans(FROM_HERE, share); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode node(&trans); WriteNode::InitUniqueByCreationResult result = node.InitUniqueByCreation(model_type, root_node, client_tag); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); node.SetIsFolder(false); return node.GetId(); } // Makes a folder child of a non-root node. Returns the id of the // newly-created node. int64 MakeFolderWithParent(UserShare* share, ModelType model_type, int64 parent_id, BaseNode* predecessor) { WriteTransaction trans(FROM_HERE, share); ReadNode parent_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id)); WriteNode node(&trans); EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor)); node.SetIsFolder(true); return node.GetId(); } int64 MakeBookmarkWithParent(UserShare* share, int64 parent_id, BaseNode* predecessor) { WriteTransaction trans(FROM_HERE, share); ReadNode parent_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent_id)); WriteNode node(&trans); EXPECT_TRUE(node.InitBookmarkByCreation(parent_node, predecessor)); return node.GetId(); } // Creates the "synced" root node for a particular datatype. We use the syncable // methods here so that the syncer treats these nodes as if they were already // received from the server. int64 MakeServerNodeForType(UserShare* share, ModelType model_type) { sync_pb::EntitySpecifics specifics; AddDefaultFieldValue(model_type, &specifics); syncable::WriteTransaction trans( FROM_HERE, syncable::UNITTEST, share->directory.get()); // Attempt to lookup by nigori tag. std::string type_tag = ModelTypeToRootTag(model_type); syncable::Id node_id = syncable::Id::CreateFromServerId(type_tag); syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM, node_id); EXPECT_TRUE(entry.good()); entry.Put(syncable::BASE_VERSION, 1); entry.Put(syncable::SERVER_VERSION, 1); entry.Put(syncable::IS_UNAPPLIED_UPDATE, false); entry.Put(syncable::SERVER_PARENT_ID, syncable::GetNullId()); entry.Put(syncable::SERVER_IS_DIR, true); entry.Put(syncable::IS_DIR, true); entry.Put(syncable::SERVER_SPECIFICS, specifics); entry.Put(syncable::UNIQUE_SERVER_TAG, type_tag); entry.Put(syncable::NON_UNIQUE_NAME, type_tag); entry.Put(syncable::IS_DEL, false); entry.Put(syncable::SPECIFICS, specifics); return entry.Get(syncable::META_HANDLE); } // Simulates creating a "synced" node as a child of the root datatype node. int64 MakeServerNode(UserShare* share, ModelType model_type, const std::string& client_tag, const std::string& hashed_tag, const sync_pb::EntitySpecifics& specifics) { syncable::WriteTransaction trans( FROM_HERE, syncable::UNITTEST, share->directory.get()); syncable::Entry root_entry(&trans, syncable::GET_BY_SERVER_TAG, ModelTypeToRootTag(model_type)); EXPECT_TRUE(root_entry.good()); syncable::Id root_id = root_entry.Get(syncable::ID); syncable::Id node_id = syncable::Id::CreateFromServerId(client_tag); syncable::MutableEntry entry(&trans, syncable::CREATE_NEW_UPDATE_ITEM, node_id); EXPECT_TRUE(entry.good()); entry.Put(syncable::BASE_VERSION, 1); entry.Put(syncable::SERVER_VERSION, 1); entry.Put(syncable::IS_UNAPPLIED_UPDATE, false); entry.Put(syncable::SERVER_PARENT_ID, root_id); entry.Put(syncable::PARENT_ID, root_id); entry.Put(syncable::SERVER_IS_DIR, false); entry.Put(syncable::IS_DIR, false); entry.Put(syncable::SERVER_SPECIFICS, specifics); entry.Put(syncable::NON_UNIQUE_NAME, client_tag); entry.Put(syncable::UNIQUE_CLIENT_TAG, hashed_tag); entry.Put(syncable::IS_DEL, false); entry.Put(syncable::SPECIFICS, specifics); return entry.Get(syncable::META_HANDLE); } } // namespace class SyncApiTest : public testing::Test { public: virtual void SetUp() { test_user_share_.SetUp(); } virtual void TearDown() { test_user_share_.TearDown(); } protected: base::MessageLoop message_loop_; TestUserShare test_user_share_; }; TEST_F(SyncApiTest, SanityCheckTest) { { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); EXPECT_TRUE(trans.GetWrappedTrans()); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); EXPECT_TRUE(trans.GetWrappedTrans()); } { // No entries but root should exist ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); // Metahandle 1 can be root, sanity check 2 EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByIdLookup(2)); } } TEST_F(SyncApiTest, BasicTagWrite) { { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); EXPECT_EQ(root_node.GetFirstChildId(), 0); } ignore_result(MakeNode(test_user_share_.user_share(), BOOKMARKS, "testtag")); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, "testtag")); ReadNode root_node(&trans); root_node.InitByRootLookup(); EXPECT_NE(node.GetId(), 0); EXPECT_EQ(node.GetId(), root_node.GetFirstChildId()); } } TEST_F(SyncApiTest, ModelTypesSiloed) { { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); EXPECT_EQ(root_node.GetFirstChildId(), 0); } ignore_result(MakeNode(test_user_share_.user_share(), BOOKMARKS, "collideme")); ignore_result(MakeNode(test_user_share_.user_share(), PREFERENCES, "collideme")); ignore_result(MakeNode(test_user_share_.user_share(), AUTOFILL, "collideme")); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode bookmarknode(&trans); EXPECT_EQ(BaseNode::INIT_OK, bookmarknode.InitByClientTagLookup(BOOKMARKS, "collideme")); ReadNode prefnode(&trans); EXPECT_EQ(BaseNode::INIT_OK, prefnode.InitByClientTagLookup(PREFERENCES, "collideme")); ReadNode autofillnode(&trans); EXPECT_EQ(BaseNode::INIT_OK, autofillnode.InitByClientTagLookup(AUTOFILL, "collideme")); EXPECT_NE(bookmarknode.GetId(), prefnode.GetId()); EXPECT_NE(autofillnode.GetId(), prefnode.GetId()); EXPECT_NE(bookmarknode.GetId(), autofillnode.GetId()); } } TEST_F(SyncApiTest, ReadMissingTagsFails) { { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByClientTagLookup(BOOKMARKS, "testtag")); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_NOT_GOOD, node.InitByClientTagLookup(BOOKMARKS, "testtag")); } } // TODO(chron): Hook this all up to the server and write full integration tests // for update->undelete behavior. TEST_F(SyncApiTest, TestDeleteBehavior) { int64 node_id; int64 folder_id; std::string test_title("test1"); { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); // we'll use this spare folder later WriteNode folder_node(&trans); EXPECT_TRUE(folder_node.InitBookmarkByCreation(root_node, NULL)); folder_id = folder_node.GetId(); WriteNode wnode(&trans); WriteNode::InitUniqueByCreationResult result = wnode.InitUniqueByCreation(BOOKMARKS, root_node, "testtag"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); wnode.SetIsFolder(false); wnode.SetTitle(UTF8ToWide(test_title)); node_id = wnode.GetId(); } // Ensure we can delete something with a tag. { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode wnode(&trans); EXPECT_EQ(BaseNode::INIT_OK, wnode.InitByClientTagLookup(BOOKMARKS, "testtag")); EXPECT_FALSE(wnode.GetIsFolder()); EXPECT_EQ(wnode.GetTitle(), test_title); wnode.Tombstone(); } // Lookup of a node which was deleted should return failure, // but have found some data about the node. { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_ENTRY_IS_DEL, node.InitByClientTagLookup(BOOKMARKS, "testtag")); // Note that for proper function of this API this doesn't need to be // filled, we're checking just to make sure the DB worked in this test. EXPECT_EQ(node.GetTitle(), test_title); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode folder_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, folder_node.InitByIdLookup(folder_id)); WriteNode wnode(&trans); // This will undelete the tag. WriteNode::InitUniqueByCreationResult result = wnode.InitUniqueByCreation(BOOKMARKS, folder_node, "testtag"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); EXPECT_EQ(wnode.GetIsFolder(), false); EXPECT_EQ(wnode.GetParentId(), folder_node.GetId()); EXPECT_EQ(wnode.GetId(), node_id); EXPECT_NE(wnode.GetTitle(), test_title); // Title should be cleared wnode.SetTitle(UTF8ToWide(test_title)); } // Now look up should work. { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, "testtag")); EXPECT_EQ(node.GetTitle(), test_title); EXPECT_EQ(node.GetModelType(), BOOKMARKS); } } TEST_F(SyncApiTest, WriteAndReadPassword) { KeyParams params = {"localhost", "username", "passphrase"}; { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); trans.GetCryptographer()->AddKey(params); } { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode password_node(&trans); WriteNode::InitUniqueByCreationResult result = password_node.InitUniqueByCreation(PASSWORDS, root_node, "foo"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); password_node.SetPasswordSpecifics(data); } { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, password_node.InitByClientTagLookup(PASSWORDS, "foo")); const sync_pb::PasswordSpecificsData& data = password_node.GetPasswordSpecifics(); EXPECT_EQ("secret", data.password_value()); } } TEST_F(SyncApiTest, WriteEncryptedTitle) { KeyParams params = {"localhost", "username", "passphrase"}; { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); trans.GetCryptographer()->AddKey(params); } test_user_share_.encryption_handler()->EnableEncryptEverything(); int bookmark_id; { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode bookmark_node(&trans); ASSERT_TRUE(bookmark_node.InitBookmarkByCreation(root_node, NULL)); bookmark_id = bookmark_node.GetId(); bookmark_node.SetTitle(UTF8ToWide("foo")); WriteNode pref_node(&trans); WriteNode::InitUniqueByCreationResult result = pref_node.InitUniqueByCreation(PREFERENCES, root_node, "bar"); ASSERT_EQ(WriteNode::INIT_SUCCESS, result); pref_node.SetTitle(UTF8ToWide("bar")); } { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); ReadNode bookmark_node(&trans); ASSERT_EQ(BaseNode::INIT_OK, bookmark_node.InitByIdLookup(bookmark_id)); EXPECT_EQ("foo", bookmark_node.GetTitle()); EXPECT_EQ(kEncryptedString, bookmark_node.GetEntry()->Get(syncable::NON_UNIQUE_NAME)); ReadNode pref_node(&trans); ASSERT_EQ(BaseNode::INIT_OK, pref_node.InitByClientTagLookup(PREFERENCES, "bar")); EXPECT_EQ(kEncryptedString, pref_node.GetTitle()); } } TEST_F(SyncApiTest, BaseNodeSetSpecifics) { int64 child_id = MakeNode(test_user_share_.user_share(), BOOKMARKS, "testtag"); WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id)); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("http://www.google.com"); EXPECT_NE(entity_specifics.SerializeAsString(), node.GetEntitySpecifics().SerializeAsString()); node.SetEntitySpecifics(entity_specifics); EXPECT_EQ(entity_specifics.SerializeAsString(), node.GetEntitySpecifics().SerializeAsString()); } TEST_F(SyncApiTest, BaseNodeSetSpecificsPreservesUnknownFields) { int64 child_id = MakeNode(test_user_share_.user_share(), BOOKMARKS, "testtag"); WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id)); EXPECT_TRUE(node.GetEntitySpecifics().unknown_fields().empty()); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("http://www.google.com"); entity_specifics.mutable_unknown_fields()->AddFixed32(5, 100); node.SetEntitySpecifics(entity_specifics); EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty()); entity_specifics.mutable_unknown_fields()->Clear(); node.SetEntitySpecifics(entity_specifics); EXPECT_FALSE(node.GetEntitySpecifics().unknown_fields().empty()); } namespace { void CheckNodeValue(const BaseNode& node, const base::DictionaryValue& value, bool is_detailed) { size_t expected_field_count = 4; ExpectInt64Value(node.GetId(), value, "id"); { bool is_folder = false; EXPECT_TRUE(value.GetBoolean("isFolder", &is_folder)); EXPECT_EQ(node.GetIsFolder(), is_folder); } ExpectDictStringValue(node.GetTitle(), value, "title"); ModelType expected_model_type = node.GetModelType(); std::string type_str; EXPECT_TRUE(value.GetString("type", &type_str)); if (expected_model_type >= FIRST_REAL_MODEL_TYPE) { ModelType model_type = ModelTypeFromString(type_str); EXPECT_EQ(expected_model_type, model_type); } else if (expected_model_type == TOP_LEVEL_FOLDER) { EXPECT_EQ("Top-level folder", type_str); } else if (expected_model_type == UNSPECIFIED) { EXPECT_EQ("Unspecified", type_str); } else { ADD_FAILURE(); } if (is_detailed) { { scoped_ptr<base::DictionaryValue> expected_entry( node.GetEntry()->ToValue(NULL)); const base::Value* entry = NULL; EXPECT_TRUE(value.Get("entry", &entry)); EXPECT_TRUE(base::Value::Equals(entry, expected_entry.get())); } ExpectInt64Value(node.GetParentId(), value, "parentId"); ExpectTimeValue(node.GetModificationTime(), value, "modificationTime"); ExpectInt64Value(node.GetExternalId(), value, "externalId"); expected_field_count += 4; if (value.HasKey("predecessorId")) { ExpectInt64Value(node.GetPredecessorId(), value, "predecessorId"); expected_field_count++; } if (value.HasKey("successorId")) { ExpectInt64Value(node.GetSuccessorId(), value, "successorId"); expected_field_count++; } if (value.HasKey("firstChildId")) { ExpectInt64Value(node.GetFirstChildId(), value, "firstChildId"); expected_field_count++; } } EXPECT_EQ(expected_field_count, value.size()); } } // namespace TEST_F(SyncApiTest, BaseNodeGetSummaryAsValue) { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); node.InitByRootLookup(); scoped_ptr<base::DictionaryValue> details(node.GetSummaryAsValue()); if (details) { CheckNodeValue(node, *details, false); } else { ADD_FAILURE(); } } TEST_F(SyncApiTest, BaseNodeGetDetailsAsValue) { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode node(&trans); node.InitByRootLookup(); scoped_ptr<base::DictionaryValue> details(node.GetDetailsAsValue()); if (details) { CheckNodeValue(node, *details, true); } else { ADD_FAILURE(); } } TEST_F(SyncApiTest, EmptyTags) { WriteTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode node(&trans); std::string empty_tag; WriteNode::InitUniqueByCreationResult result = node.InitUniqueByCreation(TYPED_URLS, root_node, empty_tag); EXPECT_NE(WriteNode::INIT_SUCCESS, result); EXPECT_EQ(BaseNode::INIT_FAILED_PRECONDITION, node.InitByTagLookup(empty_tag)); } // Test counting nodes when the type's root node has no children. TEST_F(SyncApiTest, GetTotalNodeCountEmpty) { int64 type_root = MakeServerNodeForType(test_user_share_.user_share(), BOOKMARKS); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode type_root_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root)); EXPECT_EQ(1, type_root_node.GetTotalNodeCount()); } } // Test counting nodes when there is one child beneath the type's root. TEST_F(SyncApiTest, GetTotalNodeCountOneChild) { int64 type_root = MakeServerNodeForType(test_user_share_.user_share(), BOOKMARKS); int64 parent = MakeFolderWithParent(test_user_share_.user_share(), BOOKMARKS, type_root, NULL); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode type_root_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root)); EXPECT_EQ(2, type_root_node.GetTotalNodeCount()); ReadNode parent_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, parent_node.InitByIdLookup(parent)); EXPECT_EQ(1, parent_node.GetTotalNodeCount()); } } // Test counting nodes when there are multiple children beneath the type root, // and one of those children has children of its own. TEST_F(SyncApiTest, GetTotalNodeCountMultipleChildren) { int64 type_root = MakeServerNodeForType(test_user_share_.user_share(), BOOKMARKS); int64 parent = MakeFolderWithParent(test_user_share_.user_share(), BOOKMARKS, type_root, NULL); ignore_result(MakeFolderWithParent(test_user_share_.user_share(), BOOKMARKS, type_root, NULL)); int64 child1 = MakeFolderWithParent( test_user_share_.user_share(), BOOKMARKS, parent, NULL); ignore_result(MakeBookmarkWithParent( test_user_share_.user_share(), parent, NULL)); ignore_result(MakeBookmarkWithParent( test_user_share_.user_share(), child1, NULL)); { ReadTransaction trans(FROM_HERE, test_user_share_.user_share()); ReadNode type_root_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, type_root_node.InitByIdLookup(type_root)); EXPECT_EQ(6, type_root_node.GetTotalNodeCount()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(parent)); EXPECT_EQ(4, node.GetTotalNodeCount()); } } namespace { class TestHttpPostProviderInterface : public HttpPostProviderInterface { public: virtual ~TestHttpPostProviderInterface() {} virtual void SetExtraRequestHeaders(const char* headers) OVERRIDE {} virtual void SetURL(const char* url, int port) OVERRIDE {} virtual void SetPostPayload(const char* content_type, int content_length, const char* content) OVERRIDE {} virtual bool MakeSynchronousPost(int* error_code, int* response_code) OVERRIDE { return false; } virtual int GetResponseContentLength() const OVERRIDE { return 0; } virtual const char* GetResponseContent() const OVERRIDE { return ""; } virtual const std::string GetResponseHeaderValue( const std::string& name) const OVERRIDE { return std::string(); } virtual void Abort() OVERRIDE {} }; class TestHttpPostProviderFactory : public HttpPostProviderFactory { public: virtual ~TestHttpPostProviderFactory() {} virtual HttpPostProviderInterface* Create() OVERRIDE { return new TestHttpPostProviderInterface(); } virtual void Destroy(HttpPostProviderInterface* http) OVERRIDE { delete static_cast<TestHttpPostProviderInterface*>(http); } }; class SyncManagerObserverMock : public SyncManager::Observer { public: MOCK_METHOD1(OnSyncCycleCompleted, void(const SyncSessionSnapshot&)); // NOLINT MOCK_METHOD4(OnInitializationComplete, void(const WeakHandle<JsBackend>&, const WeakHandle<DataTypeDebugInfoListener>&, bool, syncer::ModelTypeSet)); // NOLINT MOCK_METHOD1(OnConnectionStatusChange, void(ConnectionStatus)); // NOLINT MOCK_METHOD0(OnStopSyncingPermanently, void()); // NOLINT MOCK_METHOD1(OnUpdatedToken, void(const std::string&)); // NOLINT MOCK_METHOD1(OnActionableError, void(const SyncProtocolError&)); // NOLINT }; class SyncEncryptionHandlerObserverMock : public SyncEncryptionHandler::Observer { public: MOCK_METHOD2(OnPassphraseRequired, void(PassphraseRequiredReason, const sync_pb::EncryptedData&)); // NOLINT MOCK_METHOD0(OnPassphraseAccepted, void()); // NOLINT MOCK_METHOD2(OnBootstrapTokenUpdated, void(const std::string&, BootstrapTokenType type)); // NOLINT MOCK_METHOD2(OnEncryptedTypesChanged, void(ModelTypeSet, bool)); // NOLINT MOCK_METHOD0(OnEncryptionComplete, void()); // NOLINT MOCK_METHOD1(OnCryptographerStateChanged, void(Cryptographer*)); // NOLINT MOCK_METHOD2(OnPassphraseTypeChanged, void(PassphraseType, base::Time)); // NOLINT }; } // namespace class SyncManagerTest : public testing::Test, public SyncManager::ChangeDelegate { protected: enum NigoriStatus { DONT_WRITE_NIGORI, WRITE_TO_NIGORI }; enum EncryptionStatus { UNINITIALIZED, DEFAULT_ENCRYPTION, FULL_ENCRYPTION }; SyncManagerTest() : fake_invalidator_(NULL), sync_manager_("Test sync manager") { switches_.encryption_method = InternalComponentsFactory::ENCRYPTION_KEYSTORE; } virtual ~SyncManagerTest() { EXPECT_FALSE(fake_invalidator_); } // Test implementation. void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); SyncCredentials credentials; credentials.email = "foo@bar.com"; credentials.sync_token = "sometoken"; fake_invalidator_ = new FakeInvalidator(); sync_manager_.AddObserver(&manager_observer_); EXPECT_CALL(manager_observer_, OnInitializationComplete(_, _, _, _)). WillOnce(SaveArg<0>(&js_backend_)); EXPECT_FALSE(js_backend_.IsInitialized()); std::vector<ModelSafeWorker*> workers; ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); // Takes ownership of |fake_invalidator_|. sync_manager_.Init( temp_dir_.path(), WeakHandle<JsEventHandler>(), "bogus", 0, false, scoped_ptr<HttpPostProviderFactory>(new TestHttpPostProviderFactory()), workers, &extensions_activity_monitor_, this, credentials, scoped_ptr<Invalidator>(fake_invalidator_), "fake_invalidator_client_id", std::string(), std::string(), // bootstrap tokens scoped_ptr<InternalComponentsFactory>(GetFactory()), &encryptor_, &handler_, NULL, false); sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_); EXPECT_TRUE(js_backend_.IsInitialized()); for (ModelSafeRoutingInfo::iterator i = routing_info.begin(); i != routing_info.end(); ++i) { type_roots_[i->first] = MakeServerNodeForType( sync_manager_.GetUserShare(), i->first); } PumpLoop(); EXPECT_TRUE(fake_invalidator_->IsHandlerRegistered(&sync_manager_)); } void TearDown() { sync_manager_.RemoveObserver(&manager_observer_); sync_manager_.ShutdownOnSyncThread(); // We can't assert that |sync_manager_| isn't registered with // |fake_invalidator_| anymore because |fake_invalidator_| is now // destroyed. fake_invalidator_ = NULL; PumpLoop(); } void GetModelSafeRoutingInfo(ModelSafeRoutingInfo* out) { (*out)[NIGORI] = GROUP_PASSIVE; (*out)[DEVICE_INFO] = GROUP_PASSIVE; (*out)[EXPERIMENTS] = GROUP_PASSIVE; (*out)[BOOKMARKS] = GROUP_PASSIVE; (*out)[THEMES] = GROUP_PASSIVE; (*out)[SESSIONS] = GROUP_PASSIVE; (*out)[PASSWORDS] = GROUP_PASSIVE; (*out)[PREFERENCES] = GROUP_PASSIVE; (*out)[PRIORITY_PREFERENCES] = GROUP_PASSIVE; } virtual void OnChangesApplied( ModelType model_type, int64 model_version, const BaseTransaction* trans, const ImmutableChangeRecordList& changes) OVERRIDE {} virtual void OnChangesComplete(ModelType model_type) OVERRIDE {} // Helper methods. bool SetUpEncryption(NigoriStatus nigori_status, EncryptionStatus encryption_status) { UserShare* share = sync_manager_.GetUserShare(); // We need to create the nigori node as if it were an applied server update. int64 nigori_id = GetIdForDataType(NIGORI); if (nigori_id == kInvalidId) return false; // Set the nigori cryptographer information. if (encryption_status == FULL_ENCRYPTION) sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); WriteTransaction trans(FROM_HERE, share); Cryptographer* cryptographer = trans.GetCryptographer(); if (!cryptographer) return false; if (encryption_status != UNINITIALIZED) { KeyParams params = {"localhost", "dummy", "foobar"}; cryptographer->AddKey(params); } else { DCHECK_NE(nigori_status, WRITE_TO_NIGORI); } if (nigori_status == WRITE_TO_NIGORI) { sync_pb::NigoriSpecifics nigori; cryptographer->GetKeys(nigori.mutable_encryption_keybag()); share->directory->GetNigoriHandler()->UpdateNigoriFromEncryptedTypes( &nigori, trans.GetWrappedTrans()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(nigori_id)); node.SetNigoriSpecifics(nigori); } return cryptographer->is_ready(); } int64 GetIdForDataType(ModelType type) { if (type_roots_.count(type) == 0) return 0; return type_roots_[type]; } void PumpLoop() { message_loop_.RunUntilIdle(); } void SendJsMessage(const std::string& name, const JsArgList& args, const WeakHandle<JsReplyHandler>& reply_handler) { js_backend_.Call(FROM_HERE, &JsBackend::ProcessJsMessage, name, args, reply_handler); PumpLoop(); } void SetJsEventHandler(const WeakHandle<JsEventHandler>& event_handler) { js_backend_.Call(FROM_HERE, &JsBackend::SetJsEventHandler, event_handler); PumpLoop(); } // Looks up an entry by client tag and resets IS_UNSYNCED value to false. // Returns true if entry was previously unsynced, false if IS_UNSYNCED was // already false. bool ResetUnsyncedEntry(ModelType type, const std::string& client_tag) { UserShare* share = sync_manager_.GetUserShare(); syncable::WriteTransaction trans( FROM_HERE, syncable::UNITTEST, share->directory.get()); const std::string hash = syncable::GenerateSyncableHash(type, client_tag); syncable::MutableEntry entry(&trans, syncable::GET_BY_CLIENT_TAG, hash); EXPECT_TRUE(entry.good()); if (!entry.Get(IS_UNSYNCED)) return false; entry.Put(IS_UNSYNCED, false); return true; } virtual InternalComponentsFactory* GetFactory() { return new TestInternalComponentsFactory(GetSwitches(), STORAGE_IN_MEMORY); } // Returns true if we are currently encrypting all sync data. May // be called on any thread. bool EncryptEverythingEnabledForTest() { return sync_manager_.GetEncryptionHandler()->EncryptEverythingEnabled(); } // Gets the set of encrypted types from the cryptographer // Note: opens a transaction. May be called from any thread. ModelTypeSet GetEncryptedTypes() { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); return GetEncryptedTypesWithTrans(&trans); } ModelTypeSet GetEncryptedTypesWithTrans(BaseTransaction* trans) { return trans->GetDirectory()->GetNigoriHandler()-> GetEncryptedTypes(trans->GetWrappedTrans()); } void SimulateInvalidatorStateChangeForTest(InvalidatorState state) { DCHECK(sync_manager_.thread_checker_.CalledOnValidThread()); sync_manager_.OnInvalidatorStateChange(state); } void TriggerOnIncomingNotificationForTest(ModelTypeSet model_types) { DCHECK(sync_manager_.thread_checker_.CalledOnValidThread()); ModelTypeInvalidationMap invalidation_map = ModelTypeSetToInvalidationMap(model_types, std::string()); sync_manager_.OnIncomingInvalidation( ModelTypeInvalidationMapToObjectIdInvalidationMap( invalidation_map)); } void SetProgressMarkerForType(ModelType type, bool set) { if (set) { sync_pb::DataTypeProgressMarker marker; marker.set_token("token"); marker.set_data_type_id(GetSpecificsFieldNumberFromModelType(type)); sync_manager_.directory()->SetDownloadProgress(type, marker); } else { sync_pb::DataTypeProgressMarker marker; sync_manager_.directory()->SetDownloadProgress(type, marker); } } InternalComponentsFactory::Switches GetSwitches() const { return switches_; } private: // Needed by |sync_manager_|. base::MessageLoop message_loop_; // Needed by |sync_manager_|. base::ScopedTempDir temp_dir_; // Sync Id's for the roots of the enabled datatypes. std::map<ModelType, int64> type_roots_; FakeExtensionsActivityMonitor extensions_activity_monitor_; protected: FakeEncryptor encryptor_; TestUnrecoverableErrorHandler handler_; FakeInvalidator* fake_invalidator_; SyncManagerImpl sync_manager_; WeakHandle<JsBackend> js_backend_; StrictMock<SyncManagerObserverMock> manager_observer_; StrictMock<SyncEncryptionHandlerObserverMock> encryption_observer_; InternalComponentsFactory::Switches switches_; }; TEST_F(SyncManagerTest, UpdateEnabledTypes) { ModelSafeRoutingInfo routes; GetModelSafeRoutingInfo(&routes); const ModelTypeSet enabled_types = GetRoutingInfoTypes(routes); sync_manager_.UpdateEnabledTypes(enabled_types); EXPECT_EQ(ModelTypeSetToObjectIdSet(enabled_types), fake_invalidator_->GetRegisteredIds(&sync_manager_)); } TEST_F(SyncManagerTest, RegisterInvalidationHandler) { FakeInvalidationHandler fake_handler; sync_manager_.RegisterInvalidationHandler(&fake_handler); EXPECT_TRUE(fake_invalidator_->IsHandlerRegistered(&fake_handler)); const ObjectIdSet& ids = ModelTypeSetToObjectIdSet(ModelTypeSet(BOOKMARKS, PREFERENCES)); sync_manager_.UpdateRegisteredInvalidationIds(&fake_handler, ids); EXPECT_EQ(ids, fake_invalidator_->GetRegisteredIds(&fake_handler)); sync_manager_.UnregisterInvalidationHandler(&fake_handler); EXPECT_FALSE(fake_invalidator_->IsHandlerRegistered(&fake_handler)); } TEST_F(SyncManagerTest, ProcessJsMessage) { const JsArgList kNoArgs; StrictMock<MockJsReplyHandler> reply_handler; base::ListValue disabled_args; disabled_args.Append(new base::StringValue("TRANSIENT_INVALIDATION_ERROR")); EXPECT_CALL(reply_handler, HandleJsReply("getNotificationState", HasArgsAsList(disabled_args))); // This message should be dropped. SendJsMessage("unknownMessage", kNoArgs, reply_handler.AsWeakHandle()); SendJsMessage("getNotificationState", kNoArgs, reply_handler.AsWeakHandle()); } TEST_F(SyncManagerTest, ProcessJsMessageGetRootNodeDetails) { const JsArgList kNoArgs; StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; EXPECT_CALL(reply_handler, HandleJsReply("getRootNodeDetails", _)) .WillOnce(SaveArg<1>(&return_args)); SendJsMessage("getRootNodeDetails", kNoArgs, reply_handler.AsWeakHandle()); EXPECT_EQ(1u, return_args.Get().GetSize()); const base::DictionaryValue* node_info = NULL; EXPECT_TRUE(return_args.Get().GetDictionary(0, &node_info)); if (node_info) { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); node.InitByRootLookup(); CheckNodeValue(node, *node_info, true); } else { ADD_FAILURE(); } } void CheckGetNodesByIdReturnArgs(SyncManager* sync_manager, const JsArgList& return_args, int64 id, bool is_detailed) { EXPECT_EQ(1u, return_args.Get().GetSize()); const base::ListValue* nodes = NULL; ASSERT_TRUE(return_args.Get().GetList(0, &nodes)); ASSERT_TRUE(nodes); EXPECT_EQ(1u, nodes->GetSize()); const base::DictionaryValue* node_info = NULL; EXPECT_TRUE(nodes->GetDictionary(0, &node_info)); ASSERT_TRUE(node_info); ReadTransaction trans(FROM_HERE, sync_manager->GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(id)); CheckNodeValue(node, *node_info, is_detailed); } class SyncManagerGetNodesByIdTest : public SyncManagerTest { protected: virtual ~SyncManagerGetNodesByIdTest() {} void RunGetNodesByIdTest(const char* message_name, bool is_detailed) { int64 root_id = kInvalidId; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode root_node(&trans); root_node.InitByRootLookup(); root_id = root_node.GetId(); } int64 child_id = MakeNode(sync_manager_.GetUserShare(), BOOKMARKS, "testtag"); StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; const int64 ids[] = { root_id, child_id }; EXPECT_CALL(reply_handler, HandleJsReply(message_name, _)) .Times(arraysize(ids)).WillRepeatedly(SaveArg<1>(&return_args)); for (size_t i = 0; i < arraysize(ids); ++i) { base::ListValue args; base::ListValue* id_values = new base::ListValue(); args.Append(id_values); id_values->Append(new base::StringValue(base::Int64ToString(ids[i]))); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); CheckGetNodesByIdReturnArgs(&sync_manager_, return_args, ids[i], is_detailed); } } void RunGetNodesByIdFailureTest(const char* message_name) { StrictMock<MockJsReplyHandler> reply_handler; base::ListValue empty_list_args; empty_list_args.Append(new base::ListValue()); EXPECT_CALL(reply_handler, HandleJsReply(message_name, HasArgsAsList(empty_list_args))) .Times(6); { base::ListValue args; SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::ListValue()); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue(std::string())); SendJsMessage( message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue("nonsense")); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue("0")); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; base::ListValue* ids = new base::ListValue(); args.Append(ids); ids->Append(new base::StringValue("9999")); SendJsMessage(message_name, JsArgList(&args), reply_handler.AsWeakHandle()); } } }; TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesById) { RunGetNodesByIdTest("getNodeSummariesById", false); } TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsById) { RunGetNodesByIdTest("getNodeDetailsById", true); } TEST_F(SyncManagerGetNodesByIdTest, GetNodeSummariesByIdFailure) { RunGetNodesByIdFailureTest("getNodeSummariesById"); } TEST_F(SyncManagerGetNodesByIdTest, GetNodeDetailsByIdFailure) { RunGetNodesByIdFailureTest("getNodeDetailsById"); } TEST_F(SyncManagerTest, GetChildNodeIds) { StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; EXPECT_CALL(reply_handler, HandleJsReply("getChildNodeIds", _)) .Times(1).WillRepeatedly(SaveArg<1>(&return_args)); { base::ListValue args; args.Append(new base::StringValue("1")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } EXPECT_EQ(1u, return_args.Get().GetSize()); const base::ListValue* nodes = NULL; ASSERT_TRUE(return_args.Get().GetList(0, &nodes)); ASSERT_TRUE(nodes); EXPECT_EQ(9u, nodes->GetSize()); } TEST_F(SyncManagerTest, GetChildNodeIdsFailure) { StrictMock<MockJsReplyHandler> reply_handler; base::ListValue empty_list_args; empty_list_args.Append(new base::ListValue()); EXPECT_CALL(reply_handler, HandleJsReply("getChildNodeIds", HasArgsAsList(empty_list_args))) .Times(5); { base::ListValue args; SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue(std::string())); SendJsMessage( "getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue("nonsense")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue("0")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } { base::ListValue args; args.Append(new base::StringValue("9999")); SendJsMessage("getChildNodeIds", JsArgList(&args), reply_handler.AsWeakHandle()); } } TEST_F(SyncManagerTest, GetAllNodesTest) { StrictMock<MockJsReplyHandler> reply_handler; JsArgList return_args; EXPECT_CALL(reply_handler, HandleJsReply("getAllNodes", _)) .Times(1).WillRepeatedly(SaveArg<1>(&return_args)); { base::ListValue args; SendJsMessage("getAllNodes", JsArgList(&args), reply_handler.AsWeakHandle()); } // There's not much value in verifying every attribute on every node here. // Most of the value of this test has already been achieved: we've verified we // can call the above function without crashing or leaking memory. // // Let's just check the list size and a few of its elements. Anything more // would make this test brittle without greatly increasing our chances of // catching real bugs. const base::ListValue* node_list; const base::DictionaryValue* first_result; // The resulting argument list should have one argument, a list of nodes. ASSERT_EQ(1U, return_args.Get().GetSize()); ASSERT_TRUE(return_args.Get().GetList(0, &node_list)); // The database creation logic depends on the routing info. // Refer to setup methods for more information. ModelSafeRoutingInfo routes; GetModelSafeRoutingInfo(&routes); size_t directory_size = routes.size() + 1; ASSERT_EQ(directory_size, node_list->GetSize()); ASSERT_TRUE(node_list->GetDictionary(0, &first_result)); EXPECT_TRUE(first_result->HasKey("ID")); EXPECT_TRUE(first_result->HasKey("NON_UNIQUE_NAME")); } // Simulate various invalidator state changes. Those should propagate // JS events. TEST_F(SyncManagerTest, OnInvalidatorStateChangeJsEvents) { StrictMock<MockJsEventHandler> event_handler; base::DictionaryValue enabled_details; enabled_details.SetString("state", "INVALIDATIONS_ENABLED"); base::DictionaryValue credentials_rejected_details; credentials_rejected_details.SetString( "state", "INVALIDATION_CREDENTIALS_REJECTED"); base::DictionaryValue transient_error_details; transient_error_details.SetString("state", "TRANSIENT_INVALIDATION_ERROR"); base::DictionaryValue auth_error_details; auth_error_details.SetString("status", "CONNECTION_AUTH_ERROR"); EXPECT_CALL(manager_observer_, OnConnectionStatusChange(CONNECTION_AUTH_ERROR)); EXPECT_CALL( event_handler, HandleJsEvent("onConnectionStatusChange", HasDetailsAsDictionary(auth_error_details))); EXPECT_CALL(event_handler, HandleJsEvent("onNotificationStateChange", HasDetailsAsDictionary(enabled_details))); EXPECT_CALL( event_handler, HandleJsEvent("onNotificationStateChange", HasDetailsAsDictionary(credentials_rejected_details))) .Times(2); EXPECT_CALL(event_handler, HandleJsEvent("onNotificationStateChange", HasDetailsAsDictionary(transient_error_details))); // Test needs to simulate INVALIDATION_CREDENTIALS_REJECTED with event handler // attached because this is the only time when CONNECTION_AUTH_ERROR // notification will be generated, therefore the only chance to verify that // "onConnectionStatusChange" event is delivered SetJsEventHandler(event_handler.AsWeakHandle()); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SetJsEventHandler(WeakHandle<JsEventHandler>()); SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR); SetJsEventHandler(event_handler.AsWeakHandle()); SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR); SetJsEventHandler(WeakHandle<JsEventHandler>()); SimulateInvalidatorStateChangeForTest(INVALIDATIONS_ENABLED); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); SimulateInvalidatorStateChangeForTest(TRANSIENT_INVALIDATION_ERROR); // Should trigger the replies. PumpLoop(); } // Simulate the invalidator's credentials being rejected. That should // also clear the sync token. TEST_F(SyncManagerTest, OnInvalidatorStateChangeCredentialsRejected) { EXPECT_CALL(manager_observer_, OnConnectionStatusChange(CONNECTION_AUTH_ERROR)); EXPECT_FALSE(sync_manager_.GetHasInvalidAuthTokenForTest()); SimulateInvalidatorStateChangeForTest(INVALIDATION_CREDENTIALS_REJECTED); EXPECT_TRUE(sync_manager_.GetHasInvalidAuthTokenForTest()); // Should trigger the replies. PumpLoop(); } TEST_F(SyncManagerTest, OnIncomingNotification) { StrictMock<MockJsEventHandler> event_handler; const ModelTypeSet empty_model_types; const ModelTypeSet model_types( BOOKMARKS, THEMES); // Build expected_args to have a single argument with the string // equivalents of model_types. base::DictionaryValue expected_details; { base::ListValue* model_type_list = new base::ListValue(); expected_details.SetString("source", "REMOTE_INVALIDATION"); expected_details.Set("changedTypes", model_type_list); for (ModelTypeSet::Iterator it = model_types.First(); it.Good(); it.Inc()) { model_type_list->Append( new base::StringValue(ModelTypeToString(it.Get()))); } } EXPECT_CALL(event_handler, HandleJsEvent("onIncomingNotification", HasDetailsAsDictionary(expected_details))); TriggerOnIncomingNotificationForTest(empty_model_types); TriggerOnIncomingNotificationForTest(model_types); SetJsEventHandler(event_handler.AsWeakHandle()); TriggerOnIncomingNotificationForTest(model_types); SetJsEventHandler(WeakHandle<JsEventHandler>()); TriggerOnIncomingNotificationForTest(empty_model_types); TriggerOnIncomingNotificationForTest(model_types); // Should trigger the replies. PumpLoop(); } TEST_F(SyncManagerTest, RefreshEncryptionReady) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); const ModelTypeSet encrypted_types = GetEncryptedTypes(); EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(GetIdForDataType(NIGORI))); sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics(); EXPECT_TRUE(nigori.has_encryption_keybag()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag())); } } // Attempt to refresh encryption when nigori not downloaded. TEST_F(SyncManagerTest, RefreshEncryptionNotReady) { // Don't set up encryption (no nigori node created). // Should fail. Triggers an OnPassphraseRequired because the cryptographer // is not ready. EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)).Times(1); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); const ModelTypeSet encrypted_types = GetEncryptedTypes(); EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded. EXPECT_FALSE(EncryptEverythingEnabledForTest()); } // Attempt to refresh encryption when nigori is empty. TEST_F(SyncManagerTest, RefreshEncryptionEmptyNigori) { EXPECT_TRUE(SetUpEncryption(DONT_WRITE_NIGORI, DEFAULT_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(1); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); // Should write to nigori. sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); const ModelTypeSet encrypted_types = GetEncryptedTypes(); EXPECT_TRUE(encrypted_types.Has(PASSWORDS)); // Hardcoded. EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(GetIdForDataType(NIGORI))); sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics(); EXPECT_TRUE(nigori.has_encryption_keybag()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag())); } } TEST_F(SyncManagerTest, EncryptDataTypesWithNoData) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); EXPECT_TRUE(EncryptEverythingEnabledForTest()); } TEST_F(SyncManagerTest, EncryptDataTypesWithData) { size_t batch_size = 5; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); // Create some unencrypted unsynced data. int64 folder = MakeFolderWithParent(sync_manager_.GetUserShare(), BOOKMARKS, GetIdForDataType(BOOKMARKS), NULL); // First batch_size nodes are children of folder. size_t i; for (i = 0; i < batch_size; ++i) { MakeBookmarkWithParent(sync_manager_.GetUserShare(), folder, NULL); } // Next batch_size nodes are a different type and on their own. for (; i < 2*batch_size; ++i) { MakeNode(sync_manager_.GetUserShare(), SESSIONS, base::StringPrintf("%" PRIuS "", i)); } // Last batch_size nodes are a third type that will not need encryption. for (; i < 3*batch_size; ++i) { MakeNode(sync_manager_.GetUserShare(), THEMES, base::StringPrintf("%" PRIuS "", i)); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( SyncEncryptionHandler::SensitiveTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, false /* not encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), SESSIONS, false /* not encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), THEMES, false /* not encrypted */)); } EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); EXPECT_TRUE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( EncryptableUserTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), SESSIONS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), THEMES, true /* is encrypted */)); } // Trigger's a ReEncryptEverything with new passphrase. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_TRUE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( EncryptableUserTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), SESSIONS, true /* is encrypted */)); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), THEMES, true /* is encrypted */)); } // Calling EncryptDataTypes with an empty encrypted types should not trigger // a reencryption and should just notify immediately. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)).Times(0); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()).Times(0); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()).Times(0); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); } // Test that when there are no pending keys and the cryptographer is not // initialized, we add a key based on the current GAIA password. // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, SetInitialGaiaPass) { EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED)); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori = node.GetNigoriSpecifics(); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecrypt(nigori.encryption_keybag())); } } // Test that when there are no pending keys and we have on the old GAIA // password, we update and re-encrypt everything with the new GAIA password. // (case 1 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, UpdateGaiaPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer verifier(&encryptor_); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); verifier.Bootstrap(bootstrap_token); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify the default key has changed. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_FALSE(verifier.CanDecrypt(encrypted)); } } // Sets a new explicit passphrase. This should update the bootstrap token // and re-encrypt everything. // (case 2 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, SetPassphraseWithPassword) { Cryptographer verifier(&encryptor_); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); // Store the default (soon to be old) key. Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); verifier.Bootstrap(bootstrap_token); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode password_node(&trans); WriteNode::InitUniqueByCreationResult result = password_node.InitUniqueByCreation(PASSWORDS, root_node, "foo"); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); password_node.SetPasswordSpecifics(data); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify the default key has changed. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_FALSE(verifier.CanDecrypt(encrypted)); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_OK, password_node.InitByClientTagLookup(PASSWORDS, "foo")); const sync_pb::PasswordSpecificsData& data = password_node.GetPasswordSpecifics(); EXPECT_EQ("secret", data.password_value()); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with a new (unprovided) GAIA password, then supply the // password. // (case 7 in SyncManager::SyncInternal::SetDecryptionPassphrase) TEST_F(SyncManagerTest, SupplyPendingGAIAPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); other_cryptographer.Bootstrap(bootstrap_token); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "passphrase2"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); cryptographer->SetPendingKeys(nigori.encryption_keybag()); EXPECT_TRUE(cryptographer->has_pending_keys()); node.SetNigoriSpecifics(nigori); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("passphrase2"); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify we're encrypting with the new key. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted)); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with an old (unprovided) GAIA password. Attempt to supply // the current GAIA password and verify the bootstrap token is updated. Then // supply the old GAIA password, and verify we re-encrypt all data with the // new GAIA password. // (cases 4 and 5 in SyncManager::SyncInternal::SetEncryptionPassphrase) TEST_F(SyncManagerTest, SupplyPendingOldGAIAPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); other_cryptographer.Bootstrap(bootstrap_token); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "old_gaia"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); node.SetNigoriSpecifics(nigori); cryptographer->SetPendingKeys(nigori.encryption_keybag()); // other_cryptographer now contains all encryption keys, and is encrypting // with the newest gaia. KeyParams new_params = {"localhost", "dummy", "new_gaia"}; other_cryptographer.AddKey(new_params); } // The bootstrap token should have been updated. Save it to ensure it's based // on the new GAIA password. std::string bootstrap_token; EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)) .WillOnce(SaveArg<0>(&bootstrap_token)); EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_,_)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_gaia", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); testing::Mock::VerifyAndClearExpectations(&encryption_observer_); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_initialized()); EXPECT_FALSE(cryptographer->is_ready()); // Verify we're encrypting with the new key, even though we have pending // keys. sync_pb::EncryptedData encrypted; other_cryptographer.GetKeys(&encrypted); EXPECT_TRUE(cryptographer->CanDecrypt(encrypted)); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "old_gaia", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify we're encrypting with the new key. sync_pb::EncryptedData encrypted; other_cryptographer.GetKeys(&encrypted); EXPECT_TRUE(cryptographer->CanDecrypt(encrypted)); // Verify the saved bootstrap token is based on the new gaia password. Cryptographer temp_cryptographer(&encryptor_); temp_cryptographer.Bootstrap(bootstrap_token); EXPECT_TRUE(temp_cryptographer.CanDecrypt(encrypted)); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with an explicit (unprovided) passphrase, then supply the // passphrase. // (case 9 in SyncManager::SyncInternal::SetDecryptionPassphrase) TEST_F(SyncManagerTest, SupplyPendingExplicitPass) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); std::string bootstrap_token; cryptographer->GetBootstrapToken(&bootstrap_token); other_cryptographer.Bootstrap(bootstrap_token); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "explicit"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); cryptographer->SetPendingKeys(nigori.encryption_keybag()); EXPECT_TRUE(cryptographer->has_pending_keys()); nigori.set_keybag_is_frozen(true); node.SetNigoriSpecifics(nigori); } EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); EXPECT_CALL(encryption_observer_, OnPassphraseRequired(_, _)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetDecryptionPassphrase("explicit"); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); // Verify we're encrypting with the new key. sync_pb::EncryptedData encrypted; cryptographer->GetKeys(&encrypted); EXPECT_TRUE(other_cryptographer.CanDecrypt(encrypted)); } } // Manually set the pending keys in the cryptographer/nigori to reflect the data // being encrypted with a new (unprovided) GAIA password, then supply the // password as a user-provided password. // This is the android case 7/8. TEST_F(SyncManagerTest, SupplyPendingGAIAPassUserProvided) { EXPECT_FALSE(SetUpEncryption(DONT_WRITE_NIGORI, UNINITIALIZED)); Cryptographer other_cryptographer(&encryptor_); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); // Now update the nigori to reflect the new keys, and update the // cryptographer to have pending keys. KeyParams params = {"localhost", "dummy", "passphrase"}; other_cryptographer.AddKey(params); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByTagLookup(kNigoriTag)); sync_pb::NigoriSpecifics nigori; other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); node.SetNigoriSpecifics(nigori); cryptographer->SetPendingKeys(nigori.encryption_keybag()); EXPECT_FALSE(cryptographer->is_ready()); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "passphrase", false); EXPECT_EQ(IMPLICIT_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); } } TEST_F(SyncManagerTest, SetPassphraseWithEmptyPasswordNode) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); int64 node_id = 0; std::string tag = "foo"; { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode root_node(&trans); root_node.InitByRootLookup(); WriteNode password_node(&trans); WriteNode::InitUniqueByCreationResult result = password_node.InitUniqueByCreation(PASSWORDS, root_node, tag); EXPECT_EQ(WriteNode::INIT_SUCCESS, result); node_id = password_node.GetId(); } EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_FALSE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY, password_node.InitByClientTagLookup(PASSWORDS, tag)); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode password_node(&trans); EXPECT_EQ(BaseNode::INIT_FAILED_DECRYPT_IF_NECESSARY, password_node.InitByIdLookup(node_id)); } } TEST_F(SyncManagerTest, NudgeDelayTest) { EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(BOOKMARKS), base::TimeDelta::FromMilliseconds( SyncManagerImpl::GetDefaultNudgeDelay())); EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(AUTOFILL), base::TimeDelta::FromSeconds( kDefaultShortPollIntervalSeconds)); EXPECT_EQ(sync_manager_.GetNudgeDelayTimeDelta(PREFERENCES), base::TimeDelta::FromMilliseconds( SyncManagerImpl::GetPreferencesNudgeDelay())); } // Friended by WriteNode, so can't be in an anonymouse namespace. TEST_F(SyncManagerTest, EncryptBookmarksWithLegacyData) { EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); std::string title; SyncAPINameToServerName("Google", &title); std::string url = "http://www.google.com"; std::string raw_title2 = ".."; // An invalid cosmo title. std::string title2; SyncAPINameToServerName(raw_title2, &title2); std::string url2 = "http://www.bla.com"; // Create a bookmark using the legacy format. int64 node_id1 = MakeNode(sync_manager_.GetUserShare(), BOOKMARKS, "testtag"); int64 node_id2 = MakeNode(sync_manager_.GetUserShare(), BOOKMARKS, "testtag2"); { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1)); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url(url); node.SetEntitySpecifics(entity_specifics); // Set the old style title. syncable::MutableEntry* node_entry = node.entry_; node_entry->Put(syncable::NON_UNIQUE_NAME, title); WriteNode node2(&trans); EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2)); sync_pb::EntitySpecifics entity_specifics2; entity_specifics2.mutable_bookmark()->set_url(url2); node2.SetEntitySpecifics(entity_specifics2); // Set the old style title. syncable::MutableEntry* node_entry2 = node2.entry_; node_entry2->Put(syncable::NON_UNIQUE_NAME, title2); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1)); EXPECT_EQ(BOOKMARKS, node.GetModelType()); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(title, node.GetBookmarkSpecifics().title()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); ReadNode node2(&trans); EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2)); EXPECT_EQ(BOOKMARKS, node2.GetModelType()); // We should de-canonicalize the title in GetTitle(), but the title in the // specifics should be stored in the server legal form. EXPECT_EQ(raw_title2, node2.GetTitle()); EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title()); EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url()); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, false /* not encrypted */)); } EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); sync_manager_.GetEncryptionHandler()->EnableEncryptEverything(); EXPECT_TRUE(EncryptEverythingEnabledForTest()); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); EXPECT_TRUE(GetEncryptedTypesWithTrans(&trans).Equals( EncryptableUserTypes())); EXPECT_TRUE(syncable::VerifyDataTypeEncryptionForTest( trans.GetWrappedTrans(), BOOKMARKS, true /* is encrypted */)); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(node_id1)); EXPECT_EQ(BOOKMARKS, node.GetModelType()); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(title, node.GetBookmarkSpecifics().title()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); ReadNode node2(&trans); EXPECT_EQ(BaseNode::INIT_OK, node2.InitByIdLookup(node_id2)); EXPECT_EQ(BOOKMARKS, node2.GetModelType()); // We should de-canonicalize the title in GetTitle(), but the title in the // specifics should be stored in the server legal form. EXPECT_EQ(raw_title2, node2.GetTitle()); EXPECT_EQ(title2, node2.GetBookmarkSpecifics().title()); EXPECT_EQ(url2, node2.GetBookmarkSpecifics().url()); } } // Create a bookmark and set the title/url, then verify the data was properly // set. This replicates the unique way bookmarks have of creating sync nodes. // See BookmarkChangeProcessor::PlaceSyncNode(..). TEST_F(SyncManagerTest, CreateLocalBookmark) { std::string title = "title"; std::string url = "url"; { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode bookmark_root(&trans); ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitByTagLookup(ModelTypeToRootTag(BOOKMARKS))); WriteNode node(&trans); ASSERT_TRUE(node.InitBookmarkByCreation(bookmark_root, NULL)); node.SetIsFolder(false); node.SetTitle(UTF8ToWide(title)); sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics()); bookmark_specifics.set_url(url); node.SetBookmarkSpecifics(bookmark_specifics); } { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode bookmark_root(&trans); ASSERT_EQ(BaseNode::INIT_OK, bookmark_root.InitByTagLookup(ModelTypeToRootTag(BOOKMARKS))); int64 child_id = bookmark_root.GetFirstChildId(); ReadNode node(&trans); ASSERT_EQ(BaseNode::INIT_OK, node.InitByIdLookup(child_id)); EXPECT_FALSE(node.GetIsFolder()); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); } } // Verifies WriteNode::UpdateEntryWithEncryption does not make unnecessary // changes. TEST_F(SyncManagerTest, UpdateEntryWithEncryption) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same data. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetEntitySpecifics(entity_specifics); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Encrypt the datatatype, should set is_unsynced. EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Set a new passphrase. Should set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->is_ready()); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Force a re-encrypt everything. Should not set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same data. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetEntitySpecifics(entity_specifics); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_FALSE(node_entry->Get(IS_UNSYNCED)); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to different data. Should set is_unsynced. { entity_specifics.mutable_bookmark()->set_url("url2"); entity_specifics.mutable_bookmark()->set_title("title2"); WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetEntitySpecifics(entity_specifics); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_TRUE(node_entry->Get(IS_UNSYNCED)); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); Cryptographer* cryptographer = trans.GetCryptographer(); EXPECT_TRUE(cryptographer->CanDecryptUsingDefaultKey( specifics.encrypted())); } } // Passwords have their own handling for encryption. Verify it does not result // in unnecessary writes via SetEntitySpecifics. TEST_F(SyncManagerTest, UpdatePasswordSetEntitySpecificsNoChange) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()-> mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Manually change to the same data via SetEntitySpecifics. Should not set // is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PASSWORDS, client_tag)); node.SetEntitySpecifics(entity_specifics); } EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); } // Passwords have their own handling for encryption. Verify it does not result // in unnecessary writes via SetPasswordSpecifics. TEST_F(SyncManagerTest, UpdatePasswordSetPasswordSpecifics) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()-> mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Manually change to the same data via SetPasswordSpecifics. Should not set // is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PASSWORDS, client_tag)); node.SetPasswordSpecifics(node.GetPasswordSpecifics()); } EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Manually change to different data. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PASSWORDS, client_tag)); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret2"); cryptographer->Encrypt( data, entity_specifics.mutable_password()->mutable_encrypted()); node.SetPasswordSpecifics(data); const syncable::Entry* node_entry = node.GetEntry(); EXPECT_TRUE(node_entry->Get(IS_UNSYNCED)); } } // Passwords have their own handling for encryption. Verify setting a new // passphrase updates the data. TEST_F(SyncManagerTest, UpdatePasswordNewPassphrase) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()->mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Set a new passphrase. Should set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); EXPECT_CALL(encryption_observer_, OnPassphraseAccepted()); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnPassphraseTypeChanged(CUSTOM_PASSPHRASE, _)); sync_manager_.GetEncryptionHandler()->SetEncryptionPassphrase( "new_passphrase", true); EXPECT_EQ(CUSTOM_PASSPHRASE, sync_manager_.GetEncryptionHandler()->GetPassphraseType()); EXPECT_TRUE(ResetUnsyncedEntry(PASSWORDS, client_tag)); } // Passwords have their own handling for encryption. Verify it does not result // in unnecessary writes via ReencryptEverything. TEST_F(SyncManagerTest, UpdatePasswordReencryptEverything) { std::string client_tag = "title"; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); sync_pb::EntitySpecifics entity_specifics; { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* cryptographer = trans.GetCryptographer(); sync_pb::PasswordSpecificsData data; data.set_password_value("secret"); cryptographer->Encrypt( data, entity_specifics.mutable_password()->mutable_encrypted()); } MakeServerNode(sync_manager_.GetUserShare(), PASSWORDS, client_tag, syncable::GenerateSyncableHash(PASSWORDS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); // Force a re-encrypt everything. Should not set is_unsynced. testing::Mock::VerifyAndClearExpectations(&encryption_observer_); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, false)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); EXPECT_FALSE(ResetUnsyncedEntry(PASSWORDS, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for bookmarks // when we write the same data, but does set it when we write new data. TEST_F(SyncManagerTest, SetBookmarkTitle) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same title. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to new title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide("title2")); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted // bookmarks when we write the same data, but does set it when we write new // data. TEST_F(SyncManagerTest, SetBookmarkTitleWithEncryption) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Encrypt the datatatype, should set is_unsynced. EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to the same title. Should not set is_unsynced. // NON_UNIQUE_NAME should be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); } EXPECT_FALSE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); // Manually change to new title. Should set is_unsynced. NON_UNIQUE_NAME // should still be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); node.SetTitle(UTF8ToWide("title2")); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); } EXPECT_TRUE(ResetUnsyncedEntry(BOOKMARKS, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for non-bookmarks // when we write the same data, but does set it when we write new data. TEST_F(SyncManagerTest, SetNonBookmarkTitle) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_preference()->set_name("name"); entity_specifics.mutable_preference()->set_value("value"); MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, client_tag, syncable::GenerateSyncableHash(PREFERENCES, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to the same title. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); } EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to new title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide("title2")); } EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag)); } // Verify SetTitle(..) doesn't unnecessarily set IS_UNSYNCED for encrypted // non-bookmarks when we write the same data or when we write new data // data (should remained kEncryptedString). TEST_F(SyncManagerTest, SetNonBookmarkTitleWithEncryption) { std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_preference()->set_name("name"); entity_specifics.mutable_preference()->set_value("value"); MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, client_tag, syncable::GenerateSyncableHash(PREFERENCES, client_tag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Encrypt the datatatype, should set is_unsynced. EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged( HasModelTypes(EncryptableUserTypes()), true)); EXPECT_CALL(encryption_observer_, OnEncryptionComplete()); EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, FULL_ENCRYPTION)); EXPECT_CALL(encryption_observer_, OnCryptographerStateChanged(_)); EXPECT_CALL(encryption_observer_, OnEncryptedTypesChanged(_, true)); sync_manager_.GetEncryptionHandler()->Init(); PumpLoop(); EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to the same title. Should not set is_unsynced. // NON_UNIQUE_NAME should be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide(client_tag)); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); } EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, client_tag)); // Manually change to new title. Should not set is_unsynced because the // NON_UNIQUE_NAME should still be kEncryptedString. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, client_tag)); node.SetTitle(UTF8ToWide("title2")); const syncable::Entry* node_entry = node.GetEntry(); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); EXPECT_FALSE(node_entry->Get(IS_UNSYNCED)); } } // Ensure that titles are truncated to 255 bytes, and attempting to reset // them to their longer version does not set IS_UNSYNCED. TEST_F(SyncManagerTest, SetLongTitle) { const int kNumChars = 512; const std::string kClientTag = "tag"; std::string title(kNumChars, '0'); sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_preference()->set_name("name"); entity_specifics.mutable_preference()->set_value("value"); MakeServerNode(sync_manager_.GetUserShare(), PREFERENCES, "short_title", syncable::GenerateSyncableHash(PREFERENCES, kClientTag), entity_specifics); // New node shouldn't start off unsynced. EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); // Manually change to the long title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, kClientTag)); node.SetTitle(UTF8ToWide(title)); EXPECT_EQ(node.GetTitle(), title.substr(0, 255)); } EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); // Manually change to the same title. Should not set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, kClientTag)); node.SetTitle(UTF8ToWide(title)); EXPECT_EQ(node.GetTitle(), title.substr(0, 255)); } EXPECT_FALSE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); // Manually change to new title. Should set is_unsynced. { WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(PREFERENCES, kClientTag)); node.SetTitle(UTF8ToWide("title2")); } EXPECT_TRUE(ResetUnsyncedEntry(PREFERENCES, kClientTag)); } // Create an encrypted entry when the cryptographer doesn't think the type is // marked for encryption. Ensure reads/writes don't break and don't unencrypt // the data. TEST_F(SyncManagerTest, SetPreviouslyEncryptedSpecifics) { std::string client_tag = "tag"; std::string url = "url"; std::string url2 = "new_url"; std::string title = "title"; sync_pb::EntitySpecifics entity_specifics; EXPECT_TRUE(SetUpEncryption(WRITE_TO_NIGORI, DEFAULT_ENCRYPTION)); { ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); Cryptographer* crypto = trans.GetCryptographer(); sync_pb::EntitySpecifics bm_specifics; bm_specifics.mutable_bookmark()->set_title("title"); bm_specifics.mutable_bookmark()->set_url("url"); sync_pb::EncryptedData encrypted; crypto->Encrypt(bm_specifics, &encrypted); entity_specifics.mutable_encrypted()->CopyFrom(encrypted); AddDefaultFieldValue(BOOKMARKS, &entity_specifics); } MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); { // Verify the data. ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(url, node.GetBookmarkSpecifics().url()); } { // Overwrite the url (which overwrites the specifics). WriteTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); WriteNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); sync_pb::BookmarkSpecifics bookmark_specifics(node.GetBookmarkSpecifics()); bookmark_specifics.set_url(url2); node.SetBookmarkSpecifics(bookmark_specifics); } { // Verify it's still encrypted and it has the most recent url. ReadTransaction trans(FROM_HERE, sync_manager_.GetUserShare()); ReadNode node(&trans); EXPECT_EQ(BaseNode::INIT_OK, node.InitByClientTagLookup(BOOKMARKS, client_tag)); EXPECT_EQ(title, node.GetTitle()); EXPECT_EQ(url2, node.GetBookmarkSpecifics().url()); const syncable::Entry* node_entry = node.GetEntry(); EXPECT_EQ(kEncryptedString, node_entry->Get(NON_UNIQUE_NAME)); const sync_pb::EntitySpecifics& specifics = node_entry->Get(SPECIFICS); EXPECT_TRUE(specifics.has_encrypted()); } } // Verify transaction version of a model type is incremented when node of // that type is updated. TEST_F(SyncManagerTest, IncrementTransactionVersion) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); { ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare()); for (ModelSafeRoutingInfo::iterator i = routing_info.begin(); i != routing_info.end(); ++i) { // Transaction version is incremented when SyncManagerTest::SetUp() // creates a node of each type. EXPECT_EQ(1, sync_manager_.GetUserShare()->directory-> GetTransactionVersion(i->first)); } } // Create bookmark node to increment transaction version of bookmark model. std::string client_tag = "title"; sync_pb::EntitySpecifics entity_specifics; entity_specifics.mutable_bookmark()->set_url("url"); entity_specifics.mutable_bookmark()->set_title("title"); MakeServerNode(sync_manager_.GetUserShare(), BOOKMARKS, client_tag, syncable::GenerateSyncableHash(BOOKMARKS, client_tag), entity_specifics); { ReadTransaction read_trans(FROM_HERE, sync_manager_.GetUserShare()); for (ModelSafeRoutingInfo::iterator i = routing_info.begin(); i != routing_info.end(); ++i) { EXPECT_EQ(i->first == BOOKMARKS ? 2 : 1, sync_manager_.GetUserShare()->directory-> GetTransactionVersion(i->first)); } } } class MockSyncScheduler : public FakeSyncScheduler { public: MockSyncScheduler() : FakeSyncScheduler() {} virtual ~MockSyncScheduler() {} MOCK_METHOD1(Start, void(SyncScheduler::Mode)); MOCK_METHOD1(ScheduleConfiguration, bool(const ConfigurationParams&)); }; class ComponentsFactory : public TestInternalComponentsFactory { public: ComponentsFactory(const Switches& switches, SyncScheduler* scheduler_to_use, sessions::SyncSessionContext** session_context) : TestInternalComponentsFactory(switches, syncer::STORAGE_IN_MEMORY), scheduler_to_use_(scheduler_to_use), session_context_(session_context) {} virtual ~ComponentsFactory() {} virtual scoped_ptr<SyncScheduler> BuildScheduler( const std::string& name, sessions::SyncSessionContext* context) OVERRIDE { *session_context_ = context; return scheduler_to_use_.Pass(); } private: scoped_ptr<SyncScheduler> scheduler_to_use_; sessions::SyncSessionContext** session_context_; }; class SyncManagerTestWithMockScheduler : public SyncManagerTest { public: SyncManagerTestWithMockScheduler() : scheduler_(NULL) {} virtual InternalComponentsFactory* GetFactory() OVERRIDE { scheduler_ = new MockSyncScheduler(); return new ComponentsFactory(GetSwitches(), scheduler_, &session_context_); } MockSyncScheduler* scheduler() { return scheduler_; } sessions::SyncSessionContext* session_context() { return session_context_; } private: MockSyncScheduler* scheduler_; sessions::SyncSessionContext* session_context_; }; // Test that the configuration params are properly created and sent to // ScheduleConfigure. No callback should be invoked. Any disabled datatypes // should be purged. TEST_F(SyncManagerTestWithMockScheduler, BasicConfiguration) { ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION; ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES); ModelSafeRoutingInfo new_routing_info; GetModelSafeRoutingInfo(&new_routing_info); ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info); ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types); ConfigurationParams params; EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE)); EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)). WillOnce(DoAll(SaveArg<0>(&params), Return(true))); // Set data for all types. ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { SetProgressMarkerForType(iter.Get(), true); } CallbackCounter ready_task_counter, retry_task_counter; sync_manager_.ConfigureSyncer( reason, types_to_download, ModelTypeSet(), ModelTypeSet(), ModelTypeSet(), new_routing_info, base::Bind(&CallbackCounter::Callback, base::Unretained(&ready_task_counter)), base::Bind(&CallbackCounter::Callback, base::Unretained(&retry_task_counter))); EXPECT_EQ(0, ready_task_counter.times_called()); EXPECT_EQ(0, retry_task_counter.times_called()); EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source); EXPECT_TRUE(types_to_download.Equals(params.types_to_download)); EXPECT_EQ(new_routing_info, params.routing_info); // Verify all the disabled types were purged. EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().Equals( enabled_types)); EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken( ModelTypeSet::All()).Equals(disabled_types)); } // Test that on a reconfiguration (configuration where the session context // already has routing info), only those recently disabled types are purged. TEST_F(SyncManagerTestWithMockScheduler, ReConfiguration) { ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION; ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES); ModelTypeSet disabled_types = ModelTypeSet(THEMES, SESSIONS); ModelSafeRoutingInfo old_routing_info; ModelSafeRoutingInfo new_routing_info; GetModelSafeRoutingInfo(&old_routing_info); new_routing_info = old_routing_info; new_routing_info.erase(THEMES); new_routing_info.erase(SESSIONS); ModelTypeSet enabled_types = GetRoutingInfoTypes(new_routing_info); ConfigurationParams params; EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE)); EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)). WillOnce(DoAll(SaveArg<0>(&params), Return(true))); // Set data for all types except those recently disabled (so we can verify // only those recently disabled are purged) . ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { if (!disabled_types.Has(iter.Get())) { SetProgressMarkerForType(iter.Get(), true); } else { SetProgressMarkerForType(iter.Get(), false); } } // Set the context to have the old routing info. session_context()->set_routing_info(old_routing_info); CallbackCounter ready_task_counter, retry_task_counter; sync_manager_.ConfigureSyncer( reason, types_to_download, ModelTypeSet(), ModelTypeSet(), ModelTypeSet(), new_routing_info, base::Bind(&CallbackCounter::Callback, base::Unretained(&ready_task_counter)), base::Bind(&CallbackCounter::Callback, base::Unretained(&retry_task_counter))); EXPECT_EQ(0, ready_task_counter.times_called()); EXPECT_EQ(0, retry_task_counter.times_called()); EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source); EXPECT_TRUE(types_to_download.Equals(params.types_to_download)); EXPECT_EQ(new_routing_info, params.routing_info); // Verify only the recently disabled types were purged. EXPECT_TRUE(sync_manager_.GetTypesWithEmptyProgressMarkerToken( ProtocolTypes()).Equals(disabled_types)); } // Test that the retry callback is invoked on configuration failure. TEST_F(SyncManagerTestWithMockScheduler, ConfigurationRetry) { ConfigureReason reason = CONFIGURE_REASON_RECONFIGURATION; ModelTypeSet types_to_download(BOOKMARKS, PREFERENCES); ModelSafeRoutingInfo new_routing_info; GetModelSafeRoutingInfo(&new_routing_info); ConfigurationParams params; EXPECT_CALL(*scheduler(), Start(SyncScheduler::CONFIGURATION_MODE)); EXPECT_CALL(*scheduler(), ScheduleConfiguration(_)). WillOnce(DoAll(SaveArg<0>(&params), Return(false))); CallbackCounter ready_task_counter, retry_task_counter; sync_manager_.ConfigureSyncer( reason, types_to_download, ModelTypeSet(), ModelTypeSet(), ModelTypeSet(), new_routing_info, base::Bind(&CallbackCounter::Callback, base::Unretained(&ready_task_counter)), base::Bind(&CallbackCounter::Callback, base::Unretained(&retry_task_counter))); EXPECT_EQ(0, ready_task_counter.times_called()); EXPECT_EQ(1, retry_task_counter.times_called()); EXPECT_EQ(sync_pb::GetUpdatesCallerInfo::RECONFIGURATION, params.source); EXPECT_TRUE(types_to_download.Equals(params.types_to_download)); EXPECT_EQ(new_routing_info, params.routing_info); } // Test that PurgePartiallySyncedTypes purges only those types that have not // fully completed their initial download and apply. TEST_F(SyncManagerTest, PurgePartiallySyncedTypes) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info); UserShare* share = sync_manager_.GetUserShare(); // The test harness automatically initializes all types in the routing info. // Check that autofill is not among them. ASSERT_FALSE(enabled_types.Has(AUTOFILL)); // Further ensure that the test harness did not create its root node. { syncable::ReadTransaction trans(FROM_HERE, share->directory.get()); syncable::Entry autofill_root_node(&trans, syncable::GET_BY_SERVER_TAG, ModelTypeToRootTag(AUTOFILL)); ASSERT_FALSE(autofill_root_node.good()); } // One more redundant check. ASSERT_FALSE(sync_manager_.InitialSyncEndedTypes().Has(AUTOFILL)); // Give autofill a progress marker. sync_pb::DataTypeProgressMarker autofill_marker; autofill_marker.set_data_type_id( GetSpecificsFieldNumberFromModelType(AUTOFILL)); autofill_marker.set_token("token"); share->directory->SetDownloadProgress(AUTOFILL, autofill_marker); // Also add a pending autofill root node update from the server. TestEntryFactory factory_(share->directory.get()); int autofill_meta = factory_.CreateUnappliedRootNode(AUTOFILL); // Preferences is an enabled type. Check that the harness initialized it. ASSERT_TRUE(enabled_types.Has(PREFERENCES)); ASSERT_TRUE(sync_manager_.InitialSyncEndedTypes().Has(PREFERENCES)); // Give preferencse a progress marker. sync_pb::DataTypeProgressMarker prefs_marker; prefs_marker.set_data_type_id( GetSpecificsFieldNumberFromModelType(PREFERENCES)); prefs_marker.set_token("token"); share->directory->SetDownloadProgress(PREFERENCES, prefs_marker); // Add a fully synced preferences node under the root. std::string pref_client_tag = "prefABC"; std::string pref_hashed_tag = "hashXYZ"; sync_pb::EntitySpecifics pref_specifics; AddDefaultFieldValue(PREFERENCES, &pref_specifics); int pref_meta = MakeServerNode( share, PREFERENCES, pref_client_tag, pref_hashed_tag, pref_specifics); // And now, the purge. EXPECT_TRUE(sync_manager_.PurgePartiallySyncedTypes()); // Ensure that autofill lost its progress marker, but preferences did not. ModelTypeSet empty_tokens = sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All()); EXPECT_TRUE(empty_tokens.Has(AUTOFILL)); EXPECT_FALSE(empty_tokens.Has(PREFERENCES)); // Ensure that autofill lots its node, but preferences did not. { syncable::ReadTransaction trans(FROM_HERE, share->directory.get()); syncable::Entry autofill_node(&trans, GET_BY_HANDLE, autofill_meta); syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref_meta); EXPECT_FALSE(autofill_node.good()); EXPECT_TRUE(pref_node.good()); } } // Test CleanupDisabledTypes properly purges all disabled types as specified // by the previous and current enabled params. TEST_F(SyncManagerTest, PurgeDisabledTypes) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info); ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types); // The harness should have initialized the enabled_types for us. EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); // Set progress markers for all types. ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { SetProgressMarkerForType(iter.Get(), true); } // Verify all the enabled types remain after cleanup, and all the disabled // types were purged. sync_manager_.PurgeDisabledTypes(ModelTypeSet::All(), enabled_types, ModelTypeSet(), ModelTypeSet()); EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); EXPECT_TRUE(disabled_types.Equals( sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All()))); // Disable some more types. disabled_types.Put(BOOKMARKS); disabled_types.Put(PREFERENCES); ModelTypeSet new_enabled_types = Difference(ModelTypeSet::All(), disabled_types); // Verify only the non-disabled types remain after cleanup. sync_manager_.PurgeDisabledTypes(enabled_types, new_enabled_types, ModelTypeSet(), ModelTypeSet()); EXPECT_TRUE(new_enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); EXPECT_TRUE(disabled_types.Equals( sync_manager_.GetTypesWithEmptyProgressMarkerToken(ModelTypeSet::All()))); } // Test PurgeDisabledTypes properly unapplies types by deleting their local data // and preserving their server data and progress marker. TEST_F(SyncManagerTest, PurgeUnappliedTypes) { ModelSafeRoutingInfo routing_info; GetModelSafeRoutingInfo(&routing_info); ModelTypeSet unapplied_types = ModelTypeSet(BOOKMARKS, PREFERENCES); ModelTypeSet enabled_types = GetRoutingInfoTypes(routing_info); ModelTypeSet disabled_types = Difference(ModelTypeSet::All(), enabled_types); // The harness should have initialized the enabled_types for us. EXPECT_TRUE(enabled_types.Equals(sync_manager_.InitialSyncEndedTypes())); // Set progress markers for all types. ModelTypeSet protocol_types = ProtocolTypes(); for (ModelTypeSet::Iterator iter = protocol_types.First(); iter.Good(); iter.Inc()) { SetProgressMarkerForType(iter.Get(), true); } // Add the following kinds of items: // 1. Fully synced preference. // 2. Locally created preference, server unknown, unsynced // 3. Locally deleted preference, server known, unsynced // 4. Server deleted preference, locally known. // 5. Server created preference, locally unknown, unapplied. // 6. A fully synced bookmark (no unique_client_tag). UserShare* share = sync_manager_.GetUserShare(); sync_pb::EntitySpecifics pref_specifics; AddDefaultFieldValue(PREFERENCES, &pref_specifics); sync_pb::EntitySpecifics bm_specifics; AddDefaultFieldValue(BOOKMARKS, &bm_specifics); int pref1_meta = MakeServerNode( share, PREFERENCES, "pref1", "hash1", pref_specifics); int64 pref2_meta = MakeNode(share, PREFERENCES, "pref2"); int pref3_meta = MakeServerNode( share, PREFERENCES, "pref3", "hash3", pref_specifics); int pref4_meta = MakeServerNode( share, PREFERENCES, "pref4", "hash4", pref_specifics); int pref5_meta = MakeServerNode( share, PREFERENCES, "pref5", "hash5", pref_specifics); int bookmark_meta = MakeServerNode( share, BOOKMARKS, "bookmark", "", bm_specifics); { syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, share->directory.get()); // Pref's 1 and 2 are already set up properly. // Locally delete pref 3. syncable::MutableEntry pref3(&trans, GET_BY_HANDLE, pref3_meta); pref3.Put(IS_DEL, true); pref3.Put(IS_UNSYNCED, true); // Delete pref 4 at the server. syncable::MutableEntry pref4(&trans, GET_BY_HANDLE, pref4_meta); pref4.Put(syncable::SERVER_IS_DEL, true); pref4.Put(syncable::IS_UNAPPLIED_UPDATE, true); pref4.Put(syncable::SERVER_VERSION, 2); // Pref 5 is an new unapplied update. syncable::MutableEntry pref5(&trans, GET_BY_HANDLE, pref5_meta); pref5.Put(syncable::IS_UNAPPLIED_UPDATE, true); pref5.Put(syncable::IS_DEL, true); pref5.Put(syncable::BASE_VERSION, -1); // Bookmark is already set up properly } // Take a snapshot to clear all the dirty bits. share->directory.get()->SaveChanges(); // Now request a purge for the unapplied types. disabled_types.PutAll(unapplied_types); ModelTypeSet new_enabled_types = Difference(ModelTypeSet::All(), disabled_types); sync_manager_.PurgeDisabledTypes(enabled_types, new_enabled_types, ModelTypeSet(), unapplied_types); // Verify the unapplied types still have progress markers and initial sync // ended after cleanup. EXPECT_TRUE(sync_manager_.InitialSyncEndedTypes().HasAll(unapplied_types)); EXPECT_TRUE( sync_manager_.GetTypesWithEmptyProgressMarkerToken(unapplied_types). Empty()); // Ensure the items were unapplied as necessary. { syncable::ReadTransaction trans(FROM_HERE, share->directory.get()); syncable::Entry pref_node(&trans, GET_BY_HANDLE, pref1_meta); ASSERT_TRUE(pref_node.good()); EXPECT_TRUE(pref_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref_node.Get(IS_DEL)); EXPECT_GT(pref_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref_node.Get(syncable::BASE_VERSION), -1); // Pref 2 should just be locally deleted. syncable::Entry pref2_node(&trans, GET_BY_HANDLE, pref2_meta); ASSERT_TRUE(pref2_node.good()); EXPECT_TRUE(pref2_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref2_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref2_node.Get(syncable::IS_DEL)); EXPECT_FALSE(pref2_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref2_node.Get(IS_DEL)); EXPECT_EQ(pref2_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref2_node.Get(syncable::BASE_VERSION), -1); syncable::Entry pref3_node(&trans, GET_BY_HANDLE, pref3_meta); ASSERT_TRUE(pref3_node.good()); EXPECT_TRUE(pref3_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref3_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref3_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref3_node.Get(IS_DEL)); EXPECT_GT(pref3_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref3_node.Get(syncable::BASE_VERSION), -1); syncable::Entry pref4_node(&trans, GET_BY_HANDLE, pref4_meta); ASSERT_TRUE(pref4_node.good()); EXPECT_TRUE(pref4_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref4_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref4_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref4_node.Get(IS_DEL)); EXPECT_GT(pref4_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref4_node.Get(syncable::BASE_VERSION), -1); // Pref 5 should remain untouched. syncable::Entry pref5_node(&trans, GET_BY_HANDLE, pref5_meta); ASSERT_TRUE(pref5_node.good()); EXPECT_FALSE(pref5_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(pref5_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(pref5_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(pref5_node.Get(IS_DEL)); EXPECT_GT(pref5_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(pref5_node.Get(syncable::BASE_VERSION), -1); syncable::Entry bookmark_node(&trans, GET_BY_HANDLE, bookmark_meta); ASSERT_TRUE(bookmark_node.good()); EXPECT_TRUE(bookmark_node.GetKernelCopy().is_dirty()); EXPECT_FALSE(bookmark_node.Get(syncable::IS_UNSYNCED)); EXPECT_TRUE(bookmark_node.Get(syncable::IS_UNAPPLIED_UPDATE)); EXPECT_TRUE(bookmark_node.Get(IS_DEL)); EXPECT_GT(bookmark_node.Get(syncable::SERVER_VERSION), 0); EXPECT_EQ(bookmark_node.Get(syncable::BASE_VERSION), -1); } } // A test harness to exercise the code that processes and passes changes from // the "SYNCER"-WriteTransaction destructor, through the SyncManager, to the // ChangeProcessor. class SyncManagerChangeProcessingTest : public SyncManagerTest { public: virtual void OnChangesApplied( ModelType model_type, int64 model_version, const BaseTransaction* trans, const ImmutableChangeRecordList& changes) OVERRIDE { last_changes_ = changes; } virtual void OnChangesComplete(ModelType model_type) OVERRIDE {} const ImmutableChangeRecordList& GetRecentChangeList() { return last_changes_; } UserShare* share() { return sync_manager_.GetUserShare(); } // Set some flags so our nodes reasonably approximate the real world scenario // and can get past CheckTreeInvariants. // // It's never going to be truly accurate, since we're squashing update // receipt, processing and application into a single transaction. void SetNodeProperties(syncable::MutableEntry *entry) { entry->Put(syncable::ID, id_factory_.NewServerId()); entry->Put(syncable::BASE_VERSION, 10); entry->Put(syncable::SERVER_VERSION, 10); } // Looks for the given change in the list. Returns the index at which it was // found. Returns -1 on lookup failure. size_t FindChangeInList(int64 id, ChangeRecord::Action action) { SCOPED_TRACE(id); for (size_t i = 0; i < last_changes_.Get().size(); ++i) { if (last_changes_.Get()[i].id == id && last_changes_.Get()[i].action == action) { return i; } } ADD_FAILURE() << "Failed to find specified change"; return -1; } // Returns the current size of the change list. // // Note that spurious changes do not necessarily indicate a problem. // Assertions on change list size can help detect problems, but it may be // necessary to reduce their strictness if the implementation changes. size_t GetChangeListSize() { return last_changes_.Get().size(); } protected: ImmutableChangeRecordList last_changes_; TestIdFactory id_factory_; }; // Test creation of a folder and a bookmark. TEST_F(SyncManagerChangeProcessingTest, AddBookmarks) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 folder_id = kInvalidId; int64 child_id = kInvalidId; // Create a folder and a bookmark under it. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folder"); ASSERT_TRUE(folder.good()); SetNodeProperties(&folder); folder.Put(syncable::IS_DIR, true); folder_id = folder.Get(syncable::META_HANDLE); syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS, folder.Get(syncable::ID), "child"); ASSERT_TRUE(child.good()); SetNodeProperties(&child); child_id = child.Get(syncable::META_HANDLE); } // The closing of the above scope will delete the transaction. Its processed // changes should be waiting for us in a member of the test harness. EXPECT_EQ(2UL, GetChangeListSize()); // We don't need to check these return values here. The function will add a // non-fatal failure if these changes are not found. size_t folder_change_pos = FindChangeInList(folder_id, ChangeRecord::ACTION_ADD); size_t child_change_pos = FindChangeInList(child_id, ChangeRecord::ACTION_ADD); // Parents are delivered before children. EXPECT_LT(folder_change_pos, child_change_pos); } // Test moving a bookmark into an empty folder. TEST_F(SyncManagerChangeProcessingTest, MoveBookmarkIntoEmptyFolder) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 folder_b_id = kInvalidId; int64 child_id = kInvalidId; // Create two folders. Place a child under folder A. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderA"); ASSERT_TRUE(folder_a.good()); SetNodeProperties(&folder_a); folder_a.Put(syncable::IS_DIR, true); syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderB"); ASSERT_TRUE(folder_b.good()); SetNodeProperties(&folder_b); folder_b.Put(syncable::IS_DIR, true); folder_b_id = folder_b.Get(syncable::META_HANDLE); syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS, folder_a.Get(syncable::ID), "child"); ASSERT_TRUE(child.good()); SetNodeProperties(&child); child_id = child.Get(syncable::META_HANDLE); } // Close that transaction. The above was to setup the initial scenario. The // real test starts now. // Move the child from folder A to folder B. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry folder_b(&trans, syncable::GET_BY_HANDLE, folder_b_id); syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id); child.Put(syncable::PARENT_ID, folder_b.Get(syncable::ID)); } EXPECT_EQ(1UL, GetChangeListSize()); // Verify that this was detected as a real change. An early version of the // UniquePosition code had a bug where moves from one folder to another were // ignored unless the moved node's UniquePosition value was also changed in // some way. FindChangeInList(child_id, ChangeRecord::ACTION_UPDATE); } // Test moving a bookmark into a non-empty folder. TEST_F(SyncManagerChangeProcessingTest, MoveIntoPopulatedFolder) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 child_a_id = kInvalidId; int64 child_b_id = kInvalidId; // Create two folders. Place one child each under folder A and folder B. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderA"); ASSERT_TRUE(folder_a.good()); SetNodeProperties(&folder_a); folder_a.Put(syncable::IS_DIR, true); syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderB"); ASSERT_TRUE(folder_b.good()); SetNodeProperties(&folder_b); folder_b.Put(syncable::IS_DIR, true); syncable::MutableEntry child_a(&trans, syncable::CREATE, BOOKMARKS, folder_a.Get(syncable::ID), "childA"); ASSERT_TRUE(child_a.good()); SetNodeProperties(&child_a); child_a_id = child_a.Get(syncable::META_HANDLE); syncable::MutableEntry child_b(&trans, syncable::CREATE, BOOKMARKS, folder_b.Get(syncable::ID), "childB"); SetNodeProperties(&child_b); child_b_id = child_b.Get(syncable::META_HANDLE); } // Close that transaction. The above was to setup the initial scenario. The // real test starts now. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::MutableEntry child_a(&trans, syncable::GET_BY_HANDLE, child_a_id); syncable::MutableEntry child_b(&trans, syncable::GET_BY_HANDLE, child_b_id); // Move child A from folder A to folder B and update its position. child_a.Put(syncable::PARENT_ID, child_b.Get(syncable::PARENT_ID)); child_a.PutPredecessor(child_b.Get(syncable::ID)); } EXPECT_EQ(1UL, GetChangeListSize()); // Verify that only child a is in the change list. // (This function will add a failure if the lookup fails.) FindChangeInList(child_a_id, ChangeRecord::ACTION_UPDATE); } // Tests the ordering of deletion changes. TEST_F(SyncManagerChangeProcessingTest, DeletionsAndChanges) { int64 type_root = GetIdForDataType(BOOKMARKS); int64 folder_a_id = kInvalidId; int64 folder_b_id = kInvalidId; int64 child_id = kInvalidId; // Create two folders. Place a child under folder A. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::Entry root(&trans, syncable::GET_BY_HANDLE, type_root); ASSERT_TRUE(root.good()); syncable::MutableEntry folder_a(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderA"); ASSERT_TRUE(folder_a.good()); SetNodeProperties(&folder_a); folder_a.Put(syncable::IS_DIR, true); folder_a_id = folder_a.Get(syncable::META_HANDLE); syncable::MutableEntry folder_b(&trans, syncable::CREATE, BOOKMARKS, root.Get(syncable::ID), "folderB"); ASSERT_TRUE(folder_b.good()); SetNodeProperties(&folder_b); folder_b.Put(syncable::IS_DIR, true); folder_b_id = folder_b.Get(syncable::META_HANDLE); syncable::MutableEntry child(&trans, syncable::CREATE, BOOKMARKS, folder_a.Get(syncable::ID), "child"); ASSERT_TRUE(child.good()); SetNodeProperties(&child); child_id = child.Get(syncable::META_HANDLE); } // Close that transaction. The above was to setup the initial scenario. The // real test starts now. { syncable::WriteTransaction trans( FROM_HERE, syncable::SYNCER, share()->directory.get()); syncable::MutableEntry folder_a( &trans, syncable::GET_BY_HANDLE, folder_a_id); syncable::MutableEntry folder_b( &trans, syncable::GET_BY_HANDLE, folder_b_id); syncable::MutableEntry child(&trans, syncable::GET_BY_HANDLE, child_id); // Delete folder B and its child. child.Put(syncable::IS_DEL, true); folder_b.Put(syncable::IS_DEL, true); // Make an unrelated change to folder A. folder_a.Put(syncable::NON_UNIQUE_NAME, "NewNameA"); } EXPECT_EQ(3UL, GetChangeListSize()); size_t folder_a_pos = FindChangeInList(folder_a_id, ChangeRecord::ACTION_UPDATE); size_t folder_b_pos = FindChangeInList(folder_b_id, ChangeRecord::ACTION_DELETE); size_t child_pos = FindChangeInList(child_id, ChangeRecord::ACTION_DELETE); // Deletes should appear before updates. EXPECT_LT(child_pos, folder_a_pos); EXPECT_LT(folder_b_pos, folder_a_pos); } } // namespace
{ "content_hash": "c1554cd8ff509d8b3221f1b041f94392", "timestamp": "", "source": "github", "line_count": 3580, "max_line_length": 80, "avg_line_length": 38.94469273743017, "alnum_prop": 0.6963606891308401, "repo_name": "hujiajie/pa-chromium", "id": "7ef301466ed7613529d1f598226b23acca6881da", "size": "139422", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sync/internal_api/sync_manager_impl_unittest.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": "74909991" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "174451678" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "3787983" }, { "name": "JavaScript", "bytes": "19649328" }, { "name": "Logos", "bytes": "4517" }, { "name": "M", "bytes": "2190" }, { "name": "Matlab", "bytes": "3044" }, { "name": "Objective-C", "bytes": "7600008" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "1473407" }, { "name": "Python", "bytes": "10022969" }, { "name": "R", "bytes": "262" }, { "name": "Shell", "bytes": "1590292" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XSLT", "bytes": "13493" } ], "symlink_target": "" }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\Tareas */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="tareas-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'Tarea')->textInput(['maxlength' => true]) ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
{ "content_hash": "9ed8273eb0b102eb05b65849292260e1", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 150, "avg_line_length": 23.73913043478261, "alnum_prop": 0.5879120879120879, "repo_name": "Jaaviieer/PrograWeb", "id": "f6df36679f9f436dc29e9637b69faa94195d6d53", "size": "546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/tareas/_form.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "92425" } ], "symlink_target": "" }
import java.util.*; import java.lang.Math; public class SumPairsArray { private static int[] a = {4,7,3,1,8,2,6,12,-2}; public static void main(String[] args) { long startTime = System.currentTimeMillis(); // Core Function here returnSumPairs(a,10); double duration = System.currentTimeMillis() - startTime; System.out.print("Processing time: "); System.out.format("%.3f", duration / 1000); System.out.println(" seconds."); } public static void returnSumPairs(int[] a, int t) { HashSet<Integer> foundItems = new HashSet<Integer>(); for(int i = 0; i < a.length; i++) { int v = a[i]; if(foundItems.contains(t-v)) { foundItems.remove(t-v); System.out.println("(" + v + "," + (t-v) + ")"); } else { foundItems.add(v); } } } }
{ "content_hash": "6b9c697677f4b1d2d169453053269e0a", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 59, "avg_line_length": 23.5, "alnum_prop": 0.609511889862328, "repo_name": "tiagopnoliveira/programming", "id": "f599d444ab7d232823288dbff79348daf83889a6", "size": "799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SumPairsArray.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1121" }, { "name": "Java", "bytes": "280435" } ], "symlink_target": "" }
package com.sap.mentors.lemonaid.jobs; import java.util.ArrayList; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sap.mentors.lemonaid.client.SitRegClient; import com.sap.mentors.lemonaid.entities.Event; import com.sap.mentors.lemonaid.repository.EventRepository; @Service @Transactional @DisallowConcurrentExecution public class InsideTrackJob implements Job { private static final Logger log = LoggerFactory.getLogger(InsideTrackJob.class); @Autowired EventRepository eventRepository; @Autowired SitRegClient sitregClient; @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { log.info("Pulling inside track events - Start"); long startTime = System.currentTimeMillis(); ArrayList<Event> sitRegEvents = sitregClient.getEvents(); if (sitRegEvents != null) { for (Event sitRegEvent : sitRegEvents) { Event event = eventRepository.findOne(sitRegEvent.getId()); if (event == null) { eventRepository.save(sitRegEvent); } else { event.setEndDate(sitRegEvent.getEndDate()); event.setStartDate(sitRegEvent.getStartDate()); event.setId(sitRegEvent.getId()); event.setLocation(sitRegEvent.getLocation()); event.setName(sitRegEvent.getName()); event.setSource(sitRegEvent.getSource()); event.setSourceId(sitRegEvent.getSourceId()); event.setUrl(sitRegEvent.getUrl()); eventRepository.save(event); } } } log.info("Pulling inside track events - End. Duration: " + Long.toString(System.currentTimeMillis() - startTime) + "ms"); } }
{ "content_hash": "e4b12371e9d5e56ad934ae109931a6b5", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 124, "avg_line_length": 34.63636363636363, "alnum_prop": 0.7695538057742782, "repo_name": "sapmentors/lemonaid", "id": "15d147e7e1ceb3980ee17dc118a31e108112dc90", "size": "1905", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/main/java/com/sap/mentors/lemonaid/jobs/InsideTrackJob.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5181" }, { "name": "HTML", "bytes": "11516" }, { "name": "Java", "bytes": "300476" }, { "name": "JavaScript", "bytes": "269575" } ], "symlink_target": "" }
namespace King.MQC.Program { using King.Route; public class Startup : MqcApplication { public override void Start() { //Should these be handled seperately? GlobalConfiguration.Configure(MqcConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); base.Start(); } public override void End() { base.End(); } } }
{ "content_hash": "ea95e735b7425ac4f9286d60fe78af21", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 62, "avg_line_length": 21.142857142857142, "alnum_prop": 0.5518018018018018, "repo_name": "jefking/King.MQC", "id": "e603c4be1b23aee360125e89c3a65738de0b7c56", "size": "446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "King.MQC.Program/Startup.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "103" }, { "name": "C#", "bytes": "45064" }, { "name": "CSS", "bytes": "513" }, { "name": "JavaScript", "bytes": "20063" } ], "symlink_target": "" }
package org.terasology.rendering.nui.layouts; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.math.geom.Rect2i; import org.terasology.math.TeraMath; import org.terasology.math.geom.Vector2i; import org.terasology.rendering.nui.Canvas; import org.terasology.rendering.nui.CoreLayout; import org.terasology.rendering.nui.LayoutConfig; import org.terasology.rendering.nui.UIWidget; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A layout that places widgets in a row, with support for relative widths */ public class RowLayout extends CoreLayout<RowLayoutHint> { private static final Logger logger = LoggerFactory.getLogger(RowLayout.class); /** * A list of the widgets in this {@link RowLayout} */ private List<UIWidget> contents = Lists.newArrayList(); /** * Maps widgets to their layout hints */ private Map<UIWidget, RowLayoutHint> hints = Maps.newHashMap(); /** * The spacing between adjacent widgets, in pixels */ @LayoutConfig private int horizontalSpacing; /** * Creates an empty {@code RowLayout}. */ public RowLayout() { } /** * Creates an empty {@code RowLayout} with the given id. * * @param id The id assigned to this {@code RowLayout} */ public RowLayout(String id) { super(id); } /** * Creates a {@code RowLayout} containing the given widgets. * * @param widgets A variable number of {@link UIWidget}s to be added to this layout's widget list */ public RowLayout(UIWidget... widgets) { for (UIWidget widget : widgets) { addWidget(widget, null); } } /** * Adds the widget to this layout's widget list. * * @param widget The {@code UIWidget} to be added * @param hint An optional {@link RowLayoutHint} specifying how the widget should be drawn in this layout = * such as whether it has a relative width or whether it uses the content width */ @Override public void addWidget(UIWidget widget, RowLayoutHint hint) { contents.add(widget); if (hint != null) { hints.put(widget, hint); } } /** * Removes the widget from this layout's widget list. * * @param widget The {@code UIWidget} to be removed */ @Override public void removeWidget(UIWidget widget) { contents.remove(widget); hints.remove(widget); } /** * Removes all widgets from this layout's widget list. */ @Override public void removeAllWidgets() { contents.clear(); hints.clear(); } /** * Draws the widgets contained in this layout's widget list, * according to the widths calculated in {@link #calcWidths(Canvas)}. * This is called every frame. * * @param canvas The {@link Canvas} on which this {@code RowLayout} is drawn */ @Override public void onDraw(Canvas canvas) { TIntList widths = calcWidths(canvas); if (!contents.isEmpty()) { int xOffset = 0; for (int i = 0; i < contents.size(); ++i) { int itemWidth = widths.get(i); Rect2i region = Rect2i.createFromMinAndSize(xOffset, 0, itemWidth, canvas.size().y); canvas.drawWidget(contents.get(i), region); xOffset += itemWidth; xOffset += horizontalSpacing; } } } /** * Calculates the widths of each of the widgets in this layout's widget list. * Widths are first calculated for widgets with a relative width specified, * followed by widgets which follow their content width. * The remaining width is then split equally among the remaining widgets. * * @param canvas The {@link Canvas} on which this {@code RowLayout} is drawn * @return A list of the widths of the widgets in this layout's widget list, in pixels */ private TIntList calcWidths(Canvas canvas) { TIntList results = new TIntArrayList(contents.size()); if (contents.size() > 0) { int width = canvas.size().x - horizontalSpacing * (contents.size() - 1); int totalWidthUsed = 0; int unprocessedWidgets = 0; for (UIWidget widget : contents) { RowLayoutHint hint = hints.get(widget); if (hint != null) { if (!hint.isUseContentWidth() && hint.getRelativeWidth() != 0) { int elementWidth = TeraMath.floorToInt(hint.getRelativeWidth() * width); results.add(elementWidth); totalWidthUsed += elementWidth; } else { results.add(0); unprocessedWidgets++; } } else { results.add(0); unprocessedWidgets++; } } if (unprocessedWidgets > 0) { int remainingWidthPerElement = (width - totalWidthUsed) / unprocessedWidgets; for (int i = 0; i < results.size(); ++i) { if (results.get(i) == 0) { RowLayoutHint hint = hints.get(contents.get(i)); if (hint != null) { if (hint.isUseContentWidth()) { Vector2i contentSize = contents.get(i).getPreferredContentSize(canvas, new Vector2i(remainingWidthPerElement, canvas.size().y)); results.set(i, contentSize.x); totalWidthUsed += contentSize.x; unprocessedWidgets--; } } } } } if (unprocessedWidgets > 0) { int remainingWidthPerElement = (width - totalWidthUsed) / unprocessedWidgets; for (int i = 0; i < results.size(); ++i) { if (results.get(i) == 0) { results.set(i, remainingWidthPerElement); } } } } return results; } /** * Retrieves the preferred content size of this {@code RowLayout}. * This is the minimum size this layout will take, given no space restrictions. * * @param canvas The {@code Canvas} on which this {@code RowLayout} is drawn * @param areaHint A {@link Vector2i} representing the space available for widgets to be drawn in this layout * @return A {@link Vector2i} representing the preferred content size of this {@code RowLayout} */ @Override public Vector2i getPreferredContentSize(Canvas canvas, Vector2i areaHint) { TIntList widths = calcWidths(canvas); Vector2i result = new Vector2i(areaHint.x, 0); for (int i = 0; i < contents.size(); ++i) { Vector2i widgetSize = canvas.calculateRestrictedSize(contents.get(i), new Vector2i(TeraMath.floorToInt(widths.get(i)), areaHint.y)); result.y = Math.max(result.y, widgetSize.y); } return result; } /** * Retrieves the maximum content size of this {@code RowLayout}. * * @param canvas The {@code Canvas} on which this {@code RowLayout} is drawn * @return A {@code Vector2i} representing the maximum content size of this {@code RowLayout} */ @Override public Vector2i getMaxContentSize(Canvas canvas) { return new Vector2i(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Retrieves an {@link Iterator} containing this layout's widget list. * * @return An {@code Iterator} containing the list of {@code UIWidgets} */ @Override public Iterator<UIWidget> iterator() { return contents.iterator(); } /** * Sets the ratios of the widths of the widgets in this {@code RowLayout}. * * @param ratios The ratios of the widths, each corresponding to a separate widget, with a maximum total of 1 * @return This {@code RowLayout} */ public RowLayout setColumnRatios(float... ratios) { hints.clear(); for (int i = 0; i < ratios.length; ++i) { hints.put(contents.get(i), new RowLayoutHint(ratios[i])); } return this; } /** * Retrieves the spacing between adjacent widgets in this {@code RowLayout}. * * @return The spacing, in pixels */ public int getHorizontalSpacing() { return horizontalSpacing; } /** * Sets the spacing betweeen adjacent widgets in this {@code RowLayout}. * * @param spacing The spacing, in pixels * @return This {@code RowLayout} */ public RowLayout setHorizontalSpacing(int spacing) { this.horizontalSpacing = spacing; return this; } }
{ "content_hash": "8673ee7f40d848f4b5fe2d7f26fbccaf", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 160, "avg_line_length": 34.48679245283019, "alnum_prop": 0.5857314804683226, "repo_name": "kaen/Terasology", "id": "184db050605ca4346ca90d88fb3d7ea66e4b2e4c", "size": "9731", "binary": false, "copies": "12", "ref": "refs/heads/develop", "path": "engine/src/main/java/org/terasology/rendering/nui/layouts/RowLayout.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2294" }, { "name": "GLSL", "bytes": "111425" }, { "name": "Groovy", "bytes": "14427" }, { "name": "Java", "bytes": "7777489" }, { "name": "Shell", "bytes": "13413" } ], "symlink_target": "" }
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Heiko Strathmann, Soeren Sonnenburg */ #include <shogun/lib/common.h> #include <shogun/features/streaming/generators/MeanShiftDataGenerator.h> #include <shogun/mathematics/NormalDistribution.h> #include <shogun/mathematics/RandomNamespace.h> using namespace shogun; MeanShiftDataGenerator::MeanShiftDataGenerator() : RandomMixin<StreamingDenseFeatures<float64_t>>() { init(); } MeanShiftDataGenerator::MeanShiftDataGenerator(float64_t mean_shift, index_t dimension, index_t dimension_shift) : RandomMixin<StreamingDenseFeatures<float64_t>>() { init(); set_mean_shift_model(mean_shift, dimension, dimension_shift); } MeanShiftDataGenerator::~MeanShiftDataGenerator() { } void MeanShiftDataGenerator::set_mean_shift_model(float64_t mean_shift, index_t dimension, index_t dimension_shift) { require(dimension_shift<dimension, "{}::set_mean_shift_model({},{},{}): " "Dimension of shift is larger than number of dimensions!", mean_shift, dimension, dimension_shift); m_dimension=dimension; m_mean_shift=mean_shift; m_dimension_shift=dimension_shift; } void MeanShiftDataGenerator::init() { SG_ADD(&m_dimension, "dimension", "Dimension of data"); SG_ADD(&m_mean_shift, "mean_shift", "Mean shift in one dimension"); SG_ADD(&m_dimension_shift, "m_dimension_shift", "Dimension of mean shift"); m_dimension=0; m_mean_shift=0; m_dimension_shift=0; unset_generic(); } bool MeanShiftDataGenerator::get_next_example() { SG_TRACE("entering"); /* allocate space */ SGVector<float64_t> result=SGVector<float64_t>(m_dimension); /* fill with std normal data */ random::fill_array(result, NormalDistribution<float64_t>(), m_prng); /* mean shift in selected dimension */ result[m_dimension_shift]+=m_mean_shift; /* save example back to superclass */ MeanShiftDataGenerator::current_vector=result; SG_TRACE("leaving"); return true; } void MeanShiftDataGenerator::release_example() { SGVector<float64_t> temp=SGVector<float64_t>(); MeanShiftDataGenerator::current_vector=temp; }
{ "content_hash": "8eb8e1df23f93b4286ecda2501d963e0", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 78, "avg_line_length": 26.098765432098766, "alnum_prop": 0.7445600756859035, "repo_name": "lambday/shogun", "id": "186e016ee90b802a937a45605a6c0f2e966f1550", "size": "2114", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "src/shogun/features/streaming/generators/MeanShiftDataGenerator.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "64" }, { "name": "Batchfile", "bytes": "615" }, { "name": "C", "bytes": "12178" }, { "name": "C++", "bytes": "10261995" }, { "name": "CMake", "bytes": "193647" }, { "name": "Dockerfile", "bytes": "2046" }, { "name": "GDB", "bytes": "89" }, { "name": "HTML", "bytes": "2060" }, { "name": "MATLAB", "bytes": "8755" }, { "name": "Makefile", "bytes": "244" }, { "name": "Python", "bytes": "286724" }, { "name": "SWIG", "bytes": "385845" }, { "name": "Shell", "bytes": "7267" } ], "symlink_target": "" }
This library was generated with [Nx](https://nx.dev). ## Running unit tests Run `nx test services` to execute the unit tests.
{ "content_hash": "ba2f5575c5d5f9e0d7df7820be590832", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 53, "avg_line_length": 25.6, "alnum_prop": 0.7265625, "repo_name": "UIUXEngineering/ix-material", "id": "8a106f0f6a06c9febbc636aaf985fd94a65454ab", "size": "140", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "libs/services/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "176288" }, { "name": "HTML", "bytes": "93553" }, { "name": "JavaScript", "bytes": "11976" }, { "name": "Shell", "bytes": "4844" }, { "name": "TypeScript", "bytes": "879276" } ], "symlink_target": "" }
namespace Operations.RabbitMQ { using System; using global::RabbitMQ.Client; public static class QueueDeletion { static void Usage() { #region rabbit-delete-queues-endpoint-usage DeleteQueuesForEndpoint( uri: "amqp://guest:guest@localhost:5672", endpointName: "myendpoint"); #endregion #region rabbit-delete-queues-shared-usage DeleteQueue( uri: "amqp://guest:guest@localhost:5672", queueName: "error"); DeleteQueue( uri: "amqp://guest:guest@localhost:5672", queueName: "audit"); #endregion } #region rabbit-delete-queues public static void DeleteQueue(string uri, string queueName) { ConnectionFactory factory = new ConnectionFactory { Uri = uri, }; using (IConnection conn = factory.CreateConnection()) using (IModel channel = conn.CreateModel()) { channel.QueueUnbind(queueName, queueName, string.Empty, null); channel.ExchangeDelete(queueName); channel.QueueDelete(queueName); } } public static void DeleteQueuesForEndpoint(string uri, string endpointName) { //main queue DeleteQueue(uri, endpointName); //callback queue DeleteQueue(uri, endpointName + "." + Environment.MachineName); //retries queue DeleteQueue(uri, endpointName + ".Retries"); //timeout queue DeleteQueue(uri, endpointName + ".Timeouts"); //timeout dispatcher queue DeleteQueue(uri, endpointName + ".TimeoutsDispatcher"); } #endregion } }
{ "content_hash": "858fde517455b28998d5f925a5b756da", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 83, "avg_line_length": 28.029850746268657, "alnum_prop": 0.5431309904153354, "repo_name": "eclaus/docs.particular.net", "id": "3c8c7aaa5e1fd887d3b92fc6648d192dcfbcf2d0", "size": "1880", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Snippets/Operations/RabbitMQ/QueueDeletion.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "458768" }, { "name": "PostScript", "bytes": "5551" } ], "symlink_target": "" }
import { Component, ViewChild, ElementRef } from '@angular/core'; import { generatedata } from '../../../sampledata/generatedata'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('cellBeginEditLog') cellBeginEditLog: ElementRef; @ViewChild('cellEndEditLog') cellEndEditLog: ElementRef; source: any = { localdata: generatedata(200, false), datatype: 'array', datafields: [ { name: 'firstname', type: 'string' }, { name: 'lastname', type: 'string' }, { name: 'productname', type: 'string' }, { name: 'available', type: 'bool' }, { name: 'quantity', type: 'number' }, { name: 'price', type: 'number' }, { name: 'date', type: 'date' } ] }; dataAdapter: any = new jqx.dataAdapter(this.source); columns: any[] = [ { text: 'First Name', columntype: 'textbox', datafield: 'firstname', width: 80 }, { text: 'Last Name', datafield: 'lastname', columntype: 'textbox', width: 80 }, { text: 'Product', columntype: 'dropdownlist', datafield: 'productname', width: 195 }, { text: 'Available', datafield: 'available', columntype: 'checkbox', width: 67 }, { text: 'Ship Date', datafield: 'date', columntype: 'datetimeinput', width: 110, align: 'right', cellsalign: 'right', cellsformat: 'd', validation: (cell: any, value: any): any => { if (value == '') return true; let year = value.getFullYear(); if (year >= 2017) { return { result: false, message: 'Ship Date should be before 1/1/2017' }; } return true; } }, { text: 'Quantity', datafield: 'quantity', width: 70, align: 'right', cellsalign: 'right', columntype: 'numberinput', validation: (cell: any, value: number): any => { if (value < 0 || value > 150) { return { result: false, message: 'Quantity should be in the 0-150 interval' }; } return true; }, createeditor: (row: number, cellvalue: any, editor: any): void => { editor.jqxNumberInput({ decimalDigits: 0, digits: 3 }); } }, { text: 'Price', datafield: 'price', align: 'right', cellsalign: 'right', cellsformat: 'c2', columntype: 'numberinput', validation: (cell: any, value: number): any => { if (value < 0 || value > 15) { return { result: false, message: 'Price should be in the 0-15 interval' }; } return true; }, createeditor: (row: number, cellvalue: any, editor: any): void => { editor.jqxNumberInput({ digits: 3 }); } } ]; rowValues: string = ''; myGridOnCellBeginEdit(event: any): void { let args = event.args; if (args.datafield === 'firstname') { this.rowValues = ''; } this.rowValues += args.value.toString() + ' '; if (args.datafield === 'price') { this.cellBeginEditLog.nativeElement.innerHTML = 'Begin Row Edit: ' + (1 + args.rowindex) + ', Data: ' + this.rowValues; } }; myGridOnCellEndEdit(event: any): void { let args = event.args; if (args.datafield === 'firstname') { this.rowValues = ''; } this.rowValues += args.value.toString() + ' '; if (args.datafield === 'price') { this.cellEndEditLog.nativeElement.innerHTML = 'End Row Edit: ' + (1 + args.rowindex) + ', Data: ' + this.rowValues; } }; }
{ "content_hash": "484e81724feabc13a83df11dcbd4b255", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 145, "avg_line_length": 38.86868686868687, "alnum_prop": 0.5142931392931392, "repo_name": "juannelisalde/holter", "id": "02142e84dd5ba3bd1d6b9f175d3daa9fd1a11880", "size": "3850", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "assets/jqwidgets/demos/angular/app/grid/fullrowedit/app.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1327" }, { "name": "Batchfile", "bytes": "802" }, { "name": "C#", "bytes": "374733" }, { "name": "CSS", "bytes": "882785" }, { "name": "HTML", "bytes": "18898187" }, { "name": "Java", "bytes": "12788" }, { "name": "JavaScript", "bytes": "9712220" }, { "name": "PHP", "bytes": "2051144" }, { "name": "TypeScript", "bytes": "3437214" } ], "symlink_target": "" }