text
stringlengths
2
1.04M
meta
dict
disteval.scripts package ======================== Submodules ---------- disteval.scripts.classifier_characteristics module -------------------------------------------------- .. automodule:: disteval.scripts.classifier_characteristics :members: :undoc-members: :show-inheritance: disteval.scripts.preparation module ----------------------------------- .. automodule:: disteval.scripts.preparation :members: :undoc-members: :show-inheritance: disteval.scripts.recursive_selection_parallel module ---------------------------------------------------- .. automodule:: disteval.scripts.recursive_selection_parallel :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: disteval.scripts :members: :undoc-members: :show-inheritance:
{ "content_hash": "686932b323626944b4773ff02a9be066", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 61, "avg_line_length": 21.63157894736842, "alnum_prop": 0.5705596107055961, "repo_name": "tudo-astroparticlephysics/pydisteval", "id": "b0bf441ad130671f085bcb88be6012396537e0b8", "size": "822", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/disteval.scripts.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "183629" } ], "symlink_target": "" }
 #include <aws/qldb-session/model/StartTransactionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace QLDBSession { namespace Model { StartTransactionRequest::StartTransactionRequest() { } StartTransactionRequest::StartTransactionRequest(JsonView jsonValue) { *this = jsonValue; } StartTransactionRequest& StartTransactionRequest::operator =(JsonView jsonValue) { AWS_UNREFERENCED_PARAM(jsonValue); return *this; } JsonValue StartTransactionRequest::Jsonize() const { JsonValue payload; return payload; } } // namespace Model } // namespace QLDBSession } // namespace Aws
{ "content_hash": "61ef96d9f2f873eb074d7339ec490bde", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 80, "avg_line_length": 16.833333333333332, "alnum_prop": 0.7736916548797736, "repo_name": "awslabs/aws-sdk-cpp", "id": "1e63a6c0cad6d81682057a6d7d3c1ed545f09bfc", "size": "826", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-cpp-sdk-qldb-session/source/model/StartTransactionRequest.cpp", "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": "" }
'use strict' import config from '../render/config' import protocol from './protocol' import { isArray } from '../utils' import Sender from './sender' // sync call native component method. function callNativeComponent (instanceId, ref, method, args, options) { return processCall(instanceId, { component: options.component, ref, method, args }) } // sync call native module api. function callNativeModule (instanceId, module, method, args, options) { return processCall(instanceId, { module, method, args }) } // callNative: jsFramework will call this method to talk to // this renderer. // params: // - instanceId: string. // - tasks: array of object. // - callbackId: number. function callNative (instanceId, tasks, callbackId) { let calls = [] if (typeof tasks === 'string') { try { calls = JSON.parse(tasks) } catch (e) { console.error('invalid tasks:', tasks) } } else if (isArray(tasks)) { calls = tasks } const len = calls.length calls[len - 1].callbackId = (!callbackId && callbackId !== 0) ? -1 : callbackId for (let i = 0; i < len; i++) { processCall(instanceId, calls[i]) } } function processCall (instanceId, call) { const isComponent = typeof call.module === 'undefined' const res = isComponent ? componentCall(instanceId, call) : moduleCall(instanceId, call) const callbackId = call.callbackId if ((callbackId || callbackId === 0 || callbackId === '0') && callbackId !== '-1' && callbackId !== -1) { performNextTick(instanceId, callbackId) } // for sync call. return res } function moduleCall (instanceId, call) { const moduleName = call.module const methodName = call.method let module, method const args = call.args || call.arguments || [] if (!(module = protocol.apiModule[moduleName])) { return } if (!(method = module[methodName])) { return } return method.apply(global.weex.getInstance(instanceId), args) } function componentCall (instanceId, call) { const componentName = call.component const ref = call.ref const methodName = call.method const args = call.args || call.arguments || [] const elem = global.weex.getInstance(instanceId).getComponentManager().getComponent(ref) if (!elem) { return console.error(`[h5-render] component of ref ${ref} doesn't exist.`) } let method if (!(method = elem[methodName])) { return console.error(`[h5-render] component ${componentName} doesn't have a method named ${methodName}.`) } return method.apply(elem, args) } function performNextTick (instanceId, callbackId) { Sender.getSender(instanceId).performCallback(callbackId) } function nativeLog () { if (config.debug) { if (arguments[0].match(/^perf/)) { console.info.apply(console, arguments) return } console.debug.apply(console, arguments) } } function exportsBridgeMethodsToGlobal () { global.callNative = callNative global.callNativeComponent = callNativeComponent global.callNativeModule = callNativeModule global.nativeLog = nativeLog } export default { init: function () { // exports methods to global(window). exportsBridgeMethodsToGlobal() } }
{ "content_hash": "53664e0d3e59d2a6432c7c4ae8c6e940", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 109, "avg_line_length": 24.900763358778626, "alnum_prop": 0.6637032495401594, "repo_name": "MrRaindrop/incubator-weex", "id": "1e2a7a44b84337452e7ef3ac17ee9cdd97d07692", "size": "4069", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "html5/render/browser/bridge/receiver.js", "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": "" }
"""Contains functionality to use flic buttons as a binary sensor.""" import asyncio import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import ( CONF_HOST, CONF_PORT, CONF_DISCOVERY, CONF_TIMEOUT, EVENT_HOMEASSISTANT_STOP) from homeassistant.components.binary_sensor import ( BinarySensorDevice, PLATFORM_SCHEMA) from homeassistant.util.async import run_callback_threadsafe REQUIREMENTS = ['https://github.com/soldag/pyflic/archive/0.4.zip#pyflic==0.4'] _LOGGER = logging.getLogger(__name__) DEFAULT_TIMEOUT = 3 CLICK_TYPE_SINGLE = "single" CLICK_TYPE_DOUBLE = "double" CLICK_TYPE_HOLD = "hold" CLICK_TYPES = [CLICK_TYPE_SINGLE, CLICK_TYPE_DOUBLE, CLICK_TYPE_HOLD] CONF_IGNORED_CLICK_TYPES = "ignored_click_types" EVENT_NAME = "flic_click" EVENT_DATA_NAME = "button_name" EVENT_DATA_ADDRESS = "button_address" EVENT_DATA_TYPE = "click_type" EVENT_DATA_QUEUED_TIME = "queued_time" # Validation of the user's configuration PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_HOST, default='localhost'): cv.string, vol.Optional(CONF_PORT, default=5551): cv.port, vol.Optional(CONF_DISCOVERY, default=True): cv.boolean, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, vol.Optional(CONF_IGNORED_CLICK_TYPES): vol.All(cv.ensure_list, [vol.In(CLICK_TYPES)]) }) @asyncio.coroutine def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Setup the flic platform.""" import pyflic # Initialize flic client responsible for # connecting to buttons and retrieving events host = config.get(CONF_HOST) port = config.get(CONF_PORT) discovery = config.get(CONF_DISCOVERY) try: client = pyflic.FlicClient(host, port) except ConnectionRefusedError: _LOGGER.error("Failed to connect to flic server.") return def new_button_callback(address): """Setup newly verified button as device in home assistant.""" hass.add_job(async_setup_button(hass, config, async_add_entities, client, address)) client.on_new_verified_button = new_button_callback if discovery: start_scanning(hass, config, async_add_entities, client) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, lambda event: client.close()) hass.loop.run_in_executor(None, client.handle_events) # Get addresses of already verified buttons addresses = yield from async_get_verified_addresses(client) if addresses: for address in addresses: yield from async_setup_button(hass, config, async_add_entities, client, address) def start_scanning(hass, config, async_add_entities, client): """Start a new flic client for scanning & connceting to new buttons.""" import pyflic scan_wizard = pyflic.ScanWizard() def scan_completed_callback(scan_wizard, result, address, name): """Restart scan wizard to constantly check for new buttons.""" if result == pyflic.ScanWizardResult.WizardSuccess: _LOGGER.info("Found new button (%s)", address) elif result != pyflic.ScanWizardResult.WizardFailedTimeout: _LOGGER.warning("Failed to connect to button (%s). Reason: %s", address, result) # Restart scan wizard start_scanning(hass, config, async_add_entities, client) scan_wizard.on_completed = scan_completed_callback client.add_scan_wizard(scan_wizard) @asyncio.coroutine def async_setup_button(hass, config, async_add_entities, client, address): """Setup single button device.""" timeout = config.get(CONF_TIMEOUT) ignored_click_types = config.get(CONF_IGNORED_CLICK_TYPES) button = FlicButton(hass, client, address, timeout, ignored_click_types) _LOGGER.info("Connected to button (%s)", address) yield from async_add_entities([button]) @asyncio.coroutine def async_get_verified_addresses(client): """Retrieve addresses of verified buttons.""" future = asyncio.Future() loop = asyncio.get_event_loop() def get_info_callback(items): """Set the addressed of connected buttons as result of the future.""" addresses = items["bd_addr_of_verified_buttons"] run_callback_threadsafe(loop, future.set_result, addresses) client.get_info(get_info_callback) return future class FlicButton(BinarySensorDevice): """Representation of a flic button.""" def __init__(self, hass, client, address, timeout, ignored_click_types): """Initialize the flic button.""" import pyflic self._hass = hass self._address = address self._timeout = timeout self._is_down = False self._ignored_click_types = ignored_click_types or [] self._hass_click_types = { pyflic.ClickType.ButtonClick: CLICK_TYPE_SINGLE, pyflic.ClickType.ButtonSingleClick: CLICK_TYPE_SINGLE, pyflic.ClickType.ButtonDoubleClick: CLICK_TYPE_DOUBLE, pyflic.ClickType.ButtonHold: CLICK_TYPE_HOLD, } self._channel = self._create_channel() client.add_connection_channel(self._channel) def _create_channel(self): """Create a new connection channel to the button.""" import pyflic channel = pyflic.ButtonConnectionChannel(self._address) channel.on_button_up_or_down = self._on_up_down # If all types of clicks should be ignored, skip registering callbacks if set(self._ignored_click_types) == set(CLICK_TYPES): return channel if CLICK_TYPE_DOUBLE in self._ignored_click_types: # Listen to all but double click type events channel.on_button_click_or_hold = self._on_click elif CLICK_TYPE_HOLD in self._ignored_click_types: # Listen to all but hold click type events channel.on_button_single_or_double_click = self._on_click else: # Listen to all click type events channel.on_button_single_or_double_click_or_hold = self._on_click return channel @property def name(self): """Return the name of the device.""" return "flic_%s" % self.address.replace(":", "") @property def address(self): """Return the bluetooth address of the device.""" return self._address @property def is_on(self): """Return true if sensor is on.""" return self._is_down @property def should_poll(self): """No polling needed.""" return False @property def state_attributes(self): """Return device specific state attributes.""" attr = super(FlicButton, self).state_attributes attr["address"] = self.address return attr def _queued_event_check(self, click_type, time_diff): """Generate a log message and returns true if timeout exceeded.""" time_string = "{:d} {}".format( time_diff, "second" if time_diff == 1 else "seconds") if time_diff > self._timeout: _LOGGER.warning( "Queued %s dropped for %s. Time in queue was %s.", click_type, self.address, time_string) return True else: _LOGGER.info( "Queued %s allowed for %s. Time in queue was %s.", click_type, self.address, time_string) return False def _on_up_down(self, channel, click_type, was_queued, time_diff): """Update device state, if event was not queued.""" import pyflic if was_queued and self._queued_event_check(click_type, time_diff): return self._is_down = click_type == pyflic.ClickType.ButtonDown self.schedule_update_ha_state() def _on_click(self, channel, click_type, was_queued, time_diff): """Fire click event, if event was not queued.""" # Return if click event was queued beyond allowed timeout if was_queued and self._queued_event_check(click_type, time_diff): return # Return if click event is in ignored click types hass_click_type = self._hass_click_types[click_type] if hass_click_type in self._ignored_click_types: return self._hass.bus.fire(EVENT_NAME, { EVENT_DATA_NAME: self.name, EVENT_DATA_ADDRESS: self.address, EVENT_DATA_QUEUED_TIME: time_diff, EVENT_DATA_TYPE: hass_click_type }) def _connection_status_changed(self, channel, connection_status, disconnect_reason): """Remove device, if button disconnects.""" import pyflic if connection_status == pyflic.ConnectionStatus.Disconnected: _LOGGER.info("Button (%s) disconnected. Reason: %s", self.address, disconnect_reason) self.remove()
{ "content_hash": "f5f9bae456dbf42e5d49c0cdd8f06593", "timestamp": "", "source": "github", "line_count": 257, "max_line_length": 79, "avg_line_length": 35.53307392996109, "alnum_prop": 0.6371003066141042, "repo_name": "ma314smith/home-assistant", "id": "980af069f38dbb944d0478f1454d1eaa3c321181", "size": "9132", "binary": false, "copies": "3", "ref": "refs/heads/dev", "path": "homeassistant/components/binary_sensor/flic.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1436909" }, { "name": "Python", "bytes": "4511947" }, { "name": "Ruby", "bytes": "379" }, { "name": "Shell", "bytes": "4460" } ], "symlink_target": "" }
import sbt._ import Keys._ object BuildSettings { // Basic settings for our app lazy val basicSettings = Seq[Setting[_]]( organization := "Snowplow Analytics Ltd", version := "0.1.0", description := "Scala Stream Collector for Snowplow raw events", scalaVersion := "2.10.1", scalacOptions := Seq("-deprecation", "-encoding", "utf8", "-unchecked", "-feature"), scalacOptions in Test := Seq("-Yrangepos"), maxErrors := 5, // http://www.scala-sbt.org/0.13.0/docs/Detailed-Topics/Forking.html fork in run := true, resolvers ++= Dependencies.resolutionRepos ) // Makes our SBT app settings available from within the app lazy val scalifySettings = Seq(sourceGenerators in Compile <+= (sourceManaged in Compile, version, name, organization) map { (d, v, n, o) => val file = d / "settings.scala" IO.write(file, s"""package com.snowplowanalytics.snowplow.collectors.scalastream.generated |object Settings { | val organization = "$o" | val version = "$v" | val name = "$n" | val shortName = "ssc" |} |""".stripMargin) Seq(file) }) // sbt-assembly settings for building an executable import sbtassembly.Plugin._ import AssemblyKeys._ lazy val sbtAssemblySettings = assemblySettings ++ Seq( // Executable jarfile assemblyOption in assembly ~= { _.copy(prependShellScript = Some(defaultShellScript)) }, // Name it as an executable jarName in assembly := { s"${name.value}-${version.value}" } ) lazy val buildSettings = basicSettings ++ scalifySettings ++ sbtAssemblySettings }
{ "content_hash": "1e53aa6c4dbc05916b08a82692ce0bcb", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 94, "avg_line_length": 35.59183673469388, "alnum_prop": 0.6095183486238532, "repo_name": "1974kpkpkp/snowplow", "id": "6f6595d704e911cb0acca416dcf12931438f6fee", "size": "2458", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "2-collectors/scala-stream-collector/project/BuildSettings.scala", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
const webpack = require('webpack'); var merge = require('webpack-merge'); const fs = require('fs'); var CopyWebpackPlugin = require('copy-webpack-plugin'); var HTMLWebpackPlugin = require('html-webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); var path = require('path'); var TARGET_ENV = process.env.npm_lifecycle_event === 'prod' ? 'production' : 'development'; var filename = (TARGET_ENV == 'production') ? '[name]-[hash].js' : 'index.js'; var common = { entry: './src/Mainxs.js', output: { path: path.join(__dirname, "build"), // add hash when building for production filename: filename }, plugins: [new HTMLWebpackPlugin({ // using .ejs prevents other loaders causing errors template: 'src/index.ejs', // inject details of output file at end of body inject: 'body' })], resolve: { modules: [ path.join(__dirname, "src"), "node_modules" ], extensions: ['.js', '.purs', '.scss', '.png'] }, module: { rules: [ { test: /\.html$/, exclude: /node_modules/, loader: 'file-loader?name=[name].[ext]' }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { // env: automatically determines the Babel plugins you need based on your supported environments presets: ['env'] } } }, { test: /\.scss$/, exclude: [ /elm-stuff/, /node_modules/ ], loaders: ["style-loader", "css-loader", "sass-loader"] }, { test: /\.css$/, exclude: [ /elm-stuff/, /node_modules/ ], loaders: ["style-loader", "css-loader"] }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, exclude: [ /elm-stuff/, /node_modules/ ], loader: "url-loader", options: { limit: 10000, mimetype: "application/font-woff" } }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, exclude: [ /elm-stuff/, /node_modules/ ], loader: "file-loader" }, { test: /\.(jpe?g|png|gif|svg)$/i, loader: 'file-loader' } ] } } if (TARGET_ENV === 'development') { console.log('Building for dev...'); module.exports = merge(common, { mode: 'development', plugins: [ // Suggested for hot-loading new webpack.NamedModulesPlugin(), // Prevents compilation errors causing the hot loader to lose state new webpack.NoEmitOnErrorsPlugin() ], module: { rules: [ { test: /\.elm$/, exclude: [ /elm-stuff/, /node_modules/ ], use: [ { loader: "elm-hot-loader" }, { loader: "elm-webpack-loader", // add Elm's debug overlay to output options: { debug: true } } ] } ] }, devServer: { inline: true, https: { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt'), ca: fs.readFileSync('rootCA.pem'), }, contentBase: path.join(__dirname, "src/assets") } }); } if (TARGET_ENV === 'production') { console.log('Building for prod...'); module.exports = merge(common, { mode: 'production', plugins: [ new CopyWebpackPlugin([ { from: 'src/assets' } ]) ] , optimization: { minimizer: [ new UglifyJsPlugin({ sourceMap: true, uglifyOptions: { compress: { inline: false } } }) ] } , module: { rules: [ { test: /\.elm$/, exclude: [ /elm-stuff/, /node_modules/ ], use: [ { loader: "elm-webpack-loader" } ] } ] } }); }
{ "content_hash": "7959d5707e743e0e3c50047d055ae587", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 120, "avg_line_length": 30.123529411764707, "alnum_prop": 0.37844171060339776, "repo_name": "sigrlami/pollock", "id": "3661ba21e002e3e1f40a1bdf7afa4ec1aafc4e79", "size": "5121", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app-purescript/webpack.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "39523" }, { "name": "Dockerfile", "bytes": "1079" }, { "name": "HTML", "bytes": "810" }, { "name": "Haskell", "bytes": "27473" }, { "name": "JavaScript", "bytes": "20693" }, { "name": "PureScript", "bytes": "1179" }, { "name": "Shell", "bytes": "115" }, { "name": "Smarty", "bytes": "20709" }, { "name": "TypeScript", "bytes": "50631" } ], "symlink_target": "" }
/*************************************************************************/ /* line_shape_2d.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #ifndef LINE_SHAPE_2D_H #define LINE_SHAPE_2D_H #include "scene/resources/shape_2d.h" class LineShape2D : public Shape2D { GDCLASS(LineShape2D, Shape2D); Vector2 normal; real_t distance; void _update_shape(); protected: static void _bind_methods(); public: virtual bool _edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const override; void set_normal(const Vector2 &p_normal); void set_distance(real_t p_distance); Vector2 get_normal() const; real_t get_distance() const; virtual void draw(const RID &p_to_rid, const Color &p_color) override; virtual Rect2 get_rect() const override; virtual real_t get_enclosing_radius() const override; LineShape2D(); }; #endif // LINE_SHAPE_2D_H
{ "content_hash": "3ad0c73909c757add540e97017ac0036", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 99, "avg_line_length": 46.55555555555556, "alnum_prop": 0.5151721786566655, "repo_name": "Paulloz/godot", "id": "7e67a8f67cf36cd8b106c36ab207ef3f21661ca2", "size": "2933", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "scene/resources/line_shape_2d.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "50004" }, { "name": "C#", "bytes": "176259" }, { "name": "C++", "bytes": "18569070" }, { "name": "GLSL", "bytes": "1271" }, { "name": "Java", "bytes": "495377" }, { "name": "JavaScript", "bytes": "14680" }, { "name": "Makefile", "bytes": "451" }, { "name": "Objective-C", "bytes": "2645" }, { "name": "Objective-C++", "bytes": "173262" }, { "name": "Python", "bytes": "336142" }, { "name": "Shell", "bytes": "19610" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "f6bb7cef43b3e79ee840ad24594ad0e2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "ba13552b23d959132cac0e1b319a9f72d70c6d89", "size": "185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Cyperus/Cyperus pilosus/ Syn. Cyperus pilosus muticus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php use Phalcon\Mvc\View, Phalcon\Mvc\View\Engine\Volt, Phalcon\Config\Adapter\Ini; include('../app/Response.php'); include('../app/TranslationController.php'); try { $config = new Ini("config.ini"); //Register an autoloader $loader = new \Phalcon\Loader(); $loader->registerDirs(array( $config->phalcon->controllersDir, $config->phalcon->modelsDir ))->register(); //Create a DI $di = new Phalcon\DI\FactoryDefault(); //Register Volt as a service $di->set('voltService', function($view, $di) { $config = new Ini("config.ini"); $volt = new Volt($view, $di); $volt->setOptions(array( "compiledPath" => $config->volt->compiledPath, "compiledExtension" => $config->volt->compiledExtension )); return $volt; }); //Registering Volt as template engine $di->set('view', function($di) { $config = new Ini("config.ini"); $view = new \Phalcon\Mvc\View(); $view->setViewsDir($config->phalcon->viewsDir); $view->registerEngines(array( $config->volt->extension => 'voltService', )); return $view; }); //Register a controller as a service $di->set('translate', function() { $component = new TranslationController(); return $component->t(); }); //Set the database service $di->set('db', function(){ $config = new Ini("config.ini"); return new \Phalcon\Db\Adapter\Pdo\Mysql(array( "host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname )); }); $di->set('url', function () { $url = new Phalcon\Mvc\Url(); $url->setBaseUri("/"); return $url; }, true); //Start the session the first time when some component request the session service $di->setShared('session', function() { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $di->set('response',function(){ return new \Core\Http\Response(); }); //Set up the flash service $di->set('flash', function (){ $flash = new \Phalcon\Flash\Session(array( 'error' => 'error', 'success' => 'success', 'notice' => 'info', )); return $flash; }); //Handle the request $application = new \Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch(\Phalcon\Exception $e) { echo "PhalconException: ", $e->getMessage(); }
{ "content_hash": "2a10217686f2dbfe95b4b37c3243a7ac", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 86, "avg_line_length": 26.356435643564357, "alnum_prop": 0.567618332081142, "repo_name": "memiks/trytolistenme", "id": "da5b13924bc9c226d92b4d306f9c77cf3feb1f43", "size": "2662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/index.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "341" }, { "name": "CSS", "bytes": "13017" }, { "name": "JavaScript", "bytes": "594138" }, { "name": "PHP", "bytes": "23552" }, { "name": "Volt", "bytes": "11767" } ], "symlink_target": "" }
// Generated by Xamasoft JSON Class Generator // http://www.xamasoft.com/json-class-generator using Newtonsoft.Json; namespace PlayStation_App.Models.RecentActivity { public class Source2 { [JsonProperty("meta")] public string Meta { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("imageUrl")] public string ImageUrl { get; set; } } }
{ "content_hash": "d0be0fe8fcba6237d0c0f53ce328d7c9", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 47, "avg_line_length": 19.90909090909091, "alnum_prop": 0.6278538812785388, "repo_name": "drasticactions/Pureisuteshon-App", "id": "b7bd08c72f55c5e770cc9680c50dbb4b0498404b", "size": "440", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "PSX-App/Models/RecentActivity/Source2.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1980" }, { "name": "C#", "bytes": "966001" }, { "name": "HTML", "bytes": "274" }, { "name": "PowerShell", "bytes": "151" } ], "symlink_target": "" }
 #include <aws/core/client/AWSError.h> #include <aws/core/utils/HashingUtils.h> #include <aws/chime-sdk-messaging/ChimeSDKMessagingErrors.h> #include <aws/chime-sdk-messaging/model/ConflictException.h> #include <aws/chime-sdk-messaging/model/ServiceUnavailableException.h> #include <aws/chime-sdk-messaging/model/NotFoundException.h> #include <aws/chime-sdk-messaging/model/ServiceFailureException.h> #include <aws/chime-sdk-messaging/model/ForbiddenException.h> #include <aws/chime-sdk-messaging/model/ResourceLimitExceededException.h> #include <aws/chime-sdk-messaging/model/ThrottledClientException.h> #include <aws/chime-sdk-messaging/model/BadRequestException.h> #include <aws/chime-sdk-messaging/model/UnauthorizedClientException.h> using namespace Aws::Client; using namespace Aws::Utils; using namespace Aws::ChimeSDKMessaging; using namespace Aws::ChimeSDKMessaging::Model; namespace Aws { namespace ChimeSDKMessaging { template<> AWS_CHIMESDKMESSAGING_API ConflictException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::CONFLICT); return ConflictException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API ServiceUnavailableException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::SERVICE_UNAVAILABLE); return ServiceUnavailableException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API NotFoundException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::NOT_FOUND); return NotFoundException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API ServiceFailureException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::SERVICE_FAILURE); return ServiceFailureException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API ForbiddenException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::FORBIDDEN); return ForbiddenException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API ResourceLimitExceededException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::RESOURCE_LIMIT_EXCEEDED); return ResourceLimitExceededException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API ThrottledClientException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::THROTTLED_CLIENT); return ThrottledClientException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API BadRequestException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::BAD_REQUEST); return BadRequestException(this->GetJsonPayload().View()); } template<> AWS_CHIMESDKMESSAGING_API UnauthorizedClientException ChimeSDKMessagingError::GetModeledError() { assert(this->GetErrorType() == ChimeSDKMessagingErrors::UNAUTHORIZED_CLIENT); return UnauthorizedClientException(this->GetJsonPayload().View()); } namespace ChimeSDKMessagingErrorMapper { static const int CONFLICT_HASH = HashingUtils::HashString("ConflictException"); static const int NOT_FOUND_HASH = HashingUtils::HashString("NotFoundException"); static const int SERVICE_FAILURE_HASH = HashingUtils::HashString("ServiceFailureException"); static const int FORBIDDEN_HASH = HashingUtils::HashString("ForbiddenException"); static const int RESOURCE_LIMIT_EXCEEDED_HASH = HashingUtils::HashString("ResourceLimitExceededException"); static const int THROTTLED_CLIENT_HASH = HashingUtils::HashString("ThrottledClientException"); static const int BAD_REQUEST_HASH = HashingUtils::HashString("BadRequestException"); static const int UNAUTHORIZED_CLIENT_HASH = HashingUtils::HashString("UnauthorizedClientException"); AWSError<CoreErrors> GetErrorForName(const char* errorName) { int hashCode = HashingUtils::HashString(errorName); if (hashCode == CONFLICT_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::CONFLICT), false); } else if (hashCode == NOT_FOUND_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::NOT_FOUND), false); } else if (hashCode == SERVICE_FAILURE_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::SERVICE_FAILURE), false); } else if (hashCode == FORBIDDEN_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::FORBIDDEN), false); } else if (hashCode == RESOURCE_LIMIT_EXCEEDED_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::RESOURCE_LIMIT_EXCEEDED), false); } else if (hashCode == THROTTLED_CLIENT_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::THROTTLED_CLIENT), false); } else if (hashCode == BAD_REQUEST_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::BAD_REQUEST), false); } else if (hashCode == UNAUTHORIZED_CLIENT_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ChimeSDKMessagingErrors::UNAUTHORIZED_CLIENT), false); } return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false); } } // namespace ChimeSDKMessagingErrorMapper } // namespace ChimeSDKMessaging } // namespace Aws
{ "content_hash": "f17ab20772efa97177cdff23776495ea", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 114, "avg_line_length": 41.03007518796993, "alnum_prop": 0.7938427707531611, "repo_name": "cedral/aws-sdk-cpp", "id": "aba6417ba2a3eb82f0d810d544de1b3dea983004", "size": "5576", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-chime-sdk-messaging/source/ChimeSDKMessagingErrors.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
package justinb99.futureexecutor import org.scalatest.{FlatSpec, Matchers} /** * Created by justin on 4/23/17. */ class FutureExecutorStatsTest extends FlatSpec with Matchers { val testStats = FutureExecutorStats( numberOfQueuedFutures = 100, numberOfExecutingFutures = 4, executionTimeMillis = 326238l, //5 min, 26 sec, 238 ms numberOfCompletedFutures = 10, numberOfFailedFutures = 11 ) val expectedExecutionTime = "5 minutes, 26 seconds and 238 milliseconds" "FutureExecutorStats" should "return a friendly execution time" in { testStats.executionTime shouldBe expectedExecutionTime } val expectedAvgTime = "32 seconds and 623 milliseconds" it should "calculate average execution time" in { testStats.averageExecutionTimeMillis shouldBe 32623l testStats.averageExecutionTime shouldBe expectedAvgTime } it should "convert to a JSON string" in { val formatted = testStats.toString val expectedFormatted = s"""|{ | "numberOfQueuedFutures": 100, | "numberOfExecutingFutures": 4, | "executionTimeMillis": 326238, | "numberOfCompletedFutures": 10, | "numberOfFailedFutures": 11, | "executionTime": "$expectedExecutionTime", | "averageExecutionTimeMillis": 32623, | "averageExecutionTime": "$expectedAvgTime" |}""".stripMargin formatted shouldBe expectedFormatted } }
{ "content_hash": "dfdc4cc12a84ca1226cbc4416e3978ac", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 74, "avg_line_length": 30.72340425531915, "alnum_prop": 0.6980609418282548, "repo_name": "justinb99/futureexecutor", "id": "2f441ab8ee450f28f012f15492f6eab1b5b2cc91", "size": "1444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scala/justinb99/futureexecutor/FutureExecutorStatsTest.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "13309" }, { "name": "Shell", "bytes": "79" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title>ImageTransition Enumeration Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset='utf-8'> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> </head> <body> <a name="//apple_ref/swift/Enum/ImageTransition" class="dashAnchor"></a> <a title="ImageTransition Enumeration Reference"></a> <header> <div class="content-wrapper"> <p><a href="../index.html">Kingfisher Docs</a> (74% documented)</p> <p class="header-right"><a href="https://github.com/onevcat/Kingfisher"><img src="../img/gh.png"/>View on GitHub</a></p> <p class="header-right"><a href="dash-feed://http%3A%2F%2Fonevcat%2Egithub%2Eio%2FKingfisher%2Fdocsets%2FKingfisher%2Exml"><img src="../img/dash.png"/>Install in Dash</a></p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="../index.html">Kingfisher Reference</a> <img id="carat" src="../img/carat.png" /> ImageTransition Enumeration Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Classes/AnimatedImageView.html">AnimatedImageView</a> </li> <li class="nav-group-task"> <a href="../Classes/AnimatedImageView/RepeatCount.html">– RepeatCount</a> </li> <li class="nav-group-task"> <a href="../Classes/ImageCache.html">ImageCache</a> </li> <li class="nav-group-task"> <a href="../Classes/ImageCache/CacheCheckResult.html">– CacheCheckResult</a> </li> <li class="nav-group-task"> <a href="../Classes/ImageDownloader.html">ImageDownloader</a> </li> <li class="nav-group-task"> <a href="../Classes/ImagePrefetcher.html">ImagePrefetcher</a> </li> <li class="nav-group-task"> <a href="../Classes/Kingfisher.html">Kingfisher</a> </li> <li class="nav-group-task"> <a href="../Classes/KingfisherManager.html">KingfisherManager</a> </li> <li class="nav-group-task"> <a href="../Classes/RetrieveImageTask.html">RetrieveImageTask</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Global Variables.html">Global Variables</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Global Variables.html#/s:10Kingfisher0A23DiskCacheCleanedHashKeySSvp">KingfisherDiskCacheCleanedHashKey</a> </li> <li class="nav-group-task"> <a href="../Global Variables.html#/s:10Kingfisher0A11ErrorDomainSSvp">KingfisherErrorDomain</a> </li> <li class="nav-group-task"> <a href="../Global Variables.html#/s:10Kingfisher0A18ErrorStatusCodeKeySSvp">KingfisherErrorStatusCodeKey</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Enums.html">Enumerations</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Enums/CacheType.html">CacheType</a> </li> <li class="nav-group-task"> <a href="../Enums/ContentMode.html">ContentMode</a> </li> <li class="nav-group-task"> <a href="../Enums/ImageFormat.html">ImageFormat</a> </li> <li class="nav-group-task"> <a href="../Enums/ImageProcessItem.html">ImageProcessItem</a> </li> <li class="nav-group-task"> <a href="../Enums/ImageTransition.html">ImageTransition</a> </li> <li class="nav-group-task"> <a href="../Enums/ImageTransition.html">ImageTransition</a> </li> <li class="nav-group-task"> <a href="../Enums/IndicatorType.html">IndicatorType</a> </li> <li class="nav-group-task"> <a href="../Enums/KingfisherError.html">KingfisherError</a> </li> <li class="nav-group-task"> <a href="../Enums/KingfisherOptionsInfoItem.html">KingfisherOptionsInfoItem</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Extensions/CGSize.html">CGSize</a> </li> <li class="nav-group-task"> <a href="../Extensions/Collection.html">Collection</a> </li> <li class="nav-group-task"> <a href="../Extensions/Data.html">Data</a> </li> <li class="nav-group-task"> <a href="../Extensions/Notification.html">Notification</a> </li> <li class="nav-group-task"> <a href="../Extensions/Notification/Name.html">– Name</a> </li> <li class="nav-group-task"> <a href="../Extensions/URL.html">URL</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Functions.html">Functions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Functions.html#/s:10Kingfisher2ggoiyAA14ImageProcessor_pAaC_p_AaC_ptF">&gt;&gt;(_:_:)</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Protocols/AnimatedImageViewDelegate.html">AnimatedImageViewDelegate</a> </li> <li class="nav-group-task"> <a href="../Protocols/AuthenticationChallengeResponsable.html">AuthenticationChallengeResponsable</a> </li> <li class="nav-group-task"> <a href="../Protocols/CIImageProcessor.html">CIImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Protocols/CacheSerializer.html">CacheSerializer</a> </li> <li class="nav-group-task"> <a href="../Protocols/ImageDownloadRequestModifier.html">ImageDownloadRequestModifier</a> </li> <li class="nav-group-task"> <a href="../Protocols/ImageDownloaderDelegate.html">ImageDownloaderDelegate</a> </li> <li class="nav-group-task"> <a href="../Protocols/ImageModifier.html">ImageModifier</a> </li> <li class="nav-group-task"> <a href="../Protocols/ImageProcessor.html">ImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Protocols/Indicator.html">Indicator</a> </li> <li class="nav-group-task"> <a href="../Protocols/KingfisherCompatible.html">KingfisherCompatible</a> </li> <li class="nav-group-task"> <a href="../Protocols/Placeholder.html">Placeholder</a> </li> <li class="nav-group-task"> <a href="../Protocols/Resource.html">Resource</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Structs.html">Structures</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Structs/AlignmentRectInsetsImageModifier.html">AlignmentRectInsetsImageModifier</a> </li> <li class="nav-group-task"> <a href="../Structs/AnyImageModifier.html">AnyImageModifier</a> </li> <li class="nav-group-task"> <a href="../Structs/AnyModifier.html">AnyModifier</a> </li> <li class="nav-group-task"> <a href="../Structs/BlackWhiteProcessor.html">BlackWhiteProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/BlendImageProcessor.html">BlendImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/BlurImageProcessor.html">BlurImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/CGSizeProxy.html">CGSizeProxy</a> </li> <li class="nav-group-task"> <a href="../Structs/ColorControlsProcessor.html">ColorControlsProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/CompositingImageProcessor.html">CompositingImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/CroppingImageProcessor.html">CroppingImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/DataProxy.html">DataProxy</a> </li> <li class="nav-group-task"> <a href="../Structs/DefaultCacheSerializer.html">DefaultCacheSerializer</a> </li> <li class="nav-group-task"> <a href="../Structs/DefaultImageModifier.html">DefaultImageModifier</a> </li> <li class="nav-group-task"> <a href="../Structs/DefaultImageProcessor.html">DefaultImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/Filter.html">Filter</a> </li> <li class="nav-group-task"> <a href="../Structs/FlipsForRightToLeftLayoutDirectionImageModifier.html">FlipsForRightToLeftLayoutDirectionImageModifier</a> </li> <li class="nav-group-task"> <a href="../Structs/FormatIndicatedCacheSerializer.html">FormatIndicatedCacheSerializer</a> </li> <li class="nav-group-task"> <a href="../Structs/ImageResource.html">ImageResource</a> </li> <li class="nav-group-task"> <a href="../Structs/OverlayImageProcessor.html">OverlayImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/RectCorner.html">RectCorner</a> </li> <li class="nav-group-task"> <a href="../Structs/RenderingModeImageModifier.html">RenderingModeImageModifier</a> </li> <li class="nav-group-task"> <a href="../Structs/ResizingImageProcessor.html">ResizingImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/RetrieveImageDownloadTask.html">RetrieveImageDownloadTask</a> </li> <li class="nav-group-task"> <a href="../Structs/RoundCornerImageProcessor.html">RoundCornerImageProcessor</a> </li> <li class="nav-group-task"> <a href="../Structs/TintImageProcessor.html">TintImageProcessor</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Typealiases.html">Type Aliases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Typealiases.html#/Button">Button</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher6Buttona">Button</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/Color">Color</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher5Colora">Color</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher17CompletionHandlera">CompletionHandler</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher21DownloadProgressBlocka">DownloadProgressBlock</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/Image">Image</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher5Imagea">Image</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher32ImageDownloaderCompletionHandlera">ImageDownloaderCompletionHandler</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher28ImageDownloaderProgressBlocka">ImageDownloaderProgressBlock</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/ImageView">ImageView</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher9ImageViewa">ImageView</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/IndicatorView">IndicatorView</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher13IndicatorViewa">IndicatorView</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher0A11OptionsInfoa">KingfisherOptionsInfo</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher27PrefetcherCompletionHandlera">PrefetcherCompletionHandler</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher23PrefetcherProgressBlocka">PrefetcherProgressBlock</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher21RetrieveImageDiskTaska">RetrieveImageDiskTask</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher11Transformera">Transformer</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/View">View</a> </li> <li class="nav-group-task"> <a href="../Typealiases.html#/s:10Kingfisher4Viewa">View</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>ImageTransition</h1> <div class="declaration"> <div class="language"> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">ImageTransition</span></code></pre> </div> </div> <p>Transition effect which will be used when an image downloaded and set by <code>UIImageView</code> extension API in Kingfisher. You can assign an enum value with transition duration as an item in <code><a href="../Typealiases.html#/s:10Kingfisher0A11OptionsInfoa">KingfisherOptionsInfo</a></code> to enable the animation transition.</p> <p>Apple&rsquo;s UIViewAnimationOptions is used under the hood. For custom transition, you should specified your own transition options, animations and completion handler as well.</p> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:10Kingfisher15ImageTransitionO4noneyA2CmF"></a> <a name="//apple_ref/swift/Element/none" class="dashAnchor"></a> <a class="token" href="#/s:10Kingfisher15ImageTransitionO4noneyA2CmF">none</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>No animation transition.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="k">none</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/4.10.0/Sources/ImageTransition.swift#L63">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:10Kingfisher15ImageTransitionO4fadeyACSdcACmF"></a> <a name="//apple_ref/swift/Element/fade(_:)" class="dashAnchor"></a> <a class="token" href="#/s:10Kingfisher15ImageTransitionO4fadeyACSdcACmF">fade(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Fade in the loaded image.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">fade</span><span class="p">(</span><span class="kt">TimeInterval</span><span class="p">)</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/4.10.0/Sources/ImageTransition.swift#L66">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:10Kingfisher15ImageTransitionO12flipFromLeftyACSdcACmF"></a> <a name="//apple_ref/swift/Element/flipFromLeft(_:)" class="dashAnchor"></a> <a class="token" href="#/s:10Kingfisher15ImageTransitionO12flipFromLeftyACSdcACmF">flipFromLeft(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Flip from left transition.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">flipFromLeft</span><span class="p">(</span><span class="kt">TimeInterval</span><span class="p">)</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/4.10.0/Sources/ImageTransition.swift#L69">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:10Kingfisher15ImageTransitionO13flipFromRightyACSdcACmF"></a> <a name="//apple_ref/swift/Element/flipFromRight(_:)" class="dashAnchor"></a> <a class="token" href="#/s:10Kingfisher15ImageTransitionO13flipFromRightyACSdcACmF">flipFromRight(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Flip from right transition.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">flipFromRight</span><span class="p">(</span><span class="kt">TimeInterval</span><span class="p">)</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/4.10.0/Sources/ImageTransition.swift#L72">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:10Kingfisher15ImageTransitionO11flipFromTopyACSdcACmF"></a> <a name="//apple_ref/swift/Element/flipFromTop(_:)" class="dashAnchor"></a> <a class="token" href="#/s:10Kingfisher15ImageTransitionO11flipFromTopyACSdcACmF">flipFromTop(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Flip from top transition.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">flipFromTop</span><span class="p">(</span><span class="kt">TimeInterval</span><span class="p">)</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/4.10.0/Sources/ImageTransition.swift#L75">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:10Kingfisher15ImageTransitionO14flipFromBottomyACSdcACmF"></a> <a name="//apple_ref/swift/Element/flipFromBottom(_:)" class="dashAnchor"></a> <a class="token" href="#/s:10Kingfisher15ImageTransitionO14flipFromBottomyACSdcACmF">flipFromBottom(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Flip from bottom transition.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">flipFromBottom</span><span class="p">(</span><span class="kt">TimeInterval</span><span class="p">)</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/4.10.0/Sources/ImageTransition.swift#L78">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:10Kingfisher15ImageTransitionO6customyACSd_So22UIViewAnimationOptionsVySo11UIImageViewC_So0H0CtcSgySbcSgtcACmF"></a> <a name="//apple_ref/swift/Element/custom(duration:options:animations:completion:)" class="dashAnchor"></a> <a class="token" href="#/s:10Kingfisher15ImageTransitionO6customyACSd_So22UIViewAnimationOptionsVySo11UIImageViewC_So0H0CtcSgySbcSgtcACmF">custom(duration:options:animations:completion:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Custom transition.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">custom</span><span class="p">(</span><span class="nv">duration</span><span class="p">:</span> <span class="kt">TimeInterval</span><span class="p">,</span> <span class="nv">options</span><span class="p">:</span> <span class="kt">UIView</span><span class="o">.</span><span class="kt">AnimationOptions</span><span class="p">,</span> <span class="nv">animations</span><span class="p">:</span> <span class="p">((</span><span class="kt">UIImageView</span><span class="p">,</span> <span class="kt">UIImage</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)?,</span> <span class="nv">completion</span><span class="p">:</span> <span class="p">((</span><span class="kt">Bool</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Void</span><span class="p">)?)</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/onevcat/Kingfisher/tree/4.10.0/Sources/ImageTransition.swift#L81">Show on GitHub</a> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2018 <a class="link" href="https://onevcat.com" target="_blank" rel="external">Wei Wang</a>. All rights reserved. (Last updated: 2018-09-20)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.9.3</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </article> </div> </body> </div> </html>
{ "content_hash": "a9c6f1466bcc928f609230ea77d47515", "timestamp": "", "source": "github", "line_count": 576, "max_line_length": 953, "avg_line_length": 50.10243055555556, "alnum_prop": 0.49322568349561663, "repo_name": "pNre/Kingfisher", "id": "c52e33507541289bd89c792dabe9a64667299211", "size": "28869", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/Enums/ImageTransition.html", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1718" }, { "name": "Ruby", "bytes": "18908" }, { "name": "Shell", "bytes": "84" }, { "name": "Swift", "bytes": "443675" } ], "symlink_target": "" }
// ******************************************************* // MACHINE GENERATED CODE // DO NOT MODIFY // // Generated on 10/19/2014 09:06:38 // ******************************************************* package com.blastedstudios.freeboot.ai.bt.actions; /** ModelAction class created from MMPM action CooldownEnd. */ public class CooldownEnd extends jbt.model.task.leaf.action.ModelAction { /** * Value of the parameter "identifier" in case its value is specified at * construction time. null otherwise. */ private java.lang.String identifier; /** * Location, in the context, of the parameter "identifier" in case its value * is not specified at construction time. null otherwise. */ private java.lang.String identifierLoc; /** * Constructor. Constructs an instance of CooldownEnd. * * @param identifier * value of the parameter "identifier", or null in case it should * be read from the context. If null, <code>identifierLoc</code> * cannot be null. * @param identifierLoc * in case <code>identifier</code> is null, this variable * represents the place in the context where the parameter's * value will be retrieved from. */ public CooldownEnd(jbt.model.core.ModelTask guard, java.lang.String identifier, java.lang.String identifierLoc) { super(guard); this.identifier = identifier; this.identifierLoc = identifierLoc; } /** * Returns a com.blastedstudios.freeboot.ai.bt.actions.execution.CooldownEnd * task that is able to run this task. */ public jbt.execution.core.ExecutionTask createExecutor( jbt.execution.core.BTExecutor executor, jbt.execution.core.ExecutionTask parent) { return new com.blastedstudios.freeboot.ai.bt.actions.execution.CooldownEnd( this, executor, parent, this.identifier, this.identifierLoc); } }
{ "content_hash": "361f75e36dad58fe5cb3bee5feebcb49", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 77, "avg_line_length": 39.15686274509804, "alnum_prop": 0.6219328993490235, "repo_name": "narfman0/freeboot", "id": "9355ba34a1b129839516076f15cc41f364b8824e", "size": "1997", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/blastedstudios/freeboot/ai/bt/actions/CooldownEnd.java", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "479" }, { "name": "Java", "bytes": "684013" }, { "name": "OpenEdge ABL", "bytes": "31699" }, { "name": "Protocol Buffer", "bytes": "2055" } ], "symlink_target": "" }
package com.bbva.kltt.apirest.generator.java; import com.bbva.kltt.apirest.generator.java.util.ConstantsOutputJava; import com.bbva.kltt.apirest.generator.java.velocity.models.TranslatorGeneratorJavaModels; import com.bbva.kltt.apirest.generator.java.velocity.top.MvnInstallFileLinuxGenerator; import com.bbva.kltt.apirest.generator.java.velocity.top.MvnInstallFileWindowsGenerator; import com.bbva.kltt.apirest.generator.java.velocity.top.TopLevelJavaPOM; import com.bbva.kltt.apirest.core.generator.GeneratorGlobalLanguage; import com.bbva.kltt.apirest.core.generator.IGenerator; import com.bbva.kltt.apirest.core.generator.ITranslatorGenerator; import com.bbva.kltt.apirest.core.launcher.GenerationParameters; import com.bbva.kltt.apirest.core.parsed_info.ParsedInfoHandler; import com.bbva.kltt.apirest.core.util.APIRestGeneratorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; /** * ------------------------------------------------ * @author Francisco Manuel Benitez Chico * ------------------------------------------------ */ public abstract class GeneratorGlobalJava extends GeneratorGlobalLanguage { /** * Logger of the class */ private static final Logger LOGGER = LoggerFactory.getLogger(GeneratorGlobalJava.class); /** * Directory for the top level */ private File topLevelDir; /** * Constructs a new global generator for Java * * @param genParams with the parameters for the generation for java * @param parsedInfoHandler with the parsed information handler to generate from * @param generationPackage with the generation package */ public GeneratorGlobalJava(final GenerationParameters genParams, final ParsedInfoHandler parsedInfoHandler, final String generationPackage) { super(genParams, parsedInfoHandler, generationPackage); } /** * @param translatorType with the translator type * @throws APIRestGeneratorException with an occurred exception */ public void generate(final String translatorType) throws APIRestGeneratorException { // Verify the restrictions this.verifyRestrictions(); // Initialize file directories this.initializeFileDirectories(); // Generate the top level POM file this.generateTopLevelPom(translatorType); // Generate the Java Models - Project this.generateModelsProject(); // Generate the Java Rest interface - Project this.generateRestInterfaceProject(); // Generate the Java Rest interface - Project this.generateRestImplementationProject(); // Generate the Java example project this.generateExampleProject(); // Finally, generates the top level POM file this.generateMavenInstallFile(translatorType); } /** * Verify the restrictions * * @throws APIRestGeneratorException with an occurred exception */ protected abstract void verifyRestrictions() throws APIRestGeneratorException; /** * Initialize the file references and directory references for the rest of the generation. * It will also create the required directory paths for the generation. * * @throws APIRestGeneratorException exception thrown if there is any problem. */ private void initializeFileDirectories() throws APIRestGeneratorException { GeneratorGlobalJava.LOGGER.info("Initializing files and creating directories with base directory {}", this.getGenerationParams().getCodeGenOutputDirectory()); // Generate the directory paths final String topLevelPomPath = this.getGenerationParams().getCodeGenOutputDirectory(); // Create the file objects this.topLevelDir = new File(topLevelPomPath); } /** * Generate the top level pom that contains the model, controllers, etc. * * @param translatorType with the translator type * @throws APIRestGeneratorException with an occurred exception */ private void generateTopLevelPom(final String translatorType) throws APIRestGeneratorException { GeneratorGlobalJava.LOGGER.info("Generating pom for top level..."); final IGenerator generator = this.generateInstanceTopLevelPOM(this.topLevelDir, translatorType, this.getGenerationParams(), this.getParsedInfoHandler(), ConstantsOutputJava.TOP_LEVEL_POM_FILE_NAME); generator.generate(); GeneratorGlobalJava.LOGGER.info("Generated pom for top level..."); } /** * @param topLevelPomDir with the top level POM directory * @param translatorName with the translator name * @param genParams with the generation parameters * @param parsedInfoHandler with the parsed info handler * @param pomFileName with the POM file name * @return a new Top Level POM Generator instance */ protected IGenerator generateInstanceTopLevelPOM(final File topLevelPomDir, final String translatorName, final GenerationParameters genParams, final ParsedInfoHandler parsedInfoHandler, final String pomFileName) { return new TopLevelJavaPOM(topLevelPomDir, translatorName, genParams, parsedInfoHandler, pomFileName) ; } /** * Generate the models project * * @throws APIRestGeneratorException with an occurred exception */ private void generateModelsProject() throws APIRestGeneratorException { final ITranslatorGenerator javaModelsGenerator = new TranslatorGeneratorJavaModels(this.getGenerationParams(), this.getParsedInfoHandler(), this.getGenerationPackage()); javaModelsGenerator.generate(); } /** * Generate the rest interface project * * @throws APIRestGeneratorException with an occurred exception */ protected abstract void generateRestInterfaceProject() throws APIRestGeneratorException; /** * Generate the rest implementation project * * @throws APIRestGeneratorException with an occurred exception */ protected abstract void generateRestImplementationProject() throws APIRestGeneratorException; /** * Generate the Java Example Project * * @throws APIRestGeneratorException with an occurred exception */ protected abstract void generateExampleProject() throws APIRestGeneratorException; /** * Generate the MAVEN install file to be used by the developer * * @param translatorType with the translator type * @throws APIRestGeneratorException with an occurred exception */ private void generateMavenInstallFile(final String translatorType) throws APIRestGeneratorException { GeneratorGlobalJava.LOGGER.info("Generating maven install file..."); final IGenerator generatorWindows = new MvnInstallFileWindowsGenerator(this.topLevelDir, translatorType, this.getGenerationParams(), this.getParsedInfoHandler()) ; generatorWindows.generate(); final IGenerator generatorLinux = new MvnInstallFileLinuxGenerator(this.topLevelDir, translatorType, this.getGenerationParams(), this.getParsedInfoHandler()) ; generatorLinux.generate(); GeneratorGlobalJava.LOGGER.info("Generated maven install file..."); } }
{ "content_hash": "a40624f01cbe312bc8b24c83ec734c42", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 120, "avg_line_length": 42.76470588235294, "alnum_prop": 0.6052269601100413, "repo_name": "BBVA-CIB/APIRestGenerator", "id": "6cae0fd8133eaa643af69fc27cc03ae1938c9dfd", "size": "9548", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generator.java/src/main/java/com/bbva/kltt/apirest/generator/java/GeneratorGlobalJava.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "229" }, { "name": "CSS", "bytes": "504463" }, { "name": "HTML", "bytes": "9688" }, { "name": "Java", "bytes": "1098093" }, { "name": "JavaScript", "bytes": "136674" }, { "name": "Shell", "bytes": "253" } ], "symlink_target": "" }
/** * Split array into a fixed number of segments. */ /** * Description * @method split * @param {} array * @param {} segments * @return results */ function split(array, segments) { segments = segments || 2; var results = []; if (array == null) { return results; } var minLength = Math.floor(array.length / segments), remainder = array.length % segments, i = 0, len = array.length, segmentIndex = 0, segmentLength; while (i < len) { segmentLength = minLength; if (segmentIndex < remainder) { segmentLength++; } results.push(array.slice(i, i + segmentLength)); segmentIndex++; i += segmentLength; } return results; } module.exports = split;
{ "content_hash": "72147f653de08e34a6d95b3951f2a971", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 60, "avg_line_length": 22.19047619047619, "alnum_prop": 0.47317596566523606, "repo_name": "benjaminhorner/codebutler", "id": "c2b59678e23770986e4838b4cc2cbfb845a97919", "size": "932", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/bower/node_modules/bower-registry-client/node_modules/bower-config/node_modules/mout/array/split.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59795" }, { "name": "CoffeeScript", "bytes": "45462" }, { "name": "JavaScript", "bytes": "131513" }, { "name": "Shell", "bytes": "56" } ], "symlink_target": "" }
sap.ui.define([ "jquery.sap.global", "jquery.sap.strings", "sap/ui/core/format/DateFormat", "sap/ui/model/FormatException", "sap/ui/model/ParseException", "sap/ui/model/ValidateException", "sap/ui/model/odata/type/ODataType" ], function(jQuery, jQuerySapStrings, DateFormat, FormatException, ParseException, ValidateException, ODataType) { "use strict"; /* * Returns the locale-dependent error message. * * @param {sap.ui.model.odata.type.TimeOfDay} oType * The type * @returns {string} * The locale-dependent error message */ function getErrorMessage(oType) { return sap.ui.getCore().getLibraryResourceBundle().getText("EnterTime", [oType.formatValue("13:47:26", "string")]); } /* * Returns the DateFormat instance for OData values in the model. Creates it lazily. * * @param {sap.ui.model.odata.type.TimeOfDay} oType * The type * @returns {sap.ui.core.format.DateFormat} * The DateFormat */ function getModelFormat(oType) { var sPattern = "HH:mm:ss", iPrecision; if (!oType.oModelFormat) { iPrecision = oType.oConstraints && oType.oConstraints.precision; if (iPrecision) { sPattern += "." + jQuery.sap.padRight("", "S", iPrecision); } oType.oModelFormat = DateFormat.getTimeInstance({pattern : sPattern, strictParsing : true, UTC : true}); } return oType.oModelFormat; } /* * Returns the DateFormat instance for values displayed on the UI. Creates it lazily. * * @param {sap.ui.model.odata.type.TimeOfDay} oType * The type * @returns {sap.ui.core.format.DateFormat} * The DateFormat */ function getUiFormat(oType) { var oFormatOptions; if (!oType.oUiFormat) { oFormatOptions = jQuery.extend({strictParsing : true}, oType.oFormatOptions); oFormatOptions.UTC = true; // value is always UTC; no overwrite via format options oType.oUiFormat = DateFormat.getTimeInstance(oFormatOptions); } return oType.oUiFormat; } /* * Sets the constraints. Logs a warning and uses the constraint's default value, if an invalid * value is given. * * @param {sap.ui.model.odata.type.TimeOfDay} oType * The type * @param {object} [oConstraints] * The constraints * @param {boolean} [oConstraints.nullable=true] * If <code>true</code>, the value <code>null</code> is valid for this type * @param {number} [oConstraints.precision=0] * The number of decimal places allowed in the seconds portion of a valid value; only * integer values between 0 and 12 are valid. */ function setConstraints(oType, oConstraints) { var vNullable = oConstraints && oConstraints.nullable, vPrecision = oConstraints && oConstraints.precision; oType.oConstraints = undefined; if (vNullable === false) { oType.oConstraints = {nullable : false}; } else if (vNullable !== undefined && vNullable !== true) { jQuery.sap.log.warning("Illegal nullable: " + vNullable, null, oType.getName()); } if (vPrecision === Math.floor(vPrecision) && vPrecision > 0 && vPrecision <= 12) { oType.oConstraints = oType.oConstraints || {}; oType.oConstraints.precision = vPrecision; } else if (vPrecision !== undefined && vPrecision !== 0) { jQuery.sap.log.warning("Illegal precision: " + vPrecision, null, oType.getName()); } } /** * Constructor for an OData primitive type <code>Edm.TimeOfDay</code>. * * @param {object} [oFormatOptions] * Format options as defined in {@link sap.ui.core.format.DateFormat} * @param {object} [oConstraints] * Constraints; {@link #validateValue validateValue} throws an error if any constraint is * violated * @param {boolean} [oConstraints.nullable=true] * If <code>true</code>, the value <code>null</code> is accepted * @param {number} [oConstraints.precision=0] * The number of decimal places allowed in the seconds portion of a valid value; must be an * integer between 0 and 12, otherwise the default value 0 is used. * * @alias sap.ui.model.odata.type.TimeOfDay * @author SAP SE * @class This class represents the OData V4 primitive type {@link * http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part3-csdl/odata-v4.0-errata02-os-part3-csdl-complete.html#_The_edm:Documentation_Element * <code>Edm.TimeOfDay</code>}. * In {@link sap.ui.model.odata.v4.ODataModel} this type is represented as a * <code>string</code>. * @extends sap.ui.model.odata.type.ODataType * @public * @since 1.37.0 * @version ${version} */ var TimeOfDay = ODataType.extend("sap.ui.model.odata.type.TimeOfDay", { constructor : function (oFormatOptions, oConstraints) { ODataType.apply(this, arguments); this.oModelFormat = undefined; this.rTimeOfDay = undefined; this.oUiFormat = undefined; setConstraints(this, oConstraints); this.oFormatOptions = oFormatOptions; } }); /** * Called by the framework when any localization setting is changed. * * @private * @since 1.37.0 */ TimeOfDay.prototype._handleLocalizationChange = function () { this.oUiFormat = null; }; /** * Formats the given value to the given target type. * * @param {string} sValue * The value to be formatted, which is represented as a string in the model * @param {string} sTargetType * The target type, may be "any", "string", or a type with one of these types as its * {@link sap.ui.base.DataType#getPrimitiveType primitive type}. * See {@link sap.ui.model.odata.type} for more information * @returns {string} * The formatted output value in the target type; <code>undefined</code> or <code>null</code> * are formatted to <code>null</code> * @throws {sap.ui.model.FormatException} * If <code>sValue</code> is not a valid OData V4 Edm.TimeOfDay value or if * <code>sTargetType</code> is not supported * * @public * @since 1.37.0 */ TimeOfDay.prototype.formatValue = function(sValue, sTargetType) { var oDate, iIndex; if (sValue === undefined || sValue === null) { return null; } switch (this.getPrimitiveType(sTargetType)) { case "any": return sValue; case "string": iIndex = sValue.indexOf("."); if (iIndex >= 0) { sValue = sValue.slice(0, iIndex + 4); // cut off after milliseconds } oDate = getModelFormat(this).parse(sValue); if (oDate) { return getUiFormat(this).format(oDate); } throw new FormatException("Illegal " + this.getName() + " value: " + sValue); default: throw new FormatException("Don't know how to format " + this.getName() + " to " + sTargetType); } }; /** * Returns the type's name. * * @returns {string} * The type's name * * @public * @since 1.37.0 */ TimeOfDay.prototype.getName = function () { return "sap.ui.model.odata.type.TimeOfDay"; }; /** * Parses the given value, which is expected to be of the given type, to a string with an * OData V4 Edm.TimeOfDay value. * * @param {string} sValue * The value to be parsed, maps <code>""</code> to <code>null</code> * @param {string} sSourceType * The source type (the expected type of <code>sValue</code>), must be "string", or a type * with "string" as its {@link sap.ui.base.DataType#getPrimitiveType primitive type}. * See {@link sap.ui.model.odata.type} for more information. * @returns {string} * The parsed value * @throws {sap.ui.model.ParseException} * If <code>sSourceType</code> is not supported or if the value is invalid and cannot be * parsed * * @public * @since 1.37.0 */ TimeOfDay.prototype.parseValue = function (sValue, sSourceType) { var oDate; if (sValue === "" || sValue === null) { return null; } if (this.getPrimitiveType(sSourceType) !== "string") { throw new ParseException("Don't know how to parse " + this.getName() + " from " + sSourceType); } oDate = getUiFormat(this).parse(sValue); if (!oDate) { throw new ParseException(getErrorMessage(this)); } return getModelFormat(this).format(oDate); }; /** * Validates the given value in model representation and meets the type's constraints. * * @param {string} sValue * The value to be validated * @returns {void} * @throws {sap.ui.model.ValidateException} * If the value is not valid * * @public * @since 1.37.0 */ TimeOfDay.prototype.validateValue = function (sValue) { var iPrecision; if (sValue === null) { if (this.oConstraints && this.oConstraints.nullable === false) { throw new ValidateException(getErrorMessage(this)); } return; } if (!this.rTimeOfDay) { iPrecision = this.oConstraints && this.oConstraints.precision; // @see sap.ui.model.odata._AnnotationHelperExpression this.rTimeOfDay = new RegExp("^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d" + (iPrecision ? "(\\.\\d{1," + iPrecision + "})?" : "") + ")?$"); } if (!this.rTimeOfDay.test(sValue)) { throw new ValidateException("Illegal sap.ui.model.odata.type.TimeOfDay value: " + sValue); } }; return TimeOfDay; });
{ "content_hash": "13e96b50c006d6869a7af5c6c5b5e276", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 160, "avg_line_length": 31.56140350877193, "alnum_prop": 0.671928849360756, "repo_name": "olirogers/openui5", "id": "baa429ea6acd776a75b4126c08936a3bdf039ebc", "size": "9018", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sap.ui.core/src/sap/ui/model/odata/type/TimeOfDay.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3013495" }, { "name": "Gherkin", "bytes": "16431" }, { "name": "HTML", "bytes": "16645544" }, { "name": "Java", "bytes": "82129" }, { "name": "JavaScript", "bytes": "39340810" } ], "symlink_target": "" }
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). ```ts /// <reference types="node" /> import { AbortSignalLike } from '@azure/abort-controller'; import { CommonClientOptions } from '@azure/core-client'; import { PagedAsyncIterableIterator } from '@azure/core-paging'; import { PipelineRequest } from '@azure/core-rest-pipeline'; import { PipelineResponse } from '@azure/core-rest-pipeline'; import { RestError } from '@azure/core-rest-pipeline'; import { ServiceClient } from '@azure/core-client'; import { TokenCredential } from '@azure/core-auth'; // @public export class ConflictError extends Error { constructor(request: PipelineRequest, response: PipelineResponse, serverValue: unknown); readonly request: PipelineRequest; readonly response: PipelineResponse; readonly serverValue: unknown; } // @public export class DatasyncClient { constructor(endpointUrl: string | URL); constructor(endpointUrl: string | URL, clientOptions: DatasyncClientOptions); constructor(endpointUrl: string | URL, credential: TokenCredential); constructor(endpointUrl: string | URL, credential: TokenCredential, clientOptions: DatasyncClientOptions); readonly clientOptions: DatasyncClientOptions; readonly credential?: TokenCredential; readonly endpointUrl: URL; getRemoteTable<T extends DataTransferObject>(tableName: string, tablePath?: string): DatasyncTable<T>; readonly serviceClient: ServiceClient; } // @public export interface DatasyncClientOptions extends CommonClientOptions { apiVersion?: string; scopes?: string | string[]; tablePathResolver?: (tableName: string) => string; // Warning: (ae-forgotten-export) The symbol "JsonReviver" needs to be exported by the entry point index.d.ts tableReviver?: (tableName: string) => JsonReviver | undefined; timeout?: number; } // @public (undocumented) export interface DatasyncTable<T extends DataTransferObject> { createItem(item: T, options?: TableOperationOptions): Promise<T>; deleteItem(item: T | string, options?: TableOperationOptions): Promise<void>; getItem(itemId: string, options?: TableOperationOptions): Promise<T>; getPageOfItems(query?: TableQuery, options?: TableOperationOptions): Promise<Page<Partial<T>>>; listItems(query?: TableQuery, options?: TableOperationOptions): PagedAsyncIterableIterator<Partial<T>, Page<Partial<T>>>; replaceItem(item: T, options?: TableOperationOptions): Promise<T>; updateItem(item: Partial<T>, options?: TableOperationOptions): Promise<T>; } // @public export interface DataTransferObject { deleted?: boolean; id: string; updatedAt?: Date; version?: string; } // @public export class InvalidArgumentError extends Error { constructor(message: string, argumentName: string); readonly argumentName: string; } // @public export interface Page<T> { count?: number; items: Array<Partial<T>>; nextLink?: string; } // @public export class RemoteTable<T extends DataTransferObject> implements DatasyncTable<T> { constructor(serviceClient: ServiceClient, tableName: string, endpoint: URL, clientOptions: DatasyncClientOptions); readonly clientOptions: DatasyncClientOptions; createItem(item: T, options?: TableOperationOptions): Promise<T>; deleteItem(item: T | string, options?: TableOperationOptions): Promise<void>; getItem(itemId: string, options?: TableOperationOptions): Promise<T>; getPageOfItems(query?: TableQuery, options?: TableOperationOptions): Promise<Page<T>>; listItems(query?: TableQuery, options?: TableOperationOptions): PagedAsyncIterableIterator<Partial<T>, Page<T>>; replaceItem(item: T, options?: TableOperationOptions): Promise<T>; reviver?: JsonReviver; readonly serviceClient: ServiceClient; readonly tableEndpoint: string; readonly tableName: string; updateItem(item: Partial<T>, options?: TableOperationOptions): Promise<T>; } export { RestError } // @public export interface TableOperationOptions { abortSignal?: AbortSignalLike; force?: boolean; timeout?: number; } // @public export interface TableQuery { filter?: string; includeCount?: boolean; includeDeletedItems?: boolean; orderBy?: Array<string>; selection?: Array<string>; skip?: number; top?: number; } // (No @packageDocumentation comment for this package) ```
{ "content_hash": "90f8b2bda8abc6d64c4e85b4feb47965", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 125, "avg_line_length": 37.49152542372882, "alnum_prop": 0.7375678119349005, "repo_name": "Azure/azure-mobile-apps", "id": "5045505b725aefbe3f22f4bbf8070204b4f7e54d", "size": "4469", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/typescript/ms-datasync-client/review/ms-datasync-client.api.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2158769" }, { "name": "JavaScript", "bytes": "2149" }, { "name": "PowerShell", "bytes": "443" }, { "name": "TypeScript", "bytes": "128234" } ], "symlink_target": "" }
@import MapKit; @class Postcode; @interface ShowMapViewController : UIViewController <CLLocationManagerDelegate, MKReverseGeocoderDelegate, MKMapViewDelegate> @property (strong, nonatomic) Postcode* detailItem; @property (weak, nonatomic) IBOutlet MKMapView *mapView; @property (nonatomic) CLLocationManager *myLocationManager; @end
{ "content_hash": "75fd17fa030dd5fa8f1cbcbb1a5bfe3f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 125, "avg_line_length": 28.166666666666668, "alnum_prop": 0.8224852071005917, "repo_name": "peterbmarks/liveability", "id": "688fdf4a60e343ec7251c634667e3a8da1954c41", "size": "513", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Liveability/ShowMapViewController.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "189676" }, { "name": "Python", "bytes": "950" } ], "symlink_target": "" }
/* To get this list of colors inject jQuery at http://www.google.com/design/spec/style/color.html#color-color-palette Then, run this script to get the list. (function() { var colors = {}, main = {}; $(".color-group").each(function() { var color = $(this).find(".name").text().trim().toLowerCase().replace(" ", "-"); colors[color] = {}; $(this).find(".color").not(".main-color").each(function() { var shade = $(this).find(".shade").text().trim(), hex = $(this).find(".hex").text().trim(); colors[color][shade] = hex; }); main[color] = color + "-" + $(this).find(".main-color .shade").text().trim(); }); var LESS = ""; $.each(colors, function(name, shades) { LESS += "\n\n"; $.each(shades, function(shade, hex) { LESS += "@" + name + "-" + shade + ": " + hex + ";\n"; }); if (main[name]) { LESS += "@" + name + ": " + main[name] + ";\n"; } }); console.log(LESS); })(); */ /* ANIMATION */ /* SHADOWS */ /* Shadows (from mdl http://www.getmdl.io/) */ body { background-color: #EEEEEE; } body.inverse { background: #333333; } body.inverse, body.inverse .form-control { color: rgba(255,255,255, 0.84); } body.inverse .modal, body.inverse .panel-default, body.inverse .card, body.inverse .modal .form-control, body.inverse .panel-default .form-control, body.inverse .card .form-control { background-color: initial; color: initial; } body, h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4 { font-family: 'Roboto', 'Helvetica', 'Arial', sans-serif; font-weight: 300; } h5, h6 { font-weight: 400; } a, a:hover, a:focus { color: #3949ab; } a .material-icons, a:hover .material-icons, a:focus .material-icons { vertical-align: middle; } .form-horizontal .radio, .form-horizontal .checkbox, .form-horizontal .radio-inline, .form-horizontal .checkbox-inline { padding-top: 0; } .form-horizontal .radio { margin-bottom: 10px; } .form-horizontal label { text-align: right; } .form-horizontal label.control-label { margin: 0; } body .container .well.well-sm, body .container-fluid .well.well-sm { padding: 10px; } body .container .well.well-lg, body .container-fluid .well.well-lg { padding: 26px; } body .container .well, body .container-fluid .well, body .container .jumbotron, body .container-fluid .jumbotron { background-color: #fff; padding: 19px; margin-bottom: 20px; -webkit-box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 2px; border: 0; } body .container .well p, body .container-fluid .well p, body .container .jumbotron p, body .container-fluid .jumbotron p { font-weight: 300; } body .container .well, body .container-fluid .well, body .container .jumbotron, body .container-fluid .jumbotron, body .container .well-default, body .container-fluid .well-default, body .container .jumbotron-default, body .container-fluid .jumbotron-default { background-color: #ffffff; } body .container .well-inverse, body .container-fluid .well-inverse, body .container .jumbotron-inverse, body .container-fluid .jumbotron-inverse { background-color: #3f51b5; } body .container .well-primary, body .container-fluid .well-primary, body .container .jumbotron-primary, body .container-fluid .jumbotron-primary { background-color: #3949ab; } body .container .well-success, body .container-fluid .well-success, body .container .jumbotron-success, body .container-fluid .jumbotron-success { background-color: #43a047; } body .container .well-info, body .container-fluid .well-info, body .container .jumbotron-info, body .container-fluid .jumbotron-info { background-color: #039be5; } body .container .well-warning, body .container-fluid .well-warning, body .container .jumbotron-warning, body .container-fluid .jumbotron-warning { background-color: #ffa000; } body .container .well-danger, body .container-fluid .well-danger, body .container .jumbotron-danger, body .container-fluid .jumbotron-danger { background-color: #e53935; } .btn, .input-group-btn .btn { border: none; border-radius: 2px; position: relative; padding: 8px 30px; margin: 10px 1px; font-size: 14px; font-weight: 500; text-transform: uppercase; letter-spacing: 0; will-change: box-shadow, transform; -webkit-transition: -webkit-box-shadow 0.2s cubic-bezier(0.4, 0, 1, 1), background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1), color 0.2s cubic-bezier(0.4, 0, 0.2, 1); -o-transition: box-shadow 0.2s cubic-bezier(0.4, 0, 1, 1), background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1), color 0.2s cubic-bezier(0.4, 0, 0.2, 1); transition: box-shadow 0.2s cubic-bezier(0.4, 0, 1, 1), background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1), color 0.2s cubic-bezier(0.4, 0, 0.2, 1); outline: 0; cursor: pointer; text-decoration: none; background: transparent; } .btn::-moz-focus-inner, .input-group-btn .btn::-moz-focus-inner { border: 0; } .btn:not(.btn-raised), .input-group-btn .btn:not(.btn-raised) { -webkit-box-shadow: none; box-shadow: none; } .btn:not(.btn-raised), .input-group-btn .btn:not(.btn-raised), .btn:not(.btn-raised).btn-default, .input-group-btn .btn:not(.btn-raised).btn-default { color: rgba(0,0,0, 0.87); } .btn:not(.btn-raised).btn-inverse, .input-group-btn .btn:not(.btn-raised).btn-inverse { color: #3f51b5; } .btn:not(.btn-raised).btn-primary, .input-group-btn .btn:not(.btn-raised).btn-primary { color: #3949ab; } .btn:not(.btn-raised).btn-success, .input-group-btn .btn:not(.btn-raised).btn-success { color: #43a047; } .btn:not(.btn-raised).btn-info, .input-group-btn .btn:not(.btn-raised).btn-info { color: #039be5; } .btn:not(.btn-raised).btn-warning, .input-group-btn .btn:not(.btn-raised).btn-warning { color: #ffa000; } .btn:not(.btn-raised).btn-danger, .input-group-btn .btn:not(.btn-raised).btn-danger { color: #e53935; } .btn:not(.btn-raised):not(.btn-link):hover, .input-group-btn .btn:not(.btn-raised):not(.btn-link):hover, .btn:not(.btn-raised):not(.btn-link):focus, .input-group-btn .btn:not(.btn-raised):not(.btn-link):focus { background-color: rgba(153, 153, 153, 0.2); } .theme-dark .btn:not(.btn-raised):not(.btn-link):hover, .theme-dark .input-group-btn .btn:not(.btn-raised):not(.btn-link):hover, .theme-dark .btn:not(.btn-raised):not(.btn-link):focus, .theme-dark .input-group-btn .btn:not(.btn-raised):not(.btn-link):focus { background-color: rgba(204, 204, 204, 0.15); } .btn.btn-raised, .input-group-btn .btn.btn-raised, .btn.btn-fab, .input-group-btn .btn.btn-fab, .btn-group-raised .btn, .btn-group-raised .input-group-btn .btn, .btn.btn-raised.btn-default, .input-group-btn .btn.btn-raised.btn-default, .btn.btn-fab.btn-default, .input-group-btn .btn.btn-fab.btn-default, .btn-group-raised .btn.btn-default, .btn-group-raised .input-group-btn .btn.btn-default { background-color: #EEEEEE; color: rgba(0,0,0, 0.87); } .btn.btn-raised.btn-inverse, .input-group-btn .btn.btn-raised.btn-inverse, .btn.btn-fab.btn-inverse, .input-group-btn .btn.btn-fab.btn-inverse, .btn-group-raised .btn.btn-inverse, .btn-group-raised .input-group-btn .btn.btn-inverse { background-color: #3f51b5; color: #ffffff; } .btn.btn-raised.btn-primary, .input-group-btn .btn.btn-raised.btn-primary, .btn.btn-fab.btn-primary, .input-group-btn .btn.btn-fab.btn-primary, .btn-group-raised .btn.btn-primary, .btn-group-raised .input-group-btn .btn.btn-primary { background-color: #3949ab; color: rgba(255,255,255, 0.84); } .btn.btn-raised.btn-success, .input-group-btn .btn.btn-raised.btn-success, .btn.btn-fab.btn-success, .input-group-btn .btn.btn-fab.btn-success, .btn-group-raised .btn.btn-success, .btn-group-raised .input-group-btn .btn.btn-success { background-color: #43a047; color: rgba(255,255,255, 0.84); } .btn.btn-raised.btn-info, .input-group-btn .btn.btn-raised.btn-info, .btn.btn-fab.btn-info, .input-group-btn .btn.btn-fab.btn-info, .btn-group-raised .btn.btn-info, .btn-group-raised .input-group-btn .btn.btn-info { background-color: #039be5; color: rgba(255,255,255, 0.84); } .btn.btn-raised.btn-warning, .input-group-btn .btn.btn-raised.btn-warning, .btn.btn-fab.btn-warning, .input-group-btn .btn.btn-fab.btn-warning, .btn-group-raised .btn.btn-warning, .btn-group-raised .input-group-btn .btn.btn-warning { background-color: #ffa000; color: rgba(255,255,255, 0.84); } .btn.btn-raised.btn-danger, .input-group-btn .btn.btn-raised.btn-danger, .btn.btn-fab.btn-danger, .input-group-btn .btn.btn-fab.btn-danger, .btn-group-raised .btn.btn-danger, .btn-group-raised .input-group-btn .btn.btn-danger { background-color: #e53935; color: rgba(255,255,255, 0.84); } .btn.btn-raised:not(.btn-link), .input-group-btn .btn.btn-raised:not(.btn-link), .btn-group-raised .btn:not(.btn-link), .btn-group-raised .input-group-btn .btn:not(.btn-link) { -webkit-box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12); box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12); } .btn.btn-raised:not(.btn-link):hover, .input-group-btn .btn.btn-raised:not(.btn-link):hover, .btn-group-raised .btn:not(.btn-link):hover, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover, .btn.btn-raised:not(.btn-link):focus, .input-group-btn .btn.btn-raised:not(.btn-link):focus, .btn-group-raised .btn:not(.btn-link):focus, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus, .btn.btn-raised:not(.btn-link).active, .input-group-btn .btn.btn-raised:not(.btn-link).active, .btn-group-raised .btn:not(.btn-link).active, .btn-group-raised .input-group-btn .btn:not(.btn-link).active, .btn.btn-raised:not(.btn-link):active, .input-group-btn .btn.btn-raised:not(.btn-link):active, .btn-group-raised .btn:not(.btn-link):active, .btn-group-raised .input-group-btn .btn:not(.btn-link):active { outline: 0; } .btn.btn-raised:not(.btn-link):hover, .input-group-btn .btn.btn-raised:not(.btn-link):hover, .btn-group-raised .btn:not(.btn-link):hover, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover, .btn.btn-raised:not(.btn-link):focus, .input-group-btn .btn.btn-raised:not(.btn-link):focus, .btn-group-raised .btn:not(.btn-link):focus, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus, .btn.btn-raised:not(.btn-link).active, .input-group-btn .btn.btn-raised:not(.btn-link).active, .btn-group-raised .btn:not(.btn-link).active, .btn-group-raised .input-group-btn .btn:not(.btn-link).active, .btn.btn-raised:not(.btn-link):active, .input-group-btn .btn.btn-raised:not(.btn-link):active, .btn-group-raised .btn:not(.btn-link):active, .btn-group-raised .input-group-btn .btn:not(.btn-link):active, .btn.btn-raised:not(.btn-link):hover.btn-default, .input-group-btn .btn.btn-raised:not(.btn-link):hover.btn-default, .btn-group-raised .btn:not(.btn-link):hover.btn-default, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover.btn-default, .btn.btn-raised:not(.btn-link):focus.btn-default, .input-group-btn .btn.btn-raised:not(.btn-link):focus.btn-default, .btn-group-raised .btn:not(.btn-link):focus.btn-default, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.btn-default, .btn.btn-raised:not(.btn-link).active.btn-default, .input-group-btn .btn.btn-raised:not(.btn-link).active.btn-default, .btn-group-raised .btn:not(.btn-link).active.btn-default, .btn-group-raised .input-group-btn .btn:not(.btn-link).active.btn-default, .btn.btn-raised:not(.btn-link):active.btn-default, .input-group-btn .btn.btn-raised:not(.btn-link):active.btn-default, .btn-group-raised .btn:not(.btn-link):active.btn-default, .btn-group-raised .input-group-btn .btn:not(.btn-link):active.btn-default { background-color: #e4e4e4; } .btn.btn-raised:not(.btn-link):hover.btn-inverse, .input-group-btn .btn.btn-raised:not(.btn-link):hover.btn-inverse, .btn-group-raised .btn:not(.btn-link):hover.btn-inverse, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover.btn-inverse, .btn.btn-raised:not(.btn-link):focus.btn-inverse, .input-group-btn .btn.btn-raised:not(.btn-link):focus.btn-inverse, .btn-group-raised .btn:not(.btn-link):focus.btn-inverse, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.btn-inverse, .btn.btn-raised:not(.btn-link).active.btn-inverse, .input-group-btn .btn.btn-raised:not(.btn-link).active.btn-inverse, .btn-group-raised .btn:not(.btn-link).active.btn-inverse, .btn-group-raised .input-group-btn .btn:not(.btn-link).active.btn-inverse, .btn.btn-raised:not(.btn-link):active.btn-inverse, .input-group-btn .btn.btn-raised:not(.btn-link):active.btn-inverse, .btn-group-raised .btn:not(.btn-link):active.btn-inverse, .btn-group-raised .input-group-btn .btn:not(.btn-link):active.btn-inverse { background-color: #495bc0; } .btn.btn-raised:not(.btn-link):hover.btn-primary, .input-group-btn .btn.btn-raised:not(.btn-link):hover.btn-primary, .btn-group-raised .btn:not(.btn-link):hover.btn-primary, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover.btn-primary, .btn.btn-raised:not(.btn-link):focus.btn-primary, .input-group-btn .btn.btn-raised:not(.btn-link):focus.btn-primary, .btn-group-raised .btn:not(.btn-link):focus.btn-primary, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.btn-primary, .btn.btn-raised:not(.btn-link).active.btn-primary, .input-group-btn .btn.btn-raised:not(.btn-link).active.btn-primary, .btn-group-raised .btn:not(.btn-link).active.btn-primary, .btn-group-raised .input-group-btn .btn:not(.btn-link).active.btn-primary, .btn.btn-raised:not(.btn-link):active.btn-primary, .input-group-btn .btn.btn-raised:not(.btn-link):active.btn-primary, .btn-group-raised .btn:not(.btn-link):active.btn-primary, .btn-group-raised .input-group-btn .btn:not(.btn-link):active.btn-primary { background-color: #3e50ba; } .btn.btn-raised:not(.btn-link):hover.btn-success, .input-group-btn .btn.btn-raised:not(.btn-link):hover.btn-success, .btn-group-raised .btn:not(.btn-link):hover.btn-success, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover.btn-success, .btn.btn-raised:not(.btn-link):focus.btn-success, .input-group-btn .btn.btn-raised:not(.btn-link):focus.btn-success, .btn-group-raised .btn:not(.btn-link):focus.btn-success, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.btn-success, .btn.btn-raised:not(.btn-link).active.btn-success, .input-group-btn .btn.btn-raised:not(.btn-link).active.btn-success, .btn-group-raised .btn:not(.btn-link).active.btn-success, .btn-group-raised .input-group-btn .btn:not(.btn-link).active.btn-success, .btn.btn-raised:not(.btn-link):active.btn-success, .input-group-btn .btn.btn-raised:not(.btn-link):active.btn-success, .btn-group-raised .btn:not(.btn-link):active.btn-success, .btn-group-raised .input-group-btn .btn:not(.btn-link):active.btn-success { background-color: #49ae4d; } .btn.btn-raised:not(.btn-link):hover.btn-info, .input-group-btn .btn.btn-raised:not(.btn-link):hover.btn-info, .btn-group-raised .btn:not(.btn-link):hover.btn-info, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover.btn-info, .btn.btn-raised:not(.btn-link):focus.btn-info, .input-group-btn .btn.btn-raised:not(.btn-link):focus.btn-info, .btn-group-raised .btn:not(.btn-link):focus.btn-info, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.btn-info, .btn.btn-raised:not(.btn-link).active.btn-info, .input-group-btn .btn.btn-raised:not(.btn-link).active.btn-info, .btn-group-raised .btn:not(.btn-link).active.btn-info, .btn-group-raised .input-group-btn .btn:not(.btn-link).active.btn-info, .btn.btn-raised:not(.btn-link):active.btn-info, .input-group-btn .btn.btn-raised:not(.btn-link):active.btn-info, .btn-group-raised .btn:not(.btn-link):active.btn-info, .btn-group-raised .input-group-btn .btn:not(.btn-link):active.btn-info { background-color: #03a9f9; } .btn.btn-raised:not(.btn-link):hover.btn-warning, .input-group-btn .btn.btn-raised:not(.btn-link):hover.btn-warning, .btn-group-raised .btn:not(.btn-link):hover.btn-warning, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover.btn-warning, .btn.btn-raised:not(.btn-link):focus.btn-warning, .input-group-btn .btn.btn-raised:not(.btn-link):focus.btn-warning, .btn-group-raised .btn:not(.btn-link):focus.btn-warning, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.btn-warning, .btn.btn-raised:not(.btn-link).active.btn-warning, .input-group-btn .btn.btn-raised:not(.btn-link).active.btn-warning, .btn-group-raised .btn:not(.btn-link).active.btn-warning, .btn-group-raised .input-group-btn .btn:not(.btn-link).active.btn-warning, .btn.btn-raised:not(.btn-link):active.btn-warning, .input-group-btn .btn.btn-raised:not(.btn-link):active.btn-warning, .btn-group-raised .btn:not(.btn-link):active.btn-warning, .btn-group-raised .input-group-btn .btn:not(.btn-link):active.btn-warning { background-color: #eb9300; } .btn.btn-raised:not(.btn-link):hover.btn-danger, .input-group-btn .btn.btn-raised:not(.btn-link):hover.btn-danger, .btn-group-raised .btn:not(.btn-link):hover.btn-danger, .btn-group-raised .input-group-btn .btn:not(.btn-link):hover.btn-danger, .btn.btn-raised:not(.btn-link):focus.btn-danger, .input-group-btn .btn.btn-raised:not(.btn-link):focus.btn-danger, .btn-group-raised .btn:not(.btn-link):focus.btn-danger, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.btn-danger, .btn.btn-raised:not(.btn-link).active.btn-danger, .input-group-btn .btn.btn-raised:not(.btn-link).active.btn-danger, .btn-group-raised .btn:not(.btn-link).active.btn-danger, .btn-group-raised .input-group-btn .btn:not(.btn-link).active.btn-danger, .btn.btn-raised:not(.btn-link):active.btn-danger, .input-group-btn .btn.btn-raised:not(.btn-link):active.btn-danger, .btn-group-raised .btn:not(.btn-link):active.btn-danger, .btn-group-raised .input-group-btn .btn:not(.btn-link):active.btn-danger { background-color: #e74b47; } .btn.btn-raised:not(.btn-link).active, .input-group-btn .btn.btn-raised:not(.btn-link).active, .btn-group-raised .btn:not(.btn-link).active, .btn-group-raised .input-group-btn .btn:not(.btn-link).active, .btn.btn-raised:not(.btn-link):active, .input-group-btn .btn.btn-raised:not(.btn-link):active, .btn-group-raised .btn:not(.btn-link):active, .btn-group-raised .input-group-btn .btn:not(.btn-link):active, .btn.btn-raised:not(.btn-link).active:hover, .input-group-btn .btn.btn-raised:not(.btn-link).active:hover, .btn-group-raised .btn:not(.btn-link).active:hover, .btn-group-raised .input-group-btn .btn:not(.btn-link).active:hover, .btn.btn-raised:not(.btn-link):active:hover, .input-group-btn .btn.btn-raised:not(.btn-link):active:hover, .btn-group-raised .btn:not(.btn-link):active:hover, .btn-group-raised .input-group-btn .btn:not(.btn-link):active:hover { -webkit-box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.2); box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.2); } .btn.btn-raised:not(.btn-link):focus, .input-group-btn .btn.btn-raised:not(.btn-link):focus, .btn-group-raised .btn:not(.btn-link):focus, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus, .btn.btn-raised:not(.btn-link):focus.active, .input-group-btn .btn.btn-raised:not(.btn-link):focus.active, .btn-group-raised .btn:not(.btn-link):focus.active, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.active, .btn.btn-raised:not(.btn-link):focus:active, .input-group-btn .btn.btn-raised:not(.btn-link):focus:active, .btn-group-raised .btn:not(.btn-link):focus:active, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus:active, .btn.btn-raised:not(.btn-link):focus:hover, .input-group-btn .btn.btn-raised:not(.btn-link):focus:hover, .btn-group-raised .btn:not(.btn-link):focus:hover, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus:hover, .btn.btn-raised:not(.btn-link):focus.active:hover, .input-group-btn .btn.btn-raised:not(.btn-link):focus.active:hover, .btn-group-raised .btn:not(.btn-link):focus.active:hover, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus.active:hover, .btn.btn-raised:not(.btn-link):focus:active:hover, .input-group-btn .btn.btn-raised:not(.btn-link):focus:active:hover, .btn-group-raised .btn:not(.btn-link):focus:active:hover, .btn-group-raised .input-group-btn .btn:not(.btn-link):focus:active:hover { -webkit-box-shadow: 0 0 8px rgba(0, 0, 0, 0.18), 0 8px 16px rgba(0, 0, 0, 0.36); box-shadow: 0 0 8px rgba(0, 0, 0, 0.18), 0 8px 16px rgba(0, 0, 0, 0.36); } .btn.btn-fab, .input-group-btn .btn.btn-fab { border-radius: 50%; font-size: 24px; height: 56px; margin: auto; min-width: 56px; width: 56px; padding: 0; overflow: hidden; -webkit-box-shadow: 0 1px 1.5px 0 rgba(0, 0, 0, 0.12), 0 1px 1px 0 rgba(0, 0, 0, 0.24); box-shadow: 0 1px 1.5px 0 rgba(0, 0, 0, 0.12), 0 1px 1px 0 rgba(0, 0, 0, 0.24); position: relative; line-height: normal; } .btn.btn-fab .ripple-container, .input-group-btn .btn.btn-fab .ripple-container { border-radius: 50%; } .btn.btn-fab.btn-fab-mini, .input-group-btn .btn.btn-fab.btn-fab-mini, .btn-group-sm .btn.btn-fab, .btn-group-sm .input-group-btn .btn.btn-fab { height: 40px; min-width: 40px; width: 40px; } .btn.btn-fab.btn-fab-mini.material-icons, .input-group-btn .btn.btn-fab.btn-fab-mini.material-icons, .btn-group-sm .btn.btn-fab.material-icons, .btn-group-sm .input-group-btn .btn.btn-fab.material-icons { top: 0px; left: 0px; } .btn.btn-fab i.material-icons, .input-group-btn .btn.btn-fab i.material-icons { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-12px, -12px); -ms-transform: translate(-12px, -12px); -o-transform: translate(-12px, -12px); transform: translate(-12px, -12px); line-height: 24px; width: 24px; } .btn i.material-icons, .input-group-btn .btn i.material-icons { vertical-align: middle; } .btn.btn-lg, .input-group-btn .btn.btn-lg, .btn-group-lg .btn, .btn-group-lg .input-group-btn .btn { font-size: 16px; } .btn.btn-sm, .input-group-btn .btn.btn-sm, .btn-group-sm .btn, .btn-group-sm .input-group-btn .btn { padding: 5px 20px; font-size: 12px; } .btn.btn-xs, .input-group-btn .btn.btn-xs, .btn-group-xs .btn, .btn-group-xs .input-group-btn .btn { padding: 4px 15px; font-size: 10px; } fieldset[disabled][disabled] .btn, fieldset[disabled][disabled] .input-group-btn .btn, fieldset[disabled][disabled] .btn-group, fieldset[disabled][disabled] .btn-group-vertical, .btn.disabled, .input-group-btn .btn.disabled, .btn-group.disabled, .btn-group-vertical.disabled, .btn:disabled, .input-group-btn .btn:disabled, .btn-group:disabled, .btn-group-vertical:disabled, .btn[disabled][disabled], .input-group-btn .btn[disabled][disabled], .btn-group[disabled][disabled], .btn-group-vertical[disabled][disabled] { color: rgba(0, 0, 0, 0.26); background: transparent; } .theme-dark fieldset[disabled][disabled] .btn, .theme-dark fieldset[disabled][disabled] .input-group-btn .btn, .theme-dark fieldset[disabled][disabled] .btn-group, .theme-dark fieldset[disabled][disabled] .btn-group-vertical, .theme-dark .btn.disabled, .theme-dark .input-group-btn .btn.disabled, .theme-dark .btn-group.disabled, .theme-dark .btn-group-vertical.disabled, .theme-dark .btn:disabled, .theme-dark .input-group-btn .btn:disabled, .theme-dark .btn-group:disabled, .theme-dark .btn-group-vertical:disabled, .theme-dark .btn[disabled][disabled], .theme-dark .input-group-btn .btn[disabled][disabled], .theme-dark .btn-group[disabled][disabled], .theme-dark .btn-group-vertical[disabled][disabled] { color: rgba(255, 255, 255, 0.3); } fieldset[disabled][disabled] .btn.btn-raised, fieldset[disabled][disabled] .input-group-btn .btn.btn-raised, fieldset[disabled][disabled] .btn-group.btn-raised, fieldset[disabled][disabled] .btn-group-vertical.btn-raised, .btn.disabled.btn-raised, .input-group-btn .btn.disabled.btn-raised, .btn-group.disabled.btn-raised, .btn-group-vertical.disabled.btn-raised, .btn:disabled.btn-raised, .input-group-btn .btn:disabled.btn-raised, .btn-group:disabled.btn-raised, .btn-group-vertical:disabled.btn-raised, .btn[disabled][disabled].btn-raised, .input-group-btn .btn[disabled][disabled].btn-raised, .btn-group[disabled][disabled].btn-raised, .btn-group-vertical[disabled][disabled].btn-raised, fieldset[disabled][disabled] .btn.btn-group-raised, fieldset[disabled][disabled] .input-group-btn .btn.btn-group-raised, fieldset[disabled][disabled] .btn-group.btn-group-raised, fieldset[disabled][disabled] .btn-group-vertical.btn-group-raised, .btn.disabled.btn-group-raised, .input-group-btn .btn.disabled.btn-group-raised, .btn-group.disabled.btn-group-raised, .btn-group-vertical.disabled.btn-group-raised, .btn:disabled.btn-group-raised, .input-group-btn .btn:disabled.btn-group-raised, .btn-group:disabled.btn-group-raised, .btn-group-vertical:disabled.btn-group-raised, .btn[disabled][disabled].btn-group-raised, .input-group-btn .btn[disabled][disabled].btn-group-raised, .btn-group[disabled][disabled].btn-group-raised, .btn-group-vertical[disabled][disabled].btn-group-raised, fieldset[disabled][disabled] .btn.btn-raised.active, fieldset[disabled][disabled] .input-group-btn .btn.btn-raised.active, fieldset[disabled][disabled] .btn-group.btn-raised.active, fieldset[disabled][disabled] .btn-group-vertical.btn-raised.active, .btn.disabled.btn-raised.active, .input-group-btn .btn.disabled.btn-raised.active, .btn-group.disabled.btn-raised.active, .btn-group-vertical.disabled.btn-raised.active, .btn:disabled.btn-raised.active, .input-group-btn .btn:disabled.btn-raised.active, .btn-group:disabled.btn-raised.active, .btn-group-vertical:disabled.btn-raised.active, .btn[disabled][disabled].btn-raised.active, .input-group-btn .btn[disabled][disabled].btn-raised.active, .btn-group[disabled][disabled].btn-raised.active, .btn-group-vertical[disabled][disabled].btn-raised.active, fieldset[disabled][disabled] .btn.btn-group-raised.active, fieldset[disabled][disabled] .input-group-btn .btn.btn-group-raised.active, fieldset[disabled][disabled] .btn-group.btn-group-raised.active, fieldset[disabled][disabled] .btn-group-vertical.btn-group-raised.active, .btn.disabled.btn-group-raised.active, .input-group-btn .btn.disabled.btn-group-raised.active, .btn-group.disabled.btn-group-raised.active, .btn-group-vertical.disabled.btn-group-raised.active, .btn:disabled.btn-group-raised.active, .input-group-btn .btn:disabled.btn-group-raised.active, .btn-group:disabled.btn-group-raised.active, .btn-group-vertical:disabled.btn-group-raised.active, .btn[disabled][disabled].btn-group-raised.active, .input-group-btn .btn[disabled][disabled].btn-group-raised.active, .btn-group[disabled][disabled].btn-group-raised.active, .btn-group-vertical[disabled][disabled].btn-group-raised.active, fieldset[disabled][disabled] .btn.btn-raised:active, fieldset[disabled][disabled] .input-group-btn .btn.btn-raised:active, fieldset[disabled][disabled] .btn-group.btn-raised:active, fieldset[disabled][disabled] .btn-group-vertical.btn-raised:active, .btn.disabled.btn-raised:active, .input-group-btn .btn.disabled.btn-raised:active, .btn-group.disabled.btn-raised:active, .btn-group-vertical.disabled.btn-raised:active, .btn:disabled.btn-raised:active, .input-group-btn .btn:disabled.btn-raised:active, .btn-group:disabled.btn-raised:active, .btn-group-vertical:disabled.btn-raised:active, .btn[disabled][disabled].btn-raised:active, .input-group-btn .btn[disabled][disabled].btn-raised:active, .btn-group[disabled][disabled].btn-raised:active, .btn-group-vertical[disabled][disabled].btn-raised:active, fieldset[disabled][disabled] .btn.btn-group-raised:active, fieldset[disabled][disabled] .input-group-btn .btn.btn-group-raised:active, fieldset[disabled][disabled] .btn-group.btn-group-raised:active, fieldset[disabled][disabled] .btn-group-vertical.btn-group-raised:active, .btn.disabled.btn-group-raised:active, .input-group-btn .btn.disabled.btn-group-raised:active, .btn-group.disabled.btn-group-raised:active, .btn-group-vertical.disabled.btn-group-raised:active, .btn:disabled.btn-group-raised:active, .input-group-btn .btn:disabled.btn-group-raised:active, .btn-group:disabled.btn-group-raised:active, .btn-group-vertical:disabled.btn-group-raised:active, .btn[disabled][disabled].btn-group-raised:active, .input-group-btn .btn[disabled][disabled].btn-group-raised:active, .btn-group[disabled][disabled].btn-group-raised:active, .btn-group-vertical[disabled][disabled].btn-group-raised:active, fieldset[disabled][disabled] .btn.btn-raised:focus:not(:active), fieldset[disabled][disabled] .input-group-btn .btn.btn-raised:focus:not(:active), fieldset[disabled][disabled] .btn-group.btn-raised:focus:not(:active), fieldset[disabled][disabled] .btn-group-vertical.btn-raised:focus:not(:active), .btn.disabled.btn-raised:focus:not(:active), .input-group-btn .btn.disabled.btn-raised:focus:not(:active), .btn-group.disabled.btn-raised:focus:not(:active), .btn-group-vertical.disabled.btn-raised:focus:not(:active), .btn:disabled.btn-raised:focus:not(:active), .input-group-btn .btn:disabled.btn-raised:focus:not(:active), .btn-group:disabled.btn-raised:focus:not(:active), .btn-group-vertical:disabled.btn-raised:focus:not(:active), .btn[disabled][disabled].btn-raised:focus:not(:active), .input-group-btn .btn[disabled][disabled].btn-raised:focus:not(:active), .btn-group[disabled][disabled].btn-raised:focus:not(:active), .btn-group-vertical[disabled][disabled].btn-raised:focus:not(:active), fieldset[disabled][disabled] .btn.btn-group-raised:focus:not(:active), fieldset[disabled][disabled] .input-group-btn .btn.btn-group-raised:focus:not(:active), fieldset[disabled][disabled] .btn-group.btn-group-raised:focus:not(:active), fieldset[disabled][disabled] .btn-group-vertical.btn-group-raised:focus:not(:active), .btn.disabled.btn-group-raised:focus:not(:active), .input-group-btn .btn.disabled.btn-group-raised:focus:not(:active), .btn-group.disabled.btn-group-raised:focus:not(:active), .btn-group-vertical.disabled.btn-group-raised:focus:not(:active), .btn:disabled.btn-group-raised:focus:not(:active), .input-group-btn .btn:disabled.btn-group-raised:focus:not(:active), .btn-group:disabled.btn-group-raised:focus:not(:active), .btn-group-vertical:disabled.btn-group-raised:focus:not(:active), .btn[disabled][disabled].btn-group-raised:focus:not(:active), .input-group-btn .btn[disabled][disabled].btn-group-raised:focus:not(:active), .btn-group[disabled][disabled].btn-group-raised:focus:not(:active), .btn-group-vertical[disabled][disabled].btn-group-raised:focus:not(:active) { -webkit-box-shadow: none; box-shadow: none; } .btn-group, .btn-group-vertical { position: relative; margin: 10px 1px; } .btn-group.open > .dropdown-toggle.btn, .btn-group-vertical.open > .dropdown-toggle.btn, .btn-group.open > .dropdown-toggle.btn.btn-default, .btn-group-vertical.open > .dropdown-toggle.btn.btn-default { background-color: #EEEEEE; } .btn-group.open > .dropdown-toggle.btn.btn-inverse, .btn-group-vertical.open > .dropdown-toggle.btn.btn-inverse { background-color: #3f51b5; } .btn-group.open > .dropdown-toggle.btn.btn-primary, .btn-group-vertical.open > .dropdown-toggle.btn.btn-primary { background-color: #3949ab; } .btn-group.open > .dropdown-toggle.btn.btn-success, .btn-group-vertical.open > .dropdown-toggle.btn.btn-success { background-color: #43a047; } .btn-group.open > .dropdown-toggle.btn.btn-info, .btn-group-vertical.open > .dropdown-toggle.btn.btn-info { background-color: #039be5; } .btn-group.open > .dropdown-toggle.btn.btn-warning, .btn-group-vertical.open > .dropdown-toggle.btn.btn-warning { background-color: #ffa000; } .btn-group.open > .dropdown-toggle.btn.btn-danger, .btn-group-vertical.open > .dropdown-toggle.btn.btn-danger { background-color: #e53935; } .btn-group .dropdown-menu, .btn-group-vertical .dropdown-menu { border-radius: 0 0 2px 2px; } .btn-group.btn-group-raised, .btn-group-vertical.btn-group-raised { -webkit-box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12); box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12); } .btn-group .btn + .btn, .btn-group-vertical .btn + .btn, .btn-group .btn, .btn-group-vertical .btn, .btn-group .btn:active, .btn-group-vertical .btn:active, .btn-group .btn-group, .btn-group-vertical .btn-group { margin: 0; } .checkbox label, label.checkbox-inline { cursor: pointer; padding-left: 0; color: rgba(0,0,0, 0.26); } .form-group.is-focused .checkbox label, .form-group.is-focused label.checkbox-inline { color: rgba(0,0,0, 0.26); } .form-group.is-focused .checkbox label:hover, .form-group.is-focused label.checkbox-inline:hover, .form-group.is-focused .checkbox label:focus, .form-group.is-focused label.checkbox-inline:focus { color: rgba(0,0,0, .54); } fieldset[disabled] .form-group.is-focused .checkbox label, fieldset[disabled] .form-group.is-focused label.checkbox-inline { color: rgba(0,0,0, 0.26); } .checkbox input[type=checkbox], label.checkbox-inline input[type=checkbox] { opacity: 0; position: absolute; margin: 0; z-index: -1; width: 0; height: 0; overflow: hidden; left: 0; pointer-events: none; } .checkbox .checkbox-material, label.checkbox-inline .checkbox-material { vertical-align: middle; position: relative; top: 3px; } .checkbox .checkbox-material:before, label.checkbox-inline .checkbox-material:before { display: block; position: absolute; top: -5px; left: 0; content: ""; background-color: rgba(0, 0, 0, 0.84); height: 20px; width: 20px; border-radius: 100%; z-index: 1; opacity: 0; margin: 0; -webkit-transform: scale3d(2.3, 2.3, 1); transform: scale3d(2.3, 2.3, 1); } .checkbox .checkbox-material .check, label.checkbox-inline .checkbox-material .check { position: relative; display: inline-block; width: 20px; height: 20px; border: 2px solid rgba(0,0,0, .54); border-radius: 2px; overflow: hidden; z-index: 1; } .checkbox .checkbox-material .check:before, label.checkbox-inline .checkbox-material .check:before { position: absolute; content: ""; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); -o-transform: rotate(45deg); transform: rotate(45deg); display: block; margin-top: -4px; margin-left: 6px; width: 0; height: 0; -webkit-box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0 inset; box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0 inset; } .checkbox input[type=checkbox]:focus + .checkbox-material .check:after, label.checkbox-inline input[type=checkbox]:focus + .checkbox-material .check:after { opacity: 0.2; } .checkbox input[type=checkbox]:focus:checked + .checkbox-material:before, label.checkbox-inline input[type=checkbox]:focus:checked + .checkbox-material:before { -webkit-animation: rippleOn 500ms; -o-animation: rippleOn 500ms; animation: rippleOn 500ms; } .checkbox input[type=checkbox]:focus:checked + .checkbox-material .check:before, label.checkbox-inline input[type=checkbox]:focus:checked + .checkbox-material .check:before { -webkit-animation: checkbox-on 0.3s forwards; -o-animation: checkbox-on 0.3s forwards; animation: checkbox-on 0.3s forwards; } .checkbox input[type=checkbox]:focus:checked + .checkbox-material .check:after, label.checkbox-inline input[type=checkbox]:focus:checked + .checkbox-material .check:after { -webkit-animation: rippleOn 500ms forwards; -o-animation: rippleOn 500ms forwards; animation: rippleOn 500ms forwards; } .checkbox input[type=checkbox]:focus:not(:checked) + .checkbox-material:before, label.checkbox-inline input[type=checkbox]:focus:not(:checked) + .checkbox-material:before { -webkit-animation: rippleOff 500ms; -o-animation: rippleOff 500ms; animation: rippleOff 500ms; } .checkbox input[type=checkbox]:focus:not(:checked) + .checkbox-material .check:before, label.checkbox-inline input[type=checkbox]:focus:not(:checked) + .checkbox-material .check:before { -webkit-animation: checkbox-off 0.3s forwards; -o-animation: checkbox-off 0.3s forwards; animation: checkbox-off 0.3s forwards; } .checkbox input[type=checkbox]:focus:not(:checked) + .checkbox-material .check:after, label.checkbox-inline input[type=checkbox]:focus:not(:checked) + .checkbox-material .check:after { -webkit-animation: rippleOff 500ms forwards; -o-animation: rippleOff 500ms forwards; animation: rippleOff 500ms forwards; } .checkbox input[type=checkbox]:checked + .checkbox-material .check, label.checkbox-inline input[type=checkbox]:checked + .checkbox-material .check { color: #3949ab; border-color: #3949ab; } .checkbox input[type=checkbox]:checked + .checkbox-material .check:before, label.checkbox-inline input[type=checkbox]:checked + .checkbox-material .check:before { color: #3949ab; -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px; } fieldset[disabled] .checkbox, fieldset[disabled] label.checkbox-inline, fieldset[disabled] .checkbox input[type=checkbox], fieldset[disabled] label.checkbox-inline input[type=checkbox], .checkbox input[type=checkbox][disabled]:not(:checked) ~ .checkbox-material .check:before, label.checkbox-inline input[type=checkbox][disabled]:not(:checked) ~ .checkbox-material .check:before, .checkbox input[type=checkbox][disabled]:not(:checked) ~ .checkbox-material .check, label.checkbox-inline input[type=checkbox][disabled]:not(:checked) ~ .checkbox-material .check, .checkbox input[type=checkbox][disabled] + .circle, label.checkbox-inline input[type=checkbox][disabled] + .circle { opacity: 0.5; } .checkbox input[type=checkbox][disabled] + .checkbox-material .check:after, label.checkbox-inline input[type=checkbox][disabled] + .checkbox-material .check:after { background-color: rgba(0,0,0, 0.87); -webkit-transform: rotate(-45deg); -ms-transform: rotate(-45deg); -o-transform: rotate(-45deg); transform: rotate(-45deg); } @-webkit-keyframes checkbox-on { 0% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px; } 50% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px 2px 0 11px; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px 2px 0 11px; } 100% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px; } } @-o-keyframes checkbox-on { 0% { box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px; } 50% { box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px 2px 0 11px; } 100% { box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px; } } @keyframes checkbox-on { 0% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px; } 50% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px 2px 0 11px; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px 2px 0 11px; } 100% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px; } } @-webkit-keyframes checkbox-off { 0% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; } 25% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; } 50% { -webkit-transform: rotate(45deg); transform: rotate(45deg); margin-top: -4px; margin-left: 6px; width: 0; height: 0; -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px, 0 0 0 0 inset; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px, 0 0 0 0 inset; } 51% { -webkit-transform: rotate(0deg); transform: rotate(0deg); margin-top: -2px; margin-left: -2px; width: 20px; height: 20px; -webkit-box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 10px inset; box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 10px inset; } 100% { -webkit-transform: rotate(0deg); transform: rotate(0deg); margin-top: -2px; margin-left: -2px; width: 20px; height: 20px; -webkit-box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 0 inset; box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 0 inset; } } @-o-keyframes checkbox-off { 0% { box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; } 25% { box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; } 50% { -o-transform: rotate(45deg); transform: rotate(45deg); margin-top: -4px; margin-left: 6px; width: 0; height: 0; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px, 0 0 0 0 inset; } 51% { -o-transform: rotate(0deg); transform: rotate(0deg); margin-top: -2px; margin-left: -2px; width: 20px; height: 20px; box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 10px inset; } 100% { -o-transform: rotate(0deg); transform: rotate(0deg); margin-top: -2px; margin-left: -2px; width: 20px; height: 20px; box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 0 inset; } } @keyframes checkbox-off { 0% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; } 25% { -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 20px -12px 0 11px, 0 0 0 0 inset; } 50% { -webkit-transform: rotate(45deg); -o-transform: rotate(45deg); transform: rotate(45deg); margin-top: -4px; margin-left: 6px; width: 0; height: 0; -webkit-box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px, 0 0 0 0 inset; box-shadow: 0 0 0 10px, 10px -10px 0 10px, 32px 0 0 20px, 0px 32px 0 20px, -5px 5px 0 10px, 15px 2px 0 11px, 0 0 0 0 inset; } 51% { -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); margin-top: -2px; margin-left: -2px; width: 20px; height: 20px; -webkit-box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 10px inset; box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 10px inset; } 100% { -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); margin-top: -2px; margin-left: -2px; width: 20px; height: 20px; -webkit-box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 0 inset; box-shadow: 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0 0 0 0, 0px 0 0 0 inset; } } @-webkit-keyframes rippleOn { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } @-o-keyframes rippleOn { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } @keyframes rippleOn { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } @-webkit-keyframes rippleOff { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } @-o-keyframes rippleOff { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } @keyframes rippleOff { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } .togglebutton { vertical-align: middle; } .togglebutton, .togglebutton label, .togglebutton input, .togglebutton .toggle { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .togglebutton label { cursor: pointer; color: rgba(0,0,0, 0.26); } .form-group.is-focused .togglebutton label { color: rgba(0,0,0, 0.26); } .form-group.is-focused .togglebutton label:hover, .form-group.is-focused .togglebutton label:focus { color: rgba(0,0,0, .54); } fieldset[disabled] .form-group.is-focused .togglebutton label { color: rgba(0,0,0, 0.26); } .togglebutton label input[type=checkbox] { opacity: 0; width: 0; height: 0; } .togglebutton label .toggle { text-align: left; } .togglebutton label .toggle, .togglebutton label input[type=checkbox][disabled] + .toggle { content: ""; display: inline-block; width: 30px; height: 15px; background-color: rgba(80, 80, 80, 0.7); border-radius: 15px; margin-right: 15px; -webkit-transition: background 0.3s ease; -o-transition: background 0.3s ease; transition: background 0.3s ease; vertical-align: middle; } .togglebutton label .toggle:after { content: ""; display: inline-block; width: 20px; height: 20px; background-color: #F1F1F1; border-radius: 20px; position: relative; -webkit-box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4); box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4); left: -5px; top: -2px; -webkit-transition: left 0.3s ease, background 0.3s ease, -webkit-box-shadow 0.1s ease; -o-transition: left 0.3s ease, background 0.3s ease, box-shadow 0.1s ease; transition: left 0.3s ease, background 0.3s ease, box-shadow 0.1s ease; } .togglebutton label input[type=checkbox][disabled] + .toggle:after, .togglebutton label input[type=checkbox][disabled]:checked + .toggle:after { background-color: #BDBDBD; } .togglebutton label input[type=checkbox] + .toggle:active:after, .togglebutton label input[type=checkbox][disabled] + .toggle:active:after { -webkit-box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4), 0 0 0 15px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4), 0 0 0 15px rgba(0, 0, 0, 0.1); } .togglebutton label input[type=checkbox]:checked + .toggle:after { left: 15px; } .togglebutton label input[type=checkbox]:checked + .toggle { background-color: rgba(57, 73, 171, 0.5); } .togglebutton label input[type=checkbox]:checked + .toggle:after { background-color: #3949ab; } .togglebutton label input[type=checkbox]:checked + .toggle:active:after { -webkit-box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4), 0 0 0 15px rgba(57, 73, 171, 0.1); box-shadow: 0 1px 3px 1px rgba(0, 0, 0, 0.4), 0 0 0 15px rgba(57, 73, 171, 0.1); } .radio label, label.radio-inline { cursor: pointer; padding-left: 45px; position: relative; color: rgba(0,0,0, 0.26); } .form-group.is-focused .radio label, .form-group.is-focused label.radio-inline { color: rgba(0,0,0, 0.26); } .form-group.is-focused .radio label:hover, .form-group.is-focused label.radio-inline:hover, .form-group.is-focused .radio label:focus, .form-group.is-focused label.radio-inline:focus { color: rgba(0,0,0, .54); } fieldset[disabled] .form-group.is-focused .radio label, fieldset[disabled] .form-group.is-focused label.radio-inline { color: rgba(0,0,0, 0.26); } .radio span, label.radio-inline span { display: block; position: absolute; left: 10px; top: 2px; -webkit-transition-duration: 0.2s; -o-transition-duration: 0.2s; transition-duration: 0.2s; } .radio .circle, label.radio-inline .circle { border: 2px solid rgba(0,0,0, .54); height: 15px; width: 15px; border-radius: 100%; } .radio .check, label.radio-inline .check { height: 15px; width: 15px; border-radius: 100%; background-color: #3949ab; -webkit-transform: scale3d(0, 0, 0); transform: scale3d(0, 0, 0); } .radio .check:after, label.radio-inline .check:after { display: block; position: absolute; content: ""; background-color: rgba(0,0,0, 0.87); left: -18px; top: -18px; height: 50px; width: 50px; border-radius: 100%; z-index: 1; opacity: 0; margin: 0; -webkit-transform: scale3d(1.5, 1.5, 1); transform: scale3d(1.5, 1.5, 1); } .radio input[type=radio]:focus:not(:checked) ~ .check:after, label.radio-inline input[type=radio]:focus:not(:checked) ~ .check:after { -webkit-animation: rippleOff 500ms; -o-animation: rippleOff 500ms; animation: rippleOff 500ms; } .radio input[type=radio]:focus:checked ~ .check:after, label.radio-inline input[type=radio]:focus:checked ~ .check:after { -webkit-animation: rippleOn 500ms; -o-animation: rippleOn 500ms; animation: rippleOn 500ms; } .radio input[type=radio], label.radio-inline input[type=radio] { opacity: 0; height: 0; width: 0; overflow: hidden; } .radio input[type=radio]:checked ~ .check, label.radio-inline input[type=radio]:checked ~ .check, .radio input[type=radio]:checked ~ .circle, label.radio-inline input[type=radio]:checked ~ .circle { opacity: 1; } .radio input[type=radio]:checked ~ .check, label.radio-inline input[type=radio]:checked ~ .check { background-color: #3949ab; } .radio input[type=radio]:checked ~ .circle, label.radio-inline input[type=radio]:checked ~ .circle { border-color: #3949ab; } .radio input[type=radio]:checked ~ .check, label.radio-inline input[type=radio]:checked ~ .check { -webkit-transform: scale3d(0.55, 0.55, 1); transform: scale3d(0.55, 0.55, 1); } .radio input[type=radio][disabled] ~ .check, label.radio-inline input[type=radio][disabled] ~ .check, .radio input[type=radio][disabled] ~ .circle, label.radio-inline input[type=radio][disabled] ~ .circle { opacity: 0.26; } .radio input[type=radio][disabled] ~ .check, label.radio-inline input[type=radio][disabled] ~ .check { background-color: #000000; } .radio input[type=radio][disabled] ~ .circle, label.radio-inline input[type=radio][disabled] ~ .circle { border-color: #000000; } .theme-dark .radio input[type=radio][disabled] ~ .check, .theme-dark label.radio-inline input[type=radio][disabled] ~ .check, .theme-dark .radio input[type=radio][disabled] ~ .circle, .theme-dark label.radio-inline input[type=radio][disabled] ~ .circle { opacity: 0.3; } .theme-dark .radio input[type=radio][disabled] ~ .check, .theme-dark label.radio-inline input[type=radio][disabled] ~ .check { background-color: #ffffff; } .theme-dark .radio input[type=radio][disabled] ~ .circle, .theme-dark label.radio-inline input[type=radio][disabled] ~ .circle { border-color: #ffffff; } @keyframes rippleOn { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } @keyframes rippleOff { 0% { opacity: 0; } 50% { opacity: 0.2; } 100% { opacity: 0; } } legend { margin-bottom: 22px; font-size: 24px; } output { padding-top: 8px; font-size: 16px; line-height: 1.42857143; } .form-control { height: 38px; padding: 7px 0; font-size: 16px; line-height: 1.42857143; } @media screen and (-webkit-min-device-pixel-ratio: 0) { input[type="date"].form-control, input[type="time"].form-control, input[type="datetime-local"].form-control, input[type="month"].form-control { line-height: 38px; } input[type="date"].input-sm, input[type="time"].input-sm, input[type="datetime-local"].input-sm, input[type="month"].input-sm, .input-group-sm input[type="date"], .input-group-sm input[type="time"], .input-group-sm input[type="datetime-local"], .input-group-sm input[type="month"] { line-height: 24px; } input[type="date"].input-lg, input[type="time"].input-lg, input[type="datetime-local"].input-lg, input[type="month"].input-lg, .input-group-lg input[type="date"], .input-group-lg input[type="time"], .input-group-lg input[type="datetime-local"], .input-group-lg input[type="month"] { line-height: 44px; } } .radio label, .checkbox label { min-height: 22px; } .form-control-static { padding-top: 8px; padding-bottom: 8px; min-height: 38px; } .input-sm .input-sm { height: 24px; padding: 3px 0; font-size: 11px; line-height: 1.5; border-radius: 0; } .input-sm select.input-sm { height: 24px; line-height: 24px; } .input-sm textarea.input-sm, .input-sm select[multiple].input-sm { height: auto; } .form-group-sm .form-control { height: 24px; padding: 3px 0; font-size: 11px; line-height: 1.5; } .form-group-sm select.form-control { height: 24px; line-height: 24px; } .form-group-sm textarea.form-control, .form-group-sm select[multiple].form-control { height: auto; } .form-group-sm .form-control-static { height: 24px; min-height: 33px; padding: 4px 0; font-size: 11px; line-height: 1.5; } .input-lg .input-lg { height: 44px; padding: 9px 0; font-size: 18px; line-height: 1.3333333; border-radius: 0; } .input-lg select.input-lg { height: 44px; line-height: 44px; } .input-lg textarea.input-lg, .input-lg select[multiple].input-lg { height: auto; } .form-group-lg .form-control { height: 44px; padding: 9px 0; font-size: 18px; line-height: 1.3333333; } .form-group-lg select.form-control { height: 44px; line-height: 44px; } .form-group-lg textarea.form-control, .form-group-lg select[multiple].form-control { height: auto; } .form-group-lg .form-control-static { height: 44px; min-height: 40px; padding: 10px 0; font-size: 18px; line-height: 1.3333333; } .form-horizontal .radio, .form-horizontal .checkbox, .form-horizontal .radio-inline, .form-horizontal .checkbox-inline { padding-top: 8px; } .form-horizontal .radio, .form-horizontal .checkbox { min-height: 30px; } @media (min-width: 768px) { .form-horizontal .control-label { padding-top: 8px; } } @media (min-width: 768px) { .form-horizontal .form-group-lg .control-label { padding-top: 12.9999997px; font-size: 18px; } } @media (min-width: 768px) { .form-horizontal .form-group-sm .control-label { padding-top: 4px; font-size: 11px; } } .label { border-radius: 1px; padding: .3em .6em; } .label, .label.label-default { background-color: #9e9e9e; } .label.label-inverse { background-color: #3f51b5; } .label.label-primary { background-color: #3949ab; } .label.label-success { background-color: #43a047; } .label.label-info { background-color: #039be5; } .label.label-warning { background-color: #ffa000; } .label.label-danger { background-color: #e53935; } .form-control, .form-group .form-control { border: 0; background-image: -webkit-gradient(linear, left top, left bottom, from(#3949ab), to(#3949ab)), -webkit-gradient(linear, left top, left bottom, from(#D2D2D2), to(#D2D2D2)); background-image: -webkit-linear-gradient(#3949ab, #3949ab), -webkit-linear-gradient(#D2D2D2, #D2D2D2); background-image: -o-linear-gradient(#3949ab, #3949ab), -o-linear-gradient(#D2D2D2, #D2D2D2); background-image: linear-gradient(#3949ab, #3949ab), linear-gradient(#D2D2D2, #D2D2D2); -webkit-background-size: 0 2px, 100% 1px; background-size: 0 2px, 100% 1px; background-repeat: no-repeat; background-position: center bottom, center 99%; background-color: rgba(0, 0, 0, 0); -webkit-transition: background 0s ease-out; -o-transition: background 0s ease-out; transition: background 0s ease-out; float: none; -webkit-box-shadow: none; box-shadow: none; border-radius: 0; } .form-control::-moz-placeholder, .form-group .form-control::-moz-placeholder { color: #BDBDBD; font-weight: 400; } .form-control:-ms-input-placeholder, .form-group .form-control:-ms-input-placeholder { color: #BDBDBD; font-weight: 400; } .form-control::-webkit-input-placeholder, .form-group .form-control::-webkit-input-placeholder { color: #BDBDBD; font-weight: 400; } .form-control[readonly], .form-group .form-control[readonly], .form-control[disabled], .form-group .form-control[disabled], fieldset[disabled] .form-control, fieldset[disabled] .form-group .form-control { background-color: rgba(0, 0, 0, 0); } .form-control[disabled], .form-group .form-control[disabled], fieldset[disabled] .form-control, fieldset[disabled] .form-group .form-control { background-image: none; border-bottom: 1px dotted #D2D2D2; } .form-group { position: relative; } .form-group.label-static label.control-label, .form-group.label-placeholder label.control-label, .form-group.label-floating label.control-label { position: absolute; pointer-events: none; -webkit-transition: 0.3s ease all; -o-transition: 0.3s ease all; transition: 0.3s ease all; } .form-group.label-floating label.control-label { will-change: left, top, contents; } .form-group.label-placeholder:not(.is-empty) label.control-label { display: none; } .form-group .help-block { position: absolute; display: none; } .form-group.is-focused .form-control { outline: none; background-image: -webkit-gradient(linear, left top, left bottom, from(#3949ab), to(#3949ab)), -webkit-gradient(linear, left top, left bottom, from(#D2D2D2), to(#D2D2D2)); background-image: -webkit-linear-gradient(#3949ab, #3949ab), -webkit-linear-gradient(#D2D2D2, #D2D2D2); background-image: -o-linear-gradient(#3949ab, #3949ab), -o-linear-gradient(#D2D2D2, #D2D2D2); background-image: linear-gradient(#3949ab, #3949ab), linear-gradient(#D2D2D2, #D2D2D2); -webkit-background-size: 100% 2px, 100% 1px; background-size: 100% 2px, 100% 1px; -webkit-box-shadow: none; box-shadow: none; -webkit-transition-duration: 0.3s; -o-transition-duration: 0.3s; transition-duration: 0.3s; } .form-group.is-focused .form-control .material-input:after { background-color: #3949ab; } .form-group.is-focused label, .form-group.is-focused label.control-label { color: #3949ab; } .form-group.is-focused.label-placeholder label, .form-group.is-focused.label-placeholder label.control-label { color: #BDBDBD; } .form-group.is-focused .help-block { display: block; } .form-group.has-warning .form-control { -webkit-box-shadow: none; box-shadow: none; } .form-group.has-warning.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(#ffa000), to(#ffa000)), -webkit-gradient(linear, left top, left bottom, from(#D2D2D2), to(#D2D2D2)); background-image: -webkit-linear-gradient(#ffa000, #ffa000), -webkit-linear-gradient(#D2D2D2, #D2D2D2); background-image: -o-linear-gradient(#ffa000, #ffa000), -o-linear-gradient(#D2D2D2, #D2D2D2); background-image: linear-gradient(#ffa000, #ffa000), linear-gradient(#D2D2D2, #D2D2D2); } .form-group.has-warning label.control-label, .form-group.has-warning .help-block { color: #ffa000; } .form-group.has-error .form-control { -webkit-box-shadow: none; box-shadow: none; } .form-group.has-error.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(#e53935), to(#e53935)), -webkit-gradient(linear, left top, left bottom, from(#D2D2D2), to(#D2D2D2)); background-image: -webkit-linear-gradient(#e53935, #e53935), -webkit-linear-gradient(#D2D2D2, #D2D2D2); background-image: -o-linear-gradient(#e53935, #e53935), -o-linear-gradient(#D2D2D2, #D2D2D2); background-image: linear-gradient(#e53935, #e53935), linear-gradient(#D2D2D2, #D2D2D2); } .form-group.has-error label.control-label, .form-group.has-error .help-block { color: #e53935; } .form-group.has-success .form-control { -webkit-box-shadow: none; box-shadow: none; } .form-group.has-success.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(#43a047), to(#43a047)), -webkit-gradient(linear, left top, left bottom, from(#D2D2D2), to(#D2D2D2)); background-image: -webkit-linear-gradient(#43a047, #43a047), -webkit-linear-gradient(#D2D2D2, #D2D2D2); background-image: -o-linear-gradient(#43a047, #43a047), -o-linear-gradient(#D2D2D2, #D2D2D2); background-image: linear-gradient(#43a047, #43a047), linear-gradient(#D2D2D2, #D2D2D2); } .form-group.has-success label.control-label, .form-group.has-success .help-block { color: #43a047; } .form-group.has-info .form-control { -webkit-box-shadow: none; box-shadow: none; } .form-group.has-info.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(#039be5), to(#039be5)), -webkit-gradient(linear, left top, left bottom, from(#D2D2D2), to(#D2D2D2)); background-image: -webkit-linear-gradient(#039be5, #039be5), -webkit-linear-gradient(#D2D2D2, #D2D2D2); background-image: -o-linear-gradient(#039be5, #039be5), -o-linear-gradient(#D2D2D2, #D2D2D2); background-image: linear-gradient(#039be5, #039be5), linear-gradient(#D2D2D2, #D2D2D2); } .form-group.has-info label.control-label, .form-group.has-info .help-block { color: #039be5; } .form-group textarea { resize: none; } .form-group textarea ~ .form-control-highlight { margin-top: -11px; } .form-group select { -webkit-appearance: none; -moz-appearance: none; appearance: none; } .form-group select ~ .material-input:after { display: none; } .form-control { margin-bottom: 7px; } .form-control::-moz-placeholder { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } .form-control:-ms-input-placeholder { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } .form-control::-webkit-input-placeholder { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } .checkbox label, .radio label, label { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } label.control-label { font-size: 12px; line-height: 1.07142857; font-weight: 400; margin: 16px 0 0 0; } .help-block { margin-top: 0; font-size: 12px; } .form-group { padding-bottom: 7px; margin: 28px 0 0 0; } .form-group .form-control { margin-bottom: 7px; } .form-group .form-control::-moz-placeholder { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } .form-group .form-control:-ms-input-placeholder { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } .form-group .form-control::-webkit-input-placeholder { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } .form-group .checkbox label, .form-group .radio label, .form-group label { font-size: 16px; line-height: 1.42857143; color: #BDBDBD; font-weight: 400; } .form-group label.control-label { font-size: 12px; line-height: 1.07142857; font-weight: 400; margin: 16px 0 0 0; } .form-group .help-block { margin-top: 0; font-size: 12px; } .form-group.label-floating label.control-label, .form-group.label-placeholder label.control-label { top: -7px; font-size: 16px; line-height: 1.42857143; } .form-group.label-static label.control-label, .form-group.label-floating.is-focused label.control-label, .form-group.label-floating:not(.is-empty) label.control-label { top: -30px; left: 0; font-size: 12px; line-height: 1.07142857; } .form-group.label-floating input.form-control:-webkit-autofill ~ label.control-label label.control-label { top: -30px; left: 0; font-size: 12px; line-height: 1.07142857; } .form-group.form-group-sm { padding-bottom: 3px; margin: 21px 0 0 0; } .form-group.form-group-sm .form-control { margin-bottom: 3px; } .form-group.form-group-sm .form-control::-moz-placeholder { font-size: 11px; line-height: 1.5; color: #BDBDBD; font-weight: 400; } .form-group.form-group-sm .form-control:-ms-input-placeholder { font-size: 11px; line-height: 1.5; color: #BDBDBD; font-weight: 400; } .form-group.form-group-sm .form-control::-webkit-input-placeholder { font-size: 11px; line-height: 1.5; color: #BDBDBD; font-weight: 400; } .form-group.form-group-sm .checkbox label, .form-group.form-group-sm .radio label, .form-group.form-group-sm label { font-size: 11px; line-height: 1.5; color: #BDBDBD; font-weight: 400; } .form-group.form-group-sm label.control-label { font-size: 9px; line-height: 1.125; font-weight: 400; margin: 16px 0 0 0; } .form-group.form-group-sm .help-block { margin-top: 0; font-size: 9px; } .form-group.form-group-sm.label-floating label.control-label, .form-group.form-group-sm.label-placeholder label.control-label { top: -11px; font-size: 11px; line-height: 1.5; } .form-group.form-group-sm.label-static label.control-label, .form-group.form-group-sm.label-floating.is-focused label.control-label, .form-group.form-group-sm.label-floating:not(.is-empty) label.control-label { top: -25px; left: 0; font-size: 9px; line-height: 1.125; } .form-group.form-group-sm.label-floating input.form-control:-webkit-autofill ~ label.control-label label.control-label { top: -25px; left: 0; font-size: 9px; line-height: 1.125; } .form-group.form-group-lg { padding-bottom: 9px; margin: 30px 0 0 0; } .form-group.form-group-lg .form-control { margin-bottom: 9px; } .form-group.form-group-lg .form-control::-moz-placeholder { font-size: 18px; line-height: 1.3333333; color: #BDBDBD; font-weight: 400; } .form-group.form-group-lg .form-control:-ms-input-placeholder { font-size: 18px; line-height: 1.3333333; color: #BDBDBD; font-weight: 400; } .form-group.form-group-lg .form-control::-webkit-input-placeholder { font-size: 18px; line-height: 1.3333333; color: #BDBDBD; font-weight: 400; } .form-group.form-group-lg .checkbox label, .form-group.form-group-lg .radio label, .form-group.form-group-lg label { font-size: 18px; line-height: 1.3333333; color: #BDBDBD; font-weight: 400; } .form-group.form-group-lg label.control-label { font-size: 14px; line-height: 0.99999998; font-weight: 400; margin: 16px 0 0 0; } .form-group.form-group-lg .help-block { margin-top: 0; font-size: 14px; } .form-group.form-group-lg.label-floating label.control-label, .form-group.form-group-lg.label-placeholder label.control-label { top: -5px; font-size: 18px; line-height: 1.3333333; } .form-group.form-group-lg.label-static label.control-label, .form-group.form-group-lg.label-floating.is-focused label.control-label, .form-group.form-group-lg.label-floating:not(.is-empty) label.control-label { top: -32px; left: 0; font-size: 14px; line-height: 0.99999998; } .form-group.form-group-lg.label-floating input.form-control:-webkit-autofill ~ label.control-label label.control-label { top: -32px; left: 0; font-size: 14px; line-height: 0.99999998; } select.form-control { border: 0; -webkit-box-shadow: none; box-shadow: none; border-radius: 0; } .form-group.is-focused select.form-control { -webkit-box-shadow: none; box-shadow: none; border-color: #D2D2D2; } select.form-control[multiple], .form-group.is-focused select.form-control[multiple] { height: 85px; } .input-group-btn .btn { margin: 0 0 7px 0; } .form-group.form-group-sm .input-group-btn .btn { margin: 0 0 3px 0; } .form-group.form-group-lg .input-group-btn .btn { margin: 0 0 9px 0; } .input-group .input-group-btn { padding: 0 12px; } .input-group .input-group-addon { border: 0; background: transparent; } .form-group input[type=file] { opacity: 0; position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100%; height: 100%; z-index: 100; } legend { border-bottom: 0; } .list-group { border-radius: 0; } .list-group .list-group-item { background-color: transparent; overflow: hidden; border: 0; border-radius: 0; padding: 0 16px; } .list-group .list-group-item.baseline { border-bottom: 1px solid #cecece; } .list-group .list-group-item.baseline:last-child { border-bottom: none; } .list-group .list-group-item .row-picture, .list-group .list-group-item .row-action-primary { display: inline-block; padding-right: 16px; } .list-group .list-group-item .row-picture img, .list-group .list-group-item .row-action-primary img, .list-group .list-group-item .row-picture i, .list-group .list-group-item .row-action-primary i, .list-group .list-group-item .row-picture label, .list-group .list-group-item .row-action-primary label { display: block; width: 56px; height: 56px; } .list-group .list-group-item .row-picture img, .list-group .list-group-item .row-action-primary img { background: rgba(0, 0, 0, 0.1); padding: 1px; } .list-group .list-group-item .row-picture img.circle, .list-group .list-group-item .row-action-primary img.circle { border-radius: 100%; } .list-group .list-group-item .row-picture i, .list-group .list-group-item .row-action-primary i { background: rgba(0, 0, 0, 0.25); border-radius: 100%; text-align: center; line-height: 56px; font-size: 20px; color: white; } .list-group .list-group-item .row-picture label, .list-group .list-group-item .row-action-primary label { margin-left: 7px; margin-right: -7px; margin-top: 5px; margin-bottom: -5px; } .list-group .list-group-item .row-picture label .checkbox-material, .list-group .list-group-item .row-action-primary label .checkbox-material { left: -10px; } .list-group .list-group-item .row-content { display: inline-block; width: -webkit-calc(100% - 92px); width: calc(100% - 92px); min-height: 66px; } .list-group .list-group-item .row-content .action-secondary { position: absolute; right: 16px; top: 16px; } .list-group .list-group-item .row-content .action-secondary i { font-size: 20px; color: rgba(0, 0, 0, 0.25); cursor: pointer; } .list-group .list-group-item .row-content .action-secondary ~ * { max-width: -webkit-calc(100% - 30px); max-width: calc(100% - 30px); } .list-group .list-group-item .row-content .least-content { position: absolute; right: 16px; top: 0; color: rgba(0, 0, 0, 0.54); font-size: 14px; } .list-group .list-group-item .list-group-item-heading { color: rgba(0, 0, 0, 0.77); font-size: 20px; line-height: 29px; } .list-group .list-group-item.active:hover, .list-group .list-group-item.active:focus { background: rgba(0, 0, 0, 0.15); outline: 10px solid rgba(0, 0, 0, 0.15); } .list-group .list-group-item.active .list-group-item-heading, .list-group .list-group-item.active .list-group-item-text { color: rgba(0,0,0, 0.87); } .list-group .list-group-separator { clear: both; overflow: hidden; margin-top: 10px; margin-bottom: 10px; } .list-group .list-group-separator:before { content: ""; width: -webkit-calc(100% - 90px); width: calc(100% - 90px); border-bottom: 1px solid rgba(0, 0, 0, 0.1); float: right; } .list-group.list-group-no-icon .list-group-item .row-content { width: 100%; } .list-group.list-group-no-icon .list-group-separator:before { width: 100%; } .navbar { background-color: #3949ab; border: 0; border-radius: 0; } .navbar .navbar-brand { position: relative; height: 60px; line-height: 30px; color: inherit; } .navbar .navbar-brand:hover, .navbar .navbar-brand:focus { color: inherit; background-color: transparent; } .navbar .navbar-text { color: inherit; margin-top: 20px; margin-bottom: 20px; } .navbar .navbar-nav > li > a { color: inherit; padding-top: 20px; padding-bottom: 20px; } .navbar .navbar-nav > li > a:hover, .navbar .navbar-nav > li > a:focus { color: inherit; background-color: rgba(255, 255, 255, 0.05); } .navbar .navbar-nav > .active > a, .navbar .navbar-nav > .active > a:hover, .navbar .navbar-nav > .active > a:focus { color: inherit; background-color: rgba(255, 255, 255, 0.1); } .navbar .navbar-nav > .disabled > a, .navbar .navbar-nav > .disabled > a:hover, .navbar .navbar-nav > .disabled > a:focus { color: inherit; background-color: transparent; opacity: 0.9; } .navbar .navbar-toggle { border: 0; } .navbar .navbar-toggle:hover, .navbar .navbar-toggle:focus { background-color: transparent; } .navbar .navbar-toggle .icon-bar { background-color: inherit; border: 1px solid; } .navbar .navbar-default .navbar-toggle, .navbar .navbar-inverse .navbar-toggle { border-color: transparent; } .navbar .navbar-collapse, .navbar .navbar-form { border-color: rgba(0, 0, 0, 0.1); } .navbar .navbar-nav > .open > a, .navbar .navbar-nav > .open > a:hover, .navbar .navbar-nav > .open > a:focus { background-color: transparent; color: inherit; } @media (max-width: 767px) { .navbar .navbar-nav .navbar-text { color: inherit; margin-top: 15px; margin-bottom: 15px; } .navbar .navbar-nav .dropdown .dropdown-toggle .caret { display: none; } .navbar .navbar-nav .dropdown .dropdown-toggle:after { content: 'keyboard_arrow_right'; font-family: 'Material Icons'; font-size: 1.5em; float: right; -webkit-font-feature-settings: 'liga'; -moz-font-feature-settings: 'liga'; font-feature-settings: 'liga'; /* Support for IE. */ } .navbar .navbar-nav .dropdown .dropdown-menu { margin-left: 20px; } .navbar .navbar-nav .dropdown.open .dropdown-toggle:after { content: 'keyboard_arrow_down'; } .navbar .navbar-nav .dropdown.open .dropdown-menu > .dropdown-header { border: 0; color: inherit; } .navbar .navbar-nav .dropdown.open .dropdown-menu .divider { border-bottom: 1px solid; opacity: 0.08; } .navbar .navbar-nav .dropdown.open .dropdown-menu > li > a { color: inherit; font-size: inherit; } .navbar .navbar-nav .dropdown.open .dropdown-menu > li > a:hover, .navbar .navbar-nav .dropdown.open .dropdown-menu > li > a:focus { color: inherit; background-color: transparent; } .navbar .navbar-nav .dropdown.open .dropdown-menu > .active > a, .navbar .navbar-nav .dropdown.open .dropdown-menu > .active > a:hover, .navbar .navbar-nav .dropdown.open .dropdown-menu > .active > a:focus { color: inherit; background-color: transparent; } .navbar .navbar-nav .dropdown.open .dropdown-menu > .disabled > a, .navbar .navbar-nav .dropdown.open .dropdown-menu > .disabled > a:hover, .navbar .navbar-nav .dropdown.open .dropdown-menu > .disabled > a:focus { color: inherit; background-color: transparent; } } .navbar .navbar-link { color: inherit; } .navbar .navbar-link:hover { color: inherit; } .navbar .btn-link { color: inherit; } .navbar .btn-link:hover, .navbar .btn-link:focus { color: inherit; } .navbar .btn-link[disabled]:hover, fieldset[disabled] .navbar .btn-link:hover, .navbar .btn-link[disabled]:focus, fieldset[disabled] .navbar .btn-link:focus { color: inherit; } .navbar .navbar-form { margin-top: 16px; } .navbar .navbar-form .form-group { margin: 0; padding: 0; } .navbar .navbar-form .form-group .material-input:before, .navbar .navbar-form .form-group.is-focused .material-input:after { background-color: inherit; } .navbar .navbar-form .form-group .form-control, .navbar .navbar-form .form-control { border-color: inherit; color: inherit; padding: 0; margin: 0; margin-top: 4px; height: 22px; font-size: 14px; line-height: 1.42857143; } @media (max-width: 768px) { .navbar .navbar-form { margin: 8px auto; } } .navbar, .navbar.navbar-default { background-color: #3949ab; color: rgba(255,255,255, 0.84); } .navbar .navbar-form input.form-control::-moz-placeholder, .navbar.navbar-default .navbar-form input.form-control::-moz-placeholder, .navbar .navbar-form .form-group input.form-control::-moz-placeholder, .navbar.navbar-default .navbar-form .form-group input.form-control::-moz-placeholder { color: rgba(255,255,255, 0.84); } .navbar .navbar-form input.form-control:-ms-input-placeholder, .navbar.navbar-default .navbar-form input.form-control:-ms-input-placeholder, .navbar .navbar-form .form-group input.form-control:-ms-input-placeholder, .navbar.navbar-default .navbar-form .form-group input.form-control:-ms-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar .navbar-form input.form-control::-webkit-input-placeholder, .navbar.navbar-default .navbar-form input.form-control::-webkit-input-placeholder, .navbar .navbar-form .form-group input.form-control::-webkit-input-placeholder, .navbar.navbar-default .navbar-form .form-group input.form-control::-webkit-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar .navbar-form .form-group.is-focused .form-control, .navbar.navbar-default .navbar-form .form-group.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))), -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))); background-image: -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); } .navbar .navbar-form .form-group.label-floating label.control-label, .navbar.navbar-default .navbar-form .form-group.label-floating label.control-label, .navbar .navbar-form .form-group.label-placeholder label.control-label, .navbar.navbar-default .navbar-form .form-group.label-placeholder label.control-label { color: rgba(255,255,255, 0.84); text-overflow: ellipsis; overflow: hidden; white-space: nowrap; opacity: 0.87; font-size: 0.8em; } .navbar .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar.navbar-default .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label, .navbar.navbar-default .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label { top: -10px; font-size: 0.9em; } .navbar .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-default .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-default .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-default .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label, .navbar.navbar-default .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -26px; } @media (max-width: 1200px) { .navbar .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-default .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-default .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-default .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label, .navbar.navbar-default .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -23px; line-height: 1.4em; font-size: 10px; } } .navbar .dropdown-menu, .navbar.navbar-default .dropdown-menu { border-radius: 2px; } @media (max-width: 767px) { .navbar .dropdown-menu .dropdown-header, .navbar.navbar-default .dropdown-menu .dropdown-header { background-color: #3f51be; } } .navbar .dropdown-menu li > a, .navbar.navbar-default .dropdown-menu li > a { font-size: 16px; padding: 13px 16px; } .navbar .dropdown-menu li > a:hover, .navbar.navbar-default .dropdown-menu li > a:hover, .navbar .dropdown-menu li > a:focus, .navbar.navbar-default .dropdown-menu li > a:focus { color: #3949ab; background-color: #eeeeee; } .navbar .dropdown-menu .active > a, .navbar.navbar-default .dropdown-menu .active > a { background-color: #3949ab; color: rgba(255,255,255, 0.84); } .navbar .dropdown-menu .active > a:hover, .navbar.navbar-default .dropdown-menu .active > a:hover, .navbar .dropdown-menu .active > a:focus, .navbar.navbar-default .dropdown-menu .active > a:focus { color: rgba(255,255,255, 0.84); } .navbar.navbar-inverse { background-color: #3f51b5; color: #ffffff; } .navbar.navbar-inverse .navbar-form input.form-control::-moz-placeholder, .navbar.navbar-inverse .navbar-form .form-group input.form-control::-moz-placeholder { color: #ffffff; } .navbar.navbar-inverse .navbar-form input.form-control:-ms-input-placeholder, .navbar.navbar-inverse .navbar-form .form-group input.form-control:-ms-input-placeholder { color: #ffffff; } .navbar.navbar-inverse .navbar-form input.form-control::-webkit-input-placeholder, .navbar.navbar-inverse .navbar-form .form-group input.form-control::-webkit-input-placeholder { color: #ffffff; } .navbar.navbar-inverse .navbar-form .form-group.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#ffffff)), -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#ffffff)); background-image: -webkit-linear-gradient(#ffffff, #ffffff), -webkit-linear-gradient(#ffffff, #ffffff); background-image: -o-linear-gradient(#ffffff, #ffffff), -o-linear-gradient(#ffffff, #ffffff); background-image: linear-gradient(#ffffff, #ffffff), linear-gradient(#ffffff, #ffffff); } .navbar.navbar-inverse .navbar-form .form-group.label-floating label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-placeholder label.control-label { color: #ffffff; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; opacity: 0.87; font-size: 0.8em; } .navbar.navbar-inverse .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label { top: -10px; font-size: 0.9em; } .navbar.navbar-inverse .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -26px; } @media (max-width: 1200px) { .navbar.navbar-inverse .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-inverse .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -23px; line-height: 1.4em; font-size: 10px; } } .navbar.navbar-inverse .dropdown-menu { border-radius: 2px; } @media (max-width: 767px) { .navbar.navbar-inverse .dropdown-menu .dropdown-header { background-color: #4d5ec1; } } .navbar.navbar-inverse .dropdown-menu li > a { font-size: 16px; padding: 13px 16px; } .navbar.navbar-inverse .dropdown-menu li > a:hover, .navbar.navbar-inverse .dropdown-menu li > a:focus { color: #3f51b5; background-color: #eeeeee; } .navbar.navbar-inverse .dropdown-menu .active > a { background-color: #3f51b5; color: #ffffff; } .navbar.navbar-inverse .dropdown-menu .active > a:hover, .navbar.navbar-inverse .dropdown-menu .active > a:focus { color: #ffffff; } .navbar.navbar-primary { background-color: #3949ab; color: rgba(255,255,255, 0.84); } .navbar.navbar-primary .navbar-form input.form-control::-moz-placeholder, .navbar.navbar-primary .navbar-form .form-group input.form-control::-moz-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-primary .navbar-form input.form-control:-ms-input-placeholder, .navbar.navbar-primary .navbar-form .form-group input.form-control:-ms-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-primary .navbar-form input.form-control::-webkit-input-placeholder, .navbar.navbar-primary .navbar-form .form-group input.form-control::-webkit-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-primary .navbar-form .form-group.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))), -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))); background-image: -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); } .navbar.navbar-primary .navbar-form .form-group.label-floating label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-placeholder label.control-label { color: rgba(255,255,255, 0.84); text-overflow: ellipsis; overflow: hidden; white-space: nowrap; opacity: 0.87; font-size: 0.8em; } .navbar.navbar-primary .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label { top: -10px; font-size: 0.9em; } .navbar.navbar-primary .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -26px; } @media (max-width: 1200px) { .navbar.navbar-primary .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-primary .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -23px; line-height: 1.4em; font-size: 10px; } } .navbar.navbar-primary .dropdown-menu { border-radius: 2px; } @media (max-width: 767px) { .navbar.navbar-primary .dropdown-menu .dropdown-header { background-color: #3f51be; } } .navbar.navbar-primary .dropdown-menu li > a { font-size: 16px; padding: 13px 16px; } .navbar.navbar-primary .dropdown-menu li > a:hover, .navbar.navbar-primary .dropdown-menu li > a:focus { color: #3949ab; background-color: #eeeeee; } .navbar.navbar-primary .dropdown-menu .active > a { background-color: #3949ab; color: rgba(255,255,255, 0.84); } .navbar.navbar-primary .dropdown-menu .active > a:hover, .navbar.navbar-primary .dropdown-menu .active > a:focus { color: rgba(255,255,255, 0.84); } .navbar.navbar-success { background-color: #43a047; color: rgba(255,255,255, 0.84); } .navbar.navbar-success .navbar-form input.form-control::-moz-placeholder, .navbar.navbar-success .navbar-form .form-group input.form-control::-moz-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-success .navbar-form input.form-control:-ms-input-placeholder, .navbar.navbar-success .navbar-form .form-group input.form-control:-ms-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-success .navbar-form input.form-control::-webkit-input-placeholder, .navbar.navbar-success .navbar-form .form-group input.form-control::-webkit-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-success .navbar-form .form-group.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))), -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))); background-image: -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); } .navbar.navbar-success .navbar-form .form-group.label-floating label.control-label, .navbar.navbar-success .navbar-form .form-group.label-placeholder label.control-label { color: rgba(255,255,255, 0.84); text-overflow: ellipsis; overflow: hidden; white-space: nowrap; opacity: 0.87; font-size: 0.8em; } .navbar.navbar-success .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar.navbar-success .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label { top: -10px; font-size: 0.9em; } .navbar.navbar-success .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-success .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-success .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-success .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -26px; } @media (max-width: 1200px) { .navbar.navbar-success .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-success .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-success .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-success .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -23px; line-height: 1.4em; font-size: 10px; } } .navbar.navbar-success .dropdown-menu { border-radius: 2px; } @media (max-width: 767px) { .navbar.navbar-success .dropdown-menu .dropdown-header { background-color: #4bb24f; } } .navbar.navbar-success .dropdown-menu li > a { font-size: 16px; padding: 13px 16px; } .navbar.navbar-success .dropdown-menu li > a:hover, .navbar.navbar-success .dropdown-menu li > a:focus { color: #43a047; background-color: #eeeeee; } .navbar.navbar-success .dropdown-menu .active > a { background-color: #43a047; color: rgba(255,255,255, 0.84); } .navbar.navbar-success .dropdown-menu .active > a:hover, .navbar.navbar-success .dropdown-menu .active > a:focus { color: rgba(255,255,255, 0.84); } .navbar.navbar-info { background-color: #039be5; color: rgba(255,255,255, 0.84); } .navbar.navbar-info .navbar-form input.form-control::-moz-placeholder, .navbar.navbar-info .navbar-form .form-group input.form-control::-moz-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-info .navbar-form input.form-control:-ms-input-placeholder, .navbar.navbar-info .navbar-form .form-group input.form-control:-ms-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-info .navbar-form input.form-control::-webkit-input-placeholder, .navbar.navbar-info .navbar-form .form-group input.form-control::-webkit-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-info .navbar-form .form-group.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))), -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))); background-image: -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); } .navbar.navbar-info .navbar-form .form-group.label-floating label.control-label, .navbar.navbar-info .navbar-form .form-group.label-placeholder label.control-label { color: rgba(255,255,255, 0.84); text-overflow: ellipsis; overflow: hidden; white-space: nowrap; opacity: 0.87; font-size: 0.8em; } .navbar.navbar-info .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar.navbar-info .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label { top: -10px; font-size: 0.9em; } .navbar.navbar-info .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-info .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-info .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-info .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -26px; } @media (max-width: 1200px) { .navbar.navbar-info .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-info .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-info .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-info .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -23px; line-height: 1.4em; font-size: 10px; } } .navbar.navbar-info .dropdown-menu { border-radius: 2px; } @media (max-width: 767px) { .navbar.navbar-info .dropdown-menu .dropdown-header { background-color: #06abfc; } } .navbar.navbar-info .dropdown-menu li > a { font-size: 16px; padding: 13px 16px; } .navbar.navbar-info .dropdown-menu li > a:hover, .navbar.navbar-info .dropdown-menu li > a:focus { color: #039be5; background-color: #eeeeee; } .navbar.navbar-info .dropdown-menu .active > a { background-color: #039be5; color: rgba(255,255,255, 0.84); } .navbar.navbar-info .dropdown-menu .active > a:hover, .navbar.navbar-info .dropdown-menu .active > a:focus { color: rgba(255,255,255, 0.84); } .navbar.navbar-warning { background-color: #ffa000; color: rgba(255,255,255, 0.84); } .navbar.navbar-warning .navbar-form input.form-control::-moz-placeholder, .navbar.navbar-warning .navbar-form .form-group input.form-control::-moz-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-warning .navbar-form input.form-control:-ms-input-placeholder, .navbar.navbar-warning .navbar-form .form-group input.form-control:-ms-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-warning .navbar-form input.form-control::-webkit-input-placeholder, .navbar.navbar-warning .navbar-form .form-group input.form-control::-webkit-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-warning .navbar-form .form-group.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))), -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))); background-image: -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); } .navbar.navbar-warning .navbar-form .form-group.label-floating label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-placeholder label.control-label { color: rgba(255,255,255, 0.84); text-overflow: ellipsis; overflow: hidden; white-space: nowrap; opacity: 0.87; font-size: 0.8em; } .navbar.navbar-warning .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label { top: -10px; font-size: 0.9em; } .navbar.navbar-warning .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -26px; } @media (max-width: 1200px) { .navbar.navbar-warning .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-warning .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -23px; line-height: 1.4em; font-size: 10px; } } .navbar.navbar-warning .dropdown-menu { border-radius: 2px; } @media (max-width: 767px) { .navbar.navbar-warning .dropdown-menu .dropdown-header { background-color: #ffaa1a; } } .navbar.navbar-warning .dropdown-menu li > a { font-size: 16px; padding: 13px 16px; } .navbar.navbar-warning .dropdown-menu li > a:hover, .navbar.navbar-warning .dropdown-menu li > a:focus { color: #ffa000; background-color: #eeeeee; } .navbar.navbar-warning .dropdown-menu .active > a { background-color: #ffa000; color: rgba(255,255,255, 0.84); } .navbar.navbar-warning .dropdown-menu .active > a:hover, .navbar.navbar-warning .dropdown-menu .active > a:focus { color: rgba(255,255,255, 0.84); } .navbar.navbar-danger { background-color: #e53935; color: rgba(255,255,255, 0.84); } .navbar.navbar-danger .navbar-form input.form-control::-moz-placeholder, .navbar.navbar-danger .navbar-form .form-group input.form-control::-moz-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-danger .navbar-form input.form-control:-ms-input-placeholder, .navbar.navbar-danger .navbar-form .form-group input.form-control:-ms-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-danger .navbar-form input.form-control::-webkit-input-placeholder, .navbar.navbar-danger .navbar-form .form-group input.form-control::-webkit-input-placeholder { color: rgba(255,255,255, 0.84); } .navbar.navbar-danger .navbar-form .form-group.is-focused .form-control { background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))), -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255, 0.84)), to(rgba(255,255,255, 0.84))); background-image: -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -webkit-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), -o-linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); background-image: linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)), linear-gradient(rgba(255,255,255, 0.84), rgba(255,255,255, 0.84)); } .navbar.navbar-danger .navbar-form .form-group.label-floating label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-placeholder label.control-label { color: rgba(255,255,255, 0.84); text-overflow: ellipsis; overflow: hidden; white-space: nowrap; opacity: 0.87; font-size: 0.8em; } .navbar.navbar-danger .navbar-form .form-group.label-floating.is-empty:not(.is-focused) label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-placeholder.is-empty:not(.is-focused) label.control-label { top: -10px; font-size: 0.9em; } .navbar.navbar-danger .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -26px; } @media (max-width: 1200px) { .navbar.navbar-danger .navbar-form .form-group.label-floating.is-focused label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-placeholder.is-focused label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-floating:not(.is-empty) label.control-label, .navbar.navbar-danger .navbar-form .form-group.label-placeholder:not(.is-empty) label.control-label { top: -23px; line-height: 1.4em; font-size: 10px; } } .navbar.navbar-danger .dropdown-menu { border-radius: 2px; } @media (max-width: 767px) { .navbar.navbar-danger .dropdown-menu .dropdown-header { background-color: #e84f4c; } } .navbar.navbar-danger .dropdown-menu li > a { font-size: 16px; padding: 13px 16px; } .navbar.navbar-danger .dropdown-menu li > a:hover, .navbar.navbar-danger .dropdown-menu li > a:focus { color: #e53935; background-color: #eeeeee; } .navbar.navbar-danger .dropdown-menu .active > a { background-color: #e53935; color: rgba(255,255,255, 0.84); } .navbar.navbar-danger .dropdown-menu .active > a:hover, .navbar.navbar-danger .dropdown-menu .active > a:focus { color: rgba(255,255,255, 0.84); } .navbar-inverse { background-color: #3f51b5; } @media (max-width: 1199px) { .navbar .navbar-brand { height: 50px; padding: 10px 15px; } .navbar .navbar-form { margin-top: 10px; } .navbar .navbar-nav > li > a { padding-top: 15px; padding-bottom: 15px; } } .dropdown-menu { border: 0; -webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26); box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26); } .dropdown-menu .divider { background-color: rgba(0, 0, 0, 0.12); } .dropdown-menu li { overflow: hidden; position: relative; } .dropdown-menu li a:hover { background-color: transparent; color: #3949ab; } .alert { border: 0; border-radius: 0; } .alert, .alert.alert-default { background-color: rgba(255,255,255, 0.84); color: rgba(255,255,255, 0.84); } .alert a, .alert.alert-default a, .alert .alert-link, .alert.alert-default .alert-link { color: rgba(255,255,255, 0.84); } .alert.alert-inverse { background-color: #3f51b5; color: #ffffff; } .alert.alert-inverse a, .alert.alert-inverse .alert-link { color: #ffffff; } .alert.alert-primary { background-color: #3949ab; color: rgba(255,255,255, 0.84); } .alert.alert-primary a, .alert.alert-primary .alert-link { color: rgba(255,255,255, 0.84); } .alert.alert-success { background-color: #43a047; color: rgba(255,255,255, 0.84); } .alert.alert-success a, .alert.alert-success .alert-link { color: rgba(255,255,255, 0.84); } .alert.alert-info { background-color: #039be5; color: rgba(255,255,255, 0.84); } .alert.alert-info a, .alert.alert-info .alert-link { color: rgba(255,255,255, 0.84); } .alert.alert-warning { background-color: #ffa000; color: rgba(255,255,255, 0.84); } .alert.alert-warning a, .alert.alert-warning .alert-link { color: rgba(255,255,255, 0.84); } .alert.alert-danger { background-color: #e53935; color: rgba(255,255,255, 0.84); } .alert.alert-danger a, .alert.alert-danger .alert-link { color: rgba(255,255,255, 0.84); } .alert-info, .alert-danger, .alert-warning, .alert-success { color: rgba(255,255,255, 0.84); } .alert-default a, .alert-default .alert-link { color: rgba(0,0,0, 0.87); } .progress { height: 4px; border-radius: 0; -webkit-box-shadow: none; box-shadow: none; background: #c8c8c8; } .progress .progress-bar { -webkit-box-shadow: none; box-shadow: none; } .progress .progress-bar, .progress .progress-bar.progress-bar-default { background-color: #3949ab; } .progress .progress-bar.progress-bar-inverse { background-color: #3f51b5; } .progress .progress-bar.progress-bar-primary { background-color: #3949ab; } .progress .progress-bar.progress-bar-success { background-color: #43a047; } .progress .progress-bar.progress-bar-info { background-color: #039be5; } .progress .progress-bar.progress-bar-warning { background-color: #ffa000; } .progress .progress-bar.progress-bar-danger { background-color: #e53935; } .text-warning { color: #ffa000; } .text-primary { color: #3949ab; } .text-danger { color: #e53935; } .text-success { color: #43a047; } .text-info { color: #039be5; } .nav-tabs { background: #3949ab; } .nav-tabs > li > a { color: #FFFFFF; border: 0; margin: 0; } .nav-tabs > li > a:hover { background-color: transparent; border: 0; } .nav-tabs > li > a, .nav-tabs > li > a:hover, .nav-tabs > li > a:focus { background-color: transparent !important; border: 0 !important; color: #FFFFFF !important; font-weight: 500; } .nav-tabs > li.disabled > a, .nav-tabs > li.disabled > a:hover { color: rgba(255, 255, 255, 0.5); } .popover, .tooltip-inner { color: #ececec; line-height: 1em; background: rgba(101, 101, 101, 0.9); border: none; border-radius: 2px; -webkit-box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12), 0 1px 6px 0 rgba(0, 0, 0, 0.12); box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12), 0 1px 6px 0 rgba(0, 0, 0, 0.12); } .tooltip, .tooltip.in { opacity: 1; } .popover .arrow, .tooltip .arrow, .popover .tooltip-arrow, .tooltip .tooltip-arrow { display: none; } .card { /***** Make height equal to width (http://stackoverflow.com/a/6615994) ****/ display: inline-block; position: relative; width: 100%; /**************************************************************************/ border-radius: 2px; color: rgba(0,0,0, 0.87); background: #fff; -webkit-box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); } .card .card-height-indicator { margin-top: 100%; } .card .card-content { position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .card .card-image { height: 60%; position: relative; overflow: hidden; } .card .card-image img { width: 100%; height: 100%; border-top-left-radius: 2px; border-top-right-radius: 2px; pointer-events: none; } .card .card-image .card-image-headline { position: absolute; bottom: 16px; left: 18px; color: #fff; font-size: 2em; } .card .card-body { height: 30%; padding: 18px; } .card .card-footer { height: 10%; padding: 18px; } .card .card-footer button, .card .card-footer a { margin: 0 !important; position: relative; bottom: 25px; width: auto; } .card .card-footer button:first-child, .card .card-footer a:first-child { left: -15px; } .modal-content { -webkit-box-shadow: 0 27px 24px 0 rgba(0, 0, 0, 0.2), 0 40px 77px 0 rgba(0, 0, 0, 0.22); box-shadow: 0 27px 24px 0 rgba(0, 0, 0, 0.2), 0 40px 77px 0 rgba(0, 0, 0, 0.22); border-radius: 2px; border: none; } .modal-content .modal-header { border-bottom: none; padding-top: 24px; padding-right: 24px; padding-bottom: 0; padding-left: 24px; } .modal-content .modal-body { padding-top: 24px; padding-right: 24px; padding-bottom: 16px; padding-left: 24px; } .modal-content .modal-footer { border-top: none; padding: 7px; } .modal-content .modal-footer button { margin: 0; padding-left: 16px; padding-right: 16px; width: auto; } .modal-content .modal-footer button.pull-left { padding-left: 5px; padding-right: 5px; position: relative; left: -5px; } .modal-content .modal-footer button + button { margin-bottom: 16px; } .modal-content .modal-body + .modal-footer { padding-top: 0; } .modal-backdrop { background: rgba(0, 0, 0, 0.3); } .panel { border-radius: 2px; border: 0; -webkit-box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12), 0 1px 6px 0 rgba(0, 0, 0, 0.12); box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12), 0 1px 6px 0 rgba(0, 0, 0, 0.12); } .panel > .panel-heading, .panel.panel-default > .panel-heading { background-color: #eeeeee; } .panel.panel-inverse > .panel-heading { background-color: #3f51b5; } .panel.panel-primary > .panel-heading { background-color: #3949ab; } .panel.panel-success > .panel-heading { background-color: #43a047; } .panel.panel-info > .panel-heading { background-color: #039be5; } .panel.panel-warning > .panel-heading { background-color: #ffa000; } .panel.panel-danger > .panel-heading { background-color: #e53935; } [class*="panel-"] > .panel-heading { color: rgba(255,255,255, 0.84); border: 0; } .panel-default > .panel-heading, .panel:not([class*="panel-"]) > .panel-heading { color: rgba(0,0,0, 0.87); } .panel-footer { background-color: #eeeeee; } hr.on-dark { color: #1a1a1a; } hr.on-light { color: #ffffff; } @media (-webkit-min-device-pixel-ratio: 0.75), (min--moz-device-pixel-ratio: 0.75), (-o-device-pixel-ratio: 3/4), (min-device-pixel-ratio: 0.75), (-o-min-device-pixel-ratio: 3/4), (min-resolution: 0.75dppx), (-webkit-min-device-pixel-ratio: 1.25), (-o-min-device-pixel-ratio: 5/4), (min-resolution: 120dpi) { hr { height: 0.75px; } } @media (-webkit-min-device-pixel-ratio: 1), (min--moz-device-pixel-ratio: 1), (-o-device-pixel-ratio: 1), (min-device-pixel-ratio: 1), (-o-min-device-pixel-ratio: 1/1), (min-resolution: 1dppx), (-webkit-min-device-pixel-ratio: 1.6666666666666667), (-o-min-device-pixel-ratio: 5/3), (min-resolution: 160dpi) { hr { height: 1px; } } @media (-webkit-min-device-pixel-ratio: 1.33), (min--moz-device-pixel-ratio: 1.33), (-o-device-pixel-ratio: 133/100), (min-device-pixel-ratio: 1.33), (-o-min-device-pixel-ratio: 133/100), (min-resolution: 1.33dppx), (-webkit-min-device-pixel-ratio: 2.21875), (-o-min-device-pixel-ratio: 71/32), (min-resolution: 213dpi) { hr { height: 1.333px; } } @media (-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), (-o-device-pixel-ratio: 3/2), (min-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx), (-webkit-min-device-pixel-ratio: 2.5), (-o-min-device-pixel-ratio: 5/2), (min-resolution: 240dpi) { hr { height: 1.5px; } } @media (-webkit-min-device-pixel-ratio: 2), (min--moz-device-pixel-ratio: 2), (-o-device-pixel-ratio: 2/1), (min-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 2/1), (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 3.9583333333333335), (-o-min-device-pixel-ratio: 95/24), (min-resolution: 380dpi) { hr { height: 2px; } } @media (-webkit-min-device-pixel-ratio: 3), (min--moz-device-pixel-ratio: 3), (-o-device-pixel-ratio: 3/1), (min-device-pixel-ratio: 3), (-o-min-device-pixel-ratio: 3/1), (min-resolution: 3dppx), (-webkit-min-device-pixel-ratio: 5), (-o-min-device-pixel-ratio: 5/1), (min-resolution: 480dpi) { hr { height: 3px; } } @media (-webkit-min-device-pixel-ratio: 4), (min--moz-device-pixel-ratio: 4), (-o-device-pixel-ratio: 4/1), (min-device-pixel-ratio: 3), (-o-min-device-pixel-ratio: 4/1), (min-resolution: 4dppx), (-webkit-min-device-pixel-ratio: 6.666666666666667), (-o-min-device-pixel-ratio: 20/3), (min-resolution: 640dpi) { hr { height: 4px; } } * { -webkit-tap-highlight-color: rgba(255, 255, 255, 0); -webkit-tap-highlight-color: transparent; } *:focus { outline: 0; } .snackbar { background-color: #323232; color: rgba(255,255,255, 0.84); font-size: 14px; border-radius: 2px; -webkit-box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12), 0 1px 6px 0 rgba(0, 0, 0, 0.12); box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.12), 0 1px 6px 0 rgba(0, 0, 0, 0.12); height: 0; -webkit-transition: -webkit-transform 0.2s ease-in-out, opacity 0.2s ease-in, height 0s linear 0.2s, padding 0s linear 0.2s, height 0s linear 0.2s; -o-transition: -o-transform 0.2s ease-in-out, opacity 0.2s ease-in, height 0s linear 0.2s, padding 0s linear 0.2s, height 0s linear 0.2s; transition: transform 0.2s ease-in-out, opacity 0.2s ease-in, height 0s linear 0.2s, padding 0s linear 0.2s, height 0s linear 0.2s; -webkit-transform: translateY(200%); -ms-transform: translateY(200%); -o-transform: translateY(200%); transform: translateY(200%); } .snackbar.snackbar-opened { padding: 14px 15px; margin-bottom: 20px; height: auto; -webkit-transition: -webkit-transform 0.2s ease-in-out, opacity 0.2s ease-in, height 0s linear 0.2s, height 0s linear 0.2s; -o-transition: -o-transform 0.2s ease-in-out, opacity 0.2s ease-in, height 0s linear 0.2s, height 0s linear 0.2s; transition: transform 0.2s ease-in-out, opacity 0.2s ease-in, height 0s linear 0.2s, height 0s linear 0.2s; -webkit-transform: none; -ms-transform: none; -o-transform: none; transform: none; } .snackbar.toast { border-radius: 200px; } .noUi-target, .noUi-target * { -webkit-touch-callout: none; -ms-touch-action: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .noUi-base { width: 100%; height: 100%; position: relative; } .noUi-origin { position: absolute; right: 0; top: 0; left: 0; bottom: 0; } .noUi-handle { position: relative; z-index: 1; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .noUi-stacking .noUi-handle { z-index: 10; } .noUi-state-tap .noUi-origin { -webkit-transition: left 0.3s, top 0.3s; -o-transition: left 0.3s, top 0.3s; transition: left 0.3s, top 0.3s; } .noUi-state-drag * { cursor: inherit !important; } .noUi-horizontal { height: 10px; } .noUi-handle { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; width: 12px; height: 12px; left: -10px; top: -5px; cursor: ew-resize; border-radius: 100%; -webkit-transition: all 0.2s ease-out; -o-transition: all 0.2s ease-out; transition: all 0.2s ease-out; border: 1px solid; } .noUi-vertical .noUi-handle { margin-left: 5px; cursor: ns-resize; } .noUi-horizontal.noUi-extended { padding: 0 15px; } .noUi-horizontal.noUi-extended .noUi-origin { right: -15px; } .noUi-background { height: 2px; margin: 20px 0; } .noUi-origin { margin: 0; border-radius: 0; height: 2px; background: #c8c8c8; } .noUi-origin[style^="left: 0"] .noUi-handle { background-color: #fff; border: 2px solid #c8c8c8; } .noUi-origin[style^="left: 0"] .noUi-handle.noUi-active { border-width: 1px; } .noUi-target { border-radius: 2px; } .noUi-horizontal { height: 2px; margin: 15px 0; } .noUi-vertical { height: 100%; width: 2px; margin: 0 15px; display: inline-block; } .noUi-handle.noUi-active { -webkit-transform: scale3d(2.5, 2.5, 1); transform: scale3d(2.5, 2.5, 1); } [disabled].noUi-slider { opacity: 0.5; } [disabled] .noUi-handle { cursor: not-allowed; } .slider { background: #c8c8c8; } .slider.noUi-connect, .slider.slider-default.noUi-connect { background-color: #3949ab; } .slider.slider-inverse.noUi-connect { background-color: #3f51b5; } .slider.slider-primary.noUi-connect { background-color: #3949ab; } .slider.slider-success.noUi-connect { background-color: #43a047; } .slider.slider-info.noUi-connect { background-color: #039be5; } .slider.slider-warning.noUi-connect { background-color: #ffa000; } .slider.slider-danger.noUi-connect { background-color: #e53935; } .slider .noUi-connect, .slider.slider-default .noUi-connect { background-color: #3949ab; } .slider.slider-inverse .noUi-connect { background-color: #3f51b5; } .slider.slider-primary .noUi-connect { background-color: #3949ab; } .slider.slider-success .noUi-connect { background-color: #43a047; } .slider.slider-info .noUi-connect { background-color: #039be5; } .slider.slider-warning .noUi-connect { background-color: #ffa000; } .slider.slider-danger .noUi-connect { background-color: #e53935; } .slider .noUi-handle, .slider.slider-default .noUi-handle { background-color: #3949ab; } .slider.slider-inverse .noUi-handle { background-color: #3f51b5; } .slider.slider-primary .noUi-handle { background-color: #3949ab; } .slider.slider-success .noUi-handle { background-color: #43a047; } .slider.slider-info .noUi-handle { background-color: #039be5; } .slider.slider-warning .noUi-handle { background-color: #ffa000; } .slider.slider-danger .noUi-handle { background-color: #e53935; } .slider .noUi-handle, .slider.slider-default .noUi-handle { border-color: #3949ab; } .slider.slider-inverse .noUi-handle { border-color: #3f51b5; } .slider.slider-primary .noUi-handle { border-color: #3949ab; } .slider.slider-success .noUi-handle { border-color: #43a047; } .slider.slider-info .noUi-handle { border-color: #039be5; } .slider.slider-warning .noUi-handle { border-color: #ffa000; } .slider.slider-danger .noUi-handle { border-color: #e53935; } .selectize-control.single, .selectize-control.multi { padding: 0; } .selectize-control.single .selectize-input, .selectize-control.multi .selectize-input, .selectize-control.single .selectize-input.input-active, .selectize-control.multi .selectize-input.input-active { cursor: text; background: transparent; -webkit-box-shadow: none; box-shadow: none; border: 0; padding: 0; height: 100%; font-size: 14px; line-height: 30px; } .selectize-control.single .selectize-input .has-items, .selectize-control.multi .selectize-input .has-items, .selectize-control.single .selectize-input.input-active .has-items, .selectize-control.multi .selectize-input.input-active .has-items { padding: 0; } .selectize-control.single .selectize-input:after, .selectize-control.multi .selectize-input:after, .selectize-control.single .selectize-input.input-active:after, .selectize-control.multi .selectize-input.input-active:after { right: 5px; position: absolute; font-size: 25px; content: "\e5c5"; font-family: 'Material Icons'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .selectize-control.single .selectize-input input, .selectize-control.multi .selectize-input input, .selectize-control.single .selectize-input.input-active input, .selectize-control.multi .selectize-input.input-active input { font-size: 14px; outline: 0; border: 0; background: transparent; } .selectize-control.single .selectize-input.label-floating-fix input, .selectize-control.multi .selectize-input.label-floating-fix input, .selectize-control.single .selectize-input.input-active.label-floating-fix input, .selectize-control.multi .selectize-input.input-active.label-floating-fix input { opacity: 0; } .selectize-control.single .selectize-input > div, .selectize-control.multi .selectize-input > div, .selectize-control.single .selectize-input.input-active > div, .selectize-control.multi .selectize-input.input-active > div, .selectize-control.single .selectize-input > .item, .selectize-control.multi .selectize-input > .item, .selectize-control.single .selectize-input.input-active > .item, .selectize-control.multi .selectize-input.input-active > .item { display: inline-block; margin: 0 8px 3px 0; padding: 0; background: transparent; border: 0; } .selectize-control.single .selectize-input > div:after, .selectize-control.multi .selectize-input > div:after, .selectize-control.single .selectize-input.input-active > div:after, .selectize-control.multi .selectize-input.input-active > div:after, .selectize-control.single .selectize-input > .item:after, .selectize-control.multi .selectize-input > .item:after, .selectize-control.single .selectize-input.input-active > .item:after, .selectize-control.multi .selectize-input.input-active > .item:after { content: ","; } .selectize-control.single .selectize-input > div:last-of-type:after, .selectize-control.multi .selectize-input > div:last-of-type:after, .selectize-control.single .selectize-input.input-active > div:last-of-type:after, .selectize-control.multi .selectize-input.input-active > div:last-of-type:after, .selectize-control.single .selectize-input > .item:last-of-type:after, .selectize-control.multi .selectize-input > .item:last-of-type:after, .selectize-control.single .selectize-input.input-active > .item:last-of-type:after, .selectize-control.multi .selectize-input.input-active > .item:last-of-type:after { content: ""; } .selectize-control.single .selectize-input > div.active, .selectize-control.multi .selectize-input > div.active, .selectize-control.single .selectize-input.input-active > div.active, .selectize-control.multi .selectize-input.input-active > div.active, .selectize-control.single .selectize-input > .item.active, .selectize-control.multi .selectize-input > .item.active, .selectize-control.single .selectize-input.input-active > .item.active, .selectize-control.multi .selectize-input.input-active > .item.active { font-weight: bold; background: transparent; border: 0; } .selectize-control.single .selectize-dropdown, .selectize-control.multi .selectize-dropdown { position: absolute; z-index: 1000; border: 0; width: 100% !important; left: 0 !important; height: auto; background-color: #FFF; -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); border-radius: 2px; padding: 0; margin-top: 3px; } .selectize-control.single .selectize-dropdown .active, .selectize-control.multi .selectize-dropdown .active { background-color: inherit; } .selectize-control.single .selectize-dropdown .highlight, .selectize-control.multi .selectize-dropdown .highlight { background-color: #d5d8ff; } .selectize-control.single .selectize-dropdown .selected, .selectize-control.multi .selectize-dropdown .selected, .selectize-control.single .selectize-dropdown .selected.active, .selectize-control.multi .selectize-dropdown .selected.active { background-color: #EEEEEE; } .selectize-control.single .selectize-dropdown [data-selectable], .selectize-control.multi .selectize-dropdown [data-selectable], .selectize-control.single .selectize-dropdown .optgroup-header, .selectize-control.multi .selectize-dropdown .optgroup-header { padding: 10px 20px; cursor: pointer; } .selectize-control.single .dropdown-active ~ .selectize-dropdown, .selectize-control.multi .dropdown-active ~ .selectize-dropdown { display: block; } .dropdownjs::after { right: 5px; top: 3px; font-size: 25px; position: absolute; font-family: 'Material Icons'; font-style: normal; font-weight: 400; content: "\e5c5"; pointer-events: none; color: #757575; } /*# sourceMappingURL=bootstrap-material-design.css.map */
{ "content_hash": "c8325f115f6e563438f0f38e26d486b2", "timestamp": "", "source": "github", "line_count": 3758, "max_line_length": 321, "avg_line_length": 33.58408728046833, "alnum_prop": 0.695964630097695, "repo_name": "wallter/bootstrap-material-design", "id": "901e8fdc85a3325cb6365100b06c8b49e902076b", "size": "126209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/css/bootstrap-material-design.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "198024" }, { "name": "HTML", "bytes": "126088" }, { "name": "JavaScript", "bytes": "36365" }, { "name": "Ruby", "bytes": "96" } ], "symlink_target": "" }
NS_ASSUME_NONNULL_BEGIN @interface DWDPRespondedIncomingRequestObject : DWDPIncomingRequestObject <DWDPRespondedRequestItem> @end NS_ASSUME_NONNULL_END
{ "content_hash": "ca15e29b6cc7c0a8e31f6c35ec8ee8c5", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 100, "avg_line_length": 22.142857142857142, "alnum_prop": 0.8580645161290322, "repo_name": "QuantumExplorer/breadwallet", "id": "d19bc1b8ee7ea271eeb80d1123e5c40490b1f8b0", "size": "871", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DashWallet/Sources/UI/DashPay/Items/Objects/DWDPRespondedIncomingRequestObject.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "495752" }, { "name": "C++", "bytes": "13127" }, { "name": "Java", "bytes": "2100" }, { "name": "Objective-C", "bytes": "1430773" }, { "name": "Shell", "bytes": "586" } ], "symlink_target": "" }
%COPYRIGHT: MOHAMMAD MAHDI GHASSEMI %DATE: MARCH 19TH, 2015 function [ pred_labels, conf ] = ImageHOGEstimates( resized_clean_image_mat,has_stuff,hog_classifier, cellSize ) %This Function takes a matrix of images of digits and: % 1. Uses a HOG Classifier to produce a label, and a confidence bound. % PARAMTERS OF THE FUCNTION: % image_mat - This is a 3d matrix of images, where the 3rd dim is each digit % has_stuff - Indicates which cells have stuff in them. % hog_classifier - The trained HOG Classifier ClassificationECOC object. % cell_size - The cell size used in the HOG Transform conf = nan*ones(size(resized_clean_image_mat,1),size(resized_clean_image_mat,2),size(resized_clean_image_mat,3)); pred_labels{size(resized_clean_image_mat,1),size(resized_clean_image_mat,2),size(resized_clean_image_mat,3)} = [] for i = 1:size(resized_clean_image_mat,1) for j = 1:size(resized_clean_image_mat,2) if(has_stuff(i,j) == 1) for k = 1:size(resized_clean_image_mat,3) BW = resized_clean_image_mat{i,j,k}; if(~isempty(BW)) mytestFeatures = extractHOGFeatures(BW, 'CellSize', cellSize); [mypredictedLabels, ~,~,conf_interval] = predict(hog_classifier, mytestFeatures); conf(i,j,k) = max(conf_interval'); if (mypredictedLabels == 11) mypredictedLabels = '.'; else mypredictedLabels = num2str(mypredictedLabels); end pred_labels{i,j,k} = mypredictedLabels; end end end end end end
{ "content_hash": "a10825e19819fbabc807a15ba52229ca", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 113, "avg_line_length": 41.75609756097561, "alnum_prop": 0.6016355140186916, "repo_name": "deskool/images_to_spreadsheets", "id": "43ff5866eac53d139741e8ef149e6a8bc1406e72", "size": "1712", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Required/ImageHOGEstimates.m", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "69243" }, { "name": "Shell", "bytes": "2539" } ], "symlink_target": "" }
package net.sourceforge.lame.mp3; /** * allows re-use of previously computed noise values */ public class CalcNoiseData { int global_gain; int sfb_count1; int step[] = new int[39]; float noise[] = new float[39]; float noise_log[] = new float[39]; }
{ "content_hash": "96a0b72bc25bddd340f7064a17958935", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 52, "avg_line_length": 21.833333333333332, "alnum_prop": 0.6755725190839694, "repo_name": "dubenju/javay", "id": "5252cf1d1d36cb635a21d92a22326d914aed2bec", "size": "262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/net/sourceforge/lame/mp3/CalcNoiseData.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1209" }, { "name": "C", "bytes": "141915" }, { "name": "C++", "bytes": "41380" }, { "name": "COBOL", "bytes": "6059" }, { "name": "HTML", "bytes": "49704" }, { "name": "Java", "bytes": "15848922" }, { "name": "Makefile", "bytes": "3393" }, { "name": "Shell", "bytes": "822" } ], "symlink_target": "" }
package query import ( "fmt" "testing" "github.com/EverythingMe/meduza/schema" ) type User struct { Id schema.Key `db:",primary"` Name schema.Text `db:"name"` } func TestResponseMappingSlice(t *testing.T) { r := NewGetResponse(nil) r.AddEntity(*schema.NewEntity("foofoo").Set("name", schema.Text("alice"))) r.AddEntity(*schema.NewEntity("booboo").Set("name", schema.Text("bob"))) r.Done() fmt.Println(r.Entities) users := make([]User, 0, 10) err := r.MapEntities(&users) if err != nil { t.Error(err) } if len(users) != len(r.Entities) { t.Errorf("Loaded %d entities when we should have %d", len(users), len(r.Entities)) } for i, user := range users { if user.Id != r.Entities[i].Id { t.Error("Mismatching ids: %s/%s", user.Id, r.Entities[i].Id) } if user.Name != r.Entities[i].Properties["name"] { t.Error("Mismatching names: %s/%s", user.Name, r.Entities[i].Properties["name"]) } } } func TestResponseMappingSingle(t *testing.T) { // Test single entity r := NewGetResponse(nil) r.AddEntity(*schema.NewEntity("foofoo").Set("name", schema.Text("booboo"))) user := User{} if err := r.MapEntities(&user); err != nil { t.Error(err) } if user.Id != r.Entities[0].Id { t.Error("Id not mapped") } if user.Name != r.Entities[0].Properties["name"] { t.Error("Name not mapped") } //check that non pointers and nils cannot be mapped if err := r.MapEntities(user); err == nil { t.Error("Mapping non pointer should have failed") } if err := r.MapEntities(nil); err == nil { t.Error("Mapping nil pointer should have failed") } // check that mapping a multi line result to a single entity should fail r.AddEntity(*schema.NewEntity("googoo").Set("name", schema.Text("doodoo"))) if err := r.MapEntities(&user); err == nil { t.Error("Mapping many entities to a single object should have failed") } }
{ "content_hash": "e75dccd8ddf1743d2363fb6e01cf60fa", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 84, "avg_line_length": 24.272727272727273, "alnum_prop": 0.6559657570893526, "repo_name": "EverythingMe/meduza", "id": "6d38bc5b0914f6ee19ab3071c5967ca0f14a2559", "size": "1869", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "query/query_test.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Go", "bytes": "288904" } ], "symlink_target": "" }
'use strict'; // TODO: // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ // - miltiplication 2 x 4 -> 2 × 4 var defaults = require('./defaults/typographer'); var assign = require('./common/utils').assign; var Ruler = require('./ruler'); var rules = []; rules.push(require('./rules_typographer/replace')); rules.push(require('./rules_typographer/smartquotes')); function Typographer() { this._rules = []; this.options = assign({}, defaults); this.ruler = new Ruler(this.rulesUpdate.bind(this)); for (var i = 0; i < rules.length; i++) { this.ruler.after(rules[i]); } } Typographer.prototype.rulesUpdate = function () { this._rules = this.ruler.getRules(); }; Typographer.prototype.set = function (options) { assign(this.options, options); }; Typographer.prototype.process = function (state) { var i, l, rules; rules = this._rules; for (i = 0, l = rules.length; i < l; i++) { rules[i](this, state); } }; module.exports = Typographer;
{ "content_hash": "174f97654c7ada799cc93b8efcdd48d7", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 55, "avg_line_length": 18.27777777777778, "alnum_prop": 0.624113475177305, "repo_name": "mathiasbynens/remarkable", "id": "ec1748b3a8b22ce38a3e6d35db373dcaa1879157", "size": "1037", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/typographer.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
layout: page title: Seattle Police Officer 6336 Martin J. Harris permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/6336/ --- **Age as of Feb. 24, 2016:** 49
{ "content_hash": "fbb71352950b945c34e6657040c0b1a9", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 88, "avg_line_length": 31.833333333333332, "alnum_prop": 0.7591623036649214, "repo_name": "seattlepublicrecords/seattlepublicrecords.github.io", "id": "44be460a66193ff824e9e57bd15acdcaf53ef19d", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "information/agencies/city_of_seattle/seattle_police_department/copbook/6336/index.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "14496" }, { "name": "HTML", "bytes": "14591" }, { "name": "JavaScript", "bytes": "5297" }, { "name": "Ruby", "bytes": "964" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; namespace SlashTodo.Infrastructure.Configuration { public class AppSettings : IAppSettings { public string Get(string key) { return ConfigurationManager.AppSettings[key]; } } }
{ "content_hash": "801c6775054463b9878b1845abab91c9", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 57, "avg_line_length": 21.1875, "alnum_prop": 0.696165191740413, "repo_name": "Hihaj/SlashTodo", "id": "db6c41c16e18d2c3a03efddda11f0f277f27dac3", "size": "341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SlashTodo.Infrastructure/Configuration/AppSettings.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "400581" }, { "name": "CSS", "bytes": "652" }, { "name": "JavaScript", "bytes": "55420" } ], "symlink_target": "" }
package helma.xmlrpc; import java.io.*; import java.util.*; import java.lang.reflect.*; /** * A multithreaded, reusable XML-RPC server object. The name may be misleading because this does not open any * server sockets. Instead it is fed by passing an XML-RPC input stream to the execute method. * If you want to open a HTTP listener, use the WebServer class instead. */ public class XmlRpcServer { /** * */ Hashtable handlers; /** * Construct a new XML-RPC server. You have to register handlers to make it * do something useful. */ public XmlRpcServer () { handlers = new Hashtable (); } /** * Register a handler object with this name. Methods of this objects will be * callable over XML-RPC as "handlername.methodname". For more information * about XML-RPC handlers see the <a href="../index.html#1a">main documentation page</a>. */ public void addHandler (String handlername, Object handler) { if (handler instanceof XmlRpcHandler || handler instanceof AuthenticatedXmlRpcHandler) handlers.put (handlername, handler); else if (handler != null) handlers.put (handlername, new Invoker (handler)); } /** * Remove a handler object that was previously registered with this server. */ public void removeHandler (String handlername) { handlers.remove (handlername); } /** * Parse the request and execute the handler method, if one is found. Returns the result as XML. * The calling Java code doesn't need to know whether the call was successful or not since this is all * packed into the response. */ public byte[] execute (InputStream is) { return execute (is, null, null); } /** * Parse the request and execute the handler method, if one is found. If the invoked handler is * AuthenticatedXmlRpcHandler, use the credentials to authenticate the user. */ public byte[] execute (InputStream is, String user, String password) { Worker worker = getWorker (); byte[] retval = worker.execute (is, user, password); pool.push (worker); return retval; } Stack pool = new Stack (); int workers = 0; private final Worker getWorker () { try { return (Worker) pool.pop (); } catch (EmptyStackException x) { if (workers < 100) { workers += 1; return new Worker (); } throw new RuntimeException ("System overload"); } } class Worker extends XmlRpc { Vector inParams; Object outParam; byte[] result; StringBuffer strbuf; public byte[] execute (InputStream is, String user, String password) { inParams = new Vector (); if (strbuf == null) strbuf = new StringBuffer (); long now = System.currentTimeMillis (); try { parse (is); if (debug) { System.err.println ("method name: "+methodName); System.err.println ("inparams: "+inParams); } // check for errors from the XML parser if (errorLevel > NONE) throw new Exception (errorMsg); Object handler = null; String handlerName = null; int dot = methodName.indexOf ("."); if (dot > -1) { handlerName = methodName.substring (0, dot); handler = handlers.get (handlerName); if (handler != null) methodName = methodName.substring (dot+1); } if (handler == null) { handler = handlers.get ("$default"); } if (handler == null) { if (dot > -1) throw new Exception ("RPC handler object \""+handlerName+"\" not found and no default handler registered."); else throw new Exception ("RPC handler object not found for \""+methodName+"\": no default handler registered."); } if (handler instanceof AuthenticatedXmlRpcHandler) outParam = ((AuthenticatedXmlRpcHandler) handler).execute (methodName, inParams, user, password); else outParam = ((XmlRpcHandler) handler).execute (methodName, inParams); if (debug) System.err.println ("outparam = "+outParam); XmlWriter writer = new XmlWriter (strbuf); writeResponse (outParam, writer); result = writer.getBytes (); } catch (Exception x) { if (debug) x.printStackTrace (); XmlWriter writer = new XmlWriter (strbuf); String message = x.toString (); // check if XmlRpcException was thrown so we can get an error code int code = x instanceof XmlRpcException ? ((XmlRpcException) x).code : 0; try { writeError (code, message, writer); } catch (XmlRpcException xrx) { // won't happen, we just sent a struct with an int and a string } try { result = writer.getBytes (); } catch (UnsupportedEncodingException encx) { System.err.println ("XmlRpcServer.execute: "+encx); result = writer.toString().getBytes(); } } if (debug) System.err.println ("Spent "+(System.currentTimeMillis () - now)+" millis in request"); return result; } /** * Called when an object to be added to the argument list has been parsed. */ void objectParsed (Object what) { inParams.addElement (what); } /** * Writes an XML-RPC response to the XML writer. */ void writeResponse (Object param, XmlWriter writer) throws XmlRpcException { writer.startElement ("methodResponse"); // if (param == null) param = ""; // workaround for Frontier bug writer.startElement ("params"); writer.startElement ("param"); writeObject (param, writer); writer.endElement ("param"); writer.endElement ("params"); writer.endElement ("methodResponse"); } /** * Writes an XML-RPC error response to the XML writer. */ void writeError (int code, String message, XmlWriter writer) throws XmlRpcException { // System.err.println ("error: "+message); Hashtable h = new Hashtable (); h.put ("faultCode", new Integer (code)); h.put ("faultString", message); writer.startElement ("methodResponse"); writer.startElement ("fault"); writeObject (h, writer); writer.endElement ("fault"); writer.endElement ("methodResponse"); } } // end of inner class Worker } // XmlRpcServer // This class uses Java Reflection to call methods matching an XML-RPC call class Invoker implements XmlRpcHandler { private Object invokeTarget; private Class targetClass; public Invoker(Object target) { invokeTarget = target; targetClass = invokeTarget instanceof Class ? (Class) invokeTarget : invokeTarget.getClass(); if (XmlRpc.debug) System.err.println("Target object is " + targetClass); } // main method, sucht methode in object, wenn gefunden dann aufrufen. public Object execute (String methodName, Vector params) throws Exception { // Array mit Classtype bilden, ObjectAry mit Values bilden Class[] argClasses = null; Object[] argValues = null; if(params != null){ argClasses = new Class[params.size()]; argValues = new Object[params.size()]; for(int i = 0; i < params.size(); i++){ argValues[i] = params.elementAt(i); if (argValues[i] instanceof Integer) argClasses[i] = Integer.TYPE; else if (argValues[i] instanceof Double) argClasses[i] = Double.TYPE; else if (argValues[i] instanceof Boolean) argClasses[i] = Boolean.TYPE; else argClasses[i] = argValues[i].getClass(); } } // Methode da ? Method method = null; if (XmlRpc.debug) { System.err.println("Searching for method: " + methodName); for(int i = 0; i < argClasses.length; i++) System.err.println("Parameter " + i + ": " + argClasses[i] + " = " + argValues[i]); } try { method = targetClass.getMethod(methodName, argClasses); } // Wenn nicht da dann entsprechende Exception returnen catch(NoSuchMethodException nsm_e){ throw nsm_e; } catch (SecurityException s_e){ throw s_e; } // our policy is to make all public methods callable except the ones defined in java.lang.Object if (method.getDeclaringClass () == Class.forName ("java.lang.Object")) throw new XmlRpcException (0, "Invoker can't call methods defined in java.lang.Object"); // invoke Object returnValue = null; try { returnValue = method.invoke (invokeTarget, argValues); } catch (IllegalAccessException iacc_e){ throw iacc_e; } catch (IllegalArgumentException iarg_e){ throw iarg_e; } catch (InvocationTargetException it_e) { if (XmlRpc.debug) it_e.getTargetException ().printStackTrace (); // check whether the thrown exception is XmlRpcException Throwable t=it_e.getTargetException(); if ( t instanceof XmlRpcException) throw (XmlRpcException) t; // It is some other exception throw new Exception (t.toString ()); } return returnValue; } }
{ "content_hash": "369b01d13211ee4b08870c1166acf7db", "timestamp": "", "source": "github", "line_count": 293, "max_line_length": 120, "avg_line_length": 30.945392491467576, "alnum_prop": 0.6353810521671998, "repo_name": "pitpitman/GraduateWork", "id": "8182049c45a7d68ec1afb2b95d0cdbd2ac8b8241", "size": "9171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xmlrpc/src/helma/xmlrpc/XmlRpcServer.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "66281" }, { "name": "C", "bytes": "143599" }, { "name": "C++", "bytes": "86459" }, { "name": "CSS", "bytes": "26409" }, { "name": "Common Lisp", "bytes": "2491" }, { "name": "Groff", "bytes": "50553" }, { "name": "HTML", "bytes": "9543552" }, { "name": "Java", "bytes": "4712599" }, { "name": "JavaScript", "bytes": "4227" }, { "name": "Makefile", "bytes": "6748" }, { "name": "Perl", "bytes": "379818" }, { "name": "Perl6", "bytes": "2424" }, { "name": "PostScript", "bytes": "628801" }, { "name": "Prolog", "bytes": "22274" }, { "name": "Shell", "bytes": "178966" }, { "name": "XSLT", "bytes": "10526" } ], "symlink_target": "" }
<?php namespace Madkom\EventStore\Client\Domain\Socket; use Madkom\EventStore\Client\Domain\DomainException; use Madkom\EventStore\Client\Domain\Socket\Communication\CommunicationFactory; use Madkom\EventStore\Client\Domain\Socket\Message\MessageComposer; use Madkom\EventStore\Client\Domain\Socket\Message\MessageConfiguration; use Madkom\EventStore\Client\Domain\Socket\Message\MessageDecomposer; use Madkom\EventStore\Client\Domain\Socket\Message\MessageType; use Madkom\EventStore\Client\Domain\Socket\Message\SocketMessage; use Psr\Log\LoggerInterface; use TrafficCophp\ByteBuffer\Buffer; /** * Class StreamHandler * @package Madkom\EventStore\Client\Domain\Socket * @author Dariusz Gafka <[email protected]> */ class StreamHandler { /** @var Stream */ private $stream; /** @var MessageDecomposer */ private $messageDecomposer; /** @var MessageComposer */ private $messageComposer; /** * @var LoggerInterface */ private $logger; /** @var null|string current unfinish packaged recevied from ES */ private $currentMessage = null; /** @var null Length of the package */ private $currentMessageLength = null; /** * @param Stream $stream * @param LoggerInterface $logger * @param MessageDecomposer $messageDecomposer * @param MessageComposer $messageComposer */ public function __construct(Stream $stream, LoggerInterface $logger, MessageDecomposer $messageDecomposer, MessageComposer $messageComposer) { $this->stream = $stream; $this->messageDecomposer = $messageDecomposer; $this->messageComposer = $messageComposer; $this->logger = $logger; } /** * Handles received data * * @param string $data * * @return SocketMessage[]|null */ public function handle($data) { try { if (!$data) { return null; } $socketMessages = array(); if (!is_null($this->currentMessage)) { $data = $this->currentMessage . $data; } do { $buffer = new Buffer($data); $dataLength = strlen($data); $messageLength = $buffer->readInt32LE(0) + MessageConfiguration::INT_32_LENGTH; if ($dataLength == $messageLength) { $socketMessages[] = $this->decomposeMessage($data); $this->currentMessage = null; } elseif($dataLength > $messageLength) { $message = substr($data, 0, $messageLength); $socketMessages[] = $this->decomposeMessage($message); // reset data to next message $data = substr($data, $messageLength, $dataLength); $this->currentMessage = null; } else { $this->currentMessage .= $data; } } while ($dataLength > $messageLength); return $socketMessages; }catch (\Exception $e) { $this->logger->critical('Error during handling incoming message.'. ' Message Error: ' . $e->getMessage()); } } /** * Sends message to stream sever * * @param SocketMessage $socketMessage * * @return void * @throws DomainException */ public function sendMessage(SocketMessage $socketMessage) { try { $binaryMessage = $this->messageComposer->compose($socketMessage); $this->stream->write($binaryMessage); }catch (\Exception $e) { $this->logger->critical('Error during send a message with '. $socketMessage->getMessageType()->getType() . ' and id ' . $socketMessage->getCorrelationID() . '. Message Error: ' . $e->getMessage()); } } /** * @param $data * * @return SocketMessage */ private function decomposeMessage($data) { $socketMessage = $this->messageDecomposer->decomposeMessage($data); //If heartbeat then response if ($socketMessage->getMessageType()->getType() === MessageType::HEARTBEAT_REQUEST) { $this->sendMessage(new SocketMessage(new MessageType(MessageType::HEARTBEAT_RESPONSE), $socketMessage->getCorrelationID())); } return $socketMessage; } }
{ "content_hash": "a2547c9e6238316f33186bcb80b6c895", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 209, "avg_line_length": 31.302816901408452, "alnum_prop": 0.5930258717660293, "repo_name": "madkom/event-store-client", "id": "adc044eb07dd208d0c8c18096ebbc659c8bea574", "size": "4445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Domain/Socket/StreamHandler.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "229623" }, { "name": "Protocol Buffer", "bytes": "5791" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.tests.cassandra; import io.prestosql.tempto.ProductTest; import io.prestosql.tempto.Requirement; import io.prestosql.tempto.RequirementsProvider; import io.prestosql.tempto.configuration.Configuration; import org.testng.annotations.Test; import static io.prestosql.tempto.assertions.QueryAssert.assertThat; import static io.prestosql.tempto.fulfillment.table.TableRequirements.immutableTable; import static io.prestosql.tempto.query.QueryExecutor.query; import static io.prestosql.tests.TestGroups.CASSANDRA; import static io.prestosql.tests.cassandra.CassandraTpchTableDefinitions.CASSANDRA_NATION; import static io.prestosql.tests.cassandra.TestConstants.CONNECTOR_NAME; import static io.prestosql.tests.cassandra.TestConstants.KEY_SPACE; import static java.lang.String.format; public class TestInvalidSelect extends ProductTest implements RequirementsProvider { @Override public Requirement getRequirements(Configuration configuration) { return immutableTable(CASSANDRA_NATION); } @Test(groups = CASSANDRA) public void testInvalidTable() { String tableName = format("%s.%s.%s", CONNECTOR_NAME, KEY_SPACE, "bogus"); assertThat(() -> query(format("SELECT * FROM %s", tableName))) .failsWithMessage(format("Table %s does not exist", tableName)); } @Test(groups = CASSANDRA) public void testInvalidSchema() { String tableName = format("%s.%s.%s", CONNECTOR_NAME, "does_not_exist", "bogus"); assertThat(() -> query(format("SELECT * FROM %s", tableName))) .failsWithMessage("Schema does_not_exist does not exist"); } @Test(groups = CASSANDRA) public void testInvalidColumn() { String tableName = format("%s.%s.%s", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); assertThat(() -> query(format("SELECT bogus FROM %s", tableName))) .failsWithMessage("Column 'bogus' cannot be resolved"); } }
{ "content_hash": "4905afcaaa8b8e1b8f174d5ff190ce4e", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 101, "avg_line_length": 40.125, "alnum_prop": 0.7235202492211839, "repo_name": "youngwookim/presto", "id": "bf1c34e780222dd34258cef5969cc9c1917986c6", "size": "2568", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "presto-product-tests/src/main/java/io/prestosql/tests/cassandra/TestInvalidSelect.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "26917" }, { "name": "CSS", "bytes": "12957" }, { "name": "HTML", "bytes": "28832" }, { "name": "Java", "bytes": "31475945" }, { "name": "JavaScript", "bytes": "211244" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "PLpgSQL", "bytes": "11504" }, { "name": "Python", "bytes": "7664" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29871" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
module Vertica module Messages class ReadyForQuery < BackendMessage STATUSES = { 'I' => :no_transaction, 'T' => :in_transaction, 'E' => :failed_transaction } message_id 'Z' attr_reader :transaction_status def initialize(data) @transaction_status = STATUSES[data.unpack('a').first] end end end end
{ "content_hash": "27d4a901dc28ac9551753f805452f3a9", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 62, "avg_line_length": 19.35, "alnum_prop": 0.5684754521963824, "repo_name": "manastech/vertica", "id": "9352e147de793e5f46a8c3aa5905e2ddd260290b", "size": "387", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/vertica/messages/backend_messages/ready_for_query.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2865" }, { "name": "Ruby", "bytes": "59448" } ], "symlink_target": "" }
package drivers import ( "bufio" "bytes" "context" "database/sql" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net" "net/http" "os" "os/exec" "path" "path/filepath" "runtime" "sort" "strconv" "strings" "sync" "syscall" "time" "github.com/flosch/pongo2" liblxc "github.com/lxc/go-lxc" "github.com/pborman/uuid" "github.com/pkg/sftp" "golang.org/x/sys/unix" yaml "gopkg.in/yaml.v2" "github.com/lxc/lxd/lxd/apparmor" "github.com/lxc/lxd/lxd/cgroup" "github.com/lxc/lxd/lxd/daemon" "github.com/lxc/lxd/lxd/db" "github.com/lxc/lxd/lxd/db/cluster" "github.com/lxc/lxd/lxd/device" deviceConfig "github.com/lxc/lxd/lxd/device/config" "github.com/lxc/lxd/lxd/device/nictype" "github.com/lxc/lxd/lxd/instance" "github.com/lxc/lxd/lxd/instance/instancetype" "github.com/lxc/lxd/lxd/instance/operationlock" "github.com/lxc/lxd/lxd/lifecycle" "github.com/lxc/lxd/lxd/locking" "github.com/lxc/lxd/lxd/metrics" "github.com/lxc/lxd/lxd/network" "github.com/lxc/lxd/lxd/project" "github.com/lxc/lxd/lxd/response" "github.com/lxc/lxd/lxd/revert" "github.com/lxc/lxd/lxd/seccomp" "github.com/lxc/lxd/lxd/state" storagePools "github.com/lxc/lxd/lxd/storage" storageDrivers "github.com/lxc/lxd/lxd/storage/drivers" "github.com/lxc/lxd/lxd/storage/filesystem" "github.com/lxc/lxd/lxd/template" "github.com/lxc/lxd/lxd/util" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/api" "github.com/lxc/lxd/shared/idmap" "github.com/lxc/lxd/shared/instancewriter" "github.com/lxc/lxd/shared/logger" "github.com/lxc/lxd/shared/netutils" "github.com/lxc/lxd/shared/osarch" "github.com/lxc/lxd/shared/termios" "github.com/lxc/lxd/shared/units" ) // Helper functions. func lxcSetConfigItem(c *liblxc.Container, key string, value string) error { if c == nil { return fmt.Errorf("Uninitialized go-lxc struct") } if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) { switch key { case "lxc.uts.name": key = "lxc.utsname" case "lxc.pty.max": key = "lxc.pts" case "lxc.tty.dir": key = "lxc.devttydir" case "lxc.tty.max": key = "lxc.tty" case "lxc.apparmor.profile": key = "lxc.aa_profile" case "lxc.apparmor.allow_incomplete": key = "lxc.aa_allow_incomplete" case "lxc.selinux.context": key = "lxc.se_context" case "lxc.mount.fstab": key = "lxc.mount" case "lxc.console.path": key = "lxc.console" case "lxc.seccomp.profile": key = "lxc.seccomp" case "lxc.signal.halt": key = "lxc.haltsignal" case "lxc.signal.reboot": key = "lxc.rebootsignal" case "lxc.signal.stop": key = "lxc.stopsignal" case "lxc.log.syslog": key = "lxc.syslog" case "lxc.log.level": key = "lxc.loglevel" case "lxc.log.file": key = "lxc.logfile" case "lxc.init.cmd": key = "lxc.init_cmd" case "lxc.init.uid": key = "lxc.init_uid" case "lxc.init.gid": key = "lxc.init_gid" case "lxc.idmap": key = "lxc.id_map" } } if strings.HasPrefix(key, "lxc.prlimit.") { if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) { return fmt.Errorf(`Process limits require liblxc >= 2.1`) } } err := c.SetConfigItem(key, value) if err != nil { return fmt.Errorf("Failed to set LXC config: %s=%s", key, value) } return nil } func lxcStatusCode(state liblxc.State) api.StatusCode { return map[int]api.StatusCode{ 1: api.Stopped, 2: api.Starting, 3: api.Running, 4: api.Stopping, 5: api.Aborting, 6: api.Freezing, 7: api.Frozen, 8: api.Thawed, 9: api.Error, }[int(state)] } // lxcCreate creates the DB storage records and sets up instance devices. // Returns a revert fail function that can be used to undo this function if a subsequent step fails. func lxcCreate(s *state.State, args db.InstanceArgs) (instance.Instance, revert.Hook, error) { revert := revert.New() defer revert.Fail() // Create the container struct d := &lxc{ common: common{ state: s, architecture: args.Architecture, creationDate: args.CreationDate, dbType: args.Type, description: args.Description, ephemeral: args.Ephemeral, expiryDate: args.ExpiryDate, id: args.ID, lastUsedDate: args.LastUsedDate, localConfig: args.Config, localDevices: args.Devices, logger: logger.AddContext(logger.Log, logger.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}), name: args.Name, node: args.Node, profiles: args.Profiles, project: args.Project, snapshot: args.Snapshot, stateful: args.Stateful, }, } // Cleanup the zero values if d.expiryDate.IsZero() { d.expiryDate = time.Time{} } if d.creationDate.IsZero() { d.creationDate = time.Time{} } if d.lastUsedDate.IsZero() { d.lastUsedDate = time.Time{} } d.logger.Info("Creating instance", logger.Ctx{"ephemeral": d.ephemeral}) // Load the config. err := d.init() if err != nil { return nil, nil, fmt.Errorf("Failed to expand config: %w", err) } // Validate expanded config (allows mixed instance types for profiles). err = instance.ValidConfig(s.OS, d.expandedConfig, true, instancetype.Any) if err != nil { return nil, nil, fmt.Errorf("Invalid config: %w", err) } err = instance.ValidDevices(s, d.Project(), d.Type(), d.expandedDevices, true) if err != nil { return nil, nil, fmt.Errorf("Invalid devices: %w", err) } _, rootDiskDevice, err := d.getRootDiskDevice() if err != nil { return nil, nil, fmt.Errorf("Failed getting root disk: %w", err) } if rootDiskDevice["pool"] == "" { return nil, nil, fmt.Errorf("The instance's root device is missing the pool property") } // Initialize the storage pool. d.storagePool, err = storagePools.LoadByName(d.state, rootDiskDevice["pool"]) if err != nil { return nil, nil, fmt.Errorf("Failed loading storage pool: %w", err) } volType, err := storagePools.InstanceTypeToVolumeType(d.Type()) if err != nil { return nil, nil, err } storagePoolSupported := false for _, supportedType := range d.storagePool.Driver().Info().VolumeTypes { if supportedType == volType { storagePoolSupported = true break } } if !storagePoolSupported { return nil, nil, fmt.Errorf("Storage pool does not support instance type") } // Setup initial idmap config var idmap *idmap.IdmapSet base := int64(0) if !d.IsPrivileged() { idmap, base, err = findIdmap( s, args.Name, d.expandedConfig["security.idmap.isolated"], d.expandedConfig["security.idmap.base"], d.expandedConfig["security.idmap.size"], d.expandedConfig["raw.idmap"], ) if err != nil { return nil, nil, err } } var jsonIdmap string if idmap != nil { idmapBytes, err := json.Marshal(idmap.Idmap) if err != nil { return nil, nil, err } jsonIdmap = string(idmapBytes) } else { jsonIdmap = "[]" } v := map[string]string{ "volatile.idmap.next": jsonIdmap, "volatile.idmap.base": fmt.Sprintf("%v", base), } // Invalid idmap cache. d.idmapset = nil // Set last_state if not currently set. if d.localConfig["volatile.last_state.idmap"] == "" { v["volatile.last_state.idmap"] = "[]" } err = d.VolatileSet(v) if err != nil { return nil, nil, err } // Re-run init to update the idmap. err = d.init() if err != nil { return nil, nil, err } if !d.IsSnapshot() { // Add devices to container. cleanup, err := d.devicesAdd(d, false) if err != nil { return nil, nil, err } revert.Add(cleanup) } d.logger.Info("Created container", logger.Ctx{"ephemeral": d.ephemeral}) if d.snapshot { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotCreated.Event(d, nil)) } else { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceCreated.Event(d, map[string]any{ "type": api.InstanceTypeContainer, "storage-pool": d.storagePool.Name(), })) } cleanup := revert.Clone().Fail revert.Success() return d, cleanup, err } func lxcLoad(s *state.State, args db.InstanceArgs, profiles []api.Profile) (instance.Instance, error) { // Create the container struct d := lxcInstantiate(s, args, nil) // Setup finalizer runtime.SetFinalizer(d, lxcUnload) // Expand config and devices err := d.(*lxc).expandConfig(profiles) if err != nil { return nil, err } return d, nil } // Unload is called by the garbage collector. func lxcUnload(d *lxc) { runtime.SetFinalizer(d, nil) d.release() } // release releases any internal reference to a liblxc container, invalidating the go-lxc cache. func (d *lxc) release() { if d.c != nil { _ = d.c.Release() d.c = nil } } // Create a container struct without initializing it. func lxcInstantiate(s *state.State, args db.InstanceArgs, expandedDevices deviceConfig.Devices) instance.Instance { d := &lxc{ common: common{ state: s, architecture: args.Architecture, creationDate: args.CreationDate, dbType: args.Type, description: args.Description, ephemeral: args.Ephemeral, expiryDate: args.ExpiryDate, id: args.ID, lastUsedDate: args.LastUsedDate, localConfig: args.Config, localDevices: args.Devices, logger: logger.AddContext(logger.Log, logger.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}), name: args.Name, node: args.Node, profiles: args.Profiles, project: args.Project, snapshot: args.Snapshot, stateful: args.Stateful, }, } // Cleanup the zero values if d.expiryDate.IsZero() { d.expiryDate = time.Time{} } if d.creationDate.IsZero() { d.creationDate = time.Time{} } if d.lastUsedDate.IsZero() { d.lastUsedDate = time.Time{} } // This is passed during expanded config validation. if expandedDevices != nil { d.expandedDevices = expandedDevices } return d } // The LXC container driver. type lxc struct { common // Config handling. fromHook bool // Cached handles. // Do not use these variables directly, instead use their associated get functions so they // will be initialised on demand. c *liblxc.Container cConfig bool idmapset *idmap.IdmapSet } func idmapSize(state *state.State, isolatedStr string, size string) (int64, error) { isolated := false if shared.IsTrue(isolatedStr) { isolated = true } var idMapSize int64 if size == "" || size == "auto" { if isolated { idMapSize = 65536 } else { if len(state.OS.IdmapSet.Idmap) != 2 { return 0, fmt.Errorf("bad initial idmap: %v", state.OS.IdmapSet) } idMapSize = state.OS.IdmapSet.Idmap[0].Maprange } } else { size, err := strconv.ParseInt(size, 10, 64) if err != nil { return 0, err } idMapSize = size } return idMapSize, nil } var idmapLock sync.Mutex func findIdmap(state *state.State, cName string, isolatedStr string, configBase string, configSize string, rawIdmap string) (*idmap.IdmapSet, int64, error) { isolated := false if shared.IsTrue(isolatedStr) { isolated = true } rawMaps, err := idmap.ParseRawIdmap(rawIdmap) if err != nil { return nil, 0, err } if !isolated { newIdmapset := idmap.IdmapSet{Idmap: make([]idmap.IdmapEntry, len(state.OS.IdmapSet.Idmap))} copy(newIdmapset.Idmap, state.OS.IdmapSet.Idmap) for _, ent := range rawMaps { err := newIdmapset.AddSafe(ent) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } } return &newIdmapset, 0, nil } size, err := idmapSize(state, isolatedStr, configSize) if err != nil { return nil, 0, err } mkIdmap := func(offset int64, size int64) (*idmap.IdmapSet, error) { set := &idmap.IdmapSet{Idmap: []idmap.IdmapEntry{ {Isuid: true, Nsid: 0, Hostid: offset, Maprange: size}, {Isgid: true, Nsid: 0, Hostid: offset, Maprange: size}, }} for _, ent := range rawMaps { err := set.AddSafe(ent) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, err } } return set, nil } if configBase != "" { offset, err := strconv.ParseInt(configBase, 10, 64) if err != nil { return nil, 0, err } set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } idmapLock.Lock() defer idmapLock.Unlock() cts, err := instance.LoadNodeAll(state, instancetype.Container) if err != nil { return nil, 0, err } offset := state.OS.IdmapSet.Idmap[0].Hostid + 65536 mapentries := idmap.ByHostid{} for _, container := range cts { if container.Type() != instancetype.Container { continue } name := container.Name() /* Don't change our map Just Because. */ if name == cName { continue } if container.IsPrivileged() { continue } if shared.IsFalseOrEmpty(container.ExpandedConfig()["security.idmap.isolated"]) { continue } cBase := int64(0) if container.ExpandedConfig()["volatile.idmap.base"] != "" { cBase, err = strconv.ParseInt(container.ExpandedConfig()["volatile.idmap.base"], 10, 64) if err != nil { return nil, 0, err } } cSize, err := idmapSize(state, container.ExpandedConfig()["security.idmap.isolated"], container.ExpandedConfig()["security.idmap.size"]) if err != nil { return nil, 0, err } mapentries = append(mapentries, &idmap.IdmapEntry{Hostid: int64(cBase), Maprange: cSize}) } sort.Sort(mapentries) for i := range mapentries { if i == 0 { if mapentries[0].Hostid < offset+size { offset = mapentries[0].Hostid + mapentries[0].Maprange continue } set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } if mapentries[i-1].Hostid+mapentries[i-1].Maprange > offset { offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange continue } offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange if offset+size < mapentries[i].Hostid { set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } offset = mapentries[i].Hostid + mapentries[i].Maprange } if offset+size < state.OS.IdmapSet.Idmap[0].Hostid+state.OS.IdmapSet.Idmap[0].Maprange { set, err := mkIdmap(offset, size) if err != nil && err == idmap.ErrHostIdIsSubId { return nil, 0, err } return set, offset, nil } return nil, 0, fmt.Errorf("Not enough uid/gid available for the container") } func (d *lxc) init() error { // Compute the expanded config and device list err := d.expandConfig(nil) if err != nil { return err } return nil } func (d *lxc) initLXC(config bool) error { // No need to go through all that for snapshots if d.IsSnapshot() { return nil } // Check if being called from a hook if d.fromHook { return fmt.Errorf("You can't use go-lxc from inside a LXC hook") } // Check if already initialized if d.c != nil { if !config || d.cConfig { return nil } } // Load the go-lxc struct cname := project.Instance(d.Project(), d.Name()) cc, err := liblxc.NewContainer(cname, d.state.OS.LxcPath) if err != nil { return err } // Load cgroup abstraction cg, err := d.cgroup(cc) if err != nil { return err } freeContainer := true defer func() { if freeContainer { _ = cc.Release() } }() // Setup logging logfile := d.LogFilePath() err = lxcSetConfigItem(cc, "lxc.log.file", logfile) if err != nil { return err } logLevel := "warn" if daemon.Debug { logLevel = "trace" } else if daemon.Verbose { logLevel = "info" } err = lxcSetConfigItem(cc, "lxc.log.level", logLevel) if err != nil { return err } if liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 3, 0, 0) { // Default size log buffer err = lxcSetConfigItem(cc, "lxc.console.buffer.size", "auto") if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.console.size", "auto") if err != nil { return err } // File to dump ringbuffer contents to when requested or // container shutdown. consoleBufferLogFile := d.ConsoleBufferLogPath() err = lxcSetConfigItem(cc, "lxc.console.logfile", consoleBufferLogFile) if err != nil { return err } } if d.state.OS.ContainerCoreScheduling { err = lxcSetConfigItem(cc, "lxc.sched.core", "1") if err != nil { return err } } else if d.state.OS.CoreScheduling { err = lxcSetConfigItem(cc, "lxc.hook.start-host", fmt.Sprintf("/proc/%d/exe forkcoresched 1", os.Getpid())) if err != nil { return err } } // Allow for lightweight init d.cConfig = config if !config { if d.c != nil { _ = d.c.Release() } d.c = cc freeContainer = false return nil } if d.IsPrivileged() { // Base config toDrop := "sys_time sys_module sys_rawio" if !d.state.OS.AppArmorStacking || d.state.OS.AppArmorStacked { toDrop = toDrop + " mac_admin mac_override" } err = lxcSetConfigItem(cc, "lxc.cap.drop", toDrop) if err != nil { return err } } // Set an appropriate /proc, /sys/ and /sys/fs/cgroup mounts := []string{} if d.IsPrivileged() && !d.state.OS.RunningInUserNS { mounts = append(mounts, "proc:mixed") mounts = append(mounts, "sys:mixed") } else { mounts = append(mounts, "proc:rw") mounts = append(mounts, "sys:rw") } cgInfo := cgroup.GetInfo() if cgInfo.Namespacing { if cgInfo.Layout == cgroup.CgroupsUnified { mounts = append(mounts, "cgroup:rw:force") } else { mounts = append(mounts, "cgroup:mixed") } } else { mounts = append(mounts, "cgroup:mixed") } err = lxcSetConfigItem(cc, "lxc.mount.auto", strings.Join(mounts, " ")) if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.autodev", "1") if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.pty.max", "1024") if err != nil { return err } bindMounts := []string{ "/dev/fuse", "/dev/net/tun", "/proc/sys/fs/binfmt_misc", "/sys/firmware/efi/efivars", "/sys/fs/fuse/connections", "/sys/fs/pstore", "/sys/kernel/config", "/sys/kernel/debug", "/sys/kernel/security", "/sys/kernel/tracing", } if d.IsPrivileged() && !d.state.OS.RunningInUserNS { err = lxcSetConfigItem(cc, "lxc.mount.entry", "mqueue dev/mqueue mqueue rw,relatime,create=dir,optional 0 0") if err != nil { return err } } else { bindMounts = append(bindMounts, "/dev/mqueue") } for _, mnt := range bindMounts { if !shared.PathExists(mnt) { continue } if shared.IsDir(mnt) { err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none rbind,create=dir,optional 0 0", mnt, strings.TrimPrefix(mnt, "/"))) if err != nil { return err } } else { err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none bind,create=file,optional 0 0", mnt, strings.TrimPrefix(mnt, "/"))) if err != nil { return err } } } // For lxcfs templateConfDir := os.Getenv("LXD_LXC_TEMPLATE_CONFIG") if templateConfDir == "" { templateConfDir = "/usr/share/lxc/config" } if shared.PathExists(fmt.Sprintf("%s/common.conf.d/", templateConfDir)) { err = lxcSetConfigItem(cc, "lxc.include", fmt.Sprintf("%s/common.conf.d/", templateConfDir)) if err != nil { return err } } // Configure devices cgroup if d.IsPrivileged() && !d.state.OS.RunningInUserNS && d.state.OS.CGInfo.Supports(cgroup.Devices, cg) { if d.state.OS.CGInfo.Layout == cgroup.CgroupsUnified { err = lxcSetConfigItem(cc, "lxc.cgroup2.devices.deny", "a") } else { err = lxcSetConfigItem(cc, "lxc.cgroup.devices.deny", "a") } if err != nil { return err } devices := []string{ "b *:* m", // Allow mknod of block devices "c *:* m", // Allow mknod of char devices "c 136:* rwm", // /dev/pts devices "c 1:3 rwm", // /dev/null "c 1:5 rwm", // /dev/zero "c 1:7 rwm", // /dev/full "c 1:8 rwm", // /dev/random "c 1:9 rwm", // /dev/urandom "c 5:0 rwm", // /dev/tty "c 5:1 rwm", // /dev/console "c 5:2 rwm", // /dev/ptmx "c 10:229 rwm", // /dev/fuse "c 10:200 rwm", // /dev/net/tun } for _, dev := range devices { if d.state.OS.CGInfo.Layout == cgroup.CgroupsUnified { err = lxcSetConfigItem(cc, "lxc.cgroup2.devices.allow", dev) } else { err = lxcSetConfigItem(cc, "lxc.cgroup.devices.allow", dev) } if err != nil { return err } } } if d.IsNesting() { /* * mount extra /proc and /sys to work around kernel * restrictions on remounting them when covered */ err = lxcSetConfigItem(cc, "lxc.mount.entry", "proc dev/.lxc/proc proc create=dir,optional 0 0") if err != nil { return err } err = lxcSetConfigItem(cc, "lxc.mount.entry", "sys dev/.lxc/sys sysfs create=dir,optional 0 0") if err != nil { return err } } // Setup architecture personality, err := osarch.ArchitecturePersonality(d.architecture) if err != nil { personality, err = osarch.ArchitecturePersonality(d.state.OS.Architectures[0]) if err != nil { return err } } err = lxcSetConfigItem(cc, "lxc.arch", personality) if err != nil { return err } // Setup the hooks err = lxcSetConfigItem(cc, "lxc.hook.version", "1") if err != nil { return err } // Call the onstart hook on start. err = lxcSetConfigItem(cc, "lxc.hook.pre-start", fmt.Sprintf("/proc/%d/exe callhook %s %s %s start", os.Getpid(), shared.VarPath(""), strconv.Quote(d.Project()), strconv.Quote(d.Name()))) if err != nil { return err } // Call the onstopns hook on stop but before namespaces are unmounted. err = lxcSetConfigItem(cc, "lxc.hook.stop", fmt.Sprintf("%s callhook %s %s %s stopns", d.state.OS.ExecPath, shared.VarPath(""), strconv.Quote(d.Project()), strconv.Quote(d.Name()))) if err != nil { return err } // Call the onstop hook on stop. err = lxcSetConfigItem(cc, "lxc.hook.post-stop", fmt.Sprintf("%s callhook %s %s %s stop", d.state.OS.ExecPath, shared.VarPath(""), strconv.Quote(d.Project()), strconv.Quote(d.Name()))) if err != nil { return err } // Setup the console err = lxcSetConfigItem(cc, "lxc.tty.max", "0") if err != nil { return err } // Setup the hostname err = lxcSetConfigItem(cc, "lxc.uts.name", d.Name()) if err != nil { return err } // Setup devlxd if d.expandedConfig["security.devlxd"] == "" || shared.IsTrue(d.expandedConfig["security.devlxd"]) { err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/lxd none bind,create=dir 0 0", shared.VarPath("devlxd"))) if err != nil { return err } } // Setup AppArmor if d.state.OS.AppArmorAvailable { if d.state.OS.AppArmorConfined || !d.state.OS.AppArmorAdmin { // If confined but otherwise able to use AppArmor, use our own profile curProfile := util.AppArmorProfile() curProfile = strings.TrimSuffix(curProfile, " (enforce)") err := lxcSetConfigItem(cc, "lxc.apparmor.profile", curProfile) if err != nil { return err } } else { // If not currently confined, use the container's profile profile := apparmor.InstanceProfileName(d) /* In the nesting case, we want to enable the inside * LXD to load its profile. Unprivileged containers can * load profiles, but privileged containers cannot, so * let's not use a namespace so they can fall back to * the old way of nesting, i.e. using the parent's * profile. */ if d.state.OS.AppArmorStacking && !d.state.OS.AppArmorStacked { profile = fmt.Sprintf("%s//&:%s:", profile, apparmor.InstanceNamespaceName(d)) } err := lxcSetConfigItem(cc, "lxc.apparmor.profile", profile) if err != nil { return err } } } else { // Make sure that LXC won't try to apply an apparmor profile. // This may fail on liblxc compiled without apparmor, so ignore errors. _ = lxcSetConfigItem(cc, "lxc.apparmor.profile", "unconfined") } // Setup Seccomp if necessary if seccomp.InstanceNeedsPolicy(d) { err = lxcSetConfigItem(cc, "lxc.seccomp.profile", seccomp.ProfilePath(d)) if err != nil { return err } // Setup notification socket // System requirement errors are handled during policy generation instead of here ok, err := seccomp.InstanceNeedsIntercept(d.state, d) if err == nil && ok { err = lxcSetConfigItem(cc, "lxc.seccomp.notify.proxy", fmt.Sprintf("unix:%s", shared.VarPath("seccomp.socket"))) if err != nil { return err } } } // Setup idmap idmapset, err := d.NextIdmap() if err != nil { return err } if idmapset != nil { lines := idmapset.ToLxcString() for _, line := range lines { err := lxcSetConfigItem(cc, "lxc.idmap", line) if err != nil { return err } } } // Setup environment for k, v := range d.expandedConfig { if strings.HasPrefix(k, "environment.") { err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("%s=%s", strings.TrimPrefix(k, "environment."), v)) if err != nil { return err } } } // Setup NVIDIA runtime if shared.IsTrue(d.expandedConfig["nvidia.runtime"]) { hookDir := os.Getenv("LXD_LXC_HOOK") if hookDir == "" { hookDir = "/usr/share/lxc/hooks" } hookPath := filepath.Join(hookDir, "nvidia") if !shared.PathExists(hookPath) { return fmt.Errorf("The NVIDIA LXC hook couldn't be found") } _, err := exec.LookPath("nvidia-container-cli") if err != nil { return fmt.Errorf("The NVIDIA container tools couldn't be found") } err = lxcSetConfigItem(cc, "lxc.environment", "NVIDIA_VISIBLE_DEVICES=none") if err != nil { return err } nvidiaDriver := d.expandedConfig["nvidia.driver.capabilities"] if nvidiaDriver == "" { err = lxcSetConfigItem(cc, "lxc.environment", "NVIDIA_DRIVER_CAPABILITIES=compute,utility") if err != nil { return err } } else { err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_DRIVER_CAPABILITIES=%s", nvidiaDriver)) if err != nil { return err } } nvidiaRequireCuda := d.expandedConfig["nvidia.require.cuda"] if nvidiaRequireCuda == "" { err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_REQUIRE_CUDA=%s", nvidiaRequireCuda)) if err != nil { return err } } nvidiaRequireDriver := d.expandedConfig["nvidia.require.driver"] if nvidiaRequireDriver == "" { err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_REQUIRE_DRIVER=%s", nvidiaRequireDriver)) if err != nil { return err } } err = lxcSetConfigItem(cc, "lxc.hook.mount", hookPath) if err != nil { return err } } // Memory limits if d.state.OS.CGInfo.Supports(cgroup.Memory, cg) { memory := d.expandedConfig["limits.memory"] memoryEnforce := d.expandedConfig["limits.memory.enforce"] memorySwap := d.expandedConfig["limits.memory.swap"] memorySwapPriority := d.expandedConfig["limits.memory.swap.priority"] // Configure the memory limits if memory != "" { var valueInt int64 if strings.HasSuffix(memory, "%") { percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64) if err != nil { return err } memoryTotal, err := shared.DeviceTotalMemory() if err != nil { return err } valueInt = int64((memoryTotal / 100) * percent) } else { valueInt, err = units.ParseByteSizeString(memory) if err != nil { return err } } if memoryEnforce == "soft" { err = cg.SetMemorySoftLimit(valueInt) if err != nil { return err } } else { if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) { err = cg.SetMemoryLimit(valueInt) if err != nil { return err } err = cg.SetMemorySwapLimit(0) if err != nil { return err } } else { err = cg.SetMemoryLimit(valueInt) if err != nil { return err } } // Set soft limit to value 10% less than hard limit err = cg.SetMemorySoftLimit(int64(float64(valueInt) * 0.9)) if err != nil { return err } } } if d.state.OS.CGInfo.Supports(cgroup.MemorySwappiness, cg) { // Configure the swappiness if shared.IsFalse(memorySwap) { err = cg.SetMemorySwappiness(0) if err != nil { return err } } else if memorySwapPriority != "" { priority, err := strconv.Atoi(memorySwapPriority) if err != nil { return err } // Maximum priority (10) should be default swappiness (60). err = cg.SetMemorySwappiness(int64(70 - priority)) if err != nil { return err } } } } // CPU limits cpuPriority := d.expandedConfig["limits.cpu.priority"] cpuAllowance := d.expandedConfig["limits.cpu.allowance"] if (cpuPriority != "" || cpuAllowance != "") && d.state.OS.CGInfo.Supports(cgroup.CPU, cg) { cpuShares, cpuCfsQuota, cpuCfsPeriod, err := cgroup.ParseCPU(cpuAllowance, cpuPriority) if err != nil { return err } if cpuShares != 1024 { err = cg.SetCPUShare(cpuShares) if err != nil { return err } } if cpuCfsPeriod != -1 && cpuCfsQuota != -1 { err = cg.SetCPUCfsLimit(cpuCfsPeriod, cpuCfsQuota) if err != nil { return err } } } // Disk priority limits. diskPriority := d.ExpandedConfig()["limits.disk.priority"] if diskPriority != "" { if d.state.OS.CGInfo.Supports(cgroup.BlkioWeight, nil) { priorityInt, err := strconv.Atoi(diskPriority) if err != nil { return err } priority := priorityInt * 100 // Minimum valid value is 10 if priority == 0 { priority = 10 } err = cg.SetBlkioWeight(int64(priority)) if err != nil { return err } } else { return fmt.Errorf("Cannot apply limits.disk.priority as blkio.weight cgroup controller is missing") } } // Processes if d.state.OS.CGInfo.Supports(cgroup.Pids, cg) { processes := d.expandedConfig["limits.processes"] if processes != "" { valueInt, err := strconv.ParseInt(processes, 10, 64) if err != nil { return err } err = cg.SetMaxProcesses(valueInt) if err != nil { return err } } } // Hugepages if d.state.OS.CGInfo.Supports(cgroup.Hugetlb, cg) { for i, key := range shared.HugePageSizeKeys { value := d.expandedConfig[key] if value != "" { value, err := units.ParseByteSizeString(value) if err != nil { return err } err = cg.SetHugepagesLimit(shared.HugePageSizeSuffix[i], value) if err != nil { return err } } } } // Setup process limits for k, v := range d.expandedConfig { if strings.HasPrefix(k, "limits.kernel.") { prlimitSuffix := strings.TrimPrefix(k, "limits.kernel.") prlimitKey := fmt.Sprintf("lxc.prlimit.%s", prlimitSuffix) err = lxcSetConfigItem(cc, prlimitKey, v) if err != nil { return err } } } // Setup sysctls for k, v := range d.expandedConfig { if strings.HasPrefix(k, "linux.sysctl.") { sysctlSuffix := strings.TrimPrefix(k, "linux.sysctl.") sysctlKey := fmt.Sprintf("lxc.sysctl.%s", sysctlSuffix) err = lxcSetConfigItem(cc, sysctlKey, v) if err != nil { return err } } } // Setup shmounts if d.state.OS.LXCFeatures["mount_injection_file"] { err = lxcSetConfigItem(cc, "lxc.mount.auto", fmt.Sprintf("shmounts:%s:/dev/.lxd-mounts", d.ShmountsPath())) } else { err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/.lxd-mounts none bind,create=dir 0 0", d.ShmountsPath())) } if err != nil { return err } if d.c != nil { _ = d.c.Release() } d.c = cc freeContainer = false return nil } var idmappedStorageMap map[unix.Fsid]idmap.IdmapStorageType = map[unix.Fsid]idmap.IdmapStorageType{} var idmappedStorageMapLock sync.Mutex // IdmappedStorage determines if the container can use idmapped mounts or shiftfs. func (d *lxc) IdmappedStorage(path string) idmap.IdmapStorageType { var mode idmap.IdmapStorageType = idmap.IdmapStorageNone if d.state.OS.Shiftfs { // Fallback to shiftfs. mode = idmap.IdmapStorageShiftfs } if !d.state.OS.LXCFeatures["idmapped_mounts_v2"] || !d.state.OS.IdmappedMounts { return mode } buf := &unix.Statfs_t{} err := unix.Statfs(path, buf) if err != nil { // Log error but fallback to shiftfs d.logger.Error("Failed to statfs", logger.Ctx{"path": path, "err": err}) return mode } idmappedStorageMapLock.Lock() defer idmappedStorageMapLock.Unlock() val, ok := idmappedStorageMap[buf.Fsid] if ok { // Return recorded idmapping type. return val } if idmap.CanIdmapMount(path) { // Use idmapped mounts. mode = idmap.IdmapStorageIdmapped } idmappedStorageMap[buf.Fsid] = mode return mode } func (d *lxc) devlxdEventSend(eventType string, eventMessage map[string]any) error { event := shared.Jmap{} event["type"] = eventType event["timestamp"] = time.Now() event["metadata"] = eventMessage return d.state.DevlxdEvents.Send(d.ID(), eventType, eventMessage) } // RegisterDevices calls the Register() function on all of the instance's devices. func (d *lxc) RegisterDevices() { d.devicesRegister(d) } // deviceStart loads a new device and calls its Start() function. func (d *lxc) deviceStart(dev device.Device, instanceRunning bool) (*deviceConfig.RunConfig, error) { configCopy := dev.Config() l := d.logger.AddContext(logger.Ctx{"device": dev.Name(), "type": configCopy["type"]}) l.Debug("Starting device") revert := revert.New() defer revert.Fail() if instanceRunning && !dev.CanHotPlug() { return nil, fmt.Errorf("Device cannot be started when instance is running") } runConf, err := dev.Start() if err != nil { return nil, err } revert.Add(func() { runConf, _ := dev.Stop() if runConf != nil { _ = d.runHooks(runConf.PostHooks) } }) // If runConf supplied, perform any container specific setup of device. if runConf != nil { // Shift device file ownership if needed before mounting into container. // This needs to be done whether or not container is running. if len(runConf.Mounts) > 0 { err := d.deviceStaticShiftMounts(runConf.Mounts) if err != nil { return nil, err } } // If container is running and then live attach device. if instanceRunning { // Attach mounts if requested. if len(runConf.Mounts) > 0 { err = d.deviceHandleMounts(runConf.Mounts) if err != nil { return nil, err } } // Add cgroup rules if requested. if len(runConf.CGroups) > 0 { err = d.deviceAddCgroupRules(runConf.CGroups) if err != nil { return nil, err } } // Attach network interface if requested. if len(runConf.NetworkInterface) > 0 { err = d.deviceAttachNIC(configCopy, runConf.NetworkInterface) if err != nil { return nil, err } } // If running, run post start hooks now (if not running LXD will run them // once the instance is started). err = d.runHooks(runConf.PostHooks) if err != nil { return nil, err } } } revert.Success() return runConf, nil } // deviceStaticShiftMounts statically shift device mount files ownership to active idmap if needed. func (d *lxc) deviceStaticShiftMounts(mounts []deviceConfig.MountEntryItem) error { idmapSet, err := d.CurrentIdmap() if err != nil { return fmt.Errorf("Failed to get idmap for device: %s", err) } // If there is an idmap being applied and LXD not running in a user namespace then shift the // device files before they are mounted. if idmapSet != nil && !d.state.OS.RunningInUserNS { for _, mount := range mounts { // Skip UID/GID shifting if OwnerShift mode is not static, or the host-side // DevPath is empty (meaning an unmount request that doesn't need shifting). if mount.OwnerShift != deviceConfig.MountOwnerShiftStatic || mount.DevPath == "" { continue } err := idmapSet.ShiftFile(mount.DevPath) if err != nil { // uidshift failing is weird, but not a big problem. Log and proceed. d.logger.Debug("Failed to uidshift device", logger.Ctx{"mountDevPath": mount.DevPath, "err": err}) } } } return nil } // deviceAddCgroupRules live adds cgroup rules to a container. func (d *lxc) deviceAddCgroupRules(cgroups []deviceConfig.RunConfigItem) error { cg, err := d.cgroup(nil) if err != nil { return err } for _, rule := range cgroups { // Only apply devices cgroup rules if container is running privileged and host has devices cgroup controller. if strings.HasPrefix(rule.Key, "devices.") && (!d.isCurrentlyPrivileged() || d.state.OS.RunningInUserNS || !d.state.OS.CGInfo.Supports(cgroup.Devices, cg)) { continue } // Add the new device cgroup rule. err := d.CGroupSet(rule.Key, rule.Value) if err != nil { return fmt.Errorf("Failed to add cgroup rule for device") } } return nil } // deviceAttachNIC live attaches a NIC device to a container. func (d *lxc) deviceAttachNIC(configCopy map[string]string, netIF []deviceConfig.RunConfigItem) error { devName := "" for _, dev := range netIF { if dev.Key == "link" { devName = dev.Value break } } if devName == "" { return fmt.Errorf("Device didn't provide a link property to use") } // Load the go-lxc struct. err := d.initLXC(false) if err != nil { return err } // Add the interface to the container. err = d.c.AttachInterface(devName, configCopy["name"]) if err != nil { return fmt.Errorf("Failed to attach interface: %s to %s: %w", devName, configCopy["name"], err) } return nil } // deviceStop loads a new device and calls its Stop() function. // Accepts a stopHookNetnsPath argument which is required when run from the onStopNS hook before the // container's network namespace is unmounted (which is required for NIC device cleanup). func (d *lxc) deviceStop(dev device.Device, instanceRunning bool, stopHookNetnsPath string) error { configCopy := dev.Config() l := d.logger.AddContext(logger.Ctx{"device": dev.Name(), "type": configCopy["type"]}) l.Debug("Stopping device") if instanceRunning && !dev.CanHotPlug() { return fmt.Errorf("Device cannot be stopped when instance is running") } runConf, err := dev.Stop() if err != nil { return err } if runConf != nil { // If network interface settings returned, then detach NIC from container. if len(runConf.NetworkInterface) > 0 { err = d.deviceDetachNIC(configCopy, runConf.NetworkInterface, instanceRunning, stopHookNetnsPath) if err != nil { return err } } // Add cgroup rules if requested and container is running. if len(runConf.CGroups) > 0 && instanceRunning { err = d.deviceAddCgroupRules(runConf.CGroups) if err != nil { return err } } // Detach mounts if requested and container is running. if len(runConf.Mounts) > 0 && instanceRunning { err = d.deviceHandleMounts(runConf.Mounts) if err != nil { return err } } // Run post stop hooks irrespective of run state of instance. err = d.runHooks(runConf.PostHooks) if err != nil { return err } } return nil } // deviceDetachNIC detaches a NIC device from a container. // Accepts a stopHookNetnsPath argument which is required when run from the onStopNS hook before the // container's network namespace is unmounted (which is required for NIC device cleanup). func (d *lxc) deviceDetachNIC(configCopy map[string]string, netIF []deviceConfig.RunConfigItem, instanceRunning bool, stopHookNetnsPath string) error { // Get requested device name to detach interface back to on the host. devName := "" for _, dev := range netIF { if dev.Key == "link" { devName = dev.Value break } } if devName == "" { return fmt.Errorf("Device didn't provide a link property to use") } // If container is running, perform live detach of interface back to host. if instanceRunning { // For some reason, having network config confuses detach, so get our own go-lxc struct. cname := project.Instance(d.Project(), d.Name()) cc, err := liblxc.NewContainer(cname, d.state.OS.LxcPath) if err != nil { return err } defer func() { _ = cc.Release() }() // Get interfaces inside container. ifaces, err := cc.Interfaces() if err != nil { return fmt.Errorf("Failed to list network interfaces: %w", err) } // If interface doesn't exist inside container, cannot proceed. if !shared.StringInSlice(configCopy["name"], ifaces) { return nil } err = cc.DetachInterfaceRename(configCopy["name"], devName) if err != nil { return fmt.Errorf("Failed to detach interface: %q to %q: %w", configCopy["name"], devName, err) } } else { // Currently liblxc does not move devices back to the host on stop that were added // after the the container was started. For this reason we utilise the lxc.hook.stop // hook so that we can capture the netns path, enter the namespace and move the nics // back to the host and rename them if liblxc hasn't already done it. // We can only move back devices that have an expected host_name record and where // that device doesn't already exist on the host as if a device exists on the host // we can't know whether that is because liblxc has moved it back already or whether // it is a conflicting device. if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", devName)) { if stopHookNetnsPath == "" { return fmt.Errorf("Cannot detach NIC device %q without stopHookNetnsPath being provided", devName) } err := d.detachInterfaceRename(stopHookNetnsPath, configCopy["name"], devName) if err != nil { return fmt.Errorf("Failed to detach interface: %q to %q: %w", configCopy["name"], devName, err) } d.logger.Debug("Detached NIC device interface", logger.Ctx{"name": configCopy["name"], "device": devName}) } } return nil } // deviceHandleMounts live attaches or detaches mounts on a container. // If the mount DevPath is empty the mount action is treated as unmount. func (d *lxc) deviceHandleMounts(mounts []deviceConfig.MountEntryItem) error { for _, mount := range mounts { if mount.DevPath != "" { flags := 0 // Convert options into flags. for _, opt := range mount.Opts { if opt == "bind" { flags |= unix.MS_BIND } else if opt == "rbind" { flags |= unix.MS_BIND | unix.MS_REC } else if opt == "ro" { flags |= unix.MS_RDONLY } } var idmapType idmap.IdmapStorageType = idmap.IdmapStorageNone if !d.IsPrivileged() && mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic { idmapType = d.IdmappedStorage(mount.DevPath) if idmapType == idmap.IdmapStorageNone { return fmt.Errorf("Required idmapping abilities not available") } } // Mount it into the container. err := d.insertMount(mount.DevPath, mount.TargetPath, mount.FSType, flags, idmapType) if err != nil { return fmt.Errorf("Failed to add mount for device inside container: %s", err) } } else { relativeTargetPath := strings.TrimPrefix(mount.TargetPath, "/") // Connect to files API. files, err := d.FileSFTP() if err != nil { return err } defer func() { _ = files.Close() }() _, err = files.Lstat(relativeTargetPath) if err == nil { err := d.removeMount(mount.TargetPath) if err != nil { return fmt.Errorf("Error unmounting the device path inside container: %s", err) } err = files.Remove(relativeTargetPath) if err != nil { // Only warn here and don't fail as removing a directory // mount may fail if there was already files inside // directory before it was mouted over preventing delete. d.logger.Warn("Could not remove the device path inside container", logger.Ctx{"err": err}) } } } } return nil } // DeviceEventHandler actions the results of a RunConfig after an event has occurred on a device. func (d *lxc) DeviceEventHandler(runConf *deviceConfig.RunConfig) error { // Device events can only be processed when the container is running. if !d.IsRunning() { return nil } if runConf == nil { return nil } // Shift device file ownership if needed before mounting devices into container. if len(runConf.Mounts) > 0 { err := d.deviceStaticShiftMounts(runConf.Mounts) if err != nil { return err } err = d.deviceHandleMounts(runConf.Mounts) if err != nil { return err } } // Add cgroup rules if requested. if len(runConf.CGroups) > 0 { err := d.deviceAddCgroupRules(runConf.CGroups) if err != nil { return err } } // Run any post hooks requested. err := d.runHooks(runConf.PostHooks) if err != nil { return err } // Generate uevent inside container if requested. if len(runConf.Uevents) > 0 { pidFdNr, pidFd := d.inheritInitPidFd() if pidFdNr >= 0 { defer func() { _ = pidFd.Close() }() } for _, eventParts := range runConf.Uevents { ueventArray := make([]string, 6) ueventArray[0] = "forkuevent" ueventArray[1] = "inject" ueventArray[2] = "--" ueventArray[3] = fmt.Sprintf("%d", d.InitPID()) ueventArray[4] = fmt.Sprintf("%d", pidFdNr) length := 0 for _, part := range eventParts { length = length + len(part) + 1 } ueventArray[5] = fmt.Sprintf("%d", length) ueventArray = append(ueventArray, eventParts...) _, _, err := shared.RunCommandSplit(context.TODO(), nil, []*os.File{pidFd}, d.state.OS.ExecPath, ueventArray...) if err != nil { return err } } } return nil } func (d *lxc) handleIdmappedStorage() (idmap.IdmapStorageType, *idmap.IdmapSet, error) { diskIdmap, err := d.DiskIdmap() if err != nil { return idmap.IdmapStorageNone, nil, fmt.Errorf("Set last ID map: %w", err) } nextIdmap, err := d.NextIdmap() if err != nil { return idmap.IdmapStorageNone, nil, fmt.Errorf("Set ID map: %w", err) } // Identical on-disk idmaps so no changes required. if nextIdmap.Equals(diskIdmap) { return idmap.IdmapStorageNone, nextIdmap, nil } // There's no on-disk idmap applied and the container can use idmapped // storage. idmapType := d.IdmappedStorage(d.RootfsPath()) if diskIdmap == nil && idmapType != idmap.IdmapStorageNone { return idmapType, nextIdmap, nil } // We need to change the on-disk idmap but the container is protected // against idmap changes. if shared.IsTrue(d.expandedConfig["security.protection.shift"]) { return idmap.IdmapStorageNone, nil, fmt.Errorf("Container is protected against filesystem shifting") } d.logger.Debug("Container idmap changed, remapping") d.updateProgress("Remapping container filesystem") storageType, err := d.getStorageType() if err != nil { return idmap.IdmapStorageNone, nil, fmt.Errorf("Storage type: %w", err) } // Revert the currently applied on-disk idmap. if diskIdmap != nil { if storageType == "zfs" { err = diskIdmap.UnshiftRootfs(d.RootfsPath(), storageDrivers.ShiftZFSSkipper) } else if storageType == "btrfs" { err = storageDrivers.UnshiftBtrfsRootfs(d.RootfsPath(), diskIdmap) } else { err = diskIdmap.UnshiftRootfs(d.RootfsPath(), nil) } if err != nil { return idmap.IdmapStorageNone, nil, err } } jsonDiskIdmap := "[]" // If the container can't use idmapped storage apply the new on-disk // idmap of the container now. Otherwise we will later instruct LXC to // make use of idmapped storage. if nextIdmap != nil && idmapType == idmap.IdmapStorageNone { if storageType == "zfs" { err = nextIdmap.ShiftRootfs(d.RootfsPath(), storageDrivers.ShiftZFSSkipper) } else if storageType == "btrfs" { err = storageDrivers.ShiftBtrfsRootfs(d.RootfsPath(), nextIdmap) } else { err = nextIdmap.ShiftRootfs(d.RootfsPath(), nil) } if err != nil { return idmap.IdmapStorageNone, nil, err } idmapBytes, err := json.Marshal(nextIdmap.Idmap) if err != nil { return idmap.IdmapStorageNone, nil, err } jsonDiskIdmap = string(idmapBytes) } err = d.VolatileSet(map[string]string{"volatile.last_state.idmap": jsonDiskIdmap}) if err != nil { return idmap.IdmapStorageNone, nextIdmap, fmt.Errorf("Set volatile.last_state.idmap config key on container %q (id %d): %w", d.name, d.id, err) } d.updateProgress("") return idmapType, nextIdmap, nil } // Start functions. func (d *lxc) startCommon() (string, []func() error, error) { revert := revert.New() defer revert.Fail() // Load the go-lxc struct err := d.initLXC(true) if err != nil { return "", nil, fmt.Errorf("Load go-lxc struct: %w", err) } // Ensure cgroup v1 configuration is set appropriately with the image using systemd if d.localConfig["image.requirements.cgroup"] == "v1" && !shared.PathExists("/sys/fs/cgroup/systemd") { return "", nil, fmt.Errorf("The image used by this instance requires a CGroupV1 host system") } // Load any required kernel modules kernelModules := d.expandedConfig["linux.kernel_modules"] if kernelModules != "" { for _, module := range strings.Split(kernelModules, ",") { module = strings.TrimPrefix(module, " ") err := util.LoadModule(module) if err != nil { return "", nil, fmt.Errorf("Failed to load kernel module '%s': %w", module, err) } } } // Rotate the log file. logfile := d.LogFilePath() if shared.PathExists(logfile) { _ = os.Remove(logfile + ".old") err := os.Rename(logfile, logfile+".old") if err != nil { return "", nil, err } } // Wait for any file operations to complete. // This is to avoid having an active mount by forkfile and so all file operations // from this point will use the container's namespace rather than a chroot. d.stopForkfile() // Mount instance root volume. _, err = d.mount() if err != nil { return "", nil, err } revert.Add(func() { _ = d.unmount() }) idmapType, nextIdmap, err := d.handleIdmappedStorage() if err != nil { return "", nil, fmt.Errorf("Failed to handle idmapped storage: %w", err) } var idmapBytes []byte if nextIdmap == nil { idmapBytes = []byte("[]") } else { idmapBytes, err = json.Marshal(nextIdmap.Idmap) if err != nil { return "", nil, err } } if d.localConfig["volatile.idmap.current"] != string(idmapBytes) { err = d.VolatileSet(map[string]string{"volatile.idmap.current": string(idmapBytes)}) if err != nil { return "", nil, fmt.Errorf("Set volatile.idmap.current config key on container %q (id %d): %w", d.name, d.id, err) } } // Generate the Seccomp profile err = seccomp.CreateProfile(d.state, d) if err != nil { return "", nil, err } // Cleanup any existing leftover devices _ = d.removeUnixDevices() _ = d.removeDiskDevices() // Create any missing directories. err = os.MkdirAll(d.LogPath(), 0700) if err != nil { return "", nil, err } err = os.MkdirAll(d.DevicesPath(), 0711) if err != nil { return "", nil, err } err = os.MkdirAll(d.ShmountsPath(), 0711) if err != nil { return "", nil, err } volatileSet := make(map[string]string) // Generate UUID if not present (do this before UpdateBackupFile() call). instUUID := d.localConfig["volatile.uuid"] if instUUID == "" { instUUID = uuid.New() volatileSet["volatile.uuid"] = instUUID } // Apply any volatile changes that need to be made. err = d.VolatileSet(volatileSet) if err != nil { return "", nil, fmt.Errorf("Failed setting volatile keys: %w", err) } // Create the devices postStartHooks := []func() error{} nicID := -1 nvidiaDevices := []string{} sortedDevices := d.expandedDevices.Sorted() startDevices := make([]device.Device, len(sortedDevices)) // Load devices in sorted order, this ensures that device mounts are added in path order. // Loading all devices first means that validation of all devices occurs before starting any of them. for i, entry := range sortedDevices { dev, err := d.deviceLoad(d, entry.Name, entry.Config) if err != nil { return "", nil, fmt.Errorf("Failed start validation for device %q: %w", entry.Name, err) } // Run pre-start of check all devices before starting any device to avoid expensive revert. err = dev.PreStartCheck() if err != nil { return "", nil, fmt.Errorf("Failed pre-start check for device %q: %w", dev.Name(), err) } startDevices[i] = dev } // Start devices in order. for i := range startDevices { dev := startDevices[i] // Local var for revert. // Start the device. runConf, err := d.deviceStart(dev, false) if err != nil { return "", nil, fmt.Errorf("Failed to start device %q: %w", dev.Name(), err) } // Stop device on failure to setup container. revert.Add(func() { err := d.deviceStop(dev, false, "") if err != nil { d.logger.Error("Failed to cleanup device", logger.Ctx{"device": dev.Name(), "err": err}) } }) if runConf == nil { continue } if runConf.Revert != nil { revert.Add(runConf.Revert) } // Process rootfs setup. if runConf.RootFS.Path != "" { if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) { // Set the rootfs backend type if supported (must happen before any other lxc.rootfs) err := lxcSetConfigItem(d.c, "lxc.rootfs.backend", "dir") if err == nil { value := d.c.ConfigItem("lxc.rootfs.backend") if len(value) == 0 || value[0] != "dir" { _ = lxcSetConfigItem(d.c, "lxc.rootfs.backend", "") } } } // Get an absolute path for the rootfs (avoid constantly traversing the symlink). absoluteRootfs, err := filepath.EvalSymlinks(runConf.RootFS.Path) if err != nil { return "", nil, fmt.Errorf("Unable to resolve container rootfs: %w", err) } if liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) { rootfsPath := fmt.Sprintf("dir:%s", absoluteRootfs) err = lxcSetConfigItem(d.c, "lxc.rootfs.path", rootfsPath) } else { err = lxcSetConfigItem(d.c, "lxc.rootfs", absoluteRootfs) } if err != nil { return "", nil, fmt.Errorf("Failed to setup device rootfs %q: %w", dev.Name(), err) } if len(runConf.RootFS.Opts) > 0 { err = lxcSetConfigItem(d.c, "lxc.rootfs.options", strings.Join(runConf.RootFS.Opts, ",")) if err != nil { return "", nil, fmt.Errorf("Failed to setup device rootfs %q: %w", dev.Name(), err) } } if !d.IsPrivileged() { if idmapType == idmap.IdmapStorageIdmapped { err = lxcSetConfigItem(d.c, "lxc.rootfs.options", "idmap=container") if err != nil { return "", nil, fmt.Errorf("Failed to set \"idmap=container\" rootfs option: %w", err) } } else if idmapType == idmap.IdmapStorageShiftfs { // Host side mark mount. err = lxcSetConfigItem(d.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", strconv.Quote(d.RootfsPath()), strconv.Quote(d.RootfsPath()))) if err != nil { return "", nil, fmt.Errorf("Failed to setup device mount shiftfs %q: %w", dev.Name(), err) } // Container side shift mount. err = lxcSetConfigItem(d.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", strconv.Quote(d.RootfsPath()), strconv.Quote(d.RootfsPath()))) if err != nil { return "", nil, fmt.Errorf("Failed to setup device mount shiftfs %q: %w", dev.Name(), err) } // Host side umount of mark mount. err = lxcSetConfigItem(d.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", strconv.Quote(d.RootfsPath()))) if err != nil { return "", nil, fmt.Errorf("Failed to setup device mount shiftfs %q: %w", dev.Name(), err) } } } } // Pass any cgroups rules into LXC. if len(runConf.CGroups) > 0 { for _, rule := range runConf.CGroups { if strings.HasPrefix(rule.Key, "devices.") && (!d.isCurrentlyPrivileged() || d.state.OS.RunningInUserNS) { continue } if d.state.OS.CGInfo.Layout == cgroup.CgroupsUnified { err = lxcSetConfigItem(d.c, fmt.Sprintf("lxc.cgroup2.%s", rule.Key), rule.Value) } else { err = lxcSetConfigItem(d.c, fmt.Sprintf("lxc.cgroup.%s", rule.Key), rule.Value) } if err != nil { return "", nil, fmt.Errorf("Failed to setup device cgroup %q: %w", dev.Name(), err) } } } // Pass any mounts into LXC. if len(runConf.Mounts) > 0 { for _, mount := range runConf.Mounts { if shared.StringInSlice("propagation", mount.Opts) && !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 3, 0, 0) { return "", nil, fmt.Errorf("Failed to setup device mount %q: %w", dev.Name(), fmt.Errorf("liblxc 3.0 is required for mount propagation configuration")) } mntOptions := strings.Join(mount.Opts, ",") if !d.IsPrivileged() && mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic { switch d.IdmappedStorage(mount.DevPath) { case idmap.IdmapStorageIdmapped: mntOptions = strings.Join([]string{mntOptions, "idmap=container"}, ",") case idmap.IdmapStorageShiftfs: err = lxcSetConfigItem(d.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", strconv.Quote(mount.DevPath), strconv.Quote(mount.DevPath))) if err != nil { return "", nil, fmt.Errorf("Failed to setup device mount shiftfs %q: %w", dev.Name(), err) } err = lxcSetConfigItem(d.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", strconv.Quote(mount.DevPath), strconv.Quote(mount.DevPath))) if err != nil { return "", nil, fmt.Errorf("Failed to setup device mount shiftfs %q: %w", dev.Name(), err) } err = lxcSetConfigItem(d.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", strconv.Quote(mount.DevPath))) if err != nil { return "", nil, fmt.Errorf("Failed to setup device mount shiftfs %q: %w", dev.Name(), err) } case idmap.IdmapStorageNone: return "", nil, fmt.Errorf("Failed to setup device mount %q: %w", dev.Name(), fmt.Errorf("idmapping abilities are required but aren't supported on system")) } } mntVal := fmt.Sprintf("%s %s %s %s %d %d", shared.EscapePathFstab(mount.DevPath), shared.EscapePathFstab(mount.TargetPath), mount.FSType, mntOptions, mount.Freq, mount.PassNo) err = lxcSetConfigItem(d.c, "lxc.mount.entry", mntVal) if err != nil { return "", nil, fmt.Errorf("Failed to setup device mount %q: %w", dev.Name(), err) } } } // Pass any network setup config into LXC. if len(runConf.NetworkInterface) > 0 { // Increment nicID so that LXC network index is unique per device. nicID++ networkKeyPrefix := "lxc.net" if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) { networkKeyPrefix = "lxc.network" } for _, nicItem := range runConf.NetworkInterface { err = lxcSetConfigItem(d.c, fmt.Sprintf("%s.%d.%s", networkKeyPrefix, nicID, nicItem.Key), nicItem.Value) if err != nil { return "", nil, fmt.Errorf("Failed to setup device network interface %q: %w", dev.Name(), err) } } } // Add any post start hooks. if len(runConf.PostHooks) > 0 { postStartHooks = append(postStartHooks, runConf.PostHooks...) } // Build list of NVIDIA GPUs (used for MIG). if len(runConf.GPUDevice) > 0 { for _, entry := range runConf.GPUDevice { if entry.Key == device.GPUNvidiaDeviceKey { nvidiaDevices = append(nvidiaDevices, entry.Value) } } } } // Override NVIDIA_VISIBLE_DEVICES if we have devices that need it. if len(nvidiaDevices) > 0 { err = lxcSetConfigItem(d.c, "lxc.environment", fmt.Sprintf("NVIDIA_VISIBLE_DEVICES=%s", strings.Join(nvidiaDevices, ","))) if err != nil { return "", nil, fmt.Errorf("Unable to set NVIDIA_VISIBLE_DEVICES in LXC environment: %w", err) } } // Load the LXC raw config. err = d.loadRawLXCConfig() if err != nil { return "", nil, err } // Generate the LXC config configPath := filepath.Join(d.LogPath(), "lxc.conf") err = d.c.SaveConfigFile(configPath) if err != nil { _ = os.Remove(configPath) return "", nil, err } // Set ownership to match container root currentIdmapset, err := d.CurrentIdmap() if err != nil { return "", nil, err } uid := int64(0) if currentIdmapset != nil { uid, _ = currentIdmapset.ShiftFromNs(0, 0) } err = os.Chown(d.Path(), int(uid), 0) if err != nil { return "", nil, err } // We only need traversal by root in the container err = os.Chmod(d.Path(), 0100) if err != nil { return "", nil, err } // If starting stateless, wipe state if !d.IsStateful() && shared.PathExists(d.StatePath()) { _ = os.RemoveAll(d.StatePath()) } // Unmount any previously mounted shiftfs _ = unix.Unmount(d.RootfsPath(), unix.MNT_DETACH) // Snapshot if needed. err = d.startupSnapshot(d) if err != nil { return "", nil, err } revert.Success() return configPath, postStartHooks, nil } // detachInterfaceRename enters the container's network namespace and moves the named interface // in ifName back to the network namespace of the running process as the name specified in hostName. func (d *lxc) detachInterfaceRename(netns string, ifName string, hostName string) error { lxdPID := os.Getpid() // Run forknet detach _, err := shared.RunCommand( d.state.OS.ExecPath, "forknet", "detach", "--", netns, fmt.Sprintf("%d", lxdPID), ifName, hostName, ) // Process forknet detach response if err != nil { return err } return nil } // validateStartup checks any constraints that would prevent start up from succeeding under normal circumstances. func (d *lxc) validateStartup(stateful bool) error { // Because the root disk is special and is mounted before the root disk device is setup we duplicate the // pre-start check here before the isStartableStatusCode check below so that if there is a problem loading // the instance status because the storage pool isn't available we don't mask the StatusServiceUnavailable // error with an ERROR status code from the instance check instead. _, rootDiskConf, err := shared.GetRootDiskDevice(d.expandedDevices.CloneNative()) if err != nil { return err } if !storagePools.IsAvailable(rootDiskConf["pool"]) { return api.StatusErrorf(http.StatusServiceUnavailable, "Storage pool %q unavailable on this server", rootDiskConf["pool"]) } // Check that we are startable before creating an operation lock, so if the instance is in the // process of stopping we don't prevent the stop hooks from running due to our start operation lock. err = d.isStartableStatusCode(d.statusCode()) if err != nil { return err } return nil } // Start starts the instance. func (d *lxc) Start(stateful bool) error { d.logger.Debug("Start started", logger.Ctx{"stateful": stateful}) defer d.logger.Debug("Start finished", logger.Ctx{"stateful": stateful}) err := d.validateStartup(stateful) if err != nil { return err } var ctxMap logger.Ctx // Setup a new operation op, err := operationlock.CreateWaitGet(d.Project(), d.Name(), operationlock.ActionStart, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore}, false, false) if err != nil { if errors.Is(err, operationlock.ErrNonReusuableSucceeded) { // An existing matching operation has now succeeded, return. return nil } return fmt.Errorf("Failed to create instance start operation: %w", err) } defer op.Done(nil) if !daemon.SharedMountsSetup { err = fmt.Errorf("Daemon failed to setup shared mounts base. Does security.nesting need to be turned on?") op.Done(err) return err } // Run the shared start code configPath, postStartHooks, err := d.startCommon() if err != nil { op.Done(err) return err } ctxMap = logger.Ctx{ "action": op.Action(), "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "stateful": stateful} if op.Action() == "start" { d.logger.Info("Starting container", ctxMap) } // If stateful, restore now if stateful { if !d.stateful { err = fmt.Errorf("Container has no existing state to restore") op.Done(err) return err } criuMigrationArgs := instance.CriuMigrationArgs{ Cmd: liblxc.MIGRATE_RESTORE, StateDir: d.StatePath(), Function: "snapshot", Stop: false, ActionScript: false, DumpDir: "", PreDumpDir: "", } err := d.Migrate(&criuMigrationArgs) if err != nil && !d.IsRunning() { op.Done(err) return fmt.Errorf("Migrate: %w", err) } _ = os.RemoveAll(d.StatePath()) d.stateful = false err = d.state.DB.Cluster.UpdateInstanceStatefulFlag(d.id, false) if err != nil { op.Done(err) return fmt.Errorf("Start container: %w", err) } // Run any post start hooks. err = d.runHooks(postStartHooks) if err != nil { op.Done(err) // Must come before Stop() otherwise stop will not proceed. // Attempt to stop container. _ = d.Stop(false) return err } if op.Action() == "start" { d.logger.Info("Started container", ctxMap) d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStarted.Event(d, nil)) } return nil } else if d.stateful { /* stateless start required when we have state, let's delete it */ err := os.RemoveAll(d.StatePath()) if err != nil { op.Done(err) return err } d.stateful = false err = d.state.DB.Cluster.UpdateInstanceStatefulFlag(d.id, false) if err != nil { op.Done(err) return fmt.Errorf("Persist stateful flag: %w", err) } } // Update the backup.yaml file just before starting the instance process, but after all devices have been // setup, so that the backup file contains the volatile keys used for this instance start, so that they // can be used for instance cleanup. err = d.UpdateBackupFile() if err != nil { op.Done(err) return err } name := project.Instance(d.Project(), d.name) // Start the LXC container _, err = shared.RunCommand( d.state.OS.ExecPath, "forkstart", name, d.state.OS.LxcPath, configPath) if err != nil && !d.IsRunning() { // Attempt to extract the LXC errors lxcLog := "" logPath := filepath.Join(d.LogPath(), "lxc.log") if shared.PathExists(logPath) { logContent, err := ioutil.ReadFile(logPath) if err == nil { for _, line := range strings.Split(string(logContent), "\n") { fields := strings.Fields(line) if len(fields) < 4 { continue } // We only care about errors if fields[2] != "ERROR" { continue } // Prepend the line break if len(lxcLog) == 0 { lxcLog += "\n" } lxcLog += fmt.Sprintf(" %s\n", strings.Join(fields[0:], " ")) } } } d.logger.Error("Failed starting container", ctxMap) // Return the actual error op.Done(err) return err } // Run any post start hooks. err = d.runHooks(postStartHooks) if err != nil { op.Done(err) // Must come before Stop() otherwise stop will not proceed. // Attempt to stop container. _ = d.Stop(false) return err } if op.Action() == "start" { d.logger.Info("Started container", ctxMap) d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStarted.Event(d, nil)) } return nil } // OnHook is the top-level hook handler. func (d *lxc) OnHook(hookName string, args map[string]string) error { switch hookName { case instance.HookStart: return d.onStart(args) case instance.HookStopNS: return d.onStopNS(args) case instance.HookStop: return d.onStop(args) default: return instance.ErrNotImplemented } } // onStart implements the start hook. func (d *lxc) onStart(_ map[string]string) error { // Make sure we can't call go-lxc functions by mistake d.fromHook = true // Load the container AppArmor profile err := apparmor.InstanceLoad(d.state.OS, d) if err != nil { return err } // Template anything that needs templating key := "volatile.apply_template" if d.localConfig[key] != "" { // Run any template that needs running err = d.templateApplyNow(instance.TemplateTrigger(d.localConfig[key])) if err != nil { _ = apparmor.InstanceUnload(d.state.OS, d) return err } // Remove the volatile key from the DB err := d.state.DB.Cluster.DeleteInstanceConfigKey(d.id, key) if err != nil { _ = apparmor.InstanceUnload(d.state.OS, d) return err } } err = d.templateApplyNow("start") if err != nil { _ = apparmor.InstanceUnload(d.state.OS, d) return err } // Trigger a rebalance cgroup.TaskSchedulerTrigger("container", d.name, "started") // Apply network priority if d.expandedConfig["limits.network.priority"] != "" { go func(d *lxc) { d.fromHook = false err := d.setNetworkPriority() if err != nil { d.logger.Error("Failed to apply network priority", logger.Ctx{"err": err}) } }(d) } // Record last start state. err = d.recordLastState() if err != nil { return err } return nil } // Stop functions. func (d *lxc) Stop(stateful bool) error { d.logger.Debug("Stop started", logger.Ctx{"stateful": stateful}) defer d.logger.Debug("Stop finished", logger.Ctx{"stateful": stateful}) // Must be run prior to creating the operation lock. if !d.IsRunning() { return ErrInstanceIsStopped } // Setup a new operation op, err := operationlock.CreateWaitGet(d.Project(), d.Name(), operationlock.ActionStop, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore}, false, true) if err != nil { if errors.Is(err, operationlock.ErrNonReusuableSucceeded) { // An existing matching operation has now succeeded, return. return nil } return err } ctxMap := logger.Ctx{ "action": op.Action(), "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "stateful": stateful} if op.Action() == "stop" { d.logger.Info("Stopping container", ctxMap) } // Handle stateful stop if stateful { // Cleanup any existing state stateDir := d.StatePath() _ = os.RemoveAll(stateDir) err := os.MkdirAll(stateDir, 0700) if err != nil { op.Done(err) return err } criuMigrationArgs := instance.CriuMigrationArgs{ Cmd: liblxc.MIGRATE_DUMP, StateDir: stateDir, Function: "snapshot", Stop: true, ActionScript: false, DumpDir: "", PreDumpDir: "", } // Checkpoint err = d.Migrate(&criuMigrationArgs) if err != nil { op.Done(err) return err } err = op.Wait() if err != nil && d.IsRunning() { return err } d.stateful = true err = d.state.DB.Cluster.UpdateInstanceStatefulFlag(d.id, true) if err != nil { d.logger.Error("Failed stopping container", ctxMap) return err } d.logger.Info("Stopped container", ctxMap) d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStopped.Event(d, nil)) return nil } else if shared.PathExists(d.StatePath()) { _ = os.RemoveAll(d.StatePath()) } // Release liblxc container once done. defer func() { d.release() }() // Load the go-lxc struct if d.expandedConfig["raw.lxc"] != "" { err = d.initLXC(true) if err != nil { op.Done(err) return err } // Load the config. err = d.loadRawLXCConfig() if err != nil { return err } } else { err = d.initLXC(false) if err != nil { op.Done(err) return err } } // Load cgroup abstraction cg, err := d.cgroup(nil) if err != nil { op.Done(err) return err } // Fork-bomb mitigation, prevent forking from this point on if d.state.OS.CGInfo.Supports(cgroup.Pids, cg) { // Attempt to disable forking new processes _ = cg.SetMaxProcesses(0) } else if d.state.OS.CGInfo.Supports(cgroup.Freezer, cg) { // Attempt to freeze the container freezer := make(chan bool, 1) go func() { _ = d.Freeze() freezer <- true }() select { case <-freezer: case <-time.After(time.Second * 5): _ = d.Unfreeze() } } err = d.c.Stop() if err != nil { op.Done(err) return err } // Wait for operation lock to be Done. This is normally completed by onStop which picks up the same // operation lock and then marks it as Done after the instance stops and the devices have been cleaned up. // However if the operation has failed for another reason we will collect the error here. err = op.Wait() status := d.statusCode() if status != api.Stopped { errPrefix := fmt.Errorf("Failed stopping instance, status is %q", status) if err != nil { return fmt.Errorf("%s: %w", errPrefix.Error(), err) } return errPrefix } else if op.Action() == "stop" { // If instance stopped, send lifecycle event (even if there has been an error cleaning up). d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStopped.Event(d, nil)) } // Now handle errors from stop sequence and return to caller if wasn't completed cleanly. if err != nil { return err } return nil } // Shutdown stops the instance. func (d *lxc) Shutdown(timeout time.Duration) error { d.logger.Debug("Shutdown started", logger.Ctx{"timeout": timeout}) defer d.logger.Debug("Shutdown finished", logger.Ctx{"timeout": timeout}) // Must be run prior to creating the operation lock. statusCode := d.statusCode() if !d.isRunningStatusCode(statusCode) { if statusCode == api.Error { return fmt.Errorf("The instance cannot be cleanly shutdown as in %s status", statusCode) } return ErrInstanceIsStopped } // Setup a new operation op, err := operationlock.CreateWaitGet(d.Project(), d.Name(), operationlock.ActionStop, []operationlock.Action{operationlock.ActionRestart}, true, true) if err != nil { if errors.Is(err, operationlock.ErrNonReusuableSucceeded) { // An existing matching operation has now succeeded, return. return nil } return err } // If frozen, resume so the signal can be handled. if d.IsFrozen() { err := d.Unfreeze() if err != nil { return err } } ctxMap := logger.Ctx{ "action": "shutdown", "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "timeout": timeout} if op.Action() == "stop" { d.logger.Info("Shutting down container", ctxMap) } // Release liblxc container once done. defer func() { d.release() }() // Load the go-lxc struct if d.expandedConfig["raw.lxc"] != "" { err = d.initLXC(true) if err != nil { op.Done(err) return err } err = d.loadRawLXCConfig() if err != nil { return err } } else { err = d.initLXC(false) if err != nil { op.Done(err) return err } } chResult := make(chan error) go func() { chResult <- d.c.Shutdown(timeout) }() d.logger.Debug("Shutdown request sent to instance") // Setup ticker that is half the timeout of operationlock.TimeoutDefault. ticker := time.NewTicker(operationlock.TimeoutDefault / 2) defer ticker.Stop() for { select { case err = <-chResult: // Shutdown request has returned with a result. if err != nil { // If shutdown failed, cancel operation with the error, otherwise expect the // onStop() hook to cancel operation when done. op.Done(err) } case <-ticker.C: // Keep the operation alive so its around for onStop() if the instance takes longer than // the default operationlock.TimeoutDefault that the operation is kept alive for. if op.Reset() == nil { continue } } break } // Wait for operation lock to be Done. This is normally completed by onStop which picks up the same // operation lock and then marks it as Done after the instance stops and the devices have been cleaned up. // However if the operation has failed for another reason we will collect the error here. err = op.Wait() status := d.statusCode() if status != api.Stopped { errPrefix := fmt.Errorf("Failed shutting down instance, status is %q", status) if err != nil { return fmt.Errorf("%s: %w", errPrefix.Error(), err) } return errPrefix } else if op.Action() == "stop" { // If instance stopped, send lifecycle event (even if there has been an error cleaning up). d.state.Events.SendLifecycle(d.project, lifecycle.InstanceShutdown.Event(d, nil)) } // Now handle errors from shutdown sequence and return to caller if wasn't completed cleanly. if err != nil { return err } return nil } // Restart restart the instance. func (d *lxc) Restart(timeout time.Duration) error { ctxMap := logger.Ctx{ "action": "shutdown", "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "timeout": timeout} d.logger.Info("Restarting container", ctxMap) err := d.restartCommon(d, timeout) if err != nil { return err } d.logger.Info("Restarted container", ctxMap) d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRestarted.Event(d, nil)) return nil } // onStopNS is triggered by LXC's stop hook once a container is shutdown but before the container's // namespaces have been closed. The netns path of the stopped container is provided. func (d *lxc) onStopNS(args map[string]string) error { target := args["target"] netns := args["netns"] // Validate target. if !shared.StringInSlice(target, []string{"stop", "reboot"}) { d.logger.Error("Container sent invalid target to OnStopNS", logger.Ctx{"target": target}) return fmt.Errorf("Invalid stop target %q", target) } // Create/pick up operation, but don't complete it as we leave operation running for the onStop hook below. _, _, err := d.onStopOperationSetup(target) if err != nil { return err } // Clean up devices. d.cleanupDevices(false, netns) return nil } // onStop is triggered by LXC's post-stop hook once a container is shutdown and after the // container's namespaces have been closed. func (d *lxc) onStop(args map[string]string) error { target := args["target"] // Validate target if !shared.StringInSlice(target, []string{"stop", "reboot"}) { d.logger.Error("Container sent invalid target to OnStop", logger.Ctx{"target": target}) return fmt.Errorf("Invalid stop target: %s", target) } // Create/pick up operation. op, instanceInitiated, err := d.onStopOperationSetup(target) if err != nil { return err } // Make sure we can't call go-lxc functions by mistake d.fromHook = true // Record power state. err = d.VolatileSet(map[string]string{ "volatile.last_state.power": "STOPPED", "volatile.last_state.ready": "false", }) if err != nil { // Don't return an error here as we still want to cleanup the instance even if DB not available. d.logger.Error("Failed recording last power state", logger.Ctx{"err": err}) } go func(d *lxc, target string, op *operationlock.InstanceOperation) { d.fromHook = false err = nil // Unlock on return defer op.Done(nil) // Wait for other post-stop actions to be done and the container actually stopping. d.IsRunning() d.logger.Debug("Container stopped, cleaning up") // Wait for any file operations to complete. // This is to required so we can actually unmount the container. d.stopForkfile() // Clean up devices. d.cleanupDevices(false, "") // Remove directory ownership (to avoid issue if uidmap is re-used) err := os.Chown(d.Path(), 0, 0) if err != nil { op.Done(fmt.Errorf("Failed clearing ownership: %w", err)) return } err = os.Chmod(d.Path(), 0100) if err != nil { op.Done(fmt.Errorf("Failed clearing permissions: %w", err)) return } // Stop the storage for this container waitTimeout := operationlock.TimeoutShutdown _ = op.ResetTimeout(waitTimeout) err = d.unmount() if err != nil { err = fmt.Errorf("Failed unmounting instance: %w", err) op.Done(err) return } // Unload the apparmor profile err = apparmor.InstanceUnload(d.state.OS, d) if err != nil { op.Done(fmt.Errorf("Failed to destroy apparmor namespace: %w", err)) return } // Clean all the unix devices err = d.removeUnixDevices() if err != nil { op.Done(fmt.Errorf("Failed to remove unix devices: %w", err)) return } // Clean all the disk devices err = d.removeDiskDevices() if err != nil { op.Done(fmt.Errorf("Failed to remove disk devices: %w", err)) return } // Log and emit lifecycle if not user triggered if instanceInitiated { ctxMap := logger.Ctx{ "action": target, "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "stateful": false, } d.logger.Info("Shut down container", ctxMap) d.state.Events.SendLifecycle(d.project, lifecycle.InstanceShutdown.Event(d, nil)) } // Reboot the container if target == "reboot" { // Start the container again err = d.Start(false) if err != nil { op.Done(fmt.Errorf("Failed restarting container: %w", err)) return } d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRestarted.Event(d, nil)) return } // Trigger a rebalance cgroup.TaskSchedulerTrigger("container", d.name, "stopped") // Destroy ephemeral containers if d.ephemeral { err = d.Delete(true) if err != nil { op.Done(fmt.Errorf("Failed deleting ephemeral container: %w", err)) return } } }(d, target, op) return nil } // cleanupDevices performs any needed device cleanup steps when container is stopped. // Accepts a stopHookNetnsPath argument which is required when run from the onStopNS hook before the // container's network namespace is unmounted (which is required for NIC device cleanup). func (d *lxc) cleanupDevices(instanceRunning bool, stopHookNetnsPath string) { for _, entry := range d.expandedDevices.Reversed() { // Only stop NIC devices when run from the onStopNS hook, and stop all other devices when run from // the onStop hook. This way disk devices are stopped after the instance has been fully stopped. if (stopHookNetnsPath != "" && entry.Config["type"] != "nic") || (stopHookNetnsPath == "" && entry.Config["type"] == "nic") { continue } dev, err := d.deviceLoad(d, entry.Name, entry.Config) if err != nil { // Just log an error, but still allow the device to be stopped if usable device returned. d.logger.Error("Failed stop validation for device", logger.Ctx{"device": entry.Name, "err": err}) } // If a usable device was returned from deviceLoad try to stop anyway, even if validation fails. // This allows for the scenario where a new version of LXD has additional validation restrictions // than older versions and we still need to allow previously valid devices to be stopped even if // they are no longer considered valid. if dev != nil { err = d.deviceStop(dev, instanceRunning, stopHookNetnsPath) if err != nil { d.logger.Error("Failed to stop device", logger.Ctx{"device": dev.Name(), "err": err}) } } } } // Freeze functions. func (d *lxc) Freeze() error { ctxMap := logger.Ctx{ "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate} // Check that we're running if !d.IsRunning() { return fmt.Errorf("The container isn't running") } cg, err := d.cgroup(nil) if err != nil { return err } // Check if the CGroup is available if !d.state.OS.CGInfo.Supports(cgroup.Freezer, cg) { d.logger.Info("Unable to freeze container (lack of kernel support)", ctxMap) return nil } // Check that we're not already frozen if d.IsFrozen() { return fmt.Errorf("The container is already frozen") } d.logger.Info("Freezing container", ctxMap) // Load the go-lxc struct err = d.initLXC(false) if err != nil { ctxMap["err"] = err d.logger.Error("Failed freezing container", ctxMap) return err } err = d.c.Freeze() if err != nil { ctxMap["err"] = err d.logger.Error("Failed freezing container", ctxMap) return err } d.logger.Info("Froze container", ctxMap) d.state.Events.SendLifecycle(d.project, lifecycle.InstancePaused.Event(d, nil)) return err } // Unfreeze unfreezes the instance. func (d *lxc) Unfreeze() error { ctxMap := logger.Ctx{ "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate} // Check that we're running if !d.IsRunning() { return fmt.Errorf("The container isn't running") } cg, err := d.cgroup(nil) if err != nil { return err } // Check if the CGroup is available if !d.state.OS.CGInfo.Supports(cgroup.Freezer, cg) { d.logger.Info("Unable to unfreeze container (lack of kernel support)", ctxMap) return nil } // Check that we're frozen if !d.IsFrozen() { return fmt.Errorf("The container is already running") } d.logger.Info("Unfreezing container", ctxMap) // Load the go-lxc struct err = d.initLXC(false) if err != nil { d.logger.Error("Failed unfreezing container", ctxMap) return err } err = d.c.Unfreeze() if err != nil { d.logger.Error("Failed unfreezing container", ctxMap) } d.logger.Info("Unfroze container", ctxMap) d.state.Events.SendLifecycle(d.project, lifecycle.InstanceResumed.Event(d, nil)) return err } // Get lxc container state, with 1 second timeout. // If we don't get a reply, assume the lxc monitor is unresponsive. func (d *lxc) getLxcState() (liblxc.State, error) { if d.IsSnapshot() { return liblxc.StateMap["STOPPED"], nil } // Load the go-lxc struct err := d.initLXC(false) if err != nil { return liblxc.StateMap["STOPPED"], err } if d.c == nil { return liblxc.StateMap["STOPPED"], nil } monitor := make(chan liblxc.State, 1) go func(c *liblxc.Container) { monitor <- c.State() }(d.c) select { case state := <-monitor: return state, nil case <-time.After(5 * time.Second): return liblxc.StateMap["FROZEN"], fmt.Errorf("Monitor is unresponsive") } } // Render renders the state of the instance. func (d *lxc) Render(options ...func(response any) error) (any, any, error) { // Ignore err as the arch string on error is correct (unknown) architectureName, _ := osarch.ArchitectureName(d.architecture) profileNames := make([]string, 0, len(d.profiles)) for _, profile := range d.profiles { profileNames = append(profileNames, profile.Name) } if d.IsSnapshot() { // Prepare the ETag etag := []any{d.expiryDate} snapState := api.InstanceSnapshot{ CreatedAt: d.creationDate, ExpandedConfig: d.expandedConfig, ExpandedDevices: d.expandedDevices.CloneNative(), LastUsedAt: d.lastUsedDate, Name: strings.SplitN(d.name, "/", 2)[1], Stateful: d.stateful, Size: -1, // Default to uninitialised/error state (0 means no CoW usage). } snapState.Architecture = architectureName snapState.Config = d.localConfig snapState.Devices = d.localDevices.CloneNative() snapState.Ephemeral = d.ephemeral snapState.Profiles = profileNames snapState.ExpiresAt = d.expiryDate for _, option := range options { err := option(&snapState) if err != nil { return nil, nil, err } } return &snapState, etag, nil } // Prepare the ETag etag := []any{d.architecture, d.localConfig, d.localDevices, d.ephemeral, d.profiles} statusCode := d.statusCode() instState := api.Instance{ ExpandedConfig: d.expandedConfig, ExpandedDevices: d.expandedDevices.CloneNative(), Name: d.name, Status: statusCode.String(), StatusCode: statusCode, Location: d.node, Type: d.Type().String(), } instState.Description = d.description instState.Architecture = architectureName instState.Config = d.localConfig instState.CreatedAt = d.creationDate instState.Devices = d.localDevices.CloneNative() instState.Ephemeral = d.ephemeral instState.LastUsedAt = d.lastUsedDate instState.Profiles = profileNames instState.Stateful = d.stateful instState.Project = d.project for _, option := range options { err := option(&instState) if err != nil { return nil, nil, err } } return &instState, etag, nil } // RenderFull renders the full state of the instance. func (d *lxc) RenderFull() (*api.InstanceFull, any, error) { if d.IsSnapshot() { return nil, nil, fmt.Errorf("RenderFull only works with containers") } // Get the Container struct base, etag, err := d.Render() if err != nil { return nil, nil, err } // Convert to ContainerFull ct := api.InstanceFull{Instance: *base.(*api.Instance)} // Add the ContainerState ct.State, err = d.renderState(ct.StatusCode) if err != nil { return nil, nil, err } // Add the ContainerSnapshots snaps, err := d.Snapshots() if err != nil { return nil, nil, err } for _, snap := range snaps { render, _, err := snap.Render() if err != nil { return nil, nil, err } if ct.Snapshots == nil { ct.Snapshots = []api.InstanceSnapshot{} } ct.Snapshots = append(ct.Snapshots, *render.(*api.InstanceSnapshot)) } // Add the ContainerBackups backups, err := d.Backups() if err != nil { return nil, nil, err } for _, backup := range backups { render := backup.Render() if ct.Backups == nil { ct.Backups = []api.InstanceBackup{} } ct.Backups = append(ct.Backups, *render) } return &ct, etag, nil } // renderState renders just the running state of the instance. func (d *lxc) renderState(statusCode api.StatusCode) (*api.InstanceState, error) { status := api.InstanceState{ Status: statusCode.String(), StatusCode: statusCode, } if d.isRunningStatusCode(statusCode) { pid := d.InitPID() status.CPU = d.cpuState() status.Memory = d.memoryState() status.Network = d.networkState() status.Pid = int64(pid) status.Processes = d.processesState() } status.Disk = d.diskState() d.release() return &status, nil } // RenderState renders just the running state of the instance. func (d *lxc) RenderState() (*api.InstanceState, error) { return d.renderState(d.statusCode()) } // Snapshot takes a new snapshot. func (d *lxc) Snapshot(name string, expiry time.Time, stateful bool) error { // Deal with state. if stateful { // Quick checks. if !d.IsRunning() { return fmt.Errorf("Unable to create a stateful snapshot. The instance isn't running") } _, err := exec.LookPath("criu") if err != nil { return fmt.Errorf("Unable to create a stateful snapshot. CRIU isn't installed") } /* TODO: ideally we would freeze here and unfreeze below after * we've copied the filesystem, to make sure there are no * changes by the container while snapshotting. Unfortunately * there is abug in CRIU where it doesn't leave the container * in the same state it found it w.r.t. freezing, i.e. CRIU * freezes too, and then /always/ thaws, even if the container * was frozen. Until that's fixed, all calls to Unfreeze() * after snapshotting will fail. */ criuMigrationArgs := instance.CriuMigrationArgs{ Cmd: liblxc.MIGRATE_DUMP, StateDir: d.StatePath(), Function: "snapshot", Stop: false, ActionScript: false, DumpDir: "", PreDumpDir: "", } // Create the state path and Make sure we don't keep state around after the snapshot has been made. err = os.MkdirAll(d.StatePath(), 0700) if err != nil { return err } defer func() { _ = os.RemoveAll(d.StatePath()) }() // Dump the state. err = d.Migrate(&criuMigrationArgs) if err != nil { return err } } // Wait for any file operations to complete to have a more consistent snapshot. d.stopForkfile() return d.snapshotCommon(d, name, expiry, stateful) } // Restore restores a snapshot. func (d *lxc) Restore(sourceContainer instance.Instance, stateful bool) error { var ctxMap logger.Ctx op, err := operationlock.Create(d.Project(), d.Name(), operationlock.ActionRestore, false, false) if err != nil { return fmt.Errorf("Failed to create instance restore operation: %w", err) } defer op.Done(nil) // Stop the container. wasRunning := false if d.IsRunning() { wasRunning = true ephemeral := d.IsEphemeral() if ephemeral { // Unset ephemeral flag. args := db.InstanceArgs{ Architecture: d.Architecture(), Config: d.LocalConfig(), Description: d.Description(), Devices: d.LocalDevices(), Ephemeral: false, Profiles: d.Profiles(), Project: d.Project(), Type: d.Type(), Snapshot: d.IsSnapshot(), } err := d.Update(args, false) if err != nil { op.Done(err) return err } // On function return, set the flag back on. defer func() { args.Ephemeral = ephemeral _ = d.Update(args, false) }() } // This will unmount the container storage. err := d.Stop(false) if err != nil { op.Done(err) return err } // Refresh the operation as that one is now complete. op, err = operationlock.Create(d.Project(), d.Name(), operationlock.ActionRestore, false, false) if err != nil { return fmt.Errorf("Failed to create instance restore operation: %w", err) } defer op.Done(nil) } ctxMap = logger.Ctx{ "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "source": sourceContainer.Name()} d.logger.Info("Restoring container", ctxMap) // Wait for any file operations to complete. // This is required so we can actually unmount the container and restore its rootfs. d.stopForkfile() // Initialize storage interface for the container and mount the rootfs for criu state check. pool, err := storagePools.LoadByInstance(d.state, d) if err != nil { op.Done(err) return err } d.logger.Debug("Mounting instance to check for CRIU state path existence") // Ensure that storage is mounted for state path checks and for backup.yaml updates. _, err = pool.MountInstance(d, nil) if err != nil { op.Done(err) return err } // Check for CRIU if necessary, before doing a bunch of filesystem manipulations. // Requires container be mounted to check StatePath exists. if shared.PathExists(d.StatePath()) { _, err := exec.LookPath("criu") if err != nil { err = fmt.Errorf("Failed to restore container state. CRIU isn't installed") op.Done(err) return err } } err = pool.UnmountInstance(d, nil) if err != nil { op.Done(err) return err } // Restore the rootfs. err = pool.RestoreInstanceSnapshot(d, sourceContainer, nil) if err != nil { op.Done(err) return err } // Restore the configuration. args := db.InstanceArgs{ Architecture: sourceContainer.Architecture(), Config: sourceContainer.LocalConfig(), Description: sourceContainer.Description(), Devices: sourceContainer.LocalDevices(), Ephemeral: sourceContainer.IsEphemeral(), Profiles: sourceContainer.Profiles(), Project: sourceContainer.Project(), Type: sourceContainer.Type(), Snapshot: sourceContainer.IsSnapshot(), } // Don't pass as user-requested as there's no way to fix a bad config. // This will call d.UpdateBackupFile() to ensure snapshot list is up to date. err = d.Update(args, false) if err != nil { op.Done(err) return err } // If the container wasn't running but was stateful, should we restore it as running? if stateful { if !shared.PathExists(d.StatePath()) { err = fmt.Errorf("Stateful snapshot restore requested by snapshot is stateless") op.Done(err) return err } d.logger.Debug("Performing stateful restore", ctxMap) d.stateful = true criuMigrationArgs := instance.CriuMigrationArgs{ Cmd: liblxc.MIGRATE_RESTORE, StateDir: d.StatePath(), Function: "snapshot", Stop: false, ActionScript: false, DumpDir: "", PreDumpDir: "", } // Checkpoint. err := d.Migrate(&criuMigrationArgs) if err != nil { op.Done(err) return err } // Remove the state from the parent container; we only keep this in snapshots. err2 := os.RemoveAll(d.StatePath()) if err2 != nil && !os.IsNotExist(err) { op.Done(err) return err } if err != nil { op.Done(err) return err } d.logger.Debug("Performed stateful restore", ctxMap) d.logger.Info("Restored container", ctxMap) return nil } // Restart the container. if wasRunning { d.logger.Debug("Starting instance after snapshot restore") err = d.Start(false) if err != nil { op.Done(err) return err } } d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRestored.Event(d, map[string]any{"snapshot": sourceContainer.Name()})) d.logger.Info("Restored container", ctxMap) return nil } func (d *lxc) cleanup() { // Unmount any leftovers _ = d.removeUnixDevices() _ = d.removeDiskDevices() // Remove the security profiles _ = apparmor.InstanceDelete(d.state.OS, d) seccomp.DeleteProfile(d) // Remove the devices path _ = os.Remove(d.DevicesPath()) // Remove the shmounts path _ = os.RemoveAll(d.ShmountsPath()) } // Delete deletes the instance. func (d *lxc) Delete(force bool) error { ctxMap := logger.Ctx{ "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate} d.logger.Info("Deleting container", ctxMap) if !force && shared.IsTrue(d.expandedConfig["security.protection.delete"]) && !d.IsSnapshot() { err := fmt.Errorf("Container is protected") d.logger.Warn("Failed to delete container", logger.Ctx{"err": err}) return err } // Wait for any file operations to complete. // This is required so we can actually unmount the container and delete it. if !d.IsSnapshot() { d.stopForkfile() } // Delete any persistent warnings for instance. err := d.warningsDelete() if err != nil { return err } pool, err := storagePools.LoadByInstance(d.state, d) if err != nil && !response.IsNotFoundError(err) { return err } else if pool != nil { if d.IsSnapshot() { // Remove snapshot volume and database record. err = pool.DeleteInstanceSnapshot(d, nil) if err != nil { return err } } else { // Remove all snapshots by initialising each snapshot as an Instance and // calling its Delete function. err := instance.DeleteSnapshots(d) if err != nil { d.logger.Error("Failed to delete instance snapshots", logger.Ctx{"err": err}) return err } // Remove the storage volume, snapshot volumes and database records. err = pool.DeleteInstance(d, nil) if err != nil { return err } } } // Perform other cleanup steps if not snapshot. if !d.IsSnapshot() { // Remove all backups. backups, err := d.Backups() if err != nil { return err } for _, backup := range backups { err = backup.Delete() if err != nil { return err } } // Delete the MAAS entry. err = d.maasDelete(d) if err != nil { d.logger.Error("Failed deleting container MAAS record", logger.Ctx{"err": err}) return err } // Run device removal function for each device. d.devicesRemove(d) // Clean things up. d.cleanup() } // Remove the database record of the instance or snapshot instance. err = d.state.DB.Cluster.DeleteInstance(d.project, d.Name()) if err != nil { d.logger.Error("Failed deleting container entry", logger.Ctx{"err": err}) return err } // If dealing with a snapshot, refresh the backup file on the parent. if d.IsSnapshot() { parentName, _, _ := api.GetParentAndSnapshotName(d.name) // Load the parent. parent, err := instance.LoadByProjectAndName(d.state, d.project, parentName) if err != nil { return fmt.Errorf("Invalid parent: %w", err) } // Update the backup file. err = parent.UpdateBackupFile() if err != nil { return err } } d.logger.Info("Deleted container", ctxMap) if d.snapshot { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotDeleted.Event(d, nil)) } else { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceDeleted.Event(d, nil)) } return nil } // Rename renames the instance. Accepts an argument to enable applying deferred TemplateTriggerRename. func (d *lxc) Rename(newName string, applyTemplateTrigger bool) error { oldName := d.Name() ctxMap := logger.Ctx{ "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "newname": newName} d.logger.Info("Renaming container", ctxMap) // Quick checks. err := instance.ValidName(newName, d.IsSnapshot()) if err != nil { return err } if d.IsRunning() { return fmt.Errorf("Renaming of running container not allowed") } // Clean things up. d.cleanup() pool, err := storagePools.LoadByInstance(d.state, d) if err != nil { return fmt.Errorf("Failed loading instance storage pool: %w", err) } if d.IsSnapshot() { _, newSnapName, _ := api.GetParentAndSnapshotName(newName) err = pool.RenameInstanceSnapshot(d, newSnapName, nil) if err != nil { return fmt.Errorf("Rename instance snapshot: %w", err) } } else { err = pool.RenameInstance(d, newName, nil) if err != nil { return fmt.Errorf("Rename instance: %w", err) } if applyTemplateTrigger { err = d.DeferTemplateApply(instance.TemplateTriggerRename) if err != nil { return err } } } if !d.IsSnapshot() { // Rename all the instance snapshot database entries. results, err := d.state.DB.Cluster.GetInstanceSnapshotsNames(d.project, oldName) if err != nil { d.logger.Error("Failed to get container snapshots", ctxMap) return fmt.Errorf("Failed to get container snapshots: %w", err) } for _, sname := range results { // Rename the snapshot. oldSnapName := strings.SplitN(sname, shared.SnapshotDelimiter, 2)[1] baseSnapName := filepath.Base(sname) err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error { return cluster.RenameInstanceSnapshot(ctx, tx.Tx(), d.project, oldName, oldSnapName, baseSnapName) }) if err != nil { d.logger.Error("Failed renaming snapshot", ctxMap) return fmt.Errorf("Failed renaming snapshot: %w", err) } } } // Rename the instance database entry. err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error { if d.IsSnapshot() { oldParts := strings.SplitN(oldName, shared.SnapshotDelimiter, 2) newParts := strings.SplitN(newName, shared.SnapshotDelimiter, 2) return cluster.RenameInstanceSnapshot(ctx, tx.Tx(), d.project, oldParts[0], oldParts[1], newParts[1]) } return cluster.RenameInstance(ctx, tx.Tx(), d.project, oldName, newName) }) if err != nil { d.logger.Error("Failed renaming container", ctxMap) return fmt.Errorf("Failed renaming container: %w", err) } // Rename the logging path. newFullName := project.Instance(d.Project(), d.Name()) _ = os.RemoveAll(shared.LogPath(newFullName)) if shared.PathExists(d.LogPath()) { err := os.Rename(d.LogPath(), shared.LogPath(newFullName)) if err != nil { d.logger.Error("Failed renaming container", ctxMap) return fmt.Errorf("Failed renaming container: %w", err) } } // Rename the MAAS entry. if !d.IsSnapshot() { err = d.maasRename(d, newName) if err != nil { return err } } revert := revert.New() defer revert.Fail() // Set the new name in the struct. d.name = newName revert.Add(func() { d.name = oldName }) // Rename the backups. backups, err := d.Backups() if err != nil { return err } for _, backup := range backups { b := backup oldName := b.Name() backupName := strings.Split(oldName, "/")[1] newName := fmt.Sprintf("%s/%s", newName, backupName) err = b.Rename(newName) if err != nil { return err } revert.Add(func() { _ = b.Rename(oldName) }) } // Invalidate the go-lxc cache. d.release() d.cConfig = false // Update lease files. err = network.UpdateDNSMasqStatic(d.state, "") if err != nil { return err } // Reset cloud-init instance-id (causes a re-run on name changes). if !d.IsSnapshot() { err = d.resetInstanceID() if err != nil { return err } } // Update the backup file. err = d.UpdateBackupFile() if err != nil { return err } d.logger.Info("Renamed container", ctxMap) if d.snapshot { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotRenamed.Event(d, map[string]any{"old_name": oldName})) } else { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRenamed.Event(d, map[string]any{"old_name": oldName})) } revert.Success() return nil } // CGroupSet sets a cgroup value for the instance. func (d *lxc) CGroupSet(key string, value string) error { // Load the go-lxc struct err := d.initLXC(false) if err != nil { return err } // Make sure the container is running if !d.IsRunning() { return fmt.Errorf("Can't set cgroups on a stopped container") } err = d.c.SetCgroupItem(key, value) if err != nil { return fmt.Errorf("Failed to set cgroup %s=\"%s\": %w", key, value, err) } return nil } // Update applies updated config. func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { // Setup a new operation op, err := operationlock.CreateWaitGet(d.Project(), d.Name(), operationlock.ActionUpdate, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore}, false, false) if err != nil { return fmt.Errorf("Failed to create instance update operation: %w", err) } defer op.Done(nil) // Set sane defaults for unset keys if args.Project == "" { args.Project = project.Default } if args.Architecture == 0 { args.Architecture = d.architecture } if args.Config == nil { args.Config = map[string]string{} } if args.Devices == nil { args.Devices = deviceConfig.Devices{} } if args.Profiles == nil { args.Profiles = []api.Profile{} } if userRequested { // Validate the new config err := instance.ValidConfig(d.state.OS, args.Config, false, d.dbType) if err != nil { return fmt.Errorf("Invalid config: %w", err) } // Validate the new devices without using expanded devices validation (expensive checks disabled). err = instance.ValidDevices(d.state, d.Project(), d.Type(), args.Devices, false) if err != nil { return fmt.Errorf("Invalid devices: %w", err) } } // Validate the new profiles profiles, err := d.state.DB.Cluster.GetProfileNames(args.Project) if err != nil { return fmt.Errorf("Failed to get profiles: %w", err) } checkedProfiles := []string{} for _, profile := range args.Profiles { if !shared.StringInSlice(profile.Name, profiles) { return fmt.Errorf("Requested profile '%s' doesn't exist", profile.Name) } if shared.StringInSlice(profile.Name, checkedProfiles) { return fmt.Errorf("Duplicate profile found in request") } checkedProfiles = append(checkedProfiles, profile.Name) } // Validate the new architecture if args.Architecture != 0 { _, err = osarch.ArchitectureName(args.Architecture) if err != nil { return fmt.Errorf("Invalid architecture id: %s", err) } } // Get a copy of the old configuration oldDescription := d.Description() oldArchitecture := 0 err = shared.DeepCopy(&d.architecture, &oldArchitecture) if err != nil { return err } oldEphemeral := false err = shared.DeepCopy(&d.ephemeral, &oldEphemeral) if err != nil { return err } oldExpandedDevices := deviceConfig.Devices{} err = shared.DeepCopy(&d.expandedDevices, &oldExpandedDevices) if err != nil { return err } oldExpandedConfig := map[string]string{} err = shared.DeepCopy(&d.expandedConfig, &oldExpandedConfig) if err != nil { return err } oldLocalDevices := deviceConfig.Devices{} err = shared.DeepCopy(&d.localDevices, &oldLocalDevices) if err != nil { return err } oldLocalConfig := map[string]string{} err = shared.DeepCopy(&d.localConfig, &oldLocalConfig) if err != nil { return err } oldProfiles := []api.Profile{} err = shared.DeepCopy(&d.profiles, &oldProfiles) if err != nil { return err } oldExpiryDate := d.expiryDate // Define a function which reverts everything. Defer this function // so that it doesn't need to be explicitly called in every failing // return path. Track whether or not we want to undo the changes // using a closure. undoChanges := true defer func() { if undoChanges { d.description = oldDescription d.architecture = oldArchitecture d.ephemeral = oldEphemeral d.expandedConfig = oldExpandedConfig d.expandedDevices = oldExpandedDevices d.localConfig = oldLocalConfig d.localDevices = oldLocalDevices d.profiles = oldProfiles d.expiryDate = oldExpiryDate d.release() d.cConfig = false _ = d.initLXC(true) cgroup.TaskSchedulerTrigger("container", d.name, "changed") } }() // Apply the various changes d.description = args.Description d.architecture = args.Architecture d.ephemeral = args.Ephemeral d.localConfig = args.Config d.localDevices = args.Devices d.profiles = args.Profiles d.expiryDate = args.ExpiryDate // Expand the config and refresh the LXC config err = d.expandConfig(nil) if err != nil { return err } // Diff the configurations changedConfig := []string{} for key := range oldExpandedConfig { if oldExpandedConfig[key] != d.expandedConfig[key] { if !shared.StringInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } } for key := range d.expandedConfig { if oldExpandedConfig[key] != d.expandedConfig[key] { if !shared.StringInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } } // Diff the devices removeDevices, addDevices, updateDevices, allUpdatedKeys := oldExpandedDevices.Update(d.expandedDevices, func(oldDevice deviceConfig.Device, newDevice deviceConfig.Device) []string { // This function needs to return a list of fields that are excluded from differences // between oldDevice and newDevice. The result of this is that as long as the // devices are otherwise identical except for the fields returned here, then the // device is considered to be being "updated" rather than "added & removed". oldDevType, err := device.LoadByType(d.state, d.Project(), oldDevice) if err != nil { return []string{} // Couldn't create Device, so this cannot be an update. } newDevType, err := device.LoadByType(d.state, d.Project(), newDevice) if err != nil { return []string{} // Couldn't create Device, so this cannot be an update. } return newDevType.UpdatableFields(oldDevType) }) if userRequested { // Look for deleted idmap keys. protectedKeys := []string{ "volatile.idmap.base", "volatile.idmap.current", "volatile.idmap.next", "volatile.last_state.idmap", } for _, k := range changedConfig { if !shared.StringInSlice(k, protectedKeys) { continue } _, ok := d.expandedConfig[k] if !ok { return fmt.Errorf("Volatile idmap keys can't be deleted by the user") } } // Do some validation of the config diff (allows mixed instance types for profiles). err = instance.ValidConfig(d.state.OS, d.expandedConfig, true, instancetype.Any) if err != nil { return fmt.Errorf("Invalid expanded config: %w", err) } // Do full expanded validation of the devices diff. err = instance.ValidDevices(d.state, d.Project(), d.Type(), d.expandedDevices, true) if err != nil { return fmt.Errorf("Invalid expanded devices: %w", err) } // Validate root device _, oldRootDev, oldErr := shared.GetRootDiskDevice(oldExpandedDevices.CloneNative()) _, newRootDev, newErr := shared.GetRootDiskDevice(d.expandedDevices.CloneNative()) if oldErr == nil && newErr == nil && oldRootDev["pool"] != newRootDev["pool"] { return fmt.Errorf("Cannot update root disk device pool name") } } // Run through initLXC to catch anything we missed if userRequested { d.release() d.cConfig = false err = d.initLXC(true) if err != nil { return fmt.Errorf("Initialize LXC: %w", err) } } cg, err := d.cgroup(nil) if err != nil { return err } // If raw.lxc changed, re-validate the config. if shared.StringInSlice("raw.lxc", changedConfig) && d.expandedConfig["raw.lxc"] != "" { // Get a new liblxc instance. cc, err := liblxc.NewContainer(d.name, d.state.OS.LxcPath) if err != nil { return err } err = d.loadRawLXCConfig() if err != nil { return err } // Release the liblxc instance. _ = cc.Release() } // If apparmor changed, re-validate the apparmor profile (even if not running). if shared.StringInSlice("raw.apparmor", changedConfig) || shared.StringInSlice("security.nesting", changedConfig) { err = apparmor.InstanceValidate(d.state.OS, d) if err != nil { return fmt.Errorf("Parse AppArmor profile: %w", err) } } if shared.StringInSlice("security.idmap.isolated", changedConfig) || shared.StringInSlice("security.idmap.base", changedConfig) || shared.StringInSlice("security.idmap.size", changedConfig) || shared.StringInSlice("raw.idmap", changedConfig) || shared.StringInSlice("security.privileged", changedConfig) { var idmap *idmap.IdmapSet base := int64(0) if !d.IsPrivileged() { // update the idmap idmap, base, err = findIdmap( d.state, d.Name(), d.expandedConfig["security.idmap.isolated"], d.expandedConfig["security.idmap.base"], d.expandedConfig["security.idmap.size"], d.expandedConfig["raw.idmap"], ) if err != nil { return fmt.Errorf("Failed to get ID map: %w", err) } } var jsonIdmap string if idmap != nil { idmapBytes, err := json.Marshal(idmap.Idmap) if err != nil { return err } jsonIdmap = string(idmapBytes) } else { jsonIdmap = "[]" } d.localConfig["volatile.idmap.next"] = jsonIdmap d.localConfig["volatile.idmap.base"] = fmt.Sprintf("%v", base) // Invalid idmap cache d.idmapset = nil } isRunning := d.IsRunning() // Use the device interface to apply update changes. err = d.devicesUpdate(d, removeDevices, addDevices, updateDevices, oldExpandedDevices, isRunning, userRequested) if err != nil { return err } // Update MAAS (must run after the MAC addresses have been generated). updateMAAS := false for _, key := range []string{"maas.subnet.ipv4", "maas.subnet.ipv6", "ipv4.address", "ipv6.address"} { if shared.StringInSlice(key, allUpdatedKeys) { updateMAAS = true break } } if !d.IsSnapshot() && updateMAAS { err = d.maasUpdate(d, oldExpandedDevices.CloneNative()) if err != nil { return err } } // Apply the live changes if isRunning { // Live update the container config for _, key := range changedConfig { value := d.expandedConfig[key] if key == "raw.apparmor" || key == "security.nesting" { // Update the AppArmor profile err = apparmor.InstanceLoad(d.state.OS, d) if err != nil { return err } } else if key == "security.devlxd" { if value == "" || shared.IsTrue(value) { err = d.insertMount(shared.VarPath("devlxd"), "/dev/lxd", "none", unix.MS_BIND, idmap.IdmapStorageNone) if err != nil { return err } } else { // Connect to files API. files, err := d.FileSFTP() if err != nil { return err } defer func() { _ = files.Close() }() _, err = files.Lstat("/dev/lxd") if err == nil { err = d.removeMount("/dev/lxd") if err != nil { return err } err = files.Remove("/dev/lxd") if err != nil { return err } } } } else if key == "linux.kernel_modules" && value != "" { for _, module := range strings.Split(value, ",") { module = strings.TrimPrefix(module, " ") err := util.LoadModule(module) if err != nil { return fmt.Errorf("Failed to load kernel module '%s': %w", module, err) } } } else if key == "limits.disk.priority" { if !d.state.OS.CGInfo.Supports(cgroup.Blkio, cg) { continue } priorityInt := 5 diskPriority := d.expandedConfig["limits.disk.priority"] if diskPriority != "" { priorityInt, err = strconv.Atoi(diskPriority) if err != nil { return err } } // Minimum valid value is 10 priority := int64(priorityInt * 100) if priority == 0 { priority = 10 } err = cg.SetBlkioWeight(priority) if err != nil { return err } } else if key == "limits.memory" || strings.HasPrefix(key, "limits.memory.") { // Skip if no memory CGroup if !d.state.OS.CGInfo.Supports(cgroup.Memory, cg) { continue } // Set the new memory limit memory := d.expandedConfig["limits.memory"] memoryEnforce := d.expandedConfig["limits.memory.enforce"] memorySwap := d.expandedConfig["limits.memory.swap"] var memoryInt int64 // Parse memory if memory == "" { memoryInt = -1 } else if strings.HasSuffix(memory, "%") { percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64) if err != nil { return err } memoryTotal, err := shared.DeviceTotalMemory() if err != nil { return err } memoryInt = int64((memoryTotal / 100) * percent) } else { memoryInt, err = units.ParseByteSizeString(memory) if err != nil { return err } } // Store the old values for revert oldMemswLimit := int64(-1) if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) { oldMemswLimit, err = cg.GetMemorySwapLimit() if err != nil { oldMemswLimit = -1 } } oldLimit, err := cg.GetMemoryLimit() if err != nil { oldLimit = -1 } oldSoftLimit, err := cg.GetMemorySoftLimit() if err != nil { oldSoftLimit = -1 } revertMemory := func() { if oldSoftLimit != -1 { _ = cg.SetMemorySoftLimit(oldSoftLimit) } if oldLimit != -1 { _ = cg.SetMemoryLimit(oldLimit) } if oldMemswLimit != -1 { _ = cg.SetMemorySwapLimit(oldMemswLimit) } } // Reset everything if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) { err = cg.SetMemorySwapLimit(-1) if err != nil { revertMemory() return err } } err = cg.SetMemoryLimit(-1) if err != nil { revertMemory() return err } err = cg.SetMemorySoftLimit(-1) if err != nil { revertMemory() return err } // Set the new values if memoryEnforce == "soft" { // Set new limit err = cg.SetMemorySoftLimit(memoryInt) if err != nil { revertMemory() return err } } else { if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) { err = cg.SetMemoryLimit(memoryInt) if err != nil { revertMemory() return err } err = cg.SetMemorySwapLimit(0) if err != nil { revertMemory() return err } } else { err = cg.SetMemoryLimit(memoryInt) if err != nil { revertMemory() return err } } // Set soft limit to value 10% less than hard limit err = cg.SetMemorySoftLimit(int64(float64(memoryInt) * 0.9)) if err != nil { revertMemory() return err } } if !d.state.OS.CGInfo.Supports(cgroup.MemorySwappiness, cg) { continue } // Configure the swappiness if key == "limits.memory.swap" || key == "limits.memory.swap.priority" { memorySwap := d.expandedConfig["limits.memory.swap"] memorySwapPriority := d.expandedConfig["limits.memory.swap.priority"] if shared.IsFalse(memorySwap) { err = cg.SetMemorySwappiness(0) if err != nil { return err } } else { priority := 10 if memorySwapPriority != "" { priority, err = strconv.Atoi(memorySwapPriority) if err != nil { return err } } // Maximum priority (10) should be default swappiness (60). err = cg.SetMemorySwappiness(int64(70 - priority)) if err != nil { return err } } } } else if key == "limits.network.priority" { err := d.setNetworkPriority() if err != nil { return err } } else if key == "limits.cpu" { // Trigger a scheduler re-run cgroup.TaskSchedulerTrigger("container", d.name, "changed") } else if key == "limits.cpu.priority" || key == "limits.cpu.allowance" { // Skip if no cpu CGroup if !d.state.OS.CGInfo.Supports(cgroup.CPU, cg) { continue } // Apply new CPU limits cpuShares, cpuCfsQuota, cpuCfsPeriod, err := cgroup.ParseCPU(d.expandedConfig["limits.cpu.allowance"], d.expandedConfig["limits.cpu.priority"]) if err != nil { return err } err = cg.SetCPUShare(cpuShares) if err != nil { return err } err = cg.SetCPUCfsLimit(cpuCfsPeriod, cpuCfsQuota) if err != nil { return err } } else if key == "limits.processes" { if !d.state.OS.CGInfo.Supports(cgroup.Pids, cg) { continue } if value == "" { err = cg.SetMaxProcesses(-1) if err != nil { return err } } else { valueInt, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } err = cg.SetMaxProcesses(valueInt) if err != nil { return err } } } else if strings.HasPrefix(key, "limits.hugepages.") { if !d.state.OS.CGInfo.Supports(cgroup.Hugetlb, cg) { continue } pageType := "" switch key { case "limits.hugepages.64KB": pageType = "64KB" case "limits.hugepages.1MB": pageType = "1MB" case "limits.hugepages.2MB": pageType = "2MB" case "limits.hugepages.1GB": pageType = "1GB" } valueInt := int64(-1) if value != "" { valueInt, err = units.ParseByteSizeString(value) if err != nil { return err } } err = cg.SetHugepagesLimit(pageType, valueInt) if err != nil { return err } } } } // Re-generate the instance-id if needed. if !d.IsSnapshot() && d.needsNewInstanceID(changedConfig, oldExpandedDevices) { err = d.resetInstanceID() if err != nil { return err } } // Finally, apply the changes to the database err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error { // Snapshots should update only their descriptions and expiry date. if d.IsSnapshot() { return tx.UpdateInstanceSnapshot(d.id, d.description, d.expiryDate) } object, err := cluster.GetInstance(ctx, tx.Tx(), d.project, d.name) if err != nil { return err } object.Description = d.description object.Architecture = d.architecture object.Ephemeral = d.ephemeral object.ExpiryDate = sql.NullTime{Time: d.expiryDate, Valid: true} err = cluster.UpdateInstance(ctx, tx.Tx(), d.project, d.name, *object) if err != nil { return err } err = cluster.UpdateInstanceConfig(ctx, tx.Tx(), int64(object.ID), d.localConfig) if err != nil { return err } devices, err := cluster.APIToDevices(d.localDevices.CloneNative()) if err != nil { return err } err = cluster.UpdateInstanceDevices(ctx, tx.Tx(), int64(object.ID), devices) if err != nil { return err } profileNames := make([]string, 0, len(d.profiles)) for _, profile := range d.profiles { profileNames = append(profileNames, profile.Name) } return cluster.UpdateInstanceProfiles(ctx, tx.Tx(), object.ID, object.Project, profileNames) }) if err != nil { return fmt.Errorf("Failed to update database: %w", err) } err = d.UpdateBackupFile() if err != nil && !os.IsNotExist(err) { return fmt.Errorf("Failed to write backup file: %w", err) } // Send devlxd notifications if isRunning { // Config changes (only for user.* keys for _, key := range changedConfig { if !strings.HasPrefix(key, "user.") { continue } msg := map[string]any{ "key": key, "old_value": oldExpandedConfig[key], "value": d.expandedConfig[key], } err = d.devlxdEventSend("config", msg) if err != nil { return err } } // Device changes for k, m := range removeDevices { msg := map[string]any{ "action": "removed", "name": k, "config": m, } err = d.devlxdEventSend("device", msg) if err != nil { return err } } for k, m := range updateDevices { msg := map[string]any{ "action": "updated", "name": k, "config": m, } err = d.devlxdEventSend("device", msg) if err != nil { return err } } for k, m := range addDevices { msg := map[string]any{ "action": "added", "name": k, "config": m, } err = d.devlxdEventSend("device", msg) if err != nil { return err } } } // Success, update the closure to mark that the changes should be kept. undoChanges = false if userRequested { if d.snapshot { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotUpdated.Event(d, nil)) } else { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceUpdated.Event(d, nil)) } } return nil } // Export backs up the instance. func (d *lxc) Export(w io.Writer, properties map[string]string, expiration time.Time) (api.ImageMetadata, error) { ctxMap := logger.Ctx{ "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate} meta := api.ImageMetadata{} if d.IsRunning() { return meta, fmt.Errorf("Cannot export a running instance as an image") } d.logger.Info("Exporting instance", ctxMap) // Start the storage. _, err := d.mount() if err != nil { d.logger.Error("Failed exporting instance", ctxMap) return meta, err } defer func() { _ = d.unmount() }() // Get IDMap to unshift container as the tarball is created. idmap, err := d.DiskIdmap() if err != nil { d.logger.Error("Failed exporting instance", ctxMap) return meta, err } // Create the tarball. tarWriter := instancewriter.NewInstanceTarWriter(w, idmap) // Keep track of the first path we saw for each path with nlink>1. cDir := d.Path() // Path inside the tar image is the pathname starting after cDir. offset := len(cDir) + 1 writeToTar := func(path string, fi os.FileInfo, err error) error { if err != nil { return err } err = tarWriter.WriteFile(path[offset:], path, fi, false) if err != nil { d.logger.Debug("Error tarring up", logger.Ctx{"path": path, "err": err}) return err } return nil } // Look for metadata.yaml. fnam := filepath.Join(cDir, "metadata.yaml") if !shared.PathExists(fnam) { // Generate a new metadata.yaml. tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_") if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } defer func() { _ = os.RemoveAll(tempDir) }() // Get the instance's architecture. var arch string if d.IsSnapshot() { parentName, _, _ := api.GetParentAndSnapshotName(d.name) parent, err := instance.LoadByProjectAndName(d.state, d.project, parentName) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } arch, _ = osarch.ArchitectureName(parent.Architecture()) } else { arch, _ = osarch.ArchitectureName(d.architecture) } if arch == "" { arch, err = osarch.ArchitectureName(d.state.OS.Architectures[0]) if err != nil { d.logger.Error("Failed exporting instance", ctxMap) return meta, err } } // Fill in the metadata. meta.Architecture = arch meta.CreationDate = time.Now().UTC().Unix() meta.Properties = properties if !expiration.IsZero() { meta.ExpiryDate = expiration.UTC().Unix() } data, err := yaml.Marshal(&meta) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } // Write the actual file. fnam = filepath.Join(tempDir, "metadata.yaml") err = ioutil.WriteFile(fnam, data, 0644) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } fi, err := os.Lstat(fnam) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } tmpOffset := len(path.Dir(fnam)) + 1 err = tarWriter.WriteFile(fnam[tmpOffset:], fnam, fi, false) if err != nil { _ = tarWriter.Close() d.logger.Debug("Error writing to tarfile", logger.Ctx{"err": err}) d.logger.Error("Failed exporting instance", ctxMap) return meta, err } } else { // Parse the metadata. content, err := ioutil.ReadFile(fnam) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } err = yaml.Unmarshal(content, &meta) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } if !expiration.IsZero() { meta.ExpiryDate = expiration.UTC().Unix() } if properties != nil { meta.Properties = properties } if properties != nil || !expiration.IsZero() { // Generate a new metadata.yaml. tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_") if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } defer func() { _ = os.RemoveAll(tempDir) }() data, err := yaml.Marshal(&meta) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } // Write the actual file. fnam = filepath.Join(tempDir, "metadata.yaml") err = ioutil.WriteFile(fnam, data, 0644) if err != nil { _ = tarWriter.Close() d.logger.Error("Failed exporting instance", ctxMap) return meta, err } } // Include metadata.yaml in the tarball. fi, err := os.Lstat(fnam) if err != nil { _ = tarWriter.Close() d.logger.Debug("Error statting during export", logger.Ctx{"fileName": fnam}) d.logger.Error("Failed exporting instance", ctxMap) return meta, err } if properties != nil || !expiration.IsZero() { tmpOffset := len(path.Dir(fnam)) + 1 err = tarWriter.WriteFile(fnam[tmpOffset:], fnam, fi, false) } else { err = tarWriter.WriteFile(fnam[offset:], fnam, fi, false) } if err != nil { _ = tarWriter.Close() d.logger.Debug("Error writing to tarfile", logger.Ctx{"err": err}) d.logger.Error("Failed exporting instance", ctxMap) return meta, err } } // Include all the rootfs files. fnam = d.RootfsPath() err = filepath.Walk(fnam, writeToTar) if err != nil { d.logger.Error("Failed exporting instance", ctxMap) return meta, err } // Include all the templates. fnam = d.TemplatesPath() if shared.PathExists(fnam) { err = filepath.Walk(fnam, writeToTar) if err != nil { d.logger.Error("Failed exporting instance", ctxMap) return meta, err } } err = tarWriter.Close() if err != nil { d.logger.Error("Failed exporting instance", ctxMap) return meta, err } d.logger.Info("Exported instance", ctxMap) return meta, nil } func collectCRIULogFile(d instance.Instance, imagesDir string, function string, method string) error { t := time.Now().Format(time.RFC3339) newPath := filepath.Join(d.LogPath(), fmt.Sprintf("%s_%s_%s.log", function, method, t)) return shared.FileCopy(filepath.Join(imagesDir, fmt.Sprintf("%s.log", method)), newPath) } func getCRIULogErrors(imagesDir string, method string) (string, error) { f, err := os.Open(path.Join(imagesDir, fmt.Sprintf("%s.log", method))) if err != nil { return "", err } defer func() { _ = f.Close() }() scanner := bufio.NewScanner(f) ret := []string{} for scanner.Scan() { line := scanner.Text() if strings.Contains(line, "Error") || strings.Contains(line, "Warn") { ret = append(ret, scanner.Text()) } } return strings.Join(ret, "\n"), nil } // Migrate migrates the instance to another node. func (d *lxc) Migrate(args *instance.CriuMigrationArgs) error { ctxMap := logger.Ctx{ "created": d.creationDate, "ephemeral": d.ephemeral, "used": d.lastUsedDate, "statedir": args.StateDir, "actionscript": args.ActionScript, "predumpdir": args.PreDumpDir, "features": args.Features, "stop": args.Stop} _, err := exec.LookPath("criu") if err != nil { return fmt.Errorf("Unable to perform container live migration. CRIU isn't installed") } d.logger.Info("Migrating container", ctxMap) prettyCmd := "" switch args.Cmd { case liblxc.MIGRATE_PRE_DUMP: prettyCmd = "pre-dump" case liblxc.MIGRATE_DUMP: prettyCmd = "dump" case liblxc.MIGRATE_RESTORE: prettyCmd = "restore" case liblxc.MIGRATE_FEATURE_CHECK: prettyCmd = "feature-check" default: prettyCmd = "unknown" d.logger.Warn("Unknown migrate call", logger.Ctx{"cmd": args.Cmd}) } pool, err := d.getStoragePool() if err != nil { return err } preservesInodes := pool.Driver().Info().PreservesInodes /* This feature was only added in 2.0.1, let's not ask for it * before then or migrations will fail. */ if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 0, 1) { preservesInodes = false } finalStateDir := args.StateDir var migrateErr error /* For restore, we need an extra fork so that we daemonize monitor * instead of having it be a child of LXD, so let's hijack the command * here and do the extra fork. */ if args.Cmd == liblxc.MIGRATE_RESTORE { // Check that we're not already running. if d.IsRunning() { return fmt.Errorf("The container is already running") } // Run the shared start _, postStartHooks, err := d.startCommon() if err != nil { return fmt.Errorf("Failed preparing container for start: %w", err) } /* * For unprivileged containers we need to shift the * perms on the images images so that they can be * opened by the process after it is in its user * namespace. */ idmapset, err := d.CurrentIdmap() if err != nil { return err } if idmapset != nil { storageType, err := d.getStorageType() if err != nil { return fmt.Errorf("Storage type: %w", err) } if storageType == "zfs" { err = idmapset.ShiftRootfs(args.StateDir, storageDrivers.ShiftZFSSkipper) } else if storageType == "btrfs" { err = storageDrivers.ShiftBtrfsRootfs(args.StateDir, idmapset) } else { err = idmapset.ShiftRootfs(args.StateDir, nil) } if err != nil { return err } } configPath := filepath.Join(d.LogPath(), "lxc.conf") if args.DumpDir != "" { finalStateDir = fmt.Sprintf("%s/%s", args.StateDir, args.DumpDir) } // Update the backup.yaml file just before starting the instance process, but after all devices // have been setup, so that the backup file contains the volatile keys used for this instance // start, so that they can be used for instance cleanup. err = d.UpdateBackupFile() if err != nil { return err } _, migrateErr = shared.RunCommand( d.state.OS.ExecPath, "forkmigrate", d.name, d.state.OS.LxcPath, configPath, finalStateDir, fmt.Sprintf("%v", preservesInodes)) if migrateErr == nil { // Run any post start hooks. err := d.runHooks(postStartHooks) if err != nil { // Attempt to stop container. _ = d.Stop(false) return err } } } else if args.Cmd == liblxc.MIGRATE_FEATURE_CHECK { err := d.initLXC(true) if err != nil { return err } opts := liblxc.MigrateOptions{ FeaturesToCheck: args.Features, } migrateErr = d.c.Migrate(args.Cmd, opts) if migrateErr != nil { d.logger.Info("CRIU feature check failed", ctxMap) return migrateErr } return nil } else { err := d.initLXC(true) if err != nil { return err } script := "" if args.ActionScript { script = filepath.Join(args.StateDir, "action.sh") } if args.DumpDir != "" { finalStateDir = fmt.Sprintf("%s/%s", args.StateDir, args.DumpDir) } // TODO: make this configurable? Ultimately I think we don't // want to do that; what we really want to do is have "modes" // of criu operation where one is "make this succeed" and the // other is "make this fast". Anyway, for now, let's choose a // really big size so it almost always succeeds, even if it is // slow. ghostLimit := uint64(256 * 1024 * 1024) opts := liblxc.MigrateOptions{ Stop: args.Stop, Directory: finalStateDir, Verbose: true, PreservesInodes: preservesInodes, ActionScript: script, GhostLimit: ghostLimit, } if args.PreDumpDir != "" { opts.PredumpDir = fmt.Sprintf("../%s", args.PreDumpDir) } if !d.IsRunning() { // otherwise the migration will needlessly fail args.Stop = false } migrateErr = d.c.Migrate(args.Cmd, opts) } collectErr := collectCRIULogFile(d, finalStateDir, args.Function, prettyCmd) if collectErr != nil { d.logger.Error("Error collecting checkpoint log file", logger.Ctx{"err": collectErr}) } if migrateErr != nil { log, err2 := getCRIULogErrors(finalStateDir, prettyCmd) if err2 == nil { d.logger.Info("Failed migrating container", ctxMap) migrateErr = fmt.Errorf("%s %s failed\n%s", args.Function, prettyCmd, log) } return migrateErr } d.logger.Info("Migrated container", ctxMap) return nil } func (d *lxc) templateApplyNow(trigger instance.TemplateTrigger) error { // If there's no metadata, just return fname := filepath.Join(d.Path(), "metadata.yaml") if !shared.PathExists(fname) { return nil } // Parse the metadata content, err := ioutil.ReadFile(fname) if err != nil { return fmt.Errorf("Failed to read metadata: %w", err) } metadata := new(api.ImageMetadata) err = yaml.Unmarshal(content, &metadata) if err != nil { return fmt.Errorf("Could not parse %s: %w", fname, err) } // Find rootUID and rootGID idmapset, err := d.DiskIdmap() if err != nil { return fmt.Errorf("Failed to set ID map: %w", err) } rootUID := int64(0) rootGID := int64(0) // Get the right uid and gid for the container if idmapset != nil { rootUID, rootGID = idmapset.ShiftIntoNs(0, 0) } // Figure out the container architecture arch, err := osarch.ArchitectureName(d.architecture) if err != nil { arch, err = osarch.ArchitectureName(d.state.OS.Architectures[0]) if err != nil { return fmt.Errorf("Failed to detect system architecture: %w", err) } } // Generate the container metadata containerMeta := make(map[string]string) containerMeta["name"] = d.name containerMeta["type"] = "container" containerMeta["architecture"] = arch if d.ephemeral { containerMeta["ephemeral"] = "true" } else { containerMeta["ephemeral"] = "false" } if d.IsPrivileged() { containerMeta["privileged"] = "true" } else { containerMeta["privileged"] = "false" } // Go through the templates for tplPath, tpl := range metadata.Templates { err = func(tplPath string, tpl *api.ImageMetadataTemplate) error { var w *os.File // Check if the template should be applied now found := false for _, tplTrigger := range tpl.When { if tplTrigger == string(trigger) { found = true break } } if !found { return nil } // Open the file to template, create if needed fullpath := filepath.Join(d.RootfsPath(), strings.TrimLeft(tplPath, "/")) if shared.PathExists(fullpath) { if tpl.CreateOnly { return nil } // Open the existing file w, err = os.Create(fullpath) if err != nil { return fmt.Errorf("Failed to create template file: %w", err) } } else { // Create the directories leading to the file err = shared.MkdirAllOwner(path.Dir(fullpath), 0755, int(rootUID), int(rootGID)) if err != nil { return err } // Create the file itself w, err = os.Create(fullpath) if err != nil { return err } // Fix ownership and mode err = w.Chown(int(rootUID), int(rootGID)) if err != nil { return err } err = w.Chmod(0644) if err != nil { return err } } defer func() { _ = w.Close() }() // Read the template tplString, err := ioutil.ReadFile(filepath.Join(d.TemplatesPath(), tpl.Template)) if err != nil { return fmt.Errorf("Failed to read template file: %w", err) } // Restrict filesystem access to within the container's rootfs tplSet := pongo2.NewSet(fmt.Sprintf("%s-%s", d.name, tpl.Template), template.ChrootLoader{Path: d.RootfsPath()}) tplRender, err := tplSet.FromString("{% autoescape off %}" + string(tplString) + "{% endautoescape %}") if err != nil { return fmt.Errorf("Failed to render template: %w", err) } configGet := func(confKey, confDefault *pongo2.Value) *pongo2.Value { val, ok := d.expandedConfig[confKey.String()] if !ok { return confDefault } return pongo2.AsValue(strings.TrimRight(val, "\r\n")) } // Render the template err = tplRender.ExecuteWriter(pongo2.Context{"trigger": trigger, "path": tplPath, "container": containerMeta, "instance": containerMeta, "config": d.expandedConfig, "devices": d.expandedDevices, "properties": tpl.Properties, "config_get": configGet}, w) if err != nil { return err } return w.Close() }(tplPath, tpl) if err != nil { return err } } return nil } func (d *lxc) inheritInitPidFd() (int, *os.File) { if d.state.OS.PidFds { pidFdFile, err := d.InitPidFd() if err != nil { return -1, nil } return 3, pidFdFile } return -1, nil } // FileSFTPConn returns a connection to the forkfile handler. func (d *lxc) FileSFTPConn() (net.Conn, error) { // Lock to avoid concurrent spawning. spawnUnlock := locking.Lock(fmt.Sprintf("forkfile_%d", d.id)) defer spawnUnlock() // Create any missing directories in case the instance has never been started before. err := os.MkdirAll(d.LogPath(), 0700) if err != nil { return nil, err } // Trickery to handle paths > 108 chars. dirFile, err := os.Open(d.LogPath()) if err != nil { return nil, err } defer func() { _ = dirFile.Close() }() forkfileAddr, err := net.ResolveUnixAddr("unix", fmt.Sprintf("/proc/self/fd/%d/forkfile.sock", dirFile.Fd())) if err != nil { return nil, err } // Attempt to connect on existing socket. forkfilePath := filepath.Join(d.LogPath(), "forkfile.sock") forkfileConn, err := net.DialUnix("unix", nil, forkfileAddr) if err == nil { // Found an existing server. return forkfileConn, nil } // Check for ongoing operations (that may involve shifting or replacing the root volume) so as to avoid // allowing SFTP access while the container's filesystem setup is in flux. // If there is an update operation ongoing and the instance is running then do not wait for the operation // to complete before continuing as it is possible that a disk device is being removed that requires SFTP // to clean up the path inside the container. Also it is not possible to be shifting/replacing the root // volume when the instance is running, so there should be no reason to wait for the operation to finish. op := operationlock.Get(d.Project(), d.Name()) if op.Action() != operationlock.ActionUpdate || !d.IsRunning() { _ = op.Wait() } // Setup reverter. revert := revert.New() defer revert.Fail() // Create the listener. _ = os.Remove(forkfilePath) forkfileListener, err := net.ListenUnix("unix", forkfileAddr) if err != nil { return nil, err } revert.Add(func() { _ = forkfileListener.Close() _ = os.Remove(forkfilePath) }) // Spawn forkfile in a Go routine. chReady := make(chan error) go func() { // Lock to avoid concurrent running forkfile. runUnlock := locking.Lock(d.forkfileRunningLockName()) defer runUnlock() // Mount the filesystem if needed. if !d.IsRunning() { // Mount the root filesystem if required. _, err := d.mount() if err != nil { chReady <- err return } defer func() { _ = d.unmount() }() } // Start building the command. args := []string{ d.state.OS.ExecPath, "forkfile", "--", } extraFiles := []*os.File{} // Get the listener file. forkfileFile, err := forkfileListener.File() if err != nil { chReady <- err return } defer func() { _ = forkfileFile.Close() }() args = append(args, "3") extraFiles = append(extraFiles, forkfileFile) // Get the rootfs. rootfsFile, err := os.Open(d.RootfsPath()) if err != nil { chReady <- err return } defer func() { _ = rootfsFile.Close() }() args = append(args, "4") extraFiles = append(extraFiles, rootfsFile) // Get the pidfd. pidFdNr, pidFd := d.inheritInitPidFd() if pidFdNr >= 0 { defer func() { _ = pidFd.Close() }() args = append(args, "5") extraFiles = append(extraFiles, pidFd) } else { args = append(args, "-1") } // Finalize the args. args = append(args, fmt.Sprintf("%d", d.InitPID())) // Prepare sftp server. forkfile := exec.Cmd{ Path: d.state.OS.ExecPath, Args: args, ExtraFiles: extraFiles, } var stderr bytes.Buffer forkfile.Stderr = &stderr if !d.IsRunning() { // Get the disk idmap. idmapset, err := d.DiskIdmap() if err != nil { chReady <- err return } if idmapset != nil { forkfile.SysProcAttr = &syscall.SysProcAttr{ Cloneflags: syscall.CLONE_NEWUSER, Credential: &syscall.Credential{ Uid: uint32(0), Gid: uint32(0), }, UidMappings: idmapset.ToUidMappings(), GidMappings: idmapset.ToGidMappings(), } } } // Start the server. err = forkfile.Start() if err != nil { chReady <- fmt.Errorf("Failed to run forkfile: %w: %s", err, strings.TrimSpace(stderr.String())) return } // Write PID file. pidFile := filepath.Join(d.LogPath(), "forkfile.pid") err = ioutil.WriteFile(pidFile, []byte(fmt.Sprintf("%d\n", forkfile.Process.Pid)), 0600) if err != nil { chReady <- fmt.Errorf("Failed to write forkfile PID: %w", err) return } // Close the listener and delete the socket immediately after forkfile exits to avoid clients // thinking a listener is available while other deferred calls are being processed. defer func() { _ = forkfileListener.Close() _ = os.Remove(forkfilePath) _ = os.Remove(pidFile) }() // Indicate the process was spawned without error. close(chReady) // Wait for completion. err = forkfile.Wait() if err != nil { d.logger.Error("SFTP server stopped with error", logger.Ctx{"err": err, "stderr": strings.TrimSpace(stderr.String())}) return } }() // Wait for forkfile to have been spawned. err = <-chReady if err != nil { return nil, err } // Connect to the new server. forkfileConn, err = net.DialUnix("unix", nil, forkfileAddr) if err != nil { return nil, err } // All done. revert.Success() return forkfileConn, nil } // FileSFTP returns an SFTP connection to the forkfile handler. func (d *lxc) FileSFTP() (*sftp.Client, error) { // Connect to the forkfile daemon. conn, err := d.FileSFTPConn() if err != nil { return nil, err } // Get a SFTP client. client, err := sftp.NewClientPipe(conn, conn) if err != nil { _ = conn.Close() return nil, err } go func() { // Wait for the client to be done before closing the connection. _ = client.Wait() _ = conn.Close() }() return client, nil } // stopForkFile attempts to send SIGINT to forkfile then waits for it to exit. func (d *lxc) stopForkfile() { // Make sure that when the function exits, no forkfile is running by acquiring the lock (which indicates // that forkfile isn't running and holding the lock) and then releasing it. defer func() { locking.Lock(d.forkfileRunningLockName())() }() // Try to send SIGINT to forkfile to speed up shutdown. content, err := ioutil.ReadFile(filepath.Join(d.LogPath(), "forkfile.pid")) if err != nil { return } pid, err := strconv.ParseInt(strings.TrimSpace(string(content)), 10, 64) if err != nil { return } d.logger.Debug("Stopping forkfile", logger.Ctx{"pid": pid}) _ = unix.Kill(int(pid), unix.SIGINT) } // Console attaches to the instance console. func (d *lxc) Console(protocol string) (*os.File, chan error, error) { if protocol != instance.ConsoleTypeConsole { return nil, nil, fmt.Errorf("Container instances don't support %q output", protocol) } chDisconnect := make(chan error, 1) args := []string{ d.state.OS.ExecPath, "forkconsole", project.Instance(d.Project(), d.Name()), d.state.OS.LxcPath, filepath.Join(d.LogPath(), "lxc.conf"), "tty=0", "escape=-1"} idmapset, err := d.CurrentIdmap() if err != nil { return nil, nil, err } var rootUID, rootGID int64 if idmapset != nil { rootUID, rootGID = idmapset.ShiftIntoNs(0, 0) } // Create a PTS pair. ptx, pty, err := shared.OpenPty(rootUID, rootGID) if err != nil { return nil, nil, err } // Switch the console file descriptor into raw mode. _, err = termios.MakeRaw(int(ptx.Fd())) if err != nil { return nil, nil, err } cmd := exec.Cmd{} cmd.Path = d.state.OS.ExecPath cmd.Args = args cmd.Stdin = pty cmd.Stdout = pty cmd.Stderr = pty err = cmd.Start() if err != nil { return nil, nil, err } go func() { err = cmd.Wait() _ = ptx.Close() _ = pty.Close() }() go func() { <-chDisconnect _ = cmd.Process.Kill() }() d.state.Events.SendLifecycle(d.project, lifecycle.InstanceConsole.Event(d, logger.Ctx{"type": instance.ConsoleTypeConsole})) return ptx, chDisconnect, nil } // ConsoleLog returns console log. func (d *lxc) ConsoleLog(opts liblxc.ConsoleLogOptions) (string, error) { msg, err := d.c.ConsoleLog(opts) if err != nil { return "", err } if opts.ClearLog { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceConsoleReset.Event(d, nil)) } else if opts.ReadLog && opts.WriteToLogFile { d.state.Events.SendLifecycle(d.project, lifecycle.InstanceConsoleRetrieved.Event(d, nil)) } return string(msg), nil } // Exec executes a command inside the instance. func (d *lxc) Exec(req api.InstanceExecPost, stdin *os.File, stdout *os.File, stderr *os.File) (instance.Cmd, error) { // Prepare the environment envSlice := []string{} for k, v := range req.Environment { envSlice = append(envSlice, fmt.Sprintf("%s=%s", k, v)) } // Setup logfile logPath := filepath.Join(d.LogPath(), "forkexec.log") logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644) if err != nil { return nil, err } defer func() { _ = logFile.Close() }() // Prepare the subcommand cname := project.Instance(d.Project(), d.Name()) args := []string{ d.state.OS.ExecPath, "forkexec", cname, d.state.OS.LxcPath, filepath.Join(d.LogPath(), "lxc.conf"), req.Cwd, fmt.Sprintf("%d", req.User), fmt.Sprintf("%d", req.Group), } if d.state.OS.CoreScheduling && !d.state.OS.ContainerCoreScheduling { args = append(args, "1") } else { args = append(args, "0") } args = append(args, "--") args = append(args, "env") args = append(args, envSlice...) args = append(args, "--") args = append(args, "cmd") args = append(args, req.Command...) cmd := exec.Cmd{} cmd.Path = d.state.OS.ExecPath cmd.Args = args cmd.Stdin = nil cmd.Stdout = logFile cmd.Stderr = logFile // Mitigation for CVE-2019-5736 useRexec := false if d.expandedConfig["raw.idmap"] != "" { err := instance.AllowedUnprivilegedOnlyMap(d.expandedConfig["raw.idmap"]) if err != nil { useRexec = true } } if shared.IsTrue(d.expandedConfig["security.privileged"]) { useRexec = true } if useRexec { cmd.Env = append(os.Environ(), "LXC_MEMFD_REXEC=1") } // Setup communication PIPE rStatus, wStatus, err := os.Pipe() defer func() { _ = rStatus.Close() }() if err != nil { return nil, err } cmd.ExtraFiles = []*os.File{stdin, stdout, stderr, wStatus} err = cmd.Start() _ = wStatus.Close() if err != nil { return nil, err } attachedPid := shared.ReadPid(rStatus) if attachedPid <= 0 { _ = cmd.Wait() d.logger.Error("Failed to retrieve PID of executing child process") return nil, fmt.Errorf("Failed to retrieve PID of executing child process") } d.logger.Debug("Retrieved PID of executing child process", logger.Ctx{"attachedPid": attachedPid}) d.state.Events.SendLifecycle(d.project, lifecycle.InstanceExec.Event(d, logger.Ctx{"command": req.Command})) instCmd := &lxcCmd{ cmd: &cmd, attachedChildPid: int(attachedPid), } return instCmd, nil } func (d *lxc) cpuState() api.InstanceStateCPU { cpu := api.InstanceStateCPU{} // CPU usage in seconds cg, err := d.cgroup(nil) if err != nil { return cpu } if !d.state.OS.CGInfo.Supports(cgroup.CPUAcct, cg) { return cpu } value, err := cg.GetCPUAcctUsage() if err != nil { cpu.Usage = -1 return cpu } cpu.Usage = value return cpu } func (d *lxc) diskState() map[string]api.InstanceStateDisk { disk := map[string]api.InstanceStateDisk{} for _, dev := range d.expandedDevices.Sorted() { if dev.Config["type"] != "disk" { continue } var usage int64 if dev.Config["path"] == "/" { pool, err := storagePools.LoadByInstance(d.state, d) if err != nil { d.logger.Error("Error loading storage pool", logger.Ctx{"err": err}) continue } usage, err = pool.GetInstanceUsage(d) if err != nil { if !errors.Is(err, storageDrivers.ErrNotSupported) { d.logger.Error("Error getting disk usage", logger.Ctx{"err": err}) } continue } } else if dev.Config["pool"] != "" { pool, err := storagePools.LoadByName(d.state, dev.Config["pool"]) if err != nil { d.logger.Error("Error loading storage pool", logger.Ctx{"poolName": dev.Config["pool"], "err": err}) continue } usage, err = pool.GetCustomVolumeUsage(d.Project(), dev.Config["source"]) if err != nil { if !errors.Is(err, storageDrivers.ErrNotSupported) { d.logger.Error("Error getting volume usage", logger.Ctx{"volume": dev.Config["source"], "err": err}) } continue } } else { continue } disk[dev.Name] = api.InstanceStateDisk{Usage: usage} } return disk } func (d *lxc) memoryState() api.InstanceStateMemory { memory := api.InstanceStateMemory{} cg, err := d.cgroup(nil) if err != nil { return memory } if !d.state.OS.CGInfo.Supports(cgroup.Memory, cg) { return memory } // Memory in bytes value, err := cg.GetMemoryUsage() if err == nil { memory.Usage = value } // Memory peak in bytes if d.state.OS.CGInfo.Supports(cgroup.MemoryMaxUsage, cg) { value, err = cg.GetMemoryMaxUsage() if err == nil { memory.UsagePeak = value } } if d.state.OS.CGInfo.Supports(cgroup.MemorySwapUsage, cg) { // Swap in bytes if memory.Usage > 0 { value, err := cg.GetMemorySwapUsage() if err == nil { memory.SwapUsage = value } } // Swap peak in bytes if memory.UsagePeak > 0 { value, err = cg.GetMemorySwapMaxUsage() if err == nil { memory.SwapUsagePeak = value } } } return memory } func (d *lxc) networkState() map[string]api.InstanceStateNetwork { result := map[string]api.InstanceStateNetwork{} pid := d.InitPID() if pid < 1 { return result } couldUseNetnsGetifaddrs := d.state.OS.NetnsGetifaddrs if couldUseNetnsGetifaddrs { nw, err := netutils.NetnsGetifaddrs(int32(pid)) if err != nil { couldUseNetnsGetifaddrs = false d.logger.Error("Failed to retrieve network information via netlink", logger.Ctx{"pid": pid}) } else { result = nw } } if !couldUseNetnsGetifaddrs { pidFdNr, pidFd := d.inheritInitPidFd() if pidFdNr >= 0 { defer func() { _ = pidFd.Close() }() } // Get the network state from the container out, _, err := shared.RunCommandSplit( context.TODO(), nil, []*os.File{pidFd}, d.state.OS.ExecPath, "forknet", "info", "--", fmt.Sprintf("%d", pid), fmt.Sprintf("%d", pidFdNr)) // Process forkgetnet response if err != nil { d.logger.Error("Error calling 'lxd forknet", logger.Ctx{"err": err, "pid": pid}) return result } // If we can use netns_getifaddrs() but it failed and the setns() + // netns_getifaddrs() succeeded we should just always fallback to the // setns() + netns_getifaddrs() style retrieval. d.state.OS.NetnsGetifaddrs = false nw := map[string]api.InstanceStateNetwork{} err = json.Unmarshal([]byte(out), &nw) if err != nil { d.logger.Error("Failure to read forknet json", logger.Ctx{"err": err}) return result } result = nw } // Get host_name from volatile data if not set already. for name, dev := range result { if dev.HostName == "" { dev.HostName = d.localConfig[fmt.Sprintf("volatile.%s.host_name", name)] result[name] = dev } } return result } func (d *lxc) processesState() int64 { // Return 0 if not running pid := d.InitPID() if pid == -1 { return 0 } cg, err := d.cgroup(nil) if err != nil { return 0 } if d.state.OS.CGInfo.Supports(cgroup.Pids, cg) { value, err := cg.GetProcessesUsage() if err != nil { return -1 } return value } pids := []int64{int64(pid)} // Go through the pid list, adding new pids at the end so we go through them all for i := 0; i < len(pids); i++ { fname := fmt.Sprintf("/proc/%d/task/%d/children", pids[i], pids[i]) fcont, err := ioutil.ReadFile(fname) if err != nil { // the process terminated during execution of this loop continue } content := strings.Split(string(fcont), " ") for j := 0; j < len(content); j++ { pid, err := strconv.ParseInt(content[j], 10, 64) if err == nil { pids = append(pids, pid) } } } return int64(len(pids)) } // getStorageType returns the storage type of the instance's storage pool. func (d *lxc) getStorageType() (string, error) { pool, err := d.getStoragePool() if err != nil { return "", err } return pool.Driver().Info().Name, nil } // mount the instance's rootfs volume if needed. func (d *lxc) mount() (*storagePools.MountInfo, error) { pool, err := d.getStoragePool() if err != nil { return nil, err } if d.IsSnapshot() { mountInfo, err := pool.MountInstanceSnapshot(d, nil) if err != nil { return nil, err } return mountInfo, nil } mountInfo, err := pool.MountInstance(d, nil) if err != nil { return nil, err } return mountInfo, nil } // unmount the instance's rootfs volume if needed. func (d *lxc) unmount() error { pool, err := d.getStoragePool() if err != nil { return err } if d.IsSnapshot() { err = pool.UnmountInstanceSnapshot(d, nil) if err != nil { return err } return nil } // Workaround for liblxc failures on startup when shiftfs is used. diskIdmap, err := d.DiskIdmap() if err != nil { return err } if d.IdmappedStorage(d.RootfsPath()) == idmap.IdmapStorageShiftfs && !d.IsPrivileged() && diskIdmap == nil { _ = unix.Unmount(d.RootfsPath(), unix.MNT_DETACH) } err = pool.UnmountInstance(d, nil) if err != nil { return err } return nil } // insertMountLXD inserts a mount into a LXD container. // This function is used for the seccomp notifier and so cannot call any // functions that would cause LXC to talk to the container's monitor. Otherwise // we'll have a deadlock (with a timeout but still). The InitPID() call here is // the exception since the seccomp notifier will make sure to always pass a // valid PID. func (d *lxc) insertMountLXD(source, target, fstype string, flags int, mntnsPID int, idmapType idmap.IdmapStorageType) error { pid := mntnsPID if pid <= 0 { // Get the init PID pid = d.InitPID() if pid == -1 { // Container isn't running return fmt.Errorf("Can't insert mount into stopped container") } } // Create the temporary mount target var tmpMount string var err error if shared.IsDir(source) { tmpMount, err = ioutil.TempDir(d.ShmountsPath(), "lxdmount_") if err != nil { return fmt.Errorf("Failed to create shmounts path: %s", err) } } else { f, err := ioutil.TempFile(d.ShmountsPath(), "lxdmount_") if err != nil { return fmt.Errorf("Failed to create shmounts path: %s", err) } tmpMount = f.Name() _ = f.Close() } defer func() { _ = os.Remove(tmpMount) }() // Mount the filesystem err = unix.Mount(source, tmpMount, fstype, uintptr(flags), "") if err != nil { return fmt.Errorf("Failed to setup temporary mount: %s", err) } defer func() { _ = unix.Unmount(tmpMount, unix.MNT_DETACH) }() // Ensure that only flags modifying mount _properties_ make it through. // Strip things such as MS_BIND which would cause the creation of a // shiftfs mount to be skipped. // (Fyi, this is just one of the reasons why multiplexers are bad; // specifically when they do heinous things such as confusing flags // with commands.) // This is why multiplexers are bad shiftfsFlags := (flags & (unix.MS_RDONLY | unix.MS_NOSUID | unix.MS_NODEV | unix.MS_NOEXEC | unix.MS_DIRSYNC | unix.MS_NOATIME | unix.MS_NODIRATIME)) // Setup host side shiftfs as needed switch idmapType { case idmap.IdmapStorageShiftfs: err = unix.Mount(tmpMount, tmpMount, "shiftfs", uintptr(shiftfsFlags), "mark,passthrough=3") if err != nil { return fmt.Errorf("Failed to setup host side shiftfs mount: %s", err) } defer func() { _ = unix.Unmount(tmpMount, unix.MNT_DETACH) }() case idmap.IdmapStorageIdmapped: case idmap.IdmapStorageNone: default: return fmt.Errorf("Invalid idmap value specified") } // Move the mount inside the container mntsrc := filepath.Join("/dev/.lxd-mounts", filepath.Base(tmpMount)) pidStr := fmt.Sprintf("%d", pid) pidFdNr, pidFd := seccomp.MakePidFd(pid, d.state) if pidFdNr >= 0 { defer func() { _ = pidFd.Close() }() } if !strings.HasPrefix(target, "/") { target = "/" + target } _, err = shared.RunCommandInheritFds( context.TODO(), []*os.File{pidFd}, d.state.OS.ExecPath, "forkmount", "lxd-mount", "--", pidStr, fmt.Sprintf("%d", pidFdNr), mntsrc, target, string(idmapType), fmt.Sprintf("%d", shiftfsFlags)) if err != nil { return err } return nil } func (d *lxc) insertMountLXC(source, target, fstype string, flags int) error { cname := project.Instance(d.Project(), d.Name()) configPath := filepath.Join(d.LogPath(), "lxc.conf") if fstype == "" { fstype = "none" } if !strings.HasPrefix(target, "/") { target = "/" + target } _, err := shared.RunCommand( d.state.OS.ExecPath, "forkmount", "lxc-mount", "--", cname, d.state.OS.LxcPath, configPath, source, target, fstype, fmt.Sprintf("%d", flags)) if err != nil { return err } return nil } func (d *lxc) insertMount(source, target, fstype string, flags int, idmapType idmap.IdmapStorageType) error { if d.state.OS.LXCFeatures["mount_injection_file"] && idmapType == idmap.IdmapStorageNone { return d.insertMountLXC(source, target, fstype, flags) } return d.insertMountLXD(source, target, fstype, flags, -1, idmapType) } func (d *lxc) removeMount(mount string) error { // Get the init PID pid := d.InitPID() if pid == -1 { // Container isn't running return fmt.Errorf("Can't remove mount from stopped container") } if d.state.OS.LXCFeatures["mount_injection_file"] { configPath := filepath.Join(d.LogPath(), "lxc.conf") cname := project.Instance(d.Project(), d.Name()) if !strings.HasPrefix(mount, "/") { mount = "/" + mount } _, err := shared.RunCommand( d.state.OS.ExecPath, "forkmount", "lxc-umount", "--", cname, d.state.OS.LxcPath, configPath, mount) if err != nil { return err } } else { // Remove the mount from the container pidFdNr, pidFd := d.inheritInitPidFd() if pidFdNr >= 0 { defer func() { _ = pidFd.Close() }() } _, err := shared.RunCommandInheritFds( context.TODO(), []*os.File{pidFd}, d.state.OS.ExecPath, "forkmount", "lxd-umount", "--", fmt.Sprintf("%d", pid), fmt.Sprintf("%d", pidFdNr), mount) if err != nil { return err } } return nil } // InsertSeccompUnixDevice inserts a seccomp device. func (d *lxc) InsertSeccompUnixDevice(prefix string, m deviceConfig.Device, pid int) error { if pid < 0 { return fmt.Errorf("Invalid request PID specified") } rootLink := fmt.Sprintf("/proc/%d/root", pid) rootPath, err := os.Readlink(rootLink) if err != nil { return err } uid, gid, _, _, err := seccomp.TaskIDs(pid) if err != nil { return err } idmapset, err := d.CurrentIdmap() if err != nil { return err } nsuid, nsgid := idmapset.ShiftFromNs(uid, gid) m["uid"] = fmt.Sprintf("%d", nsuid) m["gid"] = fmt.Sprintf("%d", nsgid) if !path.IsAbs(m["path"]) { cwdLink := fmt.Sprintf("/proc/%d/cwd", pid) prefixPath, err := os.Readlink(cwdLink) if err != nil { return err } prefixPath = strings.TrimPrefix(prefixPath, rootPath) m["path"] = filepath.Join(rootPath, prefixPath, m["path"]) } else { m["path"] = filepath.Join(rootPath, m["path"]) } idmapSet, err := d.CurrentIdmap() if err != nil { return err } dev, err := device.UnixDeviceCreate(d.state, idmapSet, d.DevicesPath(), prefix, m, true) if err != nil { return fmt.Errorf("Failed to setup device: %s", err) } devPath := dev.HostPath tgtPath := dev.RelativePath // Bind-mount it into the container defer func() { _ = os.Remove(devPath) }() return d.insertMountLXD(devPath, tgtPath, "none", unix.MS_BIND, pid, idmap.IdmapStorageNone) } func (d *lxc) removeUnixDevices() error { // Check that we indeed have devices to remove if !shared.PathExists(d.DevicesPath()) { return nil } // Load the directory listing dents, err := ioutil.ReadDir(d.DevicesPath()) if err != nil { return err } // Go through all the unix devices for _, f := range dents { // Skip non-Unix devices if !strings.HasPrefix(f.Name(), "forkmknod.unix.") && !strings.HasPrefix(f.Name(), "unix.") && !strings.HasPrefix(f.Name(), "infiniband.unix.") { continue } // Remove the entry devicePath := filepath.Join(d.DevicesPath(), f.Name()) err := os.Remove(devicePath) if err != nil { d.logger.Error("Failed removing unix device", logger.Ctx{"err": err, "path": devicePath}) } } return nil } // FillNetworkDevice takes a nic or infiniband device type and enriches it with automatically // generated name and hwaddr properties if these are missing from the device. func (d *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfig.Device, error) { var err error newDevice := m.Clone() // Function to try and guess an available name nextInterfaceName := func() (string, error) { devNames := []string{} // Include all static interface names for _, dev := range d.expandedDevices.Sorted() { if dev.Config["name"] != "" && !shared.StringInSlice(dev.Config["name"], devNames) { devNames = append(devNames, dev.Config["name"]) } } // Include all currently allocated interface names for k, v := range d.expandedConfig { if !strings.HasPrefix(k, shared.ConfigVolatilePrefix) { continue } fields := strings.SplitN(k, ".", 3) if len(fields) != 3 { continue } if fields[2] != "name" || shared.StringInSlice(v, devNames) { continue } devNames = append(devNames, v) } // Attempt to include all existing interfaces cname := project.Instance(d.Project(), d.Name()) cc, err := liblxc.NewContainer(cname, d.state.OS.LxcPath) if err == nil { defer func() { _ = cc.Release() }() interfaces, err := cc.Interfaces() if err == nil { for _, name := range interfaces { if shared.StringInSlice(name, devNames) { continue } devNames = append(devNames, name) } } } i := 0 name := "" for { if m["type"] == "infiniband" { name = fmt.Sprintf("ib%d", i) } else { name = fmt.Sprintf("eth%d", i) } // Find a free device name if !shared.StringInSlice(name, devNames) { return name, nil } i++ } } nicType, err := nictype.NICType(d.state, d.Project(), m) if err != nil { return nil, err } // Fill in the MAC address. if !shared.StringInSlice(nicType, []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" { configKey := fmt.Sprintf("volatile.%s.hwaddr", name) volatileHwaddr := d.localConfig[configKey] if volatileHwaddr == "" { // Generate a new MAC address. volatileHwaddr, err = instance.DeviceNextInterfaceHWAddr() if err != nil || volatileHwaddr == "" { return nil, fmt.Errorf("Failed generating %q: %w", configKey, err) } // Update the database and update volatileHwaddr with stored value. volatileHwaddr, err = d.insertConfigkey(configKey, volatileHwaddr) if err != nil { return nil, fmt.Errorf("Failed storing generated config key %q: %w", configKey, err) } // Set stored value into current instance config. d.localConfig[configKey] = volatileHwaddr d.expandedConfig[configKey] = volatileHwaddr } if volatileHwaddr == "" { return nil, fmt.Errorf("Failed getting %q", configKey) } newDevice["hwaddr"] = volatileHwaddr } // Fill in the interface name. if m["name"] == "" { configKey := fmt.Sprintf("volatile.%s.name", name) volatileName := d.localConfig[configKey] if volatileName == "" { // Generate a new interface name. volatileName, err = nextInterfaceName() if err != nil || volatileName == "" { return nil, fmt.Errorf("Failed generating %q: %w", configKey, err) } // Update the database and update volatileName with stored value. volatileName, err = d.insertConfigkey(configKey, volatileName) if err != nil { return nil, fmt.Errorf("Failed storing generated config key %q: %w", configKey, err) } // Set stored value into current instance config. d.localConfig[configKey] = volatileName d.expandedConfig[configKey] = volatileName } if volatileName == "" { return nil, fmt.Errorf("Failed getting %q", configKey) } newDevice["name"] = volatileName } return newDevice, nil } func (d *lxc) removeDiskDevices() error { // Check that we indeed have devices to remove if !shared.PathExists(d.DevicesPath()) { return nil } // Load the directory listing dents, err := ioutil.ReadDir(d.DevicesPath()) if err != nil { return err } // Go through all the unix devices for _, f := range dents { // Skip non-disk devices if !strings.HasPrefix(f.Name(), "disk.") { continue } // Always try to unmount the host side _ = unix.Unmount(filepath.Join(d.DevicesPath(), f.Name()), unix.MNT_DETACH) // Remove the entry diskPath := filepath.Join(d.DevicesPath(), f.Name()) err := os.Remove(diskPath) if err != nil { d.logger.Error("Failed to remove disk device path", logger.Ctx{"err": err, "path": diskPath}) } } return nil } // Network I/O limits. func (d *lxc) setNetworkPriority() error { // Load the go-lxc struct. err := d.initLXC(false) if err != nil { return err } // Load the cgroup struct. cg, err := d.cgroup(nil) if err != nil { return err } // Check that the container is running if !d.IsRunning() { return fmt.Errorf("Can't set network priority on stopped container") } // Don't bother if the cgroup controller doesn't exist if !d.state.OS.CGInfo.Supports(cgroup.NetPrio, cg) { return nil } // Extract the current priority networkPriority := d.expandedConfig["limits.network.priority"] if networkPriority == "" { networkPriority = "0" } networkInt, err := strconv.Atoi(networkPriority) if err != nil { return err } // Get all the interfaces netifs, err := net.Interfaces() if err != nil { return err } // Check that we at least succeeded to set an entry success := false var lastError error for _, netif := range netifs { err = cg.SetNetIfPrio(fmt.Sprintf("%s %d", netif.Name, networkInt)) if err == nil { success = true } else { lastError = err } } if !success { return fmt.Errorf("Failed to set network device priority: %s", lastError) } return nil } // IsFrozen returns if instance is frozen. func (d *lxc) IsFrozen() bool { return d.statusCode() == api.Frozen } // IsNesting returns if instance is nested. func (d *lxc) IsNesting() bool { return shared.IsTrue(d.expandedConfig["security.nesting"]) } func (d *lxc) isCurrentlyPrivileged() bool { if !d.IsRunning() { return d.IsPrivileged() } idmap, err := d.CurrentIdmap() if err != nil { return d.IsPrivileged() } return idmap == nil } // IsPrivileged returns if instance is privileged. func (d *lxc) IsPrivileged() bool { return shared.IsTrue(d.expandedConfig["security.privileged"]) } // IsRunning returns if instance is running. func (d *lxc) IsRunning() bool { return d.isRunningStatusCode(d.statusCode()) } // CanMigrate returns whether the instance can be migrated. func (d *lxc) CanMigrate() (bool, bool) { return d.canMigrate(d) } // LockExclusive attempts to get exlusive access to the instance's root volume. func (d *lxc) LockExclusive() (*operationlock.InstanceOperation, error) { if d.IsRunning() { return nil, fmt.Errorf("Instance is running") } revert := revert.New() defer revert.Fail() // Prevent concurrent operations the instance. op, err := operationlock.Create(d.Project(), d.Name(), operationlock.ActionCreate, false, false) if err != nil { return nil, err } revert.Add(func() { op.Done(err) }) // Stop forkfile as otherwise it will hold the root volume open preventing unmount. d.stopForkfile() revert.Success() return op, err } // InitPID returns PID of init process. func (d *lxc) InitPID() int { // Load the go-lxc struct err := d.initLXC(false) if err != nil { return -1 } return d.c.InitPid() } // InitPidFd returns pidfd of init process. func (d *lxc) InitPidFd() (*os.File, error) { // Load the go-lxc struct err := d.initLXC(false) if err != nil { return nil, err } return d.c.InitPidFd() } // DevptsFd returns dirfd of devpts mount. func (d *lxc) DevptsFd() (*os.File, error) { // Load the go-lxc struct err := d.initLXC(false) if err != nil { return nil, err } defer d.release() if !liblxc.HasApiExtension("devpts_fd") { return nil, fmt.Errorf("Missing devpts_fd extension") } return d.c.DevptsFd() } // CurrentIdmap returns current IDMAP. func (d *lxc) CurrentIdmap() (*idmap.IdmapSet, error) { jsonIdmap, ok := d.LocalConfig()["volatile.idmap.current"] if !ok { return d.DiskIdmap() } return idmap.JSONUnmarshal(jsonIdmap) } // DiskIdmap returns DISK IDMAP. func (d *lxc) DiskIdmap() (*idmap.IdmapSet, error) { jsonIdmap, ok := d.LocalConfig()["volatile.last_state.idmap"] if !ok { return nil, nil } return idmap.JSONUnmarshal(jsonIdmap) } // NextIdmap returns next IDMAP. func (d *lxc) NextIdmap() (*idmap.IdmapSet, error) { jsonIdmap, ok := d.LocalConfig()["volatile.idmap.next"] if !ok { return d.CurrentIdmap() } return idmap.JSONUnmarshal(jsonIdmap) } // statusCode returns instance status code. func (d *lxc) statusCode() api.StatusCode { state, err := d.getLxcState() if err != nil { return api.Error } statusCode := lxcStatusCode(state) if statusCode == api.Running && shared.IsTrue(d.LocalConfig()["volatile.last_state.ready"]) { return api.Ready } return statusCode } // State returns instance state. func (d *lxc) State() string { return strings.ToUpper(d.statusCode().String()) } // LogFilePath log file path. func (d *lxc) LogFilePath() string { return filepath.Join(d.LogPath(), "lxc.log") } func (d *lxc) CGroup() (*cgroup.CGroup, error) { // Load the go-lxc struct err := d.initLXC(false) if err != nil { return nil, err } return d.cgroup(nil) } func (d *lxc) cgroup(cc *liblxc.Container) (*cgroup.CGroup, error) { rw := lxcCgroupReadWriter{} if cc != nil { rw.cc = cc rw.conf = true } else { rw.cc = d.c } cg, err := cgroup.New(&rw) if err != nil { return nil, err } cg.UnifiedCapable = liblxc.HasApiExtension("cgroup2") return cg, nil } type lxcCgroupReadWriter struct { cc *liblxc.Container conf bool } func (rw *lxcCgroupReadWriter) Get(version cgroup.Backend, controller string, key string) (string, error) { if rw.conf { lxcKey := fmt.Sprintf("lxc.cgroup.%s", key) if version == cgroup.V2 { lxcKey = fmt.Sprintf("lxc.cgroup2.%s", key) } return strings.Join(rw.cc.ConfigItem(lxcKey), "\n"), nil } return strings.Join(rw.cc.CgroupItem(key), "\n"), nil } func (rw *lxcCgroupReadWriter) Set(version cgroup.Backend, controller string, key string, value string) error { if rw.conf { if version == cgroup.V1 { return lxcSetConfigItem(rw.cc, fmt.Sprintf("lxc.cgroup.%s", key), value) } return lxcSetConfigItem(rw.cc, fmt.Sprintf("lxc.cgroup2.%s", key), value) } return rw.cc.SetCgroupItem(key, value) } // UpdateBackupFile writes the instance's backup.yaml file to storage. func (d *lxc) UpdateBackupFile() error { pool, err := d.getStoragePool() if err != nil { return err } return pool.UpdateInstanceBackupFile(d, nil) } // SaveConfigFile generates the LXC config file on disk. func (d *lxc) SaveConfigFile() error { err := d.initLXC(true) if err != nil { return fmt.Errorf("Failed to generate LXC config: %w", err) } // Generate the LXC config. configPath := filepath.Join(d.LogPath(), "lxc.conf") err = d.c.SaveConfigFile(configPath) if err != nil { _ = os.Remove(configPath) return fmt.Errorf("Failed to save LXC config to file %q: %w", configPath, err) } return nil } // Info returns "lxc" and the currently loaded version of LXC. func (d *lxc) Info() instance.Info { return instance.Info{ Name: "lxc", Version: liblxc.Version(), Type: instancetype.Container, Error: nil, } } func (d *lxc) Metrics() (*metrics.MetricSet, error) { out := metrics.NewMetricSet(map[string]string{"project": d.project, "name": d.name, "type": instancetype.Container.String()}) // Load cgroup abstraction cg, err := d.cgroup(nil) if err != nil { return nil, err } // Get Memory limit. memoryLimit, err := cg.GetEffectiveMemoryLimit() if err != nil { d.logger.Warn("Failed getting effective memory limit", logger.Ctx{"err": err}) } memoryCached := int64(0) // Get memory stats. memStats, err := cg.GetMemoryStats() if err != nil { d.logger.Warn("Failed to get memory stats", logger.Ctx{"err": err}) } else { for k, v := range memStats { var metricType metrics.MetricType switch k { case "active_anon": metricType = metrics.MemoryActiveAnonBytes case "active_file": metricType = metrics.MemoryActiveFileBytes case "active": metricType = metrics.MemoryActiveBytes case "inactive_anon": metricType = metrics.MemoryInactiveAnonBytes case "inactive_file": metricType = metrics.MemoryInactiveFileBytes case "inactive": metricType = metrics.MemoryInactiveBytes case "unevictable": metricType = metrics.MemoryUnevictableBytes case "writeback": metricType = metrics.MemoryWritebackBytes case "dirty": metricType = metrics.MemoryDirtyBytes case "mapped": metricType = metrics.MemoryMappedBytes case "rss": metricType = metrics.MemoryRSSBytes case "shmem": metricType = metrics.MemoryShmemBytes case "cache": metricType = metrics.MemoryCachedBytes memoryCached = int64(v) } out.AddSamples(metricType, metrics.Sample{Value: float64(v)}) } } // Get memory usage. memoryUsage, err := cg.GetMemoryUsage() if err != nil { d.logger.Warn("Failed to get memory usage", logger.Ctx{"err": err}) } if memoryLimit > 0 { out.AddSamples(metrics.MemoryMemTotalBytes, metrics.Sample{Value: float64(memoryLimit)}) out.AddSamples(metrics.MemoryMemAvailableBytes, metrics.Sample{Value: float64(memoryLimit - memoryUsage + memoryCached)}) out.AddSamples(metrics.MemoryMemFreeBytes, metrics.Sample{Value: float64(memoryLimit - memoryUsage)}) } // Get oom kills. oomKills, err := cg.GetOOMKills() if err != nil { d.logger.Warn("Failed to get oom kills", logger.Ctx{"err": err}) } out.AddSamples(metrics.MemoryOOMKillsTotal, metrics.Sample{Value: float64(oomKills)}) // Handle swap. if d.state.OS.CGInfo.Supports(cgroup.MemorySwapUsage, cg) { swapUsage, err := cg.GetMemorySwapUsage() if err != nil { d.logger.Warn("Failed to get swap usage", logger.Ctx{"err": err}) } else { out.AddSamples(metrics.MemorySwapBytes, metrics.Sample{Value: float64(swapUsage)}) } } // Get CPU stats usage, err := cg.GetCPUAcctUsageAll() if err != nil { d.logger.Warn("Failed to get CPU usage", logger.Ctx{"err": err}) } else { for cpu, stats := range usage { cpuID := strconv.Itoa(int(cpu)) out.AddSamples(metrics.CPUSecondsTotal, metrics.Sample{Value: float64(stats.System) / 1000000000, Labels: map[string]string{"mode": "system", "cpu": cpuID}}) out.AddSamples(metrics.CPUSecondsTotal, metrics.Sample{Value: float64(stats.User) / 1000000000, Labels: map[string]string{"mode": "user", "cpu": cpuID}}) } } // Get CPUs. CPUs, err := cg.GetEffectiveCPUs() if err != nil { d.logger.Warn("Failed to get CPUs", logger.Ctx{"err": err}) } else { out.AddSamples(metrics.CPUs, metrics.Sample{Value: float64(CPUs)}) } // Get disk stats diskStats, err := cg.GetIOStats() if err != nil { d.logger.Warn("Failed to get disk stats", logger.Ctx{"err": err}) } else { for disk, stats := range diskStats { labels := map[string]string{"device": disk} out.AddSamples(metrics.DiskReadBytesTotal, metrics.Sample{Value: float64(stats.ReadBytes), Labels: labels}) out.AddSamples(metrics.DiskReadsCompletedTotal, metrics.Sample{Value: float64(stats.ReadsCompleted), Labels: labels}) out.AddSamples(metrics.DiskWrittenBytesTotal, metrics.Sample{Value: float64(stats.WrittenBytes), Labels: labels}) out.AddSamples(metrics.DiskWritesCompletedTotal, metrics.Sample{Value: float64(stats.WritesCompleted), Labels: labels}) } } // Get filesystem stats fsStats, err := d.getFSStats() if err != nil { d.logger.Warn("Failed to get fs stats", logger.Ctx{"err": err}) } else { out.Merge(fsStats) } // Get network stats networkState := d.networkState() for name, state := range networkState { labels := map[string]string{"device": name} out.AddSamples(metrics.NetworkReceiveBytesTotal, metrics.Sample{Value: float64(state.Counters.BytesReceived), Labels: labels}) out.AddSamples(metrics.NetworkReceivePacketsTotal, metrics.Sample{Value: float64(state.Counters.PacketsReceived), Labels: labels}) out.AddSamples(metrics.NetworkTransmitBytesTotal, metrics.Sample{Value: float64(state.Counters.BytesSent), Labels: labels}) out.AddSamples(metrics.NetworkTransmitPacketsTotal, metrics.Sample{Value: float64(state.Counters.PacketsSent), Labels: labels}) out.AddSamples(metrics.NetworkReceiveErrsTotal, metrics.Sample{Value: float64(state.Counters.ErrorsReceived), Labels: labels}) out.AddSamples(metrics.NetworkTransmitErrsTotal, metrics.Sample{Value: float64(state.Counters.ErrorsSent), Labels: labels}) out.AddSamples(metrics.NetworkReceiveDropTotal, metrics.Sample{Value: float64(state.Counters.PacketsDroppedInbound), Labels: labels}) out.AddSamples(metrics.NetworkTransmitDropTotal, metrics.Sample{Value: float64(state.Counters.PacketsDroppedOutbound), Labels: labels}) } // Get number of processes pids, err := cg.GetTotalProcesses() if err != nil { d.logger.Warn("Failed to get total number of processes", logger.Ctx{"err": err}) } else { out.AddSamples(metrics.ProcsTotal, metrics.Sample{Value: float64(pids)}) } return out, nil } func (d *lxc) getFSStats() (*metrics.MetricSet, error) { type mountInfo struct { Mountpoint string FSType string } out := metrics.NewMetricSet(map[string]string{"project": d.project, "name": d.name}) mounts, err := ioutil.ReadFile("/proc/mounts") if err != nil { return nil, fmt.Errorf("Failed to read /proc/mounts: %w", err) } mountMap := make(map[string]mountInfo) scanner := bufio.NewScanner(bytes.NewReader(mounts)) for scanner.Scan() { fields := strings.Fields(scanner.Text()) mountMap[fields[0]] = mountInfo{Mountpoint: fields[1], FSType: fields[2]} } // Get disk devices for _, dev := range d.expandedDevices { if dev["type"] != "disk" || dev["path"] == "" { continue } var statfs *unix.Statfs_t labels := make(map[string]string) realDev := "" if dev["pool"] != "" { // Expected volume name. var volName string var volType storageDrivers.VolumeType if dev["source"] != "" { volName = project.StorageVolume(d.project, dev["source"]) volType = storageDrivers.VolumeTypeCustom } else { volName = project.Instance(d.project, d.name) volType = storageDrivers.VolumeTypeContainer } // Check that we have a mountpoint. mountpoint := storageDrivers.GetVolumeMountPath(dev["pool"], volType, volName) if mountpoint == "" || !shared.PathExists(mountpoint) { continue } // Grab the filesystem information. statfs, err = filesystem.StatVFS(mountpoint) if err != nil { return nil, fmt.Errorf("Failed to stat %s: %w", mountpoint, err) } isMounted := false // Check if mountPath is in mountMap for mountDev, mountInfo := range mountMap { if mountInfo.Mountpoint != mountpoint { continue } isMounted = true realDev = mountDev break } if !isMounted { realDev = dev["source"] } } else { source := shared.HostPath(dev["source"]) statfs, err = filesystem.StatVFS(source) if err != nil { return nil, fmt.Errorf("Failed to stat %s: %w", dev["source"], err) } isMounted := false // Check if mountPath is in mountMap for mountDev, mountInfo := range mountMap { if mountInfo.Mountpoint != source { continue } isMounted = true stat := unix.Stat_t{} // Check if dev has a backing file err = unix.Stat(source, &stat) if err != nil { return nil, fmt.Errorf("Failed to stat %s: %w", dev["source"], err) } backingFilePath := fmt.Sprintf("/sys/dev/block/%d:%d/loop/backing_file", unix.Major(stat.Dev), unix.Minor(stat.Dev)) if shared.PathExists(backingFilePath) { // Read backing file backingFile, err := ioutil.ReadFile(backingFilePath) if err != nil { return nil, fmt.Errorf("Failed to read %s: %w", backingFilePath, err) } realDev = string(backingFile) } else { // Use dev as device realDev = mountDev } break } if !isMounted { realDev = dev["source"] } } // Add labels labels["device"] = realDev labels["mountpoint"] = dev["path"] fsType, err := filesystem.FSTypeToName(int32(statfs.Type)) if err == nil { labels["fstype"] = fsType } // Add sample statfsBsize := uint64(statfs.Bsize) out.AddSamples(metrics.FilesystemSizeBytes, metrics.Sample{Value: float64(statfs.Blocks * statfsBsize), Labels: labels}) out.AddSamples(metrics.FilesystemAvailBytes, metrics.Sample{Value: float64(statfs.Bavail * statfsBsize), Labels: labels}) out.AddSamples(metrics.FilesystemFreeBytes, metrics.Sample{Value: float64(statfs.Bfree * statfsBsize), Labels: labels}) } return out, nil } func (d *lxc) loadRawLXCConfig() error { // Load the LXC raw config. lxcConfig, ok := d.expandedConfig["raw.lxc"] if !ok { return nil } // Write to temp config file. f, err := ioutil.TempFile("", "lxd_config_") if err != nil { return err } err = shared.WriteAll(f, []byte(lxcConfig)) if err != nil { return err } err = f.Close() if err != nil { return err } // Load the config. err = d.c.LoadConfigFile(f.Name()) if err != nil { return fmt.Errorf("Failed to load config file %q: %w", f.Name(), err) } _ = os.Remove(f.Name()) return nil } // forfileRunningLockName returns the forkfile-running_ID lock name. func (d *common) forkfileRunningLockName() string { return fmt.Sprintf("forkfile-running_%d", d.id) }
{ "content_hash": "6db76c70ef2ef18e2baac2c956963b39", "timestamp": "", "source": "github", "line_count": 7161, "max_line_length": 306, "avg_line_length": 26.02262253875157, "alnum_prop": 0.6618101616330736, "repo_name": "hallyn/lxd", "id": "af15acd358e509977ae4a5d341d5295fbe45f047", "size": "186348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lxd/instance/drivers/driver_lxc.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "221263" }, { "name": "CSS", "bytes": "3967" }, { "name": "Emacs Lisp", "bytes": "256" }, { "name": "Go", "bytes": "7958558" }, { "name": "HTML", "bytes": "7188" }, { "name": "JavaScript", "bytes": "3991" }, { "name": "Makefile", "bytes": "8445" }, { "name": "Python", "bytes": "20482" }, { "name": "Shell", "bytes": "740380" } ], "symlink_target": "" }
/** * @func !reloadfortunes * * @desc Reloads fortune images from the fortunes Imgur album */ const chalk = require('chalk'); const fs = require('fs'); const i2rss = require('imgur2rss'); const moment = require('moment'); const conf = JSON.parse(fs.readFileSync('./settings.json', 'utf8')); exports.help = { name: 'reloadfortunes', description: `Reload fortune images from Imgur album (currently, there are ${conf.fortune.amount} fortunes)`, usage: 'reloadfortunes', }; exports.conf = { enabled: true, visible: true, guildOnly: false, textChannelOnly: true, aliases: ['rf'], permLevel: 4, }; /* eslint-disable */ const getImgs = (str, node, attr) => { const regex = new RegExp(`<${node} ${attr}="(.*?)" alt="`, 'gi'); const res = []; let result; while ((result = regex.exec(str)) !== null) { res.push(result[1]); } return res; }; exports.run = (bot, message) => { let images; const obj = { fortunes: [] }; const settings = JSON.parse(fs.readFileSync('./settings.json', 'utf8')); const clientID = settings.fortune.token; message.channel.send('Reloading fortunes...').then((m) => { i2rss.album2rss(clientID, conf.fortune.album, (err, data) => { /** * @todo Research what errors can be thrown by i2rss? */ if (err) return m.edit(`Fortunes reload failed:\n\`\`\`${err}\`\`\``).then().catch(console.error()); images = getImgs(data, 'img', 'src'); images.forEach((img) => { obj.fortunes.push(img); }); // Update fortune amount in config file, and for the commands help menu if (images.length !== settings.fortune.amount) { settings.fortune.amount = images.length; fs.writeFile('./settings.json', JSON.stringify(settings), (fsErr) => { if (fsErr) throw fsErr; bot.reloadCommands(bot, 'fortune') .then(console.log(chalk.bgHex('#ffcc52').black(`[${moment().format(settings.timeFormat)}] Fortunes reloaded & settings.json updated with new fortune amount!`))) .catch(console.error()); }); } // URLs are thrown into fortunes.json file & saved fs.writeFile('./config/fortunes.json', JSON.stringify(obj), 'utf8', (fsErr) => { if (fsErr) throw fsErr; m.edit('Successfully reloaded the fortunes gallery!') .then(m.delete(1500) .then(() => { message.delete(1500); console.log(chalk.bgHex('#ffcc52').black(`[${moment().format(settings.timeFormat)}] Fortunes reloaded!`)); }).catch(console.error())) .catch(console.error()); }); }); }).catch(err => console.log(chalk.bgRed(`[${moment().format(settings.timeFormat)}] ${err}\n${err.stack}`))); };
{ "content_hash": "7a261162e568f196c28db099647aa2be", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 172, "avg_line_length": 33.40243902439025, "alnum_prop": 0.6035049288061336, "repo_name": "malouro/ggis-bot", "id": "296676dee456a8782333b88be52683146b96b592", "size": "2739", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "commands/Debug & Support/reloadfortunes.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "228714" } ], "symlink_target": "" }
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'sugarcrb' require 'minitest/autorun' require "minitest/reporters" require 'webmock/minitest' Minitest::Reporters.use!
{ "content_hash": "176ad5d3cead76bc5e2f80e43d2aa138", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 58, "avg_line_length": 23.5, "alnum_prop": 0.7393617021276596, "repo_name": "betobaz/sugarcrb", "id": "4da9be0ac9a819547de84e6aa6b60be9fc67ae92", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "12784" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
<input autocomplete="off" id="{{id}}_1" name="{{name}}_1" type="text" />
{ "content_hash": "5818f2bbcba704e3b8e03e50e86e707e", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 72, "avg_line_length": 72, "alnum_prop": 0.5833333333333334, "repo_name": "tnemis/staging-server", "id": "783e93d0a8e6601e60f631b1d235a475e1f53016", "size": "72", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "schoolnew/django-simple-captcha-master/captcha/templates/captcha/text_field.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "805986" }, { "name": "HTML", "bytes": "3648861" }, { "name": "JavaScript", "bytes": "3804321" }, { "name": "Makefile", "bytes": "3152" }, { "name": "PHP", "bytes": "5016" }, { "name": "Python", "bytes": "2084471" }, { "name": "Shell", "bytes": "148" } ], "symlink_target": "" }
#include <time.h> #include <errno.h> #include <ctype.h> #include "libgraph/graphp.h" #define tab_low(tab) ((tab)->tab_data->range_low) #define tab_high(tab) ((tab)->tab_data[(tab)->tab_n - 1].range_high) #define tab_size(grm) \ (sizeof(graph_grmap_table) + \ (sizeof(graph_grmap_range) * ((grm)->grm_table_size - 1))) /* @brief Look up the table that a given local ID is inside of. * * The ID may not have a corresponding slot at all. * * If there was a match, the location is stored in *loc_out. * If there was no match, *loc_out is either the place where * the new record should inserted, or the record that should * be extended to contain the index. * * @param grm overall map * @param tab specific table we're looking in * @param i id we're looking for * @param loc_out where to look/insert if necessary * * @return true if there's a mapping, and *loc_out is its offset; * @return false if there's no mapping, and *loc_out is where it would be * (or that location's neighbor.) */ bool graph_grmap_table_lookup(graph_grmap const* grm, graph_grmap_dbid_slot const* dis, unsigned long long i, size_t* loc_out) { cl_handle* cl = grm->grm_graph->graph_cl; unsigned short hi, lo, med; graph_grmap_table_slot const* ts; graph_grmap_table const *tab, *tab_neighbor; lo = 0; hi = dis->dis_n; while (lo + 1 < hi) { graph_grmap_table_slot const* ts; med = lo + (hi - lo) / 2; cl_assert(cl, lo < med); cl_assert(cl, med < hi); ts = dis->dis_table + med; /* Too low */ if (i < ts->ts_low) { cl_cover(grm->grm_graph->graph_cl); hi = med; } /* Too high */ else if (med + 1 < dis->dis_n && i >= ts[1].ts_low) { cl_cover(grm->grm_graph->graph_cl); lo = med + 1; } else if (i >= tab_high(ts->ts_table)) { /* This is the right spot, but * we're not actually contained in it. */ cl_cover(grm->grm_graph->graph_cl); lo = med; break; } /* Just right */ else { cl_cover(grm->grm_graph->graph_cl); *loc_out = med; return true; } } /* The entry either belongs to this record, * or belongs into the gap before or after this * record. */ if ((*loc_out = lo) >= dis->dis_n) { cl_cover(grm->grm_graph->graph_cl); return false; } ts = dis->dis_table + lo; tab = ts->ts_table; if (i < ts->ts_low) { if (lo > 0) { tab_neighbor = dis->dis_table[lo - 1].ts_table; cl_cover(grm->grm_graph->graph_cl); if (i <= tab_high(tab_neighbor)) { cl_cover(grm->grm_graph->graph_cl); --*loc_out; } else { cl_cover(grm->grm_graph->graph_cl); } } } else if (i >= tab_high(tab)) { if (lo + 1 < dis->dis_n) { tab_neighbor = dis->dis_table[lo + 1].ts_table; if (i + 1 >= tab_low(tab_neighbor)) { cl_cover(grm->grm_graph->graph_cl); ++*loc_out; } else { cl_cover(grm->grm_graph->graph_cl); } } } else { cl_cover(grm->grm_graph->graph_cl); return true; } cl_cover(grm->grm_graph->graph_cl); return false; } /* @brief Return the first table that overlaps with the given range. * * @param grm overall map * @param tab specific table we're looking in * @param i id we're looking for * @param loc_out where to look/insert if necessary * * @return true while there was still overlapping data. */ bool graph_grmap_table_next_overlap(graph_grmap const* grm, graph_grmap_dbid_slot const* dis, unsigned long long* lo, unsigned long long hi, bool* found_out, unsigned long long* lo_out, unsigned long long* hi_out, size_t* loc_out) { graph_grmap_table const* tab; cl_handle* const cl = grm->grm_graph->graph_cl; *lo_out = *lo; /* Out of stuff to look for. */ if (*lo >= hi) { cl_cover(grm->grm_graph->graph_cl); return false; } if (!(*found_out = graph_grmap_table_lookup(grm, dis, *lo, loc_out)) && *loc_out >= dis->dis_n) { cl_cover(grm->grm_graph->graph_cl); *hi_out = *lo = hi; return true; } tab = dis->dis_table[*loc_out].ts_table; if (!*found_out) { /* Wasn't found. Return a non-overlap. */ if (*lo >= tab_high(tab)) { if (*loc_out + 1 >= dis->dis_n) { *hi_out = *lo = hi; cl_cover(grm->grm_graph->graph_cl); return true; } cl_cover(grm->grm_graph->graph_cl); ++tab; ++*loc_out; } else { cl_cover(grm->grm_graph->graph_cl); cl_assert(cl, *lo < tab_low(tab)); } *hi_out = *lo = (hi <= tab_low(tab) ? hi : tab_low(tab)); } else { cl_cover(grm->grm_graph->graph_cl); *hi_out = *lo = (hi <= tab_high(tab) ? hi : tab_high(tab)); } return true; } /* @brief Delete a table. * * The ID may not have a corresponding slot at all. * * If there was a match, the location is stored in *loc_out. * If there was no match, *loc_out is either the place where * the new record should inserted, or the record that should * be extended to contain the index. * * @param grm overall map * @param tab specific table we're looking in * @param i id we're looking for * @param loc_out where to look/insert if necessary * * @return GRAPH_ERR_NO if there exists no mapping, * @return 0 if there exists a mapping, and *loc_out is its offset. */ void graph_grmap_table_delete(graph_grmap* grm, graph_grmap_dbid_slot* dis, size_t i) { cl_assert(grm->grm_graph->graph_cl, dis != NULL); cl_assert(grm->grm_graph->graph_cl, i < dis->dis_n); cm_free(grm->grm_graph->graph_cm, dis->dis_table[i].ts_table); if (i < dis->dis_n) { cl_cover(grm->grm_graph->graph_cl); memmove(dis->dis_table + i, dis->dis_table + i + 1, (dis->dis_n - (i + 1)) * sizeof(*dis->dis_table)); } else { cl_cover(grm->grm_graph->graph_cl); } dis->dis_n--; } /* @brief Allocate a range table, and add it to the list at a given index. * * The ID may not have a corresponding slot at all. * * If there was a match, the location is stored in *loc_out. * If there was no match, *loc_out is either the place where * the new record should inserted, or the record that should * be extended to contain the index. * * @param grm overall map * @param tab specific table we're looking in * @param i id we're looking for * @param loc_out where to look/insert if necessary * * @return GRAPH_ERR_NO if there exists no mapping, * @return 0 if there exists a mapping, and *loc_out is its offset. */ int graph_grmap_table_insert(graph_grmap* grm, graph_grmap_dbid_slot* dis, size_t i, unsigned long long low) { graph_grmap_table_slot* ts; graph_grmap_table* tab; cl_assert(grm->grm_graph->graph_cl, dis != NULL); cl_assert(grm->grm_graph->graph_cl, i <= dis->dis_n); tab = cm_malloc(grm->grm_graph->graph_cm, tab_size(grm)); if (tab == NULL) { int err = errno ? errno : ENOMEM; cl_log_errno(grm->grm_graph->graph_cl, CL_LEVEL_FAIL, "graph_grmap_table_alloc", err, "can't allocate range table for low=%llu", low); return err; } tab->tab_n = 0; if (dis->dis_n >= dis->dis_m) { graph_grmap_table_slot* tmp; tmp = cm_realloc(grm->grm_graph->graph_cm, dis->dis_table, (dis->dis_n + 1024) * sizeof(*dis->dis_table)); if (tmp == NULL) { int err = errno ? errno : ENOMEM; free(tab); cl_log_errno(grm->grm_graph->graph_cl, CL_LEVEL_FAIL, "cm_realloc", err, "can't grow table slots to %zu for " "low=%llu", dis->dis_n + 1024, low); return err; } dis->dis_table = tmp; dis->dis_m += 1024; cl_cover(grm->grm_graph->graph_cl); } if (i < dis->dis_n) { cl_cover(grm->grm_graph->graph_cl); memmove(dis->dis_table + i + 1, dis->dis_table + i, (dis->dis_n - i) * sizeof(*dis->dis_table)); } else { cl_cover(grm->grm_graph->graph_cl); } dis->dis_n++; ts = dis->dis_table + i; ts->ts_table = tab; ts->ts_low = low; return 0; } /* @brief Split a range table. * * @param grm overall map * @param tab specific table we're looking in * @param i id we're looking for * @param loc_out where to look/insert if necessary * * @return GRAPH_ERR_NO if there exists no mapping, * @return 0 if there exists a mapping, and *loc_out is its offset. */ int graph_grmap_table_split(graph_grmap* grm, graph_grmap_dbid_slot* dis, size_t i) { graph_grmap_table *ntab, *otab; size_t split; int err; otab = dis->dis_table[i].ts_table; split = otab->tab_n / 2; err = graph_grmap_table_insert(grm, dis, i + 1, otab->tab_data[split].range_low); if (err != 0) return err; ntab = dis->dis_table[i + 1].ts_table; ntab->tab_n = otab->tab_n - split; memcpy(ntab->tab_data, otab->tab_data + (otab->tab_n = split), ntab->tab_n * sizeof(*ntab->tab_data)); cl_cover(grm->grm_graph->graph_cl); return 0; }
{ "content_hash": "266f087336a83f594a76ce54a2a36574", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 80, "avg_line_length": 29.077639751552795, "alnum_prop": 0.5677667414290292, "repo_name": "googlearchive/graphd", "id": "21890e47b52d9ddd4834caf8e86727fa4c3577b6", "size": "9938", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libgraph/graph-grmap-table.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "661" }, { "name": "C", "bytes": "6604663" }, { "name": "C++", "bytes": "98057" }, { "name": "Go", "bytes": "25573" }, { "name": "Makefile", "bytes": "3644" }, { "name": "Python", "bytes": "19838" }, { "name": "Shell", "bytes": "5195005" } ], "symlink_target": "" }
<?php namespace Heureka\ShopCertification; /** * @author Vladimír Kašpar <[email protected]> * @author Jakub Chábek <[email protected]> */ interface IRequester { const ACTION_LOG_ORDER = 'order/log'; /** * @param ApiEndpoint $endpoint */ public function setApiEndpoint(ApiEndpoint $endpoint); /** * @param string $action @see self::ACTION_* * @param array|null $getData * @param array|null $postData * * @return Response * @throws RequesterException A RequesterException must be thrown if response is invalid or has code other than 200 */ public function request($action, array $getData = [], array $postData = []); }
{ "content_hash": "1a0b74cad5e26ed482323ccf76af2401", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 119, "avg_line_length": 24.586206896551722, "alnum_prop": 0.6549789621318373, "repo_name": "heureka/overeno-zakazniky", "id": "ab1cfcf320ea6eec5cc265fcf5f3c24fe28c0b4f", "size": "716", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ShopCertification/IRequester.php", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "223" }, { "name": "PHP", "bytes": "20882" } ], "symlink_target": "" }
package org.apache.activemq.artemis.component; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.activemq.artemis.ActiveMQWebLogger; import org.apache.activemq.artemis.components.ExternalComponent; import org.apache.activemq.artemis.dto.AppDTO; import org.apache.activemq.artemis.dto.ComponentDTO; import org.apache.activemq.artemis.dto.WebServerDTO; import org.apache.activemq.artemis.utils.TimeUtils; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.webapp.WebAppContext; public class WebServerComponent implements ExternalComponent { private Server server; private HandlerList handlers; private WebServerDTO webServerConfig; private URI uri; private String jolokiaUrl; private List<WebAppContext> webContexts; @Override public void configure(ComponentDTO config, String artemisInstance, String artemisHome) throws Exception { webServerConfig = (WebServerDTO) config; uri = new URI(webServerConfig.bind); server = new Server(); String scheme = uri.getScheme(); ServerConnector connector = null; if ("https".equals(scheme)) { SslContextFactory sslFactory = new SslContextFactory(); sslFactory.setKeyStorePath(webServerConfig.keyStorePath == null ? artemisInstance + "/etc/keystore.jks" : webServerConfig.keyStorePath); sslFactory.setKeyStorePassword(webServerConfig.keyStorePassword == null ? "password" : webServerConfig.keyStorePassword); if (webServerConfig.clientAuth != null) { sslFactory.setNeedClientAuth(webServerConfig.clientAuth); if (webServerConfig.clientAuth) { sslFactory.setTrustStorePath(webServerConfig.trustStorePath); sslFactory.setTrustStorePassword(webServerConfig.trustStorePassword); } } SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslFactory, "HTTP/1.1"); HttpConfiguration https = new HttpConfiguration(); https.addCustomizer(new SecureRequestCustomizer()); HttpConnectionFactory httpFactory = new HttpConnectionFactory(https); connector = new ServerConnector(server, sslConnectionFactory, httpFactory); } else { connector = new ServerConnector(server); } connector.setPort(uri.getPort()); connector.setHost(uri.getHost()); server.setConnectors(new Connector[]{connector}); handlers = new HandlerList(); Path warDir = Paths.get(artemisHome != null ? artemisHome : ".").resolve(webServerConfig.path).toAbsolutePath(); if (webServerConfig.apps != null && webServerConfig.apps.size() > 0) { webContexts = new ArrayList<>(); for (AppDTO app : webServerConfig.apps) { WebAppContext webContext = deployWar(app.url, app.war, warDir); webContexts.add(webContext); if (app.war.startsWith("jolokia")) { jolokiaUrl = webServerConfig.bind + "/" + app.url; } } } ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setResourceBase(warDir.toString()); resourceHandler.setDirectoriesListed(true); resourceHandler.setWelcomeFiles(new String[]{"index.html"}); DefaultHandler defaultHandler = new DefaultHandler(); defaultHandler.setServeIcon(false); ContextHandler context = new ContextHandler(); context.setContextPath("/"); context.setResourceBase(warDir.toString()); context.setHandler(resourceHandler); handlers.addHandler(context); handlers.addHandler(defaultHandler); server.setHandler(handlers); } @Override public void start() throws Exception { if (isStarted()) { return; } server.start(); ActiveMQWebLogger.LOGGER.webserverStarted(webServerConfig.bind); if (jolokiaUrl != null) { ActiveMQWebLogger.LOGGER.jolokiaAvailable(jolokiaUrl); } } public void internalStop() throws Exception { server.stop(); if (webContexts != null) { File tmpdir = null; for (WebAppContext context : webContexts) { tmpdir = context.getTempDirectory(); if (tmpdir != null && !context.isPersistTempDirectory()) { //tmpdir will be removed by deleteOnExit() //somehow when broker is stopped and restarted quickly //this tmpdir won't get deleted sometimes boolean fileDeleted = TimeUtils.waitOnBoolean(false, 10000, tmpdir::exists); if (!fileDeleted) { ActiveMQWebLogger.LOGGER.tmpFileNotDeleted(tmpdir); } } } webContexts.clear(); } } @Override public boolean isStarted() { return server != null && server.isStarted(); } private WebAppContext deployWar(String url, String warFile, Path warDirectory) throws IOException { WebAppContext webapp = new WebAppContext(); if (url.startsWith("/")) { webapp.setContextPath(url); } else { webapp.setContextPath("/" + url); } webapp.setWar(warDirectory.resolve(warFile).toString()); handlers.addHandler(webapp); return webapp; } @Override public void stop() throws Exception { stop(false); } @Override public void stop(boolean isShutdown) throws Exception { if (isShutdown) { internalStop(); } } }
{ "content_hash": "97c90680fb72584f3a4b8713ea2828ad", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 145, "avg_line_length": 35.97674418604651, "alnum_prop": 0.6898836457659987, "repo_name": "willr3/activemq-artemis", "id": "c58bafb3180435d2f1cfffaf889be50ac31aa62d", "size": "6987", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "artemis-web/src/main/java/org/apache/activemq/artemis/component/WebServerComponent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "11634" }, { "name": "C", "bytes": "26484" }, { "name": "C++", "bytes": "1197" }, { "name": "CMake", "bytes": "4260" }, { "name": "CSS", "bytes": "11732" }, { "name": "HTML", "bytes": "19329" }, { "name": "Java", "bytes": "23829073" }, { "name": "Shell", "bytes": "34875" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>ActiveSupport::XmlMini</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" /> <script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.1.8</span><br /> <h1> <span class="type">Module</span> ActiveSupport::XmlMini </h1> <ul class="files"> <li><a href="../../files/__/_rvm/gems/ruby-2_2_0/gems/activesupport-4_1_8/lib/active_support/xml_mini_rb.html">/home/kristof/.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <div class="description"> <h1 id="module-ActiveSupport::XmlMini-label-XmlMini"><a href="XmlMini.html">XmlMini</a></h1> <p>To use the much faster libxml parser:</p> <pre><code>gem &#39;libxml-ruby&#39;, &#39;=0.9.7&#39; XmlMini.backend = &#39;LibXML&#39; </code></pre> </div> <!-- Method ref --> <div class="sectiontitle">Methods</div> <dl class="methods"> <dt>#</dt> <dd> <ul> <li> <a href="#method-i-_dasherize">_dasherize</a>, </li> <li> <a href="#method-i-_parse_file">_parse_file</a> </li> </ul> </dd> <dt>B</dt> <dd> <ul> <li> <a href="#method-i-backend">backend</a>, </li> <li> <a href="#method-i-backend-3D">backend=</a> </li> </ul> </dd> <dt>R</dt> <dd> <ul> <li> <a href="#method-i-rename_key">rename_key</a> </li> </ul> </dd> <dt>T</dt> <dd> <ul> <li> <a href="#method-i-to_tag">to_tag</a> </li> </ul> </dd> <dt>W</dt> <dd> <ul> <li> <a href="#method-i-with_backend">with_backend</a> </li> </ul> </dd> </dl> <!-- Section constants --> <div class="sectiontitle">Constants</div> <table border='0' cellpadding='5'> <tr valign='top'> <td class="attr-name">DEFAULT_ENCODINGS</td> <td>=</td> <td class="attr-value">{ &quot;binary&quot; =&gt; &quot;base64&quot; } unless defined?(DEFAULT_ENCODINGS)</td> </tr> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"></td> </tr> <tr valign='top'> <td class="attr-name">TYPE_NAMES</td> <td>=</td> <td class="attr-value">{ &quot;Symbol&quot; =&gt; &quot;symbol&quot;, &quot;Fixnum&quot; =&gt; &quot;integer&quot;, &quot;Bignum&quot; =&gt; &quot;integer&quot;, &quot;BigDecimal&quot; =&gt; &quot;decimal&quot;, &quot;Float&quot; =&gt; &quot;float&quot;, &quot;TrueClass&quot; =&gt; &quot;boolean&quot;, &quot;FalseClass&quot; =&gt; &quot;boolean&quot;, &quot;Date&quot; =&gt; &quot;date&quot;, &quot;DateTime&quot; =&gt; &quot;dateTime&quot;, &quot;Time&quot; =&gt; &quot;dateTime&quot;, &quot;Array&quot; =&gt; &quot;array&quot;, &quot;Hash&quot; =&gt; &quot;hash&quot; } unless defined?(TYPE_NAMES)</td> </tr> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"></td> </tr> <tr valign='top'> <td class="attr-name">FORMATTING</td> <td>=</td> <td class="attr-value">{ &quot;symbol&quot; =&gt; Proc.new { |symbol| symbol.to_s }, &quot;date&quot; =&gt; Proc.new { |date| date.to_s(:db) }, &quot;dateTime&quot; =&gt; Proc.new { |time| time.xmlschema }, &quot;binary&quot; =&gt; Proc.new { |binary| ::Base64.encode64(binary) }, &quot;yaml&quot; =&gt; Proc.new { |yaml| yaml.to_yaml } } unless defined?(FORMATTING)</td> </tr> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"></td> </tr> <tr valign='top'> <td class="attr-name">PARSING</td> <td>=</td> <td class="attr-value">{ &quot;symbol&quot; =&gt; Proc.new { |symbol| symbol.to_s.to_sym }, &quot;date&quot; =&gt; Proc.new { |date| ::Date.parse(date) }, &quot;datetime&quot; =&gt; Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc }, &quot;integer&quot; =&gt; Proc.new { |integer| integer.to_i }, &quot;float&quot; =&gt; Proc.new { |float| float.to_f }, &quot;decimal&quot; =&gt; Proc.new { |number| BigDecimal(number) }, &quot;boolean&quot; =&gt; Proc.new { |boolean| %w(1 true).include?(boolean.to_s.strip) }, &quot;string&quot; =&gt; Proc.new { |string| string.to_s }, &quot;yaml&quot; =&gt; Proc.new { |yaml| YAML::load(yaml) rescue yaml }, &quot;base64Binary&quot; =&gt; Proc.new { |bin| ::Base64.decode64(bin) }, &quot;binary&quot; =&gt; Proc.new { |bin, entity| _parse_binary(bin, entity) }, &quot;file&quot; =&gt; Proc.new { |file, entity| _parse_file(file, entity) } }</td> </tr> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"></td> </tr> </table> <!-- Methods --> <div class="sectiontitle">Instance Public methods</div> <div class="method"> <div class="title method-title" id="method-i-backend"> <b>backend</b>() <a href="../../classes/ActiveSupport/XmlMini.html#method-i-backend" name="method-i-backend" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-backend_source')" id="l_method-i-backend_source">show</a> </p> <div id="method-i-backend_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb, line 83</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">backend</span> <span class="ruby-identifier">current_thread_backend</span> <span class="ruby-operator">||</span> <span class="ruby-ivar">@backend</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-backend-3D"> <b>backend=</b>(name) <a href="../../classes/ActiveSupport/XmlMini.html#method-i-backend-3D" name="method-i-backend-3D" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-backend-3D_source')" id="l_method-i-backend-3D_source">show</a> </p> <div id="method-i-backend-3D_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb, line 87</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">backend=</span>(<span class="ruby-identifier">name</span>) <span class="ruby-identifier">backend</span> = <span class="ruby-identifier">name</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">cast_backend_name_to_module</span>(<span class="ruby-identifier">name</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">current_thread_backend</span> = <span class="ruby-identifier">backend</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">current_thread_backend</span> <span class="ruby-ivar">@backend</span> = <span class="ruby-identifier">backend</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-rename_key"> <b>rename_key</b>(key, options = {}) <a href="../../classes/ActiveSupport/XmlMini.html#method-i-rename_key" name="method-i-rename_key" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-rename_key_source')" id="l_method-i-rename_key_source">show</a> </p> <div id="method-i-rename_key_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb, line 134</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">rename_key</span>(<span class="ruby-identifier">key</span>, <span class="ruby-identifier">options</span> = {}) <span class="ruby-identifier">camelize</span> = <span class="ruby-identifier">options</span>[<span class="ruby-value">:camelize</span>] <span class="ruby-identifier">dasherize</span> = <span class="ruby-operator">!</span><span class="ruby-identifier">options</span>.<span class="ruby-identifier">has_key?</span>(<span class="ruby-value">:dasherize</span>) <span class="ruby-operator">||</span> <span class="ruby-identifier">options</span>[<span class="ruby-value">:dasherize</span>] <span class="ruby-keyword">if</span> <span class="ruby-identifier">camelize</span> <span class="ruby-identifier">key</span> = <span class="ruby-keyword">true</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">camelize</span> <span class="ruby-operator">?</span> <span class="ruby-identifier">key</span>.<span class="ruby-identifier">camelize</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">key</span>.<span class="ruby-identifier">camelize</span>(<span class="ruby-identifier">camelize</span>) <span class="ruby-keyword">end</span> <span class="ruby-identifier">key</span> = <span class="ruby-identifier">_dasherize</span>(<span class="ruby-identifier">key</span>) <span class="ruby-keyword">if</span> <span class="ruby-identifier">dasherize</span> <span class="ruby-identifier">key</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-to_tag"> <b>to_tag</b>(key, value, options) <a href="../../classes/ActiveSupport/XmlMini.html#method-i-to_tag" name="method-i-to_tag" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-to_tag_source')" id="l_method-i-to_tag_source">show</a> </p> <div id="method-i-to_tag_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb, line 101</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">to_tag</span>(<span class="ruby-identifier">key</span>, <span class="ruby-identifier">value</span>, <span class="ruby-identifier">options</span>) <span class="ruby-identifier">type_name</span> = <span class="ruby-identifier">options</span>.<span class="ruby-identifier">delete</span>(<span class="ruby-value">:type</span>) <span class="ruby-identifier">merged_options</span> = <span class="ruby-identifier">options</span>.<span class="ruby-identifier">merge</span>(<span class="ruby-value">:root</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">key</span>, <span class="ruby-value">:skip_instruct</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-keyword">true</span>) <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">is_a?</span>(<span class="ruby-operator">::</span><span class="ruby-constant">Method</span>) <span class="ruby-operator">||</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">is_a?</span>(<span class="ruby-operator">::</span><span class="ruby-constant">Proc</span>) <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">arity</span> <span class="ruby-operator">==</span> <span class="ruby-number">1</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">call</span>(<span class="ruby-identifier">merged_options</span>) <span class="ruby-keyword">else</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">call</span>(<span class="ruby-identifier">merged_options</span>, <span class="ruby-identifier">key</span>.<span class="ruby-identifier">to_s</span>.<span class="ruby-identifier">singularize</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">elsif</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">respond_to?</span>(<span class="ruby-value">:to_xml</span>) <span class="ruby-identifier">value</span>.<span class="ruby-identifier">to_xml</span>(<span class="ruby-identifier">merged_options</span>) <span class="ruby-keyword">else</span> <span class="ruby-identifier">type_name</span> <span class="ruby-operator">||=</span> <span class="ruby-constant">TYPE_NAMES</span>[<span class="ruby-identifier">value</span>.<span class="ruby-identifier">class</span>.<span class="ruby-identifier">name</span>] <span class="ruby-identifier">type_name</span> <span class="ruby-operator">||=</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">class</span>.<span class="ruby-identifier">name</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-operator">!</span><span class="ruby-identifier">value</span>.<span class="ruby-identifier">respond_to?</span>(<span class="ruby-value">:to_str</span>) <span class="ruby-identifier">type_name</span> = <span class="ruby-identifier">type_name</span>.<span class="ruby-identifier">to_s</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">type_name</span> <span class="ruby-identifier">type_name</span> = <span class="ruby-string">&quot;dateTime&quot;</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">type_name</span> <span class="ruby-operator">==</span> <span class="ruby-string">&quot;datetime&quot;</span> <span class="ruby-identifier">key</span> = <span class="ruby-identifier">rename_key</span>(<span class="ruby-identifier">key</span>.<span class="ruby-identifier">to_s</span>, <span class="ruby-identifier">options</span>) <span class="ruby-identifier">attributes</span> = <span class="ruby-identifier">options</span>[<span class="ruby-value">:skip_types</span>] <span class="ruby-operator">||</span> <span class="ruby-identifier">type_name</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-operator">?</span> { } <span class="ruby-operator">:</span> { <span class="ruby-value">:type</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">type_name</span> } <span class="ruby-identifier">attributes</span>[<span class="ruby-value">:nil</span>] = <span class="ruby-keyword">true</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">value</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-identifier">encoding</span> = <span class="ruby-identifier">options</span>[<span class="ruby-value">:encoding</span>] <span class="ruby-operator">||</span> <span class="ruby-constant">DEFAULT_ENCODINGS</span>[<span class="ruby-identifier">type_name</span>] <span class="ruby-identifier">attributes</span>[<span class="ruby-value">:encoding</span>] = <span class="ruby-identifier">encoding</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">encoding</span> <span class="ruby-identifier">formatted_value</span> = <span class="ruby-constant">FORMATTING</span>[<span class="ruby-identifier">type_name</span>] <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-operator">!</span><span class="ruby-identifier">value</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-operator">?</span> <span class="ruby-constant">FORMATTING</span>[<span class="ruby-identifier">type_name</span>].<span class="ruby-identifier">call</span>(<span class="ruby-identifier">value</span>) <span class="ruby-operator">:</span> <span class="ruby-identifier">value</span> <span class="ruby-identifier">options</span>[<span class="ruby-value">:builder</span>].<span class="ruby-identifier">tag!</span>(<span class="ruby-identifier">key</span>, <span class="ruby-identifier">formatted_value</span>, <span class="ruby-identifier">attributes</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-with_backend"> <b>with_backend</b>(name) <a href="../../classes/ActiveSupport/XmlMini.html#method-i-with_backend" name="method-i-with_backend" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-with_backend_source')" id="l_method-i-with_backend_source">show</a> </p> <div id="method-i-with_backend_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb, line 93</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">with_backend</span>(<span class="ruby-identifier">name</span>) <span class="ruby-identifier">old_backend</span> = <span class="ruby-identifier">current_thread_backend</span> <span class="ruby-keyword">self</span>.<span class="ruby-identifier">current_thread_backend</span> = <span class="ruby-identifier">name</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">cast_backend_name_to_module</span>(<span class="ruby-identifier">name</span>) <span class="ruby-keyword">yield</span> <span class="ruby-keyword">ensure</span> <span class="ruby-keyword">self</span>.<span class="ruby-identifier">current_thread_backend</span> = <span class="ruby-identifier">old_backend</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="sectiontitle">Instance Protected methods</div> <div class="method"> <div class="title method-title" id="method-i-_dasherize"> <b>_dasherize</b>(key) <a href="../../classes/ActiveSupport/XmlMini.html#method-i-_dasherize" name="method-i-_dasherize" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-_dasherize_source')" id="l_method-i-_dasherize_source">show</a> </p> <div id="method-i-_dasherize_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb, line 146</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">_dasherize</span>(<span class="ruby-identifier">key</span>) <span class="ruby-comment"># $2 must be a non-greedy regex for this to work</span> <span class="ruby-identifier">left</span>, <span class="ruby-identifier">middle</span>, <span class="ruby-identifier">right</span> = <span class="ruby-regexp">/\A(_*)(.*?)(_*)\Z/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-identifier">key</span>.<span class="ruby-identifier">strip</span>)[<span class="ruby-number">1</span>,<span class="ruby-number">3</span>] <span class="ruby-node">&quot;#{left}#{middle.tr(&#39;_ &#39;, &#39;--&#39;)}#{right}&quot;</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-_parse_file"> <b>_parse_file</b>(file, entity) <a href="../../classes/ActiveSupport/XmlMini.html#method-i-_parse_file" name="method-i-_parse_file" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-_parse_file_source')" id="l_method-i-_parse_file_source">show</a> </p> <div id="method-i-_parse_file_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../.rvm/gems/ruby-2.2.0/gems/activesupport-4.1.8/lib/active_support/xml_mini.rb, line 162</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">_parse_file</span>(<span class="ruby-identifier">file</span>, <span class="ruby-identifier">entity</span>) <span class="ruby-identifier">f</span> = <span class="ruby-constant">StringIO</span>.<span class="ruby-identifier">new</span>(<span class="ruby-operator">::</span><span class="ruby-constant">Base64</span>.<span class="ruby-identifier">decode64</span>(<span class="ruby-identifier">file</span>)) <span class="ruby-identifier">f</span>.<span class="ruby-identifier">extend</span>(<span class="ruby-constant">FileLike</span>) <span class="ruby-identifier">f</span>.<span class="ruby-identifier">original_filename</span> = <span class="ruby-identifier">entity</span>[<span class="ruby-string">&#39;name&#39;</span>] <span class="ruby-identifier">f</span>.<span class="ruby-identifier">content_type</span> = <span class="ruby-identifier">entity</span>[<span class="ruby-string">&#39;content_type&#39;</span>] <span class="ruby-identifier">f</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </div> </div> </body> </html>
{ "content_hash": "d5cd14e13e384df59a4d7dc2cc1f8903", "timestamp": "", "source": "github", "line_count": 558, "max_line_length": 512, "avg_line_length": 46.297491039426525, "alnum_prop": 0.5607726252225749, "repo_name": "kristoferrobin/p2p", "id": "9635dff3ebed33acd4702d784951c6cd96209498", "size": "25834", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/api/classes/ActiveSupport/XmlMini.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1033" }, { "name": "CoffeeScript", "bytes": "422" }, { "name": "HTML", "bytes": "5432" }, { "name": "JavaScript", "bytes": "664" }, { "name": "Ruby", "bytes": "24321" } ], "symlink_target": "" }
<?xml version='1.0'?> <!-- 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.activemq.examples.broker</groupId> <artifactId>jms-examples</artifactId> <version>2.18.0-SNAPSHOT</version> </parent> <artifactId>static-selector</artifactId> <packaging>jar</packaging> <name>ActiveMQ Artemis Static Selector Example</name> <properties> <activemq.basedir>${project.basedir}/../../../..</activemq.basedir> </properties> <dependencies> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>artemis-jms-client-all</artifactId> <version>${project.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.activemq</groupId> <artifactId>artemis-maven-plugin</artifactId> <executions> <execution> <id>create</id> <goals> <goal>create</goal> </goals> <configuration> <ignore>${noServer}</ignore> </configuration> </execution> <execution> <id>start</id> <goals> <goal>cli</goal> </goals> <configuration> <ignore>${noServer}</ignore> <spawn>true</spawn> <testURI>tcp://localhost:61616</testURI> <args> <param>run</param> </args> </configuration> </execution> <execution> <id>runClient</id> <goals> <goal>runClient</goal> </goals> <configuration> <clientClass>org.apache.activemq.artemis.jms.example.StaticSelectorExample</clientClass> </configuration> </execution> <execution> <id>stop</id> <goals> <goal>cli</goal> </goals> <configuration> <ignore>${noServer}</ignore> <args> <param>stop</param> </args> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.apache.activemq.examples.broker</groupId> <artifactId>static-selector</artifactId> <version>${project.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "content_hash": "e51732cba234f52d84d4e90b1c6fca1f", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 201, "avg_line_length": 35.585585585585584, "alnum_prop": 0.5349367088607595, "repo_name": "jbertram/activemq-artemis", "id": "a4b9c8a20b249c174d535e897b5127db79c1779d", "size": "3950", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "examples/features/standard/static-selector/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7894" }, { "name": "CSS", "bytes": "66196" }, { "name": "Groovy", "bytes": "169650" }, { "name": "HTML", "bytes": "28321" }, { "name": "Java", "bytes": "32261402" }, { "name": "JavaScript", "bytes": "252799" }, { "name": "Shell", "bytes": "40937" } ], "symlink_target": "" }
package org.apache.asterix.metadata.external; import java.nio.ByteBuffer; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.IOperatorNodePushable; import org.apache.hyracks.api.dataflow.value.INullWriterFactory; import org.apache.hyracks.api.dataflow.value.IRecordDescriptorProvider; import org.apache.hyracks.api.dataflow.value.RecordDescriptor; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.api.job.IOperatorDescriptorRegistry; import org.apache.hyracks.dataflow.std.base.AbstractUnaryInputUnaryOutputOperatorNodePushable; import org.apache.hyracks.dataflow.std.file.IFileSplitProvider; import org.apache.hyracks.storage.am.common.api.IIndexLifecycleManagerProvider; import org.apache.hyracks.storage.am.common.api.ISearchOperationCallbackFactory; import org.apache.hyracks.storage.am.common.dataflow.AbstractTreeIndexOperatorDescriptor; import org.apache.hyracks.storage.am.lsm.btree.dataflow.ExternalBTreeDataflowHelper; import org.apache.hyracks.storage.am.lsm.btree.dataflow.ExternalBTreeDataflowHelperFactory; import org.apache.hyracks.storage.common.IStorageManagerInterface; /* * This operator is intended for using record ids to access data in external sources */ public class ExternalLoopkupOperatorDiscriptor extends AbstractTreeIndexOperatorDescriptor { private static final long serialVersionUID = 1L; private final IControlledAdapterFactory adapterFactory; private final INullWriterFactory iNullWriterFactory; public ExternalLoopkupOperatorDiscriptor(IOperatorDescriptorRegistry spec, IControlledAdapterFactory adapterFactory, RecordDescriptor outRecDesc, ExternalBTreeDataflowHelperFactory externalFilesIndexDataFlowHelperFactory, boolean propagateInput, IIndexLifecycleManagerProvider lcManagerProvider, IStorageManagerInterface storageManager, IFileSplitProvider fileSplitProvider, int datasetId, double bloomFilterFalsePositiveRate, ISearchOperationCallbackFactory searchOpCallbackFactory, boolean retainNull, INullWriterFactory iNullWriterFactory) { super(spec, 1, 1, outRecDesc, storageManager, lcManagerProvider, fileSplitProvider, new FilesIndexDescription().EXTERNAL_FILE_INDEX_TYPE_TRAITS, new FilesIndexDescription().FILES_INDEX_COMP_FACTORIES, FilesIndexDescription.BLOOM_FILTER_FIELDS, externalFilesIndexDataFlowHelperFactory, null, propagateInput, retainNull, iNullWriterFactory, null, searchOpCallbackFactory, null); this.adapterFactory = adapterFactory; this.iNullWriterFactory = iNullWriterFactory; } @Override public IOperatorNodePushable createPushRuntime(final IHyracksTaskContext ctx, final IRecordDescriptorProvider recordDescProvider, final int partition, int nPartitions) throws HyracksDataException { // Create a file index accessor to be used for files lookup operations // Note that all file index accessors will use partition 0 since we only have 1 files index per NC final ExternalFileIndexAccessor fileIndexAccessor = new ExternalFileIndexAccessor( (ExternalBTreeDataflowHelper) dataflowHelperFactory.createIndexDataflowHelper(this, ctx, partition), this); return new AbstractUnaryInputUnaryOutputOperatorNodePushable() { // The adapter that uses the file index along with the coming tuples to access files in HDFS private final IControlledAdapter adapter = adapterFactory.createAdapter(ctx, fileIndexAccessor, recordDescProvider.getInputRecordDescriptor(getActivityId(), 0)); @Override public void open() throws HyracksDataException { //Open the file index accessor here fileIndexAccessor.openIndex(); try { adapter.initialize(ctx, iNullWriterFactory); } catch (Exception e) { // close the files index fileIndexAccessor.closeIndex(); throw new HyracksDataException("error during opening a controlled adapter", e); } writer.open(); } @Override public void close() throws HyracksDataException { try { adapter.close(writer); } catch (Exception e) { e.printStackTrace(); throw new HyracksDataException("controlled adapter failed to close", e); } finally { //close the file index fileIndexAccessor.closeIndex(); writer.close(); } } @Override public void fail() throws HyracksDataException { try { adapter.fail(); writer.fail(); } catch (Exception e) { throw new HyracksDataException("controlled adapter failed to clean up", e); } finally { // close the open index fileIndexAccessor.closeIndex(); } } @Override public void nextFrame(ByteBuffer buffer) throws HyracksDataException { try { adapter.nextFrame(buffer, writer); } catch (Exception e) { throw new HyracksDataException("controlled adapter failed to process a frame", e); } } }; } }
{ "content_hash": "7783c17db33cb4b6a6014913c0931f55", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 116, "avg_line_length": 50.660714285714285, "alnum_prop": 0.6787099048290448, "repo_name": "amoudi87/asterixdb", "id": "a7844ce68c91b26f0e040cf4250b9d1d3065eee5", "size": "6481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "asterix-metadata/src/main/java/org/apache/asterix/metadata/external/ExternalLoopkupOperatorDiscriptor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6115" }, { "name": "CSS", "bytes": "4763" }, { "name": "Crystal", "bytes": "453" }, { "name": "HTML", "bytes": "114488" }, { "name": "Java", "bytes": "9375622" }, { "name": "JavaScript", "bytes": "237719" }, { "name": "Python", "bytes": "268336" }, { "name": "Ruby", "bytes": "2666" }, { "name": "Scheme", "bytes": "1105" }, { "name": "Shell", "bytes": "182529" }, { "name": "Smarty", "bytes": "31412" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e201e25d1d2c669a5df66bb332887225", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "2a3e467312d622d56e2e0e7174061cee473fcfe0", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Arthroclianthus/Arthroclianthus comptonii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import _plotly_utils.basevalidators class NameValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="name", parent_name="layout.mapbox.layer", **kwargs): super(NameValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "style"), **kwargs )
{ "content_hash": "809cf80127b89c32e551080065c29231", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 88, "avg_line_length": 37.083333333333336, "alnum_prop": 0.6067415730337079, "repo_name": "plotly/python-api", "id": "d3b3e2d971a17c8b92fb2e68bcc9e5a0c8e471ea", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/python/plotly/plotly/validators/layout/mapbox/layer/_name.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6870" }, { "name": "Makefile", "bytes": "1708" }, { "name": "Python", "bytes": "823245" }, { "name": "Shell", "bytes": "3238" } ], "symlink_target": "" }
package java.security; /** * This interface represents the abstract notion of a principal, which * can be used to represent any entity, such as an individual, a * corporation, and a login id. * * @see java.security.cert.X509Certificate * * @version 1.23, 05/11/17 * @author Li Gong */ public interface Principal { /** * Compares this principal to the specified object. Returns true * if the object passed in matches the principal represented by * the implementation of this interface. * * @param another principal to compare with. * * @return true if the principal passed in is the same as that * encapsulated by this principal, and false otherwise. */ public boolean equals(Object another); /** * Returns a string representation of this principal. * * @return a string representation of this principal. */ public String toString(); /** * Returns a hashcode for this principal. * * @return a hashcode for this principal. */ public int hashCode(); /** * Returns the name of this principal. * * @return the name of this principal. */ public String getName(); }
{ "content_hash": "3aa73ea467f5754ddf380b72f1f75aac", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 70, "avg_line_length": 24.28, "alnum_prop": 0.6466227347611203, "repo_name": "jgaltidor/VarJ", "id": "ae7cc5f09c9f8178bd617bbc373c47eae6f58596", "size": "1387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "analyzed_libs/jdk1.6.0_06_src/java/security/Principal.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2125" }, { "name": "CSS", "bytes": "9913" }, { "name": "Emacs Lisp", "bytes": "12570" }, { "name": "Java", "bytes": "31711742" }, { "name": "JavaScript", "bytes": "3251" }, { "name": "Makefile", "bytes": "257" }, { "name": "Perl", "bytes": "5179" }, { "name": "Prolog", "bytes": "292" }, { "name": "Python", "bytes": "1080" }, { "name": "Scala", "bytes": "42424" }, { "name": "Shell", "bytes": "43707" }, { "name": "TeX", "bytes": "372287" } ], "symlink_target": "" }
package io.vertigo.engines.command.tcp; import io.vertigo.lang.Assertion; import io.vertigo.shell.command.VCommand; import io.vertigo.shell.command.VResponse; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.SocketChannel; /** * TCP socket Client . * @author pchretien */ public final class VClient implements AutoCloseable { private static int DEFAULT_TIMEOUT = 5000; private final SocketChannel socketChannel; private final VProtocol protocol = new VProtocol(); public VClient(final SocketAddress socketAddress) { Assertion.checkNotNull(socketAddress); //----- try { socketChannel = SocketChannel.open(socketAddress); socketChannel.socket().setSoTimeout(DEFAULT_TIMEOUT); //socketChannel.configureBlocking(true); // socket.setReuseAddress(true); // socket.setKeepAlive(true); //Will monitor the TCP connection is valid // socket.setTcpNoDelay(true); //Socket buffer Whetherclosed, to ensure timely delivery of data // socket.setSoLinger(true, 0); //Control calls close () method, the underlying socket is closed immediately } catch (final IOException e) { throw new RuntimeException(e); } } @Override public void close() { try { //On notifie l'autre que l'on part. // quit(); //On ferme tjrs la socket socketChannel.close(); } catch (final IOException e) { throw new RuntimeException(e); } } // // private void quit() { // try { // protocol.fire(socketChannel, "quit"); // } catch (IOException e) { // //return VResponse.createResponseWithError(e.getMessage() == null ? e.getClass().getName() : e.getMessage()); // } // } public VResponse execCommand(final VCommand command) { try { return protocol.sendCommand(socketChannel, command); } catch (final IOException e) { return VResponse.createResponseWithError(e.getMessage() == null ? e.getClass().getName() : e.getMessage()); } } // public String getRemoteAddress() { // try { // return socketChannel.getRemoteAddress().toString(); // } catch (IOException e) { // throw new RuntimeException(e); // } // } }
{ "content_hash": "144676aa39f6a7736e57005c078013ca", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 115, "avg_line_length": 29.041095890410958, "alnum_prop": 0.7023584905660377, "repo_name": "KleeGroup/vertigo-labs", "id": "7239d863753cd52f1ff258b463b399343f17b34e", "size": "2910", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vertigo-labs-test/src/main/java/io/vertigo/engines/command/tcp/VClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3063" }, { "name": "FreeMarker", "bytes": "18080" }, { "name": "HTML", "bytes": "10294" }, { "name": "Java", "bytes": "548291" }, { "name": "JavaScript", "bytes": "1839" }, { "name": "Shell", "bytes": "72" }, { "name": "TypeScript", "bytes": "35202" } ], "symlink_target": "" }
package com.tntntnt.android.testfordudeweather.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.tntntnt.android.testfordudeweather.R; import com.tntntnt.android.testfordudeweather.model.Weather; import com.tntntnt.android.testfordudeweather.model.WeatherDailyForecast; import com.tntntnt.android.testfordudeweather.tools.DateToWeek; /** * Created by tntnt on 2016/11/16. */ public class DayWeekFragment extends Fragment { private WeatherDailyForecast mWeatherDailyForecast; private int mPosition; private Button mButtonBack; private TextView mToolbarTextView; private TextView mTmpMin; private TextView mTmpMax; private TextView mCondTxtD; private TextView mCondTxtN; private TextView mHum; private TextView mPop; private TextView mVis; private TextView mSc; private TextView mAstroSr; private TextView mAstroSs; public DayWeekFragment(WeatherDailyForecast weatherDailyForecast, int position){ mWeatherDailyForecast = weatherDailyForecast; mPosition = position; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.fragment_day_week, container, false); initView(view); initText(); mButtonBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().finish(); } }); return view; } private void initView(View v){ mButtonBack = (Button)v.findViewById(R.id.button_day_week_back); mToolbarTextView = (TextView)v.findViewById(R.id.toolbar_text_view_day_week); mTmpMin = (TextView)v.findViewById(R.id.wdf_text_view_tmp_min); mTmpMax = (TextView)v.findViewById(R.id.wdf_text_view_tmp_max); mCondTxtD = (TextView)v.findViewById(R.id.wdf_text_view_cond_txt_d); mCondTxtN = (TextView)v.findViewById(R.id.wdf_text_view_cond_txt_n); mHum = (TextView)v.findViewById(R.id.wdf_text_view_hum); mPop = (TextView)v.findViewById(R.id.wdf_text_view_pop); mVis = (TextView)v.findViewById(R.id.wdf_text_view_vis); mSc = (TextView)v.findViewById(R.id.wdf_text_view_sc); mAstroSr = (TextView)v.findViewById(R.id.wdf_text_view_astrosr); mAstroSs = (TextView)v.findViewById(R.id.wdf_text_view_astross); } private void initText(){ mToolbarTextView.setText(DateToWeek.go(mPosition)); mTmpMin.setText(mWeatherDailyForecast.getTmpMin() + "°"); mTmpMax.setText(mWeatherDailyForecast.getTmpMax() + "°"); mCondTxtD.setText("白天 " + mWeatherDailyForecast.getCondTxtd()); mCondTxtN.setText("夜间 " + mWeatherDailyForecast.getCondTxtn()); mHum.setText(mWeatherDailyForecast.getHum() + "%"); mPop.setText(mWeatherDailyForecast.getPop() + "%"); mVis.setText(mWeatherDailyForecast.getVis() + "km"); mSc.setText(mWeatherDailyForecast.getWindSc()); mAstroSr.setText(mWeatherDailyForecast.getAstroSr()); mAstroSs.setText(mWeatherDailyForecast.getAstroSs()); } }
{ "content_hash": "77d380029256019a81b3d45d5d9f7aa0", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 102, "avg_line_length": 35.0625, "alnum_prop": 0.702020202020202, "repo_name": "tntntnt7/TestForDudeWeather", "id": "20cb0502f2ea237c0fb32f94420a17dce9b3c6fb", "size": "3376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/tntntnt/android/testfordudeweather/fragment/DayWeekFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "102381" } ], "symlink_target": "" }
package edu.uci.ics.asterix.om.typecomputer.impl; import edu.uci.ics.asterix.om.typecomputer.base.IResultTypeComputer; import edu.uci.ics.asterix.om.types.AOrderedListType; import edu.uci.ics.asterix.om.types.BuiltinType; import edu.uci.ics.asterix.om.types.IAType; import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException; import edu.uci.ics.hyracks.algebricks.core.algebra.base.ILogicalExpression; import edu.uci.ics.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment; import edu.uci.ics.hyracks.algebricks.core.algebra.metadata.IMetadataProvider; public class OrderedListOfAStringTypeComputer implements IResultTypeComputer { public static final OrderedListOfAStringTypeComputer INSTANCE = new OrderedListOfAStringTypeComputer(); private OrderedListOfAStringTypeComputer() { } @Override public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env, IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException { return new AOrderedListType(BuiltinType.ASTRING, null); } }
{ "content_hash": "221c0a2aefbe9c0db7f509642a70cf4e", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 107, "avg_line_length": 43.8, "alnum_prop": 0.8146118721461187, "repo_name": "sjaco002/incubator-asterixdb", "id": "fdbefcd745cce04b8415df04166ec845b8d9a775", "size": "1730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "asterix-om/src/main/java/edu/uci/ics/asterix/om/typecomputer/impl/OrderedListOfAStringTypeComputer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3954" }, { "name": "HTML", "bytes": "69593" }, { "name": "Java", "bytes": "7985438" }, { "name": "JavaScript", "bytes": "232059" }, { "name": "Python", "bytes": "264407" }, { "name": "Ruby", "bytes": "1880" }, { "name": "Scheme", "bytes": "1105" }, { "name": "Shell", "bytes": "76117" }, { "name": "Smarty", "bytes": "29789" } ], "symlink_target": "" }
package io.github.cjstehno.ersatz.encdec; import io.github.cjstehno.ersatz.cfg.ContentType; import java.util.Collection; import java.util.List; import java.util.function.Function; /** * A function chain for response encoders. */ @SuppressWarnings("ClassCanBeRecord") public class EncoderChain { private final ResponseEncoders serverLevel; private final ResponseEncoders responseLevel; /** * Creates a new encoder chain with the provided encoders. * * @param serverLevel the server configured response encoders * @param responseLevel the response configured response encoders */ public EncoderChain(final ResponseEncoders serverLevel, final ResponseEncoders responseLevel) { this.serverLevel = serverLevel != null ? serverLevel : new ResponseEncoders(); this.responseLevel = responseLevel != null ? responseLevel : new ResponseEncoders(); } /** * Resolves the encoder for the specified response content-type and object type. * * @param contentType the response content-type * @param objectType the response object type * @return the encoder */ public Function<Object, byte[]> resolve(final String contentType, final Class objectType) { var found = responseLevel.findEncoder(contentType, objectType); if (found == null) { found = serverLevel.findEncoder(contentType, objectType); } return found; } /** * Resolves the encoder for the specified response content-type and object type. * * @param contentType the response content-type * @param objectType the response object type * @return the encoder */ public Function<Object, byte[]> resolve(final ContentType contentType, final Class objectType) { return resolve(contentType.getValue(), objectType); } /** * Resolves the encoder for the specified response content-type and object type from the server level encoders. * * @param contentType the response content-type * @param objectType the response object type * @return the encoder */ public Function<Object, byte[]> resolveServerLevel(final String contentType, final Class objectType) { return serverLevel.findEncoder(contentType, objectType); } /** * Resolves the encoder for the specified response content-type and object type from the server level encoders. * * @param contentType the response content-type * @param objectType the response object type * @return the encoder */ public Function<Object, byte[]> resolveServerLevel(final ContentType contentType, final Class objectType) { return serverLevel.findEncoder(contentType, objectType); } /** * Retrieves an ordered collection containing the server-level and response-level encoders. * * @return a list of the encoder configurations */ public Collection<ResponseEncoders> items() { return List.of(serverLevel, responseLevel); } }
{ "content_hash": "0f3d352aec5b8cfe6fddb98b72e82643", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 115, "avg_line_length": 36.372093023255815, "alnum_prop": 0.6790281329923273, "repo_name": "cjstehno/ersatz", "id": "44bd7776210cfee19041b6dd51a76a17309ad0ac", "size": "3755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/EncoderChain.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23371" }, { "name": "Groovy", "bytes": "36441" }, { "name": "HTML", "bytes": "10412" }, { "name": "Java", "bytes": "656381" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngrinder.home.service; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.ngrinder.home.model.PanelEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.ngrinder.common.util.TypeConvertUtils.cast; /** * nGrinder index page data retrieval service. * * @author JunHo Yoon * @since 3.1 */ @Component public class HomeService { private static final int PANEL_ENTRY_SIZE = 6; private static final Logger LOG = LoggerFactory.getLogger(HomeService.class); /** * Get the let panel entries from the given feed RUL. * * @param feedURL feed url * @return the list of {@link PanelEntry} */ @SuppressWarnings("unchecked") @Cacheable(value = "left_panel_entries") public List<PanelEntry> getLeftPanelEntries(String feedURL) { return getPanelEntries(feedURL, PANEL_ENTRY_SIZE, false); } /** * Get the right panel entries containing the entries from the given RSS * url. * * @param feedURL rss url message * @return {@link PanelEntry} list */ @Cacheable(value = "right_panel_entries") public List<PanelEntry> getRightPanelEntries(String feedURL) { return getPanelEntries(feedURL, PANEL_ENTRY_SIZE, true); } /** * Get panel entries containing the entries from the given RSS * url. * * @param feedURL rss url message * @param maxSize max size * @param includeReply if including reply * @return {@link PanelEntry} list */ public List<PanelEntry> getPanelEntries(String feedURL, int maxSize, boolean includeReply) { SyndFeedInput input = new SyndFeedInput(); XmlReader reader = null; HttpURLConnection feedConnection = null; try { List<PanelEntry> panelEntries = new ArrayList<PanelEntry>(); URL url = new URL(feedURL); feedConnection = (HttpURLConnection) url.openConnection(); feedConnection.setConnectTimeout(8000); feedConnection.setReadTimeout(8000); reader = new XmlReader(feedConnection); SyndFeed feed = input.build(reader); int count = 0; for (Object eachObj : feed.getEntries()) { SyndEntryImpl each = cast(eachObj); if (!includeReply && StringUtils.startsWithIgnoreCase(each.getTitle(), "Re: ")) { continue; } if (count++ >= maxSize) { break; } panelEntries.add(getPanelEntry(each)); } Collections.sort(panelEntries); return panelEntries; } catch (Exception e) { LOG.error("Error while patching the feed entries for {} : {}", feedURL, e.getMessage()); } finally { if (feedConnection != null) { feedConnection.disconnect(); } IOUtils.closeQuietly(reader); } return Collections.emptyList(); } private PanelEntry getPanelEntry(SyndEntryImpl each) { PanelEntry entry = new PanelEntry(); entry.setAuthor(each.getAuthor()); entry.setLastUpdatedDate(each.getUpdatedDate() == null ? each.getPublishedDate() : each .getUpdatedDate()); if (each.getTitle() == null) { String[] split = StringUtils.split(each.getLink(), "/"); entry.setTitle(split[split.length - 1].replace("-", " ")); } else { entry.setTitle(each.getTitle()); } if (StringUtils.startsWith(each.getLink(), "http")) { entry.setLink(each.getLink()); } else { String uri = each.getUri(); if (isGithubWiki(uri)) { uri = uri.substring(0, StringUtils.lastIndexOf(uri, "/")); } entry.setLink(uri); } return entry; } private boolean isGithubWiki(String uri) { return StringUtils.startsWith(uri, "https://github.com") && StringUtils.contains(uri, "/wiki/"); } }
{ "content_hash": "ff1f79fc1d6d84788e273867538833fa", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 98, "avg_line_length": 31.144827586206898, "alnum_prop": 0.7156775907883083, "repo_name": "songeunwoo/ngrinder", "id": "a4480fdd9e8e579a25d2bafb019463e591e0e564", "size": "4516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ngrinder-controller/src/main/java/org/ngrinder/home/service/HomeService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1479" }, { "name": "CSS", "bytes": "82241" }, { "name": "FreeMarker", "bytes": "238988" }, { "name": "Groff", "bytes": "51750" }, { "name": "Groovy", "bytes": "4964" }, { "name": "HTML", "bytes": "15768" }, { "name": "Java", "bytes": "1755579" }, { "name": "JavaScript", "bytes": "587275" }, { "name": "Python", "bytes": "2890" }, { "name": "Shell", "bytes": "5378" } ], "symlink_target": "" }
package me.chanjar.weixin.mp.util.json; import com.google.gson.*; import me.chanjar.weixin.common.util.json.GsonHelper; import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult; import java.lang.reflect.Type; /** * @author Daniel Qian */ public class WxMpMassUploadResultAdapter implements JsonDeserializer<WxMpMassUploadResult> { @Override public WxMpMassUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpMassUploadResult uploadResult = new WxMpMassUploadResult(); JsonObject uploadResultJsonObject = json.getAsJsonObject(); if (uploadResultJsonObject.get("type") != null && !uploadResultJsonObject.get("type").isJsonNull()) { uploadResult.setType(GsonHelper.getAsString(uploadResultJsonObject.get("type"))); } if (uploadResultJsonObject.get("media_id") != null && !uploadResultJsonObject.get("media_id").isJsonNull()) { uploadResult.setMediaId(GsonHelper.getAsString(uploadResultJsonObject.get("media_id"))); } if (uploadResultJsonObject.get("created_at") != null && !uploadResultJsonObject.get("created_at").isJsonNull()) { uploadResult.setCreatedAt(GsonHelper.getAsPrimitiveLong(uploadResultJsonObject.get("created_at"))); } return uploadResult; } }
{ "content_hash": "fd4bae0819935d17a5401e21d1dcab53", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 137, "avg_line_length": 40.6875, "alnum_prop": 0.7634408602150538, "repo_name": "chunwei/weixin-java-tools", "id": "e20175d76766b492e3b0ee7bd2b04d5c147bc78a", "size": "1741", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassUploadResultAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "658953" } ], "symlink_target": "" }
from morse.builder import * # Land robot ATRV = Robot('atrv') Pose = Sensor('pose') Pose.translate(x=-0.2000, z=0.9000) ATRV.append(Pose) Camera = Sensor('video_camera') Camera.translate(x=0.2000, z=0.9000) ATRV.append(Camera) Motion_Controller = Actuator('waypoint') ATRV.append(Motion_Controller) # Scene configuration Motion_Controller.configure_mw('yarp') Pose.configure_mw('yarp') Camera.configure_mw('yarp') env = Environment('indoors-1/indoor-1') env.aim_camera([1.0470, 0, 0.7854])
{ "content_hash": "d8a727f7b9b4ed2ca294a505f9515585", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 40, "avg_line_length": 20.708333333333332, "alnum_prop": 0.7283702213279678, "repo_name": "Arkapravo/morse-0.6", "id": "ffa7a1c06ffe841d4d3813eab788492f91412c6c", "size": "497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/tutorials/tutorial-2-yarp.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "46148" }, { "name": "C++", "bytes": "30878" }, { "name": "Perl", "bytes": "1705" }, { "name": "Python", "bytes": "1117700" }, { "name": "Shell", "bytes": "684" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:id="@+id/relativelayout_question" tools:context="com.dreamteam.octodrive.activity.QuestionActivity"> <com.parse.ParseImageView android:layout_width="150dp" android:layout_height="150dp" android:id="@+id/imageView_question" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Question Placeholder" android:id="@+id/textView_question" android:layout_below="@+id/imageView_question" android:layout_centerHorizontal="true" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Answer 1" android:id="@+id/checkBox_answer1" android:layout_below="@+id/textView_question" android:layout_alignParentStart="true" android:layout_marginTop="32dp" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Answer 2" android:id="@+id/checkBox_answer2" android:layout_below="@+id/checkBox_answer1" android:layout_alignParentStart="true" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Answer 3" android:id="@+id/checkBox_answer3" android:layout_below="@+id/checkBox_answer2" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/action_previous" android:id="@+id/button_prev" android:layout_alignParentBottom="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/action_next" android:id="@+id/button_next" android:layout_alignParentBottom="true" android:layout_toEndOf="@+id/button_prev" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/action_finish" android:id="@+id/button_finish" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" /> </RelativeLayout>
{ "content_hash": "194337ccaf0d3ca4ef9d9fd341820d4a", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 74, "avg_line_length": 38.06410256410256, "alnum_prop": 0.6682384641293365, "repo_name": "lordzsolt/OctoDrive", "id": "56b574cf685600e0aa85766bb8a21a938b0f8b0e", "size": "2969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_question.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "123832" } ], "symlink_target": "" }
exec &>hgsc_analysis.out ############################################ # Cross-population analysis of high-grade serous ovarian cancer does not support # four subtypes # # Way, G.P., Rudd, J., Wang, C., Hamidi, H., Fridley, L.B, # Konecny, G., Goode, E., Greene, C.S., Doherty, J.A. # ~~~~~~~~~~~~~~~~~~~~~ # This script stores instructions to reproduce the HGSC subtyping analysis # across populations. All scripts and relevant files are included in the # repository and the workflow depends on the running sequential scripts within # the larger folder structure. See the README for general information and # INSTALL.R for package dependencies. # This script is run using a Docker image # (see <https://hub.docker.com/r/gregway/hgsc_subtypes/>) # ~~~~~~~~~~~~~~~~~~~~~ ############################################ ################# # PART ZERO: # Download Mayo data ################# # COMBAT adjust Mayo data Rscript 1.DataInclusion/Scripts/processMayoEset/\ Agilent1and2and3_COMBAT_datamerge.R # Create an eset from the Mayo data # NOTE: This requires the Normalizer function from the Sleipnir library # (http://libsleipnir.bitbucket.org/) Rscript 1.DataInclusion/Scripts/processMayoEset/createMayoEset.R # Define Constants DATASETS="TCGA_eset mayo.eset GSE32062.GPL6480_eset GSE9891_eset" KMIN=2 KMAX=4 SEED=123 NSTARTS=20 NO_SHUFFLE=FALSE SHUFFLE=TRUE SAM_SUBSET='commongenes' ################# # PART ONE: # Dataset Selection and Inclusion ################# # ~~~~~~~~~~~~~~~~~~~~~ # This section will determine which samples meet a specific inclusion criteria # for use in downstream analyses # ~~~~~~~~~~~~~~~~~~~~~ # We are using data from curatedOvarianData version 1.8.0 # NOTE: The Mayo Clinic Data is not currently in curatedOvarianData. # Output the samples for each dataset that pass the inclusion criteria Rscript 1.DataInclusion/Scripts/A.getInclusion.R # (Table 1) # Output the common genes and the MAD (Median Absolute Deviation) genes to be # used in developing moderated t score vectors and in clustering, respectively. # This script will also output Venn diagrams for visualizing overlapping genes # (Sup. Fig. S1) #NOTE: Bonome (GSE12672) is removed following the across # dataset correlations analysis. Add it here. R --no-save --args $DATASETS "GSE26712_eset" < 1.DataInclusion/Scripts/\ B.getGenes.R ################# # PART TWO: # Run k means and SAM ################# # ~~~~~~~~~~~~~~~~~~~~~ # The scripts will take as inputs the samples and genes from the previous # section that passed the inclusion criteria. It will also run k means for # k min - k max, output several figures (moderated t score heatmaps, kmeans bar # chart distributions, correlation matrices) and tables (cluster membership by # dataset, within dataset cluster correlations) # ~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~ # SAM with MAD genes # ~~~~~~~~~~~~~ # Output across dataset correlations for MAD genes # NOTE: common genes used in downstream analyses R --no-save --args $KMIN $KMAX $NSTARTS $SEED FALSE $NO_SHUFFLE "madgenes" \ $DATASETS "GSE26712_eset" < 2.Clustering_DiffExprs/Scripts/A.run_kmeans_SAM.R # ~~~~~~~~~~~~~ # k means & SAM (with common genes) # ~~~~~~~~~~~~~ # Perform k means and SAM (Figure 1) R --no-save --args $KMIN $KMAX $NSTARTS $SEED FALSE $NO_SHUFFLE $SAM_SUBSET \ $DATASETS "GSE26712_eset" < 2.Clustering_DiffExprs/Scripts/A.run_kmeans_SAM.R # Output correlation matrices (Sup. Fig. S2) R --no-save --args $KMIN $KMAX $SEED Figures/CorrelationMatrix/ $DATASETS \ "GSE26712_eset" < 2.Clustering_DiffExprs/Scripts/B.CorrelationMatrix.R # Output k-means barcharts (Figure S8) R --no-save --args $KMIN $KMAX $DATASETS < 2.Clustering_DiffExprs/Scripts/\ C.KMeansBarCharts.R # Shuffle genes to compare across population correlations in real data R --no-save --args $KMIN $KMAX $NSTARTS $SEED FALSE $SHUFFLE $SAM_SUBSET \ $DATASETS "GSE26712_eset" < 2.Clustering_DiffExprs/Scripts/A.run_kmeans_SAM.R # ~~~~~~~~~~~~~ # NMF # ~~~~~~~~~~~~~ # Output consensus matrices, NMF cluster membership files (Sup. Figure S2) and # cophenetic coefficients (Sup. Figures S3-S7) R --no-save --args $KMIN $KMAX $NSTARTS $SEED $DATASETS "GSE26712_eset" \ < 2.Clustering_DiffExprs/Scripts/D.NMF.R # Run SAM on NMF clusters (TRUE argument forces NMF analysis) R --no-save --args $KMIN $KMAX $NSTARTS $SEED TRUE $NO_SHUFFLE $SAM_SUBSET \ $DATASETS "GSE26712_eset" < 2.Clustering_DiffExprs/Scripts/A.run_kmeans_SAM.R # ~~~~~~~~~~~~~ # k means vs. NMF # ~~~~~~~~~~~~~ # Compare k-means defined clusters with NMF defined clusters (Figure 2) R --no-save --args $DATASETS < 2.Clustering_DiffExprs/Scripts/E.kmeans_v_nmf.R # Compile table with all cluster membership information (Sup. Table S2) R --no-save --args $DATASETS < 2.Clustering_DiffExprs/Scripts/\ F.clusterMembership.R # ~~~~~~~~~~~~~ # Dataset Concordance # ~~~~~~~~~~~~~ # Investigate the similarities in cluster membership in original TCGA 2011 # paper, the Konecny 2014 paper, and the Tothill 2008 paper (Table 4) R --no-save < 2.Clustering_DiffExprs/Scripts/G.Dataset_concordance.R # ~~~~~~~~~~~~~ # Tothill LMP # ~~~~~~~~~~~~~ # Observe consensus matrices and cophenetic coefficients for Tothill dataset if # LMP samples are not removed. This is similar to the results presented by TCGA # supplementary figure S6.2 (Figure 3) R --no-save < 2.Clustering_DiffExprs/Scripts/H.TCGA_LMP_TothillPrediction.R ################# # PART THREE: # Goodness of Fit ################# # ~~~~~~~~~~~~~~~~~~~~~ # The section will output several figures, all different goodness of fit # metrics, for each dataset. The metrics include AIC, BIC, Gap Statistic, and # Silhouette Widths (Note: Cophenetic obtained in step 2) # ~~~~~~~~~~~~~~~~~~~~~ # Perform AIC, BIC, and silhouette width analyses R --no-save --args 2 8 20 $NSTARTS $SEED $DATASETS < \ 3.Fit/Scripts/A.GoodnessFit.R # Determine gap statistic # NOTE: This step was performed on the Discovery Cluster at Dartmouth College # R --no-save --args 8 250 20 50 $SEED $DATSETS < 3.Fit/Scripts/\ # B.GAP_GoodnessFit.R ################# # PART FOUR: # Survival ################# # ~~~~~~~~~~~~~~~~~~~~~ # This section will perform all survival analyses and output summary tables # ~~~~~~~~~~~~~~~~~~~~~ # Output Kaplan-Meier survival curves, and perform a cox proportional hazards # regression model (Sup. Fig. S11) R --no-save --args $DATASETS < 4.Survival/Scripts/A.Survival.R # Summarize the results of the survival analysis (Sup. Table S3) R --no-save --args $DATASETS < 4.Survival/Scripts/B.Summarize_Survival.R ################# # PART FIVE: # Gene and pathway Analyses ################# # ~~~~~~~~~~~~~~~~~~~~~ # Describe the cluster driving genes in common across populations # ~~~~~~~~~~~~~~~~~~~~~ # Output tables of cluster specific genes based on significant SAM FDR values R --no-save --args $DATASETS < 5.Pathway/Scripts/A.GeneEnrichment.R # The output of this script is input into a PANTHER pathways analysis # (http://pantherdb.org/) ################# # PART Six: # Immune Infiltrate Analysis ################# # ~~~~~~~~~~~~~~~~~~~~~ # This section will perform analysis of immune cell infiltration and # output figures characterizing results by subtype # ~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~ # ESTIMATE # ~~~~~~~~~~~~~ # Perform ESTIMATE analysis to observe immune/stromal cell # infiltration and infer a tumor purity for each individual tumor # sample R --no-save --args $DATASETS < 6.Immune_Infiltrate/Scripts/A.ESTIMATE.R # ~~~~~~~~~~~~~ # ssGSEA # ~~~~~~~~~~~~~ # Perform ssGSEA analysis to observe gene set enrichment of 22 leukocyte # signatures (LM22) R --no-save --args $DATASETS < 6.Immune_Infiltrate/Scripts/B.ssGSEA.R # ~~~~~~~~~~~~~ # MCPcounter # ~~~~~~~~~~~~~ # Perform MCPcounter analysis on Tothill to estimate the abundance of # immune and stromal infiltration into tumor samples Rscript 6.Immune_Infiltrate/Scripts/C.MCPcounter.R
{ "content_hash": "6bf7e2cc78971fdfe46a3eda3c65df73", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 80, "avg_line_length": 36.210045662100455, "alnum_prop": 0.6704918032786885, "repo_name": "gwaygenomics/hgsc_subtypes", "id": "48e488c547538b55536738821b63ca47209afed0", "size": "7943", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hgsc_subtypes_pipeline.sh", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Dockerfile", "bytes": "1744" }, { "name": "R", "bytes": "238946" }, { "name": "Shell", "bytes": "13252" } ], "symlink_target": "" }
namespace Linq { public sealed class Person { public string Name; public Person(string name) { Name = name; } public override string ToString() { return Name; } } }
{ "content_hash": "580afda4299f89f59885d04273bbc34d", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 41, "avg_line_length": 15.764705882352942, "alnum_prop": 0.44776119402985076, "repo_name": "mika-s/Misc", "id": "862169ca3707853ef485f7700b280fa8ed96820d", "size": "270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CSharp/Linq/Person.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "536" }, { "name": "C", "bytes": "2614" }, { "name": "C#", "bytes": "146624" }, { "name": "F#", "bytes": "10967" }, { "name": "JavaScript", "bytes": "9086" }, { "name": "Makefile", "bytes": "1729" }, { "name": "Python", "bytes": "1333" }, { "name": "Shell", "bytes": "56" }, { "name": "Vim Snippet", "bytes": "5950" } ], "symlink_target": "" }
import { get } from '@ember/object'; import { run } from '@ember/runloop'; import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; import JSONAPIAdapter from '@ember-data/adapter/json-api'; import Model, { attr, belongsTo, hasMany } from '@ember-data/model'; import JSONAPISerializer from '@ember-data/serializer/json-api'; module( 'integration/backwards-compat/non-dasherized-lookups - non dasherized lookups in application code finders', function(hooks) { setupTest(hooks); hooks.beforeEach(function() { const PostNote = Model.extend({ name: attr('string'), }); const ApplicationAdapter = JSONAPIAdapter.extend({ shouldBackgroundReloadRecord() { return false; }, }); this.owner.register('model:post-note', PostNote); this.owner.register('adapter:application', ApplicationAdapter); this.owner.register('serializer:application', JSONAPISerializer.extend()); }); test('can lookup records using camelCase strings', function(assert) { assert.expect(1); let store = this.owner.lookup('service:store'); run(() => { store.pushPayload('post-note', { data: { type: 'post-notes', id: '1', attributes: { name: 'Ember Data', }, }, }); }); run(() => { store.findRecord('postNote', 1).then(postNote => { assert.equal(get(postNote, 'name'), 'Ember Data', 'record found'); }); }); }); test('can lookup records using under_scored strings', function(assert) { assert.expect(1); let store = this.owner.lookup('service:store'); run(() => { store.pushPayload('post-note', { data: { type: 'post-notes', id: '1', attributes: { name: 'Ember Data', }, }, }); }); run(() => { store.findRecord('post_note', 1).then(postNote => { assert.equal(get(postNote, 'name'), 'Ember Data', 'record found'); }); }); }); } ); module( 'integration/backwards-compat/non-dasherized-lookups - non dasherized lookups in application code relationship macros', function(hooks) { setupTest(hooks); hooks.beforeEach(function() { const PostNote = Model.extend({ notePost: belongsTo('note-post', { async: false }), name: attr('string'), }); const NotePost = Model.extend({ name: attr('string'), }); const LongModelName = Model.extend({ postNotes: hasMany('post_note'), }); const ApplicationAdapter = JSONAPIAdapter.extend({ shouldBackgroundReloadRecord() { return false; }, }); this.owner.register('model:long-model-name', LongModelName); this.owner.register('model:note-post', NotePost); this.owner.register('model:post-note', PostNote); this.owner.register('adapter:application', ApplicationAdapter); this.owner.register('serializer:application', JSONAPISerializer.extend()); }); test('looks up belongsTo using camelCase strings', function(assert) { assert.expect(1); let store = this.owner.lookup('service:store'); run(() => { store.pushPayload('post-note', { data: { type: 'post-notes', id: '1', attributes: { name: 'Ember Data', }, relationships: { 'note-post': { data: { type: 'note-post', id: '1' }, }, }, }, }); store.pushPayload('notePost', { data: { type: 'note-posts', id: '1', attributes: { name: 'Inverse', }, }, }); }); run(() => { store.findRecord('post-note', 1).then(postNote => { assert.equal(get(postNote, 'notePost.name'), 'Inverse', 'inverse record found'); }); }); }); test('looks up belongsTo using under_scored strings', function(assert) { assert.expect(1); let store = this.owner.lookup('service:store'); run(() => { store.pushPayload('long_model_name', { data: { type: 'long-model-names', id: '1', attributes: {}, relationships: { 'post-notes': { data: [{ type: 'post-note', id: '1' }], }, }, }, }); store.pushPayload('post-note', { data: { type: 'post-notes', id: '1', attributes: { name: 'Ember Data', }, }, }); }); run(() => { store.findRecord('long_model_name', 1).then(longModelName => { const postNotes = get(longModelName, 'postNotes').toArray(); assert.deepEqual(postNotes, [store.peekRecord('postNote', 1)], 'inverse records found'); }); }); }); } );
{ "content_hash": "cf9259f166631a28ef9f9195c8b8b964", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 121, "avg_line_length": 26.564766839378237, "alnum_prop": 0.5162863272869124, "repo_name": "arenoir/data", "id": "ec1dc922bdc7464504d2d2c996a51fac30fe5c90", "size": "5127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/-ember-data/tests/integration/backwards-compat/non-dasherized-lookups-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2521" }, { "name": "JavaScript", "bytes": "1831319" }, { "name": "Ruby", "bytes": "1139" }, { "name": "Shell", "bytes": "4920" } ], "symlink_target": "" }
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :current_user def current_user @current_user ||= User.where(id: session[:user_id]).first if session[:user_id] end def authorize redirect_to new_user_path unless current_user end def logged_in? current_user != nil end end
{ "content_hash": "9a2c84aaeaf2176c9c7763f4c1d3789a", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 82, "avg_line_length": 24.473684210526315, "alnum_prop": 0.7182795698924731, "repo_name": "jengjao515/emoticom", "id": "e42d0c8b0938f83e15aabf42aa5a9b6fceb148f0", "size": "465", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/application_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1736" }, { "name": "CoffeeScript", "bytes": "211" }, { "name": "HTML", "bytes": "8050" }, { "name": "JavaScript", "bytes": "1456" }, { "name": "Ruby", "bytes": "25603" } ], "symlink_target": "" }
package rhogenwizard.project; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import rhogenwizard.Activator; import rhogenwizard.BuildInfoHolder; import rhogenwizard.project.extension.BadProjectTagException; import rhogenwizard.project.extension.ProjectNotFoundException; public class ProjectFactory implements IProjectFactory { private static ProjectFactory factoryInstance = null; public static IProjectFactory getInstance() { if (factoryInstance == null) factoryInstance = new ProjectFactory(); return (IProjectFactory) factoryInstance; } public IPath getWorkspaceDir() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IPath location = root.getLocation(); return location; } /** * Just do the basics: create a basic project. * * @param location * @param projectName * @throws CoreException */ private IProject createBaseProject(BuildInfoHolder projectInfo) throws CoreException { // it is acceptable to use the ResourcesPlugin class IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectInfo.appName); if (newProject.exists()) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Project " + projectInfo.appName + " already exists.")); } IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName()); if (!projectInfo.isInDefaultWs) { if (projectInfo.existCreate && !isProjectLocationInWorkspace(projectInfo.appDir)) { desc.setLocation(projectInfo.getAppDirPath()); } else if (!projectInfo.existCreate) { desc.setLocation(projectInfo.getAppDirPath()); } } newProject.create(desc, new NullProgressMonitor()); if (!newProject.isOpen()) { newProject.open(new NullProgressMonitor()); } return newProject; } private IRhomobileProject createRhomobileProject(Class<? extends IRhomobileProject> projectTag, IProject project) throws BadProjectTagException { if (projectTag.equals(RhodesProject.class)) { return new RhodesProject(project); } else if (projectTag.equals(RhoconnectProject.class)) { return new RhoconnectProject(project); } else if (projectTag.equals(RhoelementsProject.class)) { return new RhoelementsProject(project); } throw new BadProjectTagException(projectTag); } public boolean isProjectLocationInWorkspace(final String projectPath) { String wsPath = getWorkspaceDir().toOSString(); return projectPath.toLowerCase().contains(wsPath.toLowerCase()); } public IRhomobileProject createProject(Class<? extends IRhomobileProject> projectTag, BuildInfoHolder projectInfo) throws CoreException, ProjectNotFoundException, BadProjectTagException { Assert.isNotNull(projectInfo.appName); Assert.isTrue(projectInfo.appName.trim().length() != 0); IProject project = createBaseProject(projectInfo); IRhomobileProject rhoProject = createRhomobileProject(projectTag, project); rhoProject.addNature(); return rhoProject; } @Override public IProject getSelectedProject() { IProject project = null; IWorkbenchWindow[] workbenchWindows = PlatformUI.getWorkbench().getWorkbenchWindows(); if (workbenchWindows.length > 0) { IWorkbenchPage page = workbenchWindows[0].getActivePage(); ISelection selection = page.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection sel = (IStructuredSelection) selection; Object res = sel.getFirstElement(); if (res instanceof IResource) { project = ((IResource)res).getProject(); } } } return project; } @Override public IRhomobileProject convertFromProject(IProject project) throws BadProjectTagException { if (RhodesProject.checkNature(project)) { return createRhomobileProject(RhodesProject.class, project); } else if (RhoconnectProject.checkNature(project)) { return createRhomobileProject(RhoconnectProject.class, project); } else if (RhoelementsProject.checkNature(project)) { return createRhomobileProject(RhoelementsProject.class, project); } throw new BadProjectTagException(IProject.class); } @Override public Class<?> typeFromProject(IProject project) throws BadProjectTagException { if (RhodesProject.checkNature(project)) { return RhodesProject.class; } else if (RhoconnectProject.checkNature(project)) { return RhoconnectProject.class; } else if (RhoelementsProject.checkNature(project)) { return RhoelementsProject.class; } throw new BadProjectTagException(IProject.class); } }
{ "content_hash": "89392be592c6945a5060548d493a6c69", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 147, "avg_line_length": 29.77720207253886, "alnum_prop": 0.7130676874891247, "repo_name": "rhomobile/rhostudio", "id": "3277acaadb298b8d40e29d639f65e840379c3093", "size": "5747", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rhogen-wizard/src/rhogenwizard/project/ProjectFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "773" }, { "name": "Java", "bytes": "669141" }, { "name": "Objective-J", "bytes": "15554" }, { "name": "Ruby", "bytes": "6318" } ], "symlink_target": "" }
/** */ package uk.ac.kcl.inf.robotics.rigidBodies.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import uk.ac.kcl.inf.robotics.rigidBodies.NumberLiteral; import uk.ac.kcl.inf.robotics.rigidBodies.RigidBodiesPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Number Literal</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link uk.ac.kcl.inf.robotics.rigidBodies.impl.NumberLiteralImpl#isNeg <em>Neg</em>}</li> * <li>{@link uk.ac.kcl.inf.robotics.rigidBodies.impl.NumberLiteralImpl#getValue <em>Value</em>}</li> * </ul> * * @generated */ public class NumberLiteralImpl extends ExpressionImpl implements NumberLiteral { /** * The default value of the '{@link #isNeg() <em>Neg</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isNeg() * @generated * @ordered */ protected static final boolean NEG_EDEFAULT = false; /** * The cached value of the '{@link #isNeg() <em>Neg</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isNeg() * @generated * @ordered */ protected boolean neg = NEG_EDEFAULT; /** * The default value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected static final String VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected String value = VALUE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected NumberLiteralImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RigidBodiesPackage.Literals.NUMBER_LITERAL; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isNeg() { return neg; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setNeg(boolean newNeg) { boolean oldNeg = neg; neg = newNeg; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RigidBodiesPackage.NUMBER_LITERAL__NEG, oldNeg, neg)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setValue(String newValue) { String oldValue = value; value = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RigidBodiesPackage.NUMBER_LITERAL__VALUE, oldValue, value)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case RigidBodiesPackage.NUMBER_LITERAL__NEG: return isNeg(); case RigidBodiesPackage.NUMBER_LITERAL__VALUE: return getValue(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case RigidBodiesPackage.NUMBER_LITERAL__NEG: setNeg((Boolean)newValue); return; case RigidBodiesPackage.NUMBER_LITERAL__VALUE: setValue((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case RigidBodiesPackage.NUMBER_LITERAL__NEG: setNeg(NEG_EDEFAULT); return; case RigidBodiesPackage.NUMBER_LITERAL__VALUE: setValue(VALUE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case RigidBodiesPackage.NUMBER_LITERAL__NEG: return neg != NEG_EDEFAULT; case RigidBodiesPackage.NUMBER_LITERAL__VALUE: return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (neg: "); result.append(neg); result.append(", value: "); result.append(value); result.append(')'); return result.toString(); } } //NumberLiteralImpl
{ "content_hash": "9e9e4758bc6f0f1f63290eabe87d4b98", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 120, "avg_line_length": 22.400862068965516, "alnum_prop": 0.5918799307292669, "repo_name": "szschaler/RigidBodies", "id": "923c9995b2879ce9b1f14753c3766dfa1026f2b8", "size": "5197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "uk.ac.kcl.inf.robotics.rigid_bodies/src-gen/uk/ac/kcl/inf/robotics/rigidBodies/impl/NumberLiteralImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "GAP", "bytes": "277754" }, { "name": "Java", "bytes": "3224683" }, { "name": "Matlab", "bytes": "17117" }, { "name": "Xtend", "bytes": "56499" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Eucalyptus xanthope A.R.Bean & Brooker ### Remarks null
{ "content_hash": "b84950f4cc66e3e0cac401d455d6fba6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 12.923076923076923, "alnum_prop": 0.7142857142857143, "repo_name": "mdoering/backbone", "id": "ad888493ca7cbba38976fd3f767812966b1960ab", "size": "255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Corymbia/Corymbia xanthope/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
layout: post title: "Surviving Burnout" tags: [burnout, "mental health"] link: http://dev-human.io/~squinones/surviving-burnout share: true --- I wrote a short piece about my experiences with occupational burnout for the absolutely fantastic site [dev-human](http://dev-human.io) Please check it out [here](http://dev-human.io/~squinones/surviving-burnout)
{ "content_hash": "c0971c5a72a9f3b7f5b0a1f0bdd92a62", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 135, "avg_line_length": 35.9, "alnum_prop": 0.7632311977715878, "repo_name": "squinones/squinones.github.io", "id": "c6cb56b5af06edcca52a9a85631fda14a90d51d9", "size": "363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2015-10-14-surviving-burnout.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "53098" }, { "name": "HTML", "bytes": "30900" }, { "name": "JavaScript", "bytes": "64238" }, { "name": "Ruby", "bytes": "3633" }, { "name": "Shell", "bytes": "76" } ], "symlink_target": "" }
package models.core.security import java.security.{NoSuchAlgorithmException, SecureRandom} import java.security.spec.{InvalidKeySpecException, KeySpec} import javax.crypto.SecretKeyFactory import javax.crypto.spec.PBEKeySpec object PasswordEncryption { @throws[NoSuchAlgorithmException]("if the algorithm doesn't exists") @throws[InvalidKeySpecException] def authenticate(attemptedPassword: String, encryptedPassword: String, salt: String): Boolean = { val encryptedAttemptedPassword: String = getEncryptedPassword(attemptedPassword, salt) encryptedPassword == encryptedAttemptedPassword } @throws[NoSuchAlgorithmException]("if the algorithm doesn't exists") @throws[InvalidKeySpecException] def getEncryptedPassword(password: String, salt: String, algorithm: String = "PBKDF2WithHmacSHA1"): String = { val derivedKeyLength: Int = 160 val iterations: Int = 50000 val spec: KeySpec = new PBEKeySpec(password.toCharArray, salt.grouped(2).map(Integer.parseInt(_, 16).toByte).toArray, iterations, derivedKeyLength) val factory: SecretKeyFactory = SecretKeyFactory.getInstance(algorithm) factory.generateSecret(spec).getEncoded.mkString } @throws[NoSuchAlgorithmException] def generateSalt(instance: String = "SHA1PRNG", saltSize: Int = 16): String = { val random: SecureRandom = SecureRandom.getInstance(instance) val salt: Array[Byte] = Array.ofDim[Byte](saltSize) random.nextBytes(salt) salt.map("%02X" format _).mkString } }
{ "content_hash": "0e169e9f647983b16422a243586b39c2", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 151, "avg_line_length": 42.714285714285715, "alnum_prop": 0.7752508361204014, "repo_name": "HackerSchool/Passport", "id": "95a95e8a35452dd22028c3994202535a432e4b6a", "size": "1495", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "app/models/core/security/PasswordEncryption.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "2146" }, { "name": "CSS", "bytes": "6070" }, { "name": "HTML", "bytes": "29854" }, { "name": "JavaScript", "bytes": "14727" }, { "name": "PHP", "bytes": "2476" }, { "name": "Scala", "bytes": "20185" } ], "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 (version 1.7.0_45) on Tue Jan 07 16:24:28 PST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class com.google.android.apps.common.testing.ui.espresso.action.EditorAction (TestKit 1.1 API)</title> <meta name="date" content="2014-01-07"> <link rel="stylesheet" type="text/css" href="../../../../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.google.android.apps.common.testing.ui.espresso.action.EditorAction (TestKit 1.1 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../../../com/google/android/apps/common/testing/ui/espresso/action/EditorAction.html" title="class in com.google.android.apps.common.testing.ui.espresso.action">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../../../index.html?com/google/android/apps/common/testing/ui/espresso/action/class-use/EditorAction.html" target="_top">Frames</a></li> <li><a href="EditorAction.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.google.android.apps.common.testing.ui.espresso.action.EditorAction" class="title">Uses of Class<br>com.google.android.apps.common.testing.ui.espresso.action.EditorAction</h2> </div> <div class="classUseContainer">No usage of com.google.android.apps.common.testing.ui.espresso.action.EditorAction</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../../../com/google/android/apps/common/testing/ui/espresso/action/EditorAction.html" title="class in com.google.android.apps.common.testing.ui.espresso.action">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../../../index.html?com/google/android/apps/common/testing/ui/espresso/action/class-use/EditorAction.html" target="_top">Frames</a></li> <li><a href="EditorAction.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014. All rights reserved.</small></p> </body> </html>
{ "content_hash": "db43e7c8ebd52200141603f5dab4d429", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 209, "avg_line_length": 41.957264957264954, "alnum_prop": 0.6048074964351192, "repo_name": "DocuSignDev/android-test-kit", "id": "ad44e8747be6f69b06d3ba29bad8cb9668cfa114", "size": "4909", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "docs/javadocs/apidocs/com/google/android/apps/common/testing/ui/espresso/action/class-use/EditorAction.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "Groovy", "bytes": "6053" }, { "name": "Java", "bytes": "649243" } ], "symlink_target": "" }
package com.Kuesty.fragments; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.Kuesty.R; import com.actionbarsherlock.app.SherlockFragment; public class RightMenuFragment extends SherlockFragment{ private View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_rightmenu, container, false); return view; } }
{ "content_hash": "d7218398aae7001fd7b122fe3f41c301", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 73, "avg_line_length": 23.193548387096776, "alnum_prop": 0.803894297635605, "repo_name": "Urucas/kuesty-as", "id": "133819f66e6fa8c6fc5897c48e42aeb9f28b8032", "size": "719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com.Kuesty/src/main/java/com/Kuesty/fragments/RightMenuFragment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "1158" }, { "name": "Java", "bytes": "20959" } ], "symlink_target": "" }
{% extends "reports/async/tabular.html" %} {% load hq_shared_tags %} {% load i18n %} {% block js-inline %} {{ block.super }} <script type="text/javascript"> $(function() { var select = $(".dataTables_length select"); select.val(-1); select.change(); }); </script> {% endblock %} {% block reportcontent %} {{ block.super }} {% if is_previewer %} <form action="{% url "fri_upload_message_bank" domain %}" method="post" enctype="multipart/form-data" style="padding: 10px;"> {% csrf_token %} <h4>Upload Additional Messages</h4> <div style="border-bottom: 1px solid #CCC; padding: 10px;"> <input type="file" name="message_bank_file" /> <input type="submit" class="btn btn-primary" value="Upload" /> </div> <div style="padding: 10px;"> NOTE: Message bank file must be an Excel 2007 or higher (.xlsx) file containing two columns with column headers "ID" and "Message". </div> </form> {% endif %} {% endblock %}
{ "content_hash": "ca8091c87c7d731b32f1600578d46f53", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 143, "avg_line_length": 36.06896551724138, "alnum_prop": 0.5774378585086042, "repo_name": "qedsoftware/commcare-hq", "id": "10aee37943b8ef5fad831e3db4224b64db05f319", "size": "1046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "custom/fri/templates/fri/message_bank.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "15950" }, { "name": "CSS", "bytes": "508392" }, { "name": "HTML", "bytes": "2869325" }, { "name": "JavaScript", "bytes": "2395360" }, { "name": "PHP", "bytes": "2232" }, { "name": "PLpgSQL", "bytes": "125298" }, { "name": "Python", "bytes": "14670713" }, { "name": "Shell", "bytes": "37514" } ], "symlink_target": "" }
using System; using Should; using Xunit; namespace AutoMapper.UnitTests.Bug { public class NonExistingProperty : AutoMapperSpecBase { public class Source { } public class Destination { } [Fact] public void Should_report_missing_property() { var mapping = Mapper.CreateMap<Source, Destination>(); new Action(() => mapping.ForMember("X", s => { })).ShouldThrow<ArgumentOutOfRangeException>(); } } }
{ "content_hash": "95c2b23f00cf2193a9ec0140fb6e7e9d", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 106, "avg_line_length": 21.541666666666668, "alnum_prop": 0.5764023210831721, "repo_name": "ssalaberry/AutoMapper", "id": "f59c23370c43f90ed5c8ecadc5c5f40cb31846d3", "size": "519", "binary": false, "copies": "11", "ref": "refs/heads/develop", "path": "src/UnitTests/Bug/NonExistingProperty.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1458" }, { "name": "C#", "bytes": "1251573" }, { "name": "PowerShell", "bytes": "19035" }, { "name": "XSLT", "bytes": "10095" } ], "symlink_target": "" }
- Working towards initial release
{ "content_hash": "8b4d0f7f8b1aaf17fee409fc84f3c1ef", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 33, "avg_line_length": 34, "alnum_prop": 0.8235294117647058, "repo_name": "arnold-almeida/laravel-elasticsearch", "id": "b65731e324f3d8011b25ef148b9752c7e5873005", "size": "46", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "changes.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "5855" } ], "symlink_target": "" }
package com.enjoy.love.web.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; public class HttpHeaderUtils { /** * * 获得真实IP地址 */ public static String getClientIP(HttpServletRequest request) { /* * String ip = request.getRemoteAddr(); String originIP = * request.getHeader("x-forwarded-for"); if (originIP == null || * originIP.length() == 0) { return ip; } else { return originIP; } */ String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } /** * 获得referer * * @param request * @return */ public static String getReferer(HttpServletRequest request) { return request.getHeader("Referer"); } /** * 获得所有的cookie * * @param request * @return */ public static Map<String, Cookie> getAllCookie(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); Cookie[] cookies = request.getCookies(); if (null != cookies) { int length = cookies.length; for (int i = 0; i < length; i++) { cookieMap.put(cookies[i].getName(), cookies[i]); } } return cookieMap; } /** * 取得某个cookie的值 * * @param cookieName * @param request * @return */ public static String getCookieValue(String cookieName, HttpServletRequest request) { Cookie cookie = getAllCookie(request).get(cookieName); if (cookie != null) { return cookie.getValue(); } else { return ""; } } /** * 获得URL,同时附加所有参数 * * @param request * @return */ @SuppressWarnings("rawtypes") public static String getRequestURLWithParameter(HttpServletRequest request) { StringBuffer buffer = request.getRequestURL(); Map parameter = request.getParameterMap(); if (null != parameter && !parameter.isEmpty()) { buffer.append("?"); Iterator keys = parameter.keySet().iterator(); String key = null; String[] value = null; while (keys.hasNext()) { key = (String) keys.next(); value = request.getParameterValues(key); if ((null == value) || (value.length == 0)) { buffer.append(key).append("=").append(""); } else if (value.length > 0) { buffer.append(key).append("=").append(value[0]); } if (keys.hasNext()) { buffer.append("&"); } } } return buffer.toString(); } /** * 获得URL,不附加任何输入参数 * * @param request * @return */ public static String getRequestURL(HttpServletRequest request) { StringBuffer buffer = request.getRequestURL(); return buffer.toString(); } /** * 获得 Http://xxxx:yyy/ * * @param request * @return */ public static String getHttpRootAddress(HttpServletRequest request) { String protocol = request.getProtocol(); if (StringUtils.isNotBlank(protocol)) { int p = protocol.indexOf("/"); if (p > -1) { protocol = protocol.substring(0, p); } } StringBuffer buffer = new StringBuffer(protocol); buffer.append("://"); buffer.append(request.getServerName()); buffer.append(":"); buffer.append(request.getServerPort()); String contextPath = request.getContextPath(); if (StringUtils.isNotBlank(contextPath)) { buffer.append("/").append(contextPath); } return buffer.toString(); } }
{ "content_hash": "e9cf190d72ee9cd41d992b72c59fe88a", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 78, "avg_line_length": 25.614864864864863, "alnum_prop": 0.622527037720918, "repo_name": "520github/enjoy-love", "id": "fde88e1830dbdb4a264596e7ace10a2af63869e6", "size": "3879", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/enjoy/love/web/util/HttpHeaderUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "140530" }, { "name": "HTML", "bytes": "103824" }, { "name": "Java", "bytes": "339897" }, { "name": "JavaScript", "bytes": "1544370" } ], "symlink_target": "" }
@interface dengLuViewController () @end @implementation dengLuViewController -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; self.navigationController.navigationBar.hidden = YES; self.navigationController.tabBarController.tabBar.hidden = YES; } -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; self.navigationController.navigationBar.hidden = NO; self.navigationController.tabBarController.tabBar.hidden = NO; } - (void)viewDidLoad { [super viewDidLoad]; UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds]; imageView.image =[UIImage imageNamed:@"brand_bg.png"]; [self.view addSubview:imageView]; [self createUI]; [self createTextField]; } -(void)createUI{ UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-50, 30, 100, 20)]; lable.text = @"登录良仓"; lable.backgroundColor = [UIColor clearColor]; lable.textAlignment = NSTextAlignmentCenter; lable.textColor = [UIColor whiteColor]; lable.font = [UIFont systemFontOfSize:18]; [self.view addSubview:lable]; UIButton *button =[[UIButton alloc]initWithFrame:CGRectMake(10, 30, 20, 20)]; [button setBackgroundImage:[UIImage imageNamed:@"loginBack.png"] forState:UIControlStateNormal]; [button addTarget:self action:@selector(button) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } -(void)createTextField{ UIImageView *nameView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 100, self.view.frame.size.width-80, 40)]; nameView.image =[UIImage imageNamed:@"loginUsername.png"]; nameView.userInteractionEnabled = YES; [self.view addSubview:nameView]; UITextField *nameField = [[UITextField alloc]initWithFrame:CGRectMake(48 , 5, self.view.frame.size.width-128, 30)]; nameField.backgroundColor = [UIColor clearColor]; nameField.placeholder = @" 手机号/用户名/邮箱"; nameField.tag = 10; nameField.textColor = [UIColor whiteColor]; [nameView addSubview:nameField]; UIImageView *passWordView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 160, self.view.frame.size.width-80, 40)]; passWordView.image =[UIImage imageNamed:@"loginPassWord.png"]; passWordView.userInteractionEnabled = YES; [self.view addSubview:passWordView]; UITextField *passWordField = [[UITextField alloc]initWithFrame:CGRectMake(48, 5, self.view.frame.size.width-128, 30)]; passWordField.backgroundColor = [UIColor clearColor]; passWordField.placeholder = @" 请输入密码"; passWordField.textColor = [UIColor whiteColor]; passWordField.tag = 20; [passWordView addSubview:passWordField]; UIButton *dendluButton = [[UIButton alloc]initWithFrame:CGRectMake(50, 240, self.view.frame.size.width-100, 40)]; [dendluButton setBackgroundImage:[UIImage imageNamed:@"bg_nav_bar.png"] forState:UIControlStateNormal]; [dendluButton setTitle:@"登录" forState:UIControlStateNormal]; [dendluButton addTarget:self action:@selector(dengluClicked) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:dendluButton]; } -(void)button{ [self.navigationController popViewControllerAnimated:YES]; } -(void)dengluClicked{ UITextField *textField1 = (id)[self.view viewWithTag:10]; UITextField *textField2 = (id)[self.view viewWithTag:20]; //取出所有已存在的用户 NSString *path = [NSString stringWithFormat:@"%@/Documents/UserInfo.plist",NSHomeDirectory()]; NSArray *array = [NSArray arrayWithContentsOfFile:path]; BOOL isHaven = NO;//标记用户是否存在 BOOL isError = NO;// 标记密码是否错误 for(NSData *data in array) { userInfo *user = [NSKeyedUnarchiver unarchiveObjectWithData:data]; if ([user.userName isEqualToString:textField1.text]) { isHaven = YES; if (![user.password isEqualToString:textField2.text]) { isError = YES; } //结束循环 break; } } if(isHaven && isError == NO) { [[NSUserDefaults standardUserDefaults]setObject:@YES forKey:@"isLogin"]; [self.navigationController popToRootViewControllerAnimated:YES]; }else if(isHaven == NO) { UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名不存在" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil]; alertView.alertViewStyle = UIAlertViewStyleDefault; [alertView show]; NSLog(@"用户不存在"); }else { UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"密码错误" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil]; alertView.alertViewStyle = UIAlertViewStyleDefault; [alertView show]; NSLog(@"密码错误"); } NSUserDefaults *defauts = [NSUserDefaults standardUserDefaults]; [defauts setObject:textField1.text forKey:@"showText"]; [defauts synchronize]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end
{ "content_hash": "4969fbb2aee7f20b4d3071e4bdfc9b5a", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 157, "avg_line_length": 27.804123711340207, "alnum_prop": 0.6646273637374861, "repo_name": "Sss-Song/BSBD", "id": "8e8bfe5c202220856b115ac7a8d6007744963d5f", "size": "5771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "良仓/个人中心/登录/dengLuViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "115743" }, { "name": "HTML", "bytes": "4555" }, { "name": "Objective-C", "bytes": "1533109" } ], "symlink_target": "" }
package s3 import ( "context" "io" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/s3" ) type writer struct { ctx context.Context client *s3.Client bucket string key string done chan struct{} isOpened bool pw *io.PipeWriter err error } // newWriter returns a writer that creates and writes to an S3 object. If an object with the same // bucket and key already exists, it will be overwritten. The caller must call Close on the writer // when done writing for the object to become available. func newWriter( ctx context.Context, client *s3.Client, bucket string, key string, ) *writer { return &writer{ ctx: ctx, client: client, bucket: bucket, key: key, done: make(chan struct{}), } } // Write writes data to a pipe. func (w *writer) Write(p []byte) (int, error) { if !w.isOpened { w.open() } return w.pw.Write(p) } // Close completes the write operation. func (w *writer) Close() error { if !w.isOpened { w.open() } if err := w.pw.Close(); err != nil { return err } <-w.done return w.err } // open creates a pipe for writing to the S3 object. func (w *writer) open() { pr, pw := io.Pipe() w.pw = pw go func() { defer close(w.done) params := &s3.PutObjectInput{ Bucket: aws.String(w.bucket), Key: aws.String(w.key), Body: io.Reader(pr), } uploader := manager.NewUploader(w.client) if _, err := uploader.Upload(w.ctx, params); err != nil { w.err = err pr.CloseWithError(err) } }() w.isOpened = true }
{ "content_hash": "337f56af2311e7e98311e9c1e5d17a87", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 98, "avg_line_length": 18.88235294117647, "alnum_prop": 0.6429906542056075, "repo_name": "apache/beam", "id": "3f16e770d1d568c4fbf0f505d975ae19fa0c79eb", "size": "2400", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sdks/go/pkg/beam/io/filesystem/s3/writer.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1598" }, { "name": "C", "bytes": "3869" }, { "name": "CSS", "bytes": "4957" }, { "name": "Cython", "bytes": "70760" }, { "name": "Dart", "bytes": "912687" }, { "name": "Dockerfile", "bytes": "59805" }, { "name": "FreeMarker", "bytes": "7933" }, { "name": "Go", "bytes": "5508697" }, { "name": "Groovy", "bytes": "936956" }, { "name": "HCL", "bytes": "103872" }, { "name": "HTML", "bytes": "184151" }, { "name": "Java", "bytes": "41223435" }, { "name": "JavaScript", "bytes": "119576" }, { "name": "Jupyter Notebook", "bytes": "55818" }, { "name": "Kotlin", "bytes": "220768" }, { "name": "Lua", "bytes": "3620" }, { "name": "Python", "bytes": "10728612" }, { "name": "Rust", "bytes": "5168" }, { "name": "SCSS", "bytes": "318364" }, { "name": "Sass", "bytes": "25954" }, { "name": "Scala", "bytes": "1429" }, { "name": "Shell", "bytes": "375834" }, { "name": "Smarty", "bytes": "2618" }, { "name": "Thrift", "bytes": "3260" }, { "name": "TypeScript", "bytes": "1997829" } ], "symlink_target": "" }
package slick.driver import java.util.UUID import java.sql.{PreparedStatement, ResultSet} import scala.concurrent.ExecutionContext import slick.dbio._ import slick.lifted._ import slick.profile.{SqlProfile, RelationalProfile, Capability} import slick.ast.{SequenceNode, Library, FieldSymbol, Node, Insert, InsertColumn, Select, ElementSymbol, ColumnOption } import slick.ast.Util._ import slick.util.MacroSupport.macroSupportInterpolation import slick.compiler.CompilerState import slick.jdbc.meta.{MIndexInfo, MColumn, MTable} import slick.jdbc.{JdbcModelBuilder, JdbcType} import slick.model.Model /** Slick driver for PostgreSQL. * * This driver implements [[slick.driver.JdbcProfile]] * ''without'' the following capabilities: * * <ul> * <li>[[slick.driver.JdbcProfile.capabilities.insertOrUpdate]]: * InsertOrUpdate operations are emulated on the server side with a single * JDBC statement executing multiple server-side statements in a transaction. * This is faster than a client-side emulation but may still fail due to * concurrent updates. InsertOrUpdate operations with `returning` are * emulated on the client side.</li> * <li>[[slick.driver.JdbcProfile.capabilities.nullableNoDefault]]: * Nullable columns always have NULL as a default according to the SQL * standard. Consequently Postgres treats no specifying a default value * just as specifying NULL and reports NULL as the default value. * Some other dbms treat queries with no default as NULL default, but * distinguish NULL from no default value in the meta data.</li> * <li>[[slick.driver.JdbcProfile.capabilities.supportsByte]]: * Postgres doesn't have a corresponding type for Byte. * SMALLINT is used instead and mapped to Short in the Slick model.</li> * </ul> * * Notes: * * <ul> * <li>[[slick.profile.RelationalProfile.capabilities.typeBlob]]: * The default implementation of the <code>Blob</code> type uses the * database type <code>lo</code> and the stored procedure * <code>lo_manage</code>, both of which are provided by the "lo" * extension in PostgreSQL.</li> * </ul> */ trait PostgresDriver extends JdbcDriver { driver => override protected def computeCapabilities: Set[Capability] = (super.computeCapabilities - JdbcProfile.capabilities.insertOrUpdate - JdbcProfile.capabilities.nullableNoDefault - JdbcProfile.capabilities.supportsByte ) class ModelBuilder(mTables: Seq[MTable], ignoreInvalidDefaults: Boolean)(implicit ec: ExecutionContext) extends JdbcModelBuilder(mTables, ignoreInvalidDefaults) { override def createTableNamer(mTable: MTable): TableNamer = new TableNamer(mTable) { override def schema = super.schema.filter(_ != "public") // remove default schema } override def createColumnBuilder(tableBuilder: TableBuilder, meta: MColumn): ColumnBuilder = new ColumnBuilder(tableBuilder, meta) { val VarCharPattern = "^'(.*)'::character varying$".r val IntPattern = "^\\((-?[0-9]*)\\)$".r override def default = meta.columnDef.map((_,tpe)).collect{ case ("true","Boolean") => Some(Some(true)) case ("false","Boolean") => Some(Some(false)) case (VarCharPattern(str),"String") => Some(Some(str)) case (IntPattern(v),"Int") => Some(Some(v.toInt)) case (IntPattern(v),"Long") => Some(Some(v.toLong)) case ("NULL::character varying","String") => Some(None) case (v,"java.util.UUID") => { val uuid = v.replaceAll("[\'\"]", "") //strip quotes .stripSuffix("::uuid") //strip suffix Some(Some(java.util.UUID.fromString(uuid))) } }.getOrElse{ val d = super.default if(meta.nullable == Some(true) && d == None){ Some(None) } else d } override def length: Option[Int] = { val l = super.length if(tpe == "String" && varying && l == Some(2147483647)) None else l } override def tpe = meta.typeName match { case "bytea" => "Array[Byte]" case "lo" if meta.sqlType == java.sql.Types.DISTINCT => "java.sql.Blob" case "uuid" => "java.util.UUID" case _ => super.tpe } } override def createIndexBuilder(tableBuilder: TableBuilder, meta: Seq[MIndexInfo]): IndexBuilder = new IndexBuilder(tableBuilder, meta) { // FIXME: this needs a test override def columns = super.columns.map(_.stripPrefix("\"").stripSuffix("\"")) } } override def createModelBuilder(tables: Seq[MTable], ignoreInvalidDefaults: Boolean)(implicit ec: ExecutionContext): JdbcModelBuilder = new ModelBuilder(tables, ignoreInvalidDefaults) override def defaultTables(implicit ec: ExecutionContext): DBIO[Seq[MTable]] = MTable.getTables(None, None, None, Some(Seq("TABLE"))) override val columnTypes = new JdbcTypes override def createQueryBuilder(n: Node, state: CompilerState): QueryBuilder = new QueryBuilder(n, state) override def createUpsertBuilder(node: Insert): InsertBuilder = new UpsertBuilder(node) override def createTableDDLBuilder(table: Table[_]): TableDDLBuilder = new TableDDLBuilder(table) override def createColumnDDLBuilder(column: FieldSymbol, table: Table[_]): ColumnDDLBuilder = new ColumnDDLBuilder(column) override protected lazy val useServerSideUpsert = true override protected lazy val useTransactionForUpsert = true override protected lazy val useServerSideUpsertReturning = false override def defaultSqlTypeName(tmd: JdbcType[_], size: Option[RelationalProfile.ColumnOption.Length]): String = tmd.sqlType match { case java.sql.Types.VARCHAR => size.fold("VARCHAR")(l => if(l.varying) s"VARCHAR(${l.length})" else s"CHAR(${l.length})") case java.sql.Types.BLOB => "lo" case java.sql.Types.DOUBLE => "DOUBLE PRECISION" /* PostgreSQL does not have a TINYINT type, so we use SMALLINT instead. */ case java.sql.Types.TINYINT => "SMALLINT" case _ => super.defaultSqlTypeName(tmd, size) } class QueryBuilder(tree: Node, state: CompilerState) extends super.QueryBuilder(tree, state) { override protected val concatOperator = Some("||") override protected val quotedJdbcFns = Some(Vector(Library.Database, Library.User)) override protected def buildFetchOffsetClause(fetch: Option[Node], offset: Option[Node]) = (fetch, offset) match { case (Some(t), Some(d)) => b"\nlimit $t offset $d" case (Some(t), None ) => b"\nlimit $t" case (None, Some(d)) => b"\noffset $d" case _ => } override def expr(n: Node, skipParens: Boolean = false) = n match { case Library.UCase(ch) => b"upper($ch)" case Library.LCase(ch) => b"lower($ch)" case Library.IfNull(ch, d) => b"coalesce($ch, $d)" case Library.NextValue(SequenceNode(name)) => b"nextval('$name')" case Library.CurrentValue(SequenceNode(name)) => b"currval('$name')" case _ => super.expr(n, skipParens) } } class UpsertBuilder(ins: Insert) extends super.UpsertBuilder(ins) { override def buildInsert: InsertBuilderResult = { val update = "update " + tableName + " set " + softNames.map(n => s"$n=?").mkString(",") + " where " + pkNames.map(n => s"$n=?").mkString(" and ") val nonAutoIncNames = nonAutoIncSyms.map(fs => quoteIdentifier(fs.name)).mkString(",") val nonAutoIncVars = nonAutoIncSyms.map(_ => "?").mkString(",") val cond = pkNames.map(n => s"$n=?").mkString(" and ") val insert = s"insert into $tableName ($nonAutoIncNames) select $nonAutoIncVars where not exists (select 1 from $tableName where $cond)" new InsertBuilderResult(table, s"begin; $update; $insert; end", softSyms ++ pkSyms) } override def transformMapping(n: Node) = reorderColumns(n, softSyms ++ pkSyms ++ nonAutoIncSyms ++ pkSyms) } class TableDDLBuilder(table: Table[_]) extends super.TableDDLBuilder(table) { override def createPhase1 = super.createPhase1 ++ columns.flatMap { case cb: ColumnDDLBuilder => cb.createLobTrigger(table.tableName) } override def dropPhase1 = { val dropLobs = columns.flatMap { case cb: ColumnDDLBuilder => cb.dropLobTrigger(table.tableName) } if(dropLobs.isEmpty) super.dropPhase1 else Seq("delete from "+quoteIdentifier(table.tableName)) ++ dropLobs ++ super.dropPhase1 } } class ColumnDDLBuilder(column: FieldSymbol) extends super.ColumnDDLBuilder(column) { override def appendColumn(sb: StringBuilder) { sb append quoteIdentifier(column.name) append ' ' if(autoIncrement && !customSqlType) { sb append (if(sqlType.toUpperCase == "BIGINT") "BIGSERIAL" else "SERIAL") } else appendType(sb) autoIncrement = false appendOptions(sb) } def lobTrigger(tname: String) = quoteIdentifier(tname+"__"+quoteIdentifier(column.name)+"_lob") def createLobTrigger(tname: String): Option[String] = if(sqlType == "lo") Some( "create trigger "+lobTrigger(tname)+" before update or delete on "+ quoteIdentifier(tname)+" for each row execute procedure lo_manage("+quoteIdentifier(column.name)+")" ) else None def dropLobTrigger(tname: String): Option[String] = if(sqlType == "lo") Some( "drop trigger "+lobTrigger(tname)+" on "+quoteIdentifier(tname) ) else None } class JdbcTypes extends super.JdbcTypes { override val byteArrayJdbcType = new ByteArrayJdbcType override val uuidJdbcType = new UUIDJdbcType class ByteArrayJdbcType extends super.ByteArrayJdbcType { override val sqlType = java.sql.Types.BINARY override def sqlTypeName(size: Option[RelationalProfile.ColumnOption.Length]) = "BYTEA" } class UUIDJdbcType extends super.UUIDJdbcType { override def sqlTypeName(size: Option[RelationalProfile.ColumnOption.Length]) = "UUID" override def setValue(v: UUID, p: PreparedStatement, idx: Int) = p.setObject(idx, v, sqlType) override def getValue(r: ResultSet, idx: Int) = r.getObject(idx).asInstanceOf[UUID] override def updateValue(v: UUID, r: ResultSet, idx: Int) = r.updateObject(idx, v) override def valueToSQLLiteral(value: UUID) = "'" + value + "'" override def hasLiteralForm = true } } } object PostgresDriver extends PostgresDriver
{ "content_hash": "bfa35f6ee53ccce7b7704fda72d0db77", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 164, "avg_line_length": 47.5, "alnum_prop": 0.6868179623370353, "repo_name": "olivergg/slick", "id": "299669df8d9653a967b7ac8a9da0cac5623fdff5", "size": "10355", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "slick/src/main/scala/slick/driver/PostgresDriver.scala", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "HTML", "bytes": "3306" }, { "name": "Python", "bytes": "15655" }, { "name": "Scala", "bytes": "1232170" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "13e76f5764074e3153eff9c123aee46f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "70d219492efd15cdafc9f04e3dbc080123ec9841", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex yunlingensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
class CreateAhoyEvents < ActiveRecord::Migration def change create_table :ahoy_events, id: false do |t| t.uuid :id, default: nil, primary_key: true t.uuid :visit_id, default: nil # user t.integer :user_id # add t.string :user_type if polymorphic t.string :name t.jsonb :properties t.timestamp :time end add_index :ahoy_events, [:visit_id] add_index :ahoy_events, [:user_id] add_index :ahoy_events, [:time] end end
{ "content_hash": "c2b8367b5875ed92b9a1aa16bf16ef9b", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 49, "avg_line_length": 24.45, "alnum_prop": 0.623721881390593, "repo_name": "rememberlenny/harlemreport", "id": "81fb71f3761d872fb859edaf475e3b897727dd74", "size": "489", "binary": false, "copies": "28", "ref": "refs/heads/master", "path": "db/migrate/20160207050152_create_ahoy_events.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24052" }, { "name": "CoffeeScript", "bytes": "2847" }, { "name": "HTML", "bytes": "41013" }, { "name": "JavaScript", "bytes": "163949" }, { "name": "Ruby", "bytes": "186311" } ], "symlink_target": "" }
ListView/GridView添加加载更多 ## Import [JitPack](https://jitpack.io/) Add it in your project's build.gradle at the end of repositories: ```gradle repositories { // ... maven { url "https://jitpack.io" } } ``` Step 2. Add the dependency in the form ```gradle dependencies { compile 'com.github.vilyever:AndroidAbsListViewLoadMore:1.0.4' } ``` ## Usage ```java VDAbsListViewLoadMore.addLoadMoreDelegate(listView, new VDAbsListViewLoadMore.LoadMoreDelegate() { @Override public void requireLoadMore(AbsListView absListView) { } }); ``` ## License [Apache License Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt)
{ "content_hash": "5262d8488e187981d0d0ae9774b28b71", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 98, "avg_line_length": 18.37142857142857, "alnum_prop": 0.713841368584759, "repo_name": "vilyever/AndroidAbsListViewLoadMore", "id": "d329d9f7195a32b5e7bbd259cbb44c43c81feb7e", "size": "684", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "6872" } ], "symlink_target": "" }
define([ 'Utils/Debug', 'Utils/CheckType' ], function( debug, checkType ) { var console = debug.console(['utils/text', 'utils/text/text']), consoleProcess = console.console('process'), consoleError = console.console('error'); var obj = function(text) { this._origin = ''; this._result = ''; this._handlers = []; this.setText(text); } obj.prototype.setText = setText; obj.prototype.getText = getResult; obj.prototype.getOrigin = getOrigin; obj.prototype.handler = addHandler; function setText(text) { this._origin = ''; if (checkType.exists(text)) { this._origin = text; } this._result = this._origin; consoleProcess.log('set text to', this._origin); return this; } function getOrigin() { return this._origin; } function getResult() { this._result = handleText(this._origin, this._handlers); return this._result; } function addHandler(handler) { if (checkType.exists(handler) && checkType.exists(handler.handle)) { consoleProcess.log('add handler', handler); this._handlers.push(handler); } else { consoleError.log('incorrect handler:', handler); } return this; } function handleText(text, handlers) { consoleProcess.log('start handle with', text); for (var index in handlers) { text = handlers[index].handle(text); consoleProcess.log('handle [%s]', index); } consoleProcess.log('end handle with', text); return text; } function objBuilder(text) { return new obj(text); } return objBuilder; });
{ "content_hash": "02f32bf9ab4de4426d1ccf2236b7aef4", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 76, "avg_line_length": 22.275, "alnum_prop": 0.563973063973064, "repo_name": "Glifery/Maxplayer", "id": "bb9a649deab16e0f33b59e1986d98cf797fc4d8c", "size": "1782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Maxplayer/FrontendBundle/Resources/public/js/modules/Utils/Text/Text.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2204" }, { "name": "JavaScript", "bytes": "26610" }, { "name": "PHP", "bytes": "97165" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Remote developing with Amber</title> <link rel="stylesheet" href="style.css" type="text/css" media="screen"> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="author" content="Khubbatov Rustem" /> <script type='text/javascript' src='bower_components/amber/support/requirejs/require.min.js'></script> <script type='text/javascript' src='bower_components/amber/support/amber.js'></script> </head> <body> <script type='text/javascript'> require.config({ paths: { 'hubbatov': 'src' }}); require([ 'amber/devel', 'hubbatov/AmberRemoteDeveloping' ], function (smalltalk) { smalltalk.initialize({ 'transport.defaultAmdNamespace': "hubbatov" }); $(function() { smalltalk.AmberRemoteDevelopingClient._new()._createDefaultConnection(); }); }); </script> <button onclick="require('amber/helpers').globals.Browser._open()">legacy IDE</button> <button onclick="require('amber/helpers').popupHelios()">Helios IDE</button> <div id="header"> <input id="browserButton" type="button" value= "Open Amber browser" onclick="require('amber_vm/smalltalk').Browser._open()"></button> </div> <div id="messages"> <textarea id="messagesField" readonly="readonly" wrap="soft"></textarea> </div> </body> </html>
{ "content_hash": "60d2693d4819bc965e74a7427f5d2b7b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 139, "avg_line_length": 36.275, "alnum_prop": 0.6257753273604411, "repo_name": "hubbatov/GSoC2013", "id": "b52509788954bc61d297e514ccc79f5fddfa3375", "size": "1451", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1039" }, { "name": "JavaScript", "bytes": "25201" }, { "name": "Smalltalk", "bytes": "6607" } ], "symlink_target": "" }
package api import ( "context" "net/http" "github.com/gorilla/mux" "github.com/ovh/cds/engine/api/authentication" "github.com/ovh/cds/engine/api/event" "github.com/ovh/cds/engine/api/group" "github.com/ovh/cds/engine/api/project" "github.com/ovh/cds/engine/api/user" "github.com/ovh/cds/engine/service" "github.com/ovh/cds/sdk" ) func (api *API) getGroupsHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { var groups []sdk.Group var err error withoutDefault := service.FormBool(r, "withoutDefault") if isMaintainer(ctx) { groups, err = group.LoadAll(ctx, api.mustDB(), group.LoadOptions.WithOrganization) } else { groups, err = group.LoadAllByUserID(ctx, api.mustDB(), getUserConsumer(ctx).AuthConsumerUser.AuthentifiedUser.ID, group.LoadOptions.WithOrganization) } if err != nil { return err } // withoutDefault is use by project add, to avoid selecting the default group on project creation if withoutDefault { var filteredGroups []sdk.Group for _, g := range groups { if !group.IsDefaultGroupID(g.ID) { filteredGroups = append(filteredGroups, g) } } return service.WriteJSON(w, filteredGroups, http.StatusOK) } return service.WriteJSON(w, groups, http.StatusOK) } } func (api *API) getProjectGroupHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) name := vars["permGroupName"] g, err := group.LoadByName(ctx, api.mustDB(), name) if err != nil { return err } projects, err := project.LoadAllByGroupIDs(ctx, api.mustDB(), api.Cache, []int64{g.ID}) if err != nil { return err } return service.WriteJSON(w, projects, http.StatusOK) } } func (api *API) getGroupHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) name := vars["permGroupName"] g, err := group.LoadByName(ctx, api.mustDB(), name, group.LoadOptions.Default) if err != nil { return err } return service.WriteJSON(w, g, http.StatusOK) } } func (api *API) postGroupHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { var newGroup sdk.Group if err := service.UnmarshalBody(r, &newGroup); err != nil { return err } if err := newGroup.IsValid(); err != nil { return err } tx, err := api.mustDB().Begin() if err != nil { return sdk.WrapError(err, "cannot begin tx") } defer tx.Rollback() // nolint existingGroup, err := group.LoadByName(ctx, tx, newGroup.Name) if err != nil && !sdk.ErrorIs(err, sdk.ErrNotFound) { return err } if existingGroup != nil { return sdk.WithStack(sdk.ErrGroupPresent) } consumer := getUserConsumer(ctx) if err := group.Create(ctx, tx, &newGroup, consumer.AuthConsumerUser.AuthentifiedUser); err != nil { return err } if err := tx.Commit(); err != nil { return sdk.WrapError(err, "cannot commit tx") } if err := group.LoadOptions.Default(ctx, api.mustDB(), &newGroup); err != nil { return err } return service.WriteJSON(w, &newGroup, http.StatusCreated) } } func (api *API) putGroupHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { if isService(ctx) { return sdk.WithStack(sdk.ErrForbidden) } vars := mux.Vars(r) groupName := vars["permGroupName"] var data sdk.Group if err := service.UnmarshalBody(r, &data); err != nil { return err } if err := data.IsValid(); err != nil { return err } tx, err := api.mustDB().Begin() if err != nil { return sdk.WrapError(err, "cannot start transaction") } defer tx.Rollback() // nolint oldGroup, err := group.LoadByName(ctx, tx, groupName) if err != nil { return sdk.WrapError(err, "cannot load group: %s", groupName) } // In case of rename, checks that new name is not already used if data.Name != oldGroup.Name { exstingGroup, err := group.LoadByName(ctx, tx, data.Name) if err != nil && !sdk.ErrorIs(err, sdk.ErrNotFound) { return err } if exstingGroup != nil { return sdk.WithStack(sdk.ErrGroupPresent) } } data.ID = oldGroup.ID if err := group.EnsureOrganization(ctx, tx, &data); err != nil { return err } if err := group.Update(ctx, tx, &data); err != nil { return sdk.WrapError(err, "cannot update group with id: %d", oldGroup.ID) } // TODO Update all requirements that was using the group name if err := tx.Commit(); err != nil { return sdk.WithStack(err) } // Load extra data for group if err := group.LoadOptions.Default(ctx, api.mustDB(), &data); err != nil { return err } return service.WriteJSON(w, data, http.StatusOK) } } func (api *API) deleteGroupHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) name := vars["permGroupName"] tx, err := api.mustDB().Begin() if err != nil { return sdk.WrapError(err, "cannot start transaction") } defer tx.Rollback() // nolint g, err := group.LoadByName(ctx, tx, name) if err != nil { return sdk.WrapError(err, "cannot load %s", name) } // Get project permission projPerms, err := project.LoadPermissions(ctx, tx, g.ID) if err != nil { return sdk.WrapError(err, "cannot load projects for group") } // Remove the group from all consumers if err := authentication.ConsumerRemoveGroup(ctx, tx, g); err != nil { return err } if err := group.Delete(ctx, tx, g); err != nil { return sdk.WrapError(err, "cannot delete group") } if err := tx.Commit(); err != nil { return sdk.WithStack(err) } // Send project permission changes for _, pg := range projPerms { event.PublishDeleteProjectPermission(ctx, &pg.Project, sdk.GroupPermission{Group: *g}, getUserConsumer(ctx)) } return service.WriteJSON(w, nil, http.StatusOK) } } func (api *API) postGroupUserHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) groupName := vars["permGroupName"] var data sdk.GroupMember if err := service.UnmarshalBody(r, &data); err != nil { return err } if data.ID == "" && data.Username == "" { return sdk.NewErrorFrom(sdk.ErrWrongRequest, "invalid given user id or username") } tx, err := api.mustDB().Begin() if err != nil { return sdk.WithStack(err) } defer tx.Rollback() // nolint g, err := group.LoadByName(ctx, tx, groupName) if err != nil { return sdk.WrapError(err, "cannot load group with name: %s", groupName) } var u *sdk.AuthentifiedUser if data.ID != "" { u, err = user.LoadByID(ctx, tx, data.ID, user.LoadOptions.WithOrganization) } else { u, err = user.LoadByUsername(ctx, tx, data.Username, user.LoadOptions.WithOrganization) } if err != nil { return err } // If the user is already in group return an error link, err := group.LoadLinkGroupUserForGroupIDAndUserID(ctx, tx, g.ID, u.ID) if err != nil && !sdk.ErrorIs(err, sdk.ErrNotFound) { return err } if link != nil { return sdk.NewErrorFrom(sdk.ErrForbidden, "given user is already in group") } // Check that user's Organization match group Organization if err := group.EnsureOrganization(ctx, tx, g); err != nil { return err } if g.Organization != "" && u.Organization != g.Organization { if u.Organization == "" { return sdk.NewErrorFrom(sdk.ErrForbidden, "given user without organization don't match group organization %q", g.Organization) } return sdk.NewErrorFrom(sdk.ErrForbidden, "given user with organization %q don't match group organization %q", u.Organization, g.Organization) } // Create the link between group and user with admin flag from request if err := group.InsertLinkGroupUser(ctx, tx, &group.LinkGroupUser{ GroupID: g.ID, AuthentifiedUserID: u.ID, Admin: data.Admin, }); err != nil { return sdk.WrapError(err, "cannot add user %s in group %s", u.Username, g.Name) } // Ensure again group org to prevent organization conflict on group's projects if err := group.EnsureOrganization(ctx, tx, g); err != nil { return err } // Restore invalid group for existing user's consumer if err := authentication.ConsumerRestoreInvalidatedGroupForUser(ctx, tx, g.ID, u.ID); err != nil { return err } if err := tx.Commit(); err != nil { return sdk.WithStack(err) } // Load extra data for group if err := group.LoadOptions.Default(ctx, api.mustDB(), g); err != nil { return err } return service.WriteJSON(w, g, http.StatusCreated) } } func (api *API) putGroupUserHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) groupName := vars["permGroupName"] username := vars["username"] var data sdk.GroupMember if err := service.UnmarshalBody(r, &data); err != nil { return err } tx, err := api.mustDB().Begin() if err != nil { return sdk.WithStack(err) } defer tx.Rollback() // nolint g, err := group.LoadByName(ctx, tx, groupName) if err != nil { return sdk.WrapError(err, "cannot load group with name: %s", groupName) } u, err := user.LoadByUsername(ctx, tx, username) if err != nil { return err } link, err := group.LoadLinkGroupUserForGroupIDAndUserID(ctx, tx, g.ID, u.ID) if err != nil { return err } // Check that user's Organization match group Organization if err := group.EnsureOrganization(ctx, tx, g); err != nil { return err } // In case we are removing admin rights to user, we need to check that it's not the last admin if link.Admin && !data.Admin { links, err := group.LoadLinksGroupUserForGroupIDs(ctx, tx, []int64{g.ID}) if err != nil { return err } var adminFound bool for i := range links { if links[i].AuthentifiedUserID != u.ID && links[i].Admin { adminFound = true break } } if !adminFound { return sdk.NewErrorFrom(sdk.ErrGroupNeedAdmin, "cannot remove the last admin of the group") } } link.Admin = data.Admin if err := group.UpdateLinkGroupUser(ctx, tx, link); err != nil { return err } if err := tx.Commit(); err != nil { return sdk.WithStack(err) } // Load extra data for group if err := group.LoadOptions.Default(ctx, api.mustDB(), g); err != nil { return err } return service.WriteJSON(w, g, http.StatusOK) } } func (api *API) deleteGroupUserHandler() service.Handler { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) groupName := vars["permGroupName"] username := vars["username"] tx, err := api.mustDB().Begin() if err != nil { return sdk.WithStack(err) } defer tx.Rollback() // nolint g, err := group.LoadByName(ctx, tx, groupName) if err != nil { return sdk.WrapError(err, "cannot load group with name: %s", groupName) } u, err := user.LoadByUsername(ctx, tx, username) if err != nil { return err } link, err := group.LoadLinkGroupUserForGroupIDAndUserID(ctx, tx, g.ID, u.ID) if err != nil { return err } // In case we are removing an admin from the group, we need to check that it's not the last admin if link.Admin { links, err := group.LoadLinksGroupUserForGroupIDs(ctx, tx, []int64{g.ID}) if err != nil { return err } var adminFound bool for i := range links { if links[i].AuthentifiedUserID != u.ID && links[i].Admin { adminFound = true break } } if !adminFound { return sdk.NewErrorFrom(sdk.ErrGroupNeedAdmin, "cannot remove the last admin of the group") } } if err := group.DeleteLinkGroupUser(tx, link); err != nil { return err } if err := group.EnsureOrganization(ctx, tx, g); err != nil { return err } // Remove the group from all consumers if err := authentication.ConsumerInvalidateGroupForUser(ctx, tx, g, u); err != nil { return err } if err := tx.Commit(); err != nil { return sdk.WithStack(err) } // In case where the user remove himself from group, do not return it if link.AuthentifiedUserID == getUserConsumer(ctx).AuthConsumerUser.AuthentifiedUser.ID { return service.WriteJSON(w, nil, http.StatusOK) } // Load extra data for group if err := group.LoadOptions.Default(ctx, api.mustDB(), g); err != nil { return err } return service.WriteJSON(w, g, http.StatusOK) } }
{ "content_hash": "9f3779ccedb5cb551039a34a0ab039c7", "timestamp": "", "source": "github", "line_count": 463, "max_line_length": 152, "avg_line_length": 27.166306695464364, "alnum_prop": 0.6650500874542853, "repo_name": "ovh/cds", "id": "61469a062b88d208d734c8ea98ed6b564b02deb5", "size": "12578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/api/group.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Dockerfile", "bytes": "1616" }, { "name": "Go", "bytes": "7822995" }, { "name": "HTML", "bytes": "594997" }, { "name": "JavaScript", "bytes": "47672" }, { "name": "Less", "bytes": "793" }, { "name": "Makefile", "bytes": "79754" }, { "name": "PLpgSQL", "bytes": "38853" }, { "name": "SCSS", "bytes": "114372" }, { "name": "Shell", "bytes": "14838" }, { "name": "TypeScript", "bytes": "1760477" } ], "symlink_target": "" }
<?php get_header(); ?> <div class="container"> <div class="row"> <div class="col-md-3 col-md-offset-2 hidden-sm hidden-xs text-right"> <h2 style="margin-top:0px">Let's Chat</h2> <a class="noBorder" href="http://www.linkedin.com/in/tim-s-wilson" target="_blank"><i class="fa fa-linkedin-square fa-1x" aria-hidden="true"></i></a> <a class="noBorder" href="mailto:[email protected]"><i class="fa fa-envelope fa-1x" aria-hidden="true"></i></a> </div> <div class="col-sm-12 hidden-md hidden-lg text-center"> <h2 style="margin-top:0px">Let's Chat</h2> <a class="noBorder" href="http://www.linkedin.com/in/tim-s-wilson" target="_blank"><i class="fa fa-linkedin-square fa-1x" aria-hidden="true"></i></a> <a class="noBorder" href="mailto:[email protected]"><i class="fa fa-envelope fa-1x" aria-hidden="true"></i></a> </div> <div class="col-md-5"> <?php echo do_shortcode( '[contact-form-7 id="32" title="Contact form"]' ); ?> </div> </div> </div> <?php get_footer(); ?>
{ "content_hash": "2a3e8b53084cba469c2c61264182dfbf", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 153, "avg_line_length": 45.26086956521739, "alnum_prop": 0.6176753121998079, "repo_name": "timswilson/Personal-Website", "id": "441d515e6dfbf21067666caf15c6c2f1fd11ddd4", "size": "1041", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bootstrap-basic-tw/page-contact.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15988" }, { "name": "HTML", "bytes": "87476" }, { "name": "JavaScript", "bytes": "6765" }, { "name": "PHP", "bytes": "197250" } ], "symlink_target": "" }
package cn.lym.json; import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Test; public class JSONFormatterTest { @Test public void testFormat() throws Exception { String pathname = JSONFormatterTest.class.getClassLoader() .getResource("test.json").getFile(); File file = new File(pathname); String source = FileUtils.readFileToString(file); System.out.println(JSONFormatter.format(source)); } }
{ "content_hash": "a72c15c8e1352fb027db460734600e27", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 60, "avg_line_length": 22.05, "alnum_prop": 0.7505668934240363, "repo_name": "1120101929/JSONFormatter", "id": "98cc677dd7b553ac3a5ca4914f78849f9f433df2", "size": "441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JSONFormatter/src/test/java/cn/lym/json/JSONFormatterTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4022" } ], "symlink_target": "" }
<?php return \yii\helpers\ArrayHelper::merge( (require __DIR__ . '/overrides/base.php'), (require __DIR__ . '/overrides/web_base.php'), (require __DIR__ . '/overrides/local.php') );
{ "content_hash": "82cbbce23e183769f83a403d89519f51", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 50, "avg_line_length": 27.714285714285715, "alnum_prop": 0.6030927835051546, "repo_name": "natalka76/evaluetion", "id": "74ed598c68e8f484707c001988658730b755e0cf", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/web.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "511" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1842" }, { "name": "GAP", "bytes": "707" }, { "name": "PHP", "bytes": "43695" } ], "symlink_target": "" }
Sub Main() Dim y As Integer Test(y) End Sub Sub Test(ByRef x As Integer) x = 42 End Sub 'https://pt.stackoverflow.com/q/42871/101
{ "content_hash": "51714261976cf2f6761222b772303674", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 41, "avg_line_length": 13.8, "alnum_prop": 0.6811594202898551, "repo_name": "maniero/SOpt", "id": "66f044dda8f1e1dc31cea83381441da688f73de3", "size": "138", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "VB.NET/Reference.vb", "mode": "33188", "license": "mit", "language": [ { "name": "ABAP", "bytes": "447" }, { "name": "ASP.NET", "bytes": "318" }, { "name": "Assembly", "bytes": "8524" }, { "name": "C", "bytes": "364697" }, { "name": "C#", "bytes": "638419" }, { "name": "C++", "bytes": "139511" }, { "name": "CSS", "bytes": "308" }, { "name": "Dart", "bytes": "1153" }, { "name": "Elixir", "bytes": "398" }, { "name": "F#", "bytes": "85" }, { "name": "Forth", "bytes": "909" }, { "name": "GLSL", "bytes": "73" }, { "name": "Go", "bytes": "1205" }, { "name": "Groovy", "bytes": "1986" }, { "name": "HTML", "bytes": "6964" }, { "name": "Hack", "bytes": "11250" }, { "name": "Java", "bytes": "242308" }, { "name": "JavaScript", "bytes": "134134" }, { "name": "Kotlin", "bytes": "7424" }, { "name": "Lua", "bytes": "11238" }, { "name": "MATLAB", "bytes": "80" }, { "name": "Makefile", "bytes": "389" }, { "name": "PHP", "bytes": "102650" }, { "name": "Pascal", "bytes": "728" }, { "name": "PostScript", "bytes": "114" }, { "name": "Python", "bytes": "72427" }, { "name": "RenderScript", "bytes": "115" }, { "name": "Ruby", "bytes": "3562" }, { "name": "Rust", "bytes": "1455" }, { "name": "Scheme", "bytes": "852" }, { "name": "Smalltalk", "bytes": "103" }, { "name": "Swift", "bytes": "827" }, { "name": "TSQL", "bytes": "4011" }, { "name": "TypeScript", "bytes": "7501" }, { "name": "VBA", "bytes": "137" }, { "name": "Visual Basic .NET", "bytes": "12125" }, { "name": "xBase", "bytes": "1152" } ], "symlink_target": "" }
package cogx.compiler.codegenerator.opencl.hyperkernels import cogx.platform.types._ import cogx.compiler.codegenerator.opencl.fragments._ import cogx.cogmath.geometry.Shape import cogx.compiler.parser.op.DeterminantOp /** A hyperkernel that computes the determinant for every 2 x 2 matrix * in a matrix field. * * @author Greg Snider * * @param in Input matrix virtual field register. * @param operation Opcode * @param resultType The FieldType of the result of this kernel. */ private[cogx] class DeterminantHyperKernel private (in: VirtualFieldRegister, operation: Opcode, resultType: FieldType) extends HyperKernel(operation, Array(in), resultType, SmallTensorAddressing) { val code = """ | // Read in matrix. | float4 m = read(@in0); | float m00 = m.x; | float m01 = m.y; | float m10 = m.z; | float m11 = m.w; | | // Compute determinant. | float determinant = m00 * m11 - m01 * m10; | @out0 = determinant; """.stripMargin addCode(code) // debugCompile } /** Factory object for creating kernels of this type. */ private[cogx] object DeterminantHyperKernel { /** Compute the condition number for every matrix in a matrix field. * * @param in The matrix virtual field register. * @param operation The binary opcode for this operation. * @param resultType The FieldType of the result of this kernel. * @return The synthesized hyperkernel. */ def apply(in: VirtualFieldRegister, operation: Opcode, resultType: FieldType): AbstractKernel = { require(in.fieldType.tensorShape == Shape(2, 2)) require(resultType.tensorShape.dimensions == 0) require(in.fieldType.fieldShape == resultType.fieldShape) require(operation == DeterminantOp) new DeterminantHyperKernel(in, operation, resultType) } }
{ "content_hash": "43a8e74cd23e52cd2c7a43bfec73a372", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 70, "avg_line_length": 30.092307692307692, "alnum_prop": 0.6574642126789366, "repo_name": "hpe-cct/cct-core", "id": "549e38e3ed96446e0035d972e8ae2ebf27d2ca63", "size": "2580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/cogx/compiler/codegenerator/opencl/hyperkernels/DeterminantHyperKernel.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "19286" }, { "name": "Scala", "bytes": "4878983" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/1998/REC-html40-19980424/loose.dtd"> <html><style type="text/css"><!--a:link {text-decoration: none; font-family: Verdana, Gene va, Helvetica, Arial, sans-serif; font-size: small}a:visited {text-decoration: none; font-family: Verdana, G eneva, Helvetica, Arial, sans-serif; font-size: small}a:active {text-decoration: none; font-family: Verdana, Ge neva, Helvetica, Arial, sans-serif; font-size: small}a:hover {text-decoration: underline; font-family: Verdana , Geneva, Helvetica, Arial, sans-serif; font-size: small}h4 {text-decoration: none; font-family: Verdana,Geneva,Ar ial,Helvetica,sans-serif; size: tiny; font-weight: bold}--></style><head> <title>Methods</title> <meta name="generator" content="HeaderDoc"> </head><body bgcolor="#ffffff"><h1><font face="Geneva,Arial,Helvtica">Methods</font></h1><br> <hr><a name="//apple_ref/occ/instm/AGRegexMatch/count"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="count">count</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (int)<B>count;</B> </tt><br> </pre></blockquote> <p>The number of capturing subpatterns, including the pattern itself. </p> <hr><a name="//apple_ref/occ/instm/AGRegexMatch/group"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="group">group</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (NSString *)<B>group;</B> </tt><br> </pre></blockquote> <p>Returns the part of the target string that matched the pattern. </p> <hr><a name="//apple_ref/occ/instm/AGRegexMatch/groupAtIndex:"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="groupAtIndex:">groupAtIndex:</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (NSString *)<B>groupAtIndex:</B>(int)<I>idx;</I> </tt><br> </pre></blockquote> <p>Returns the part of the target string that matched the subpattern at the given index or nil if it wasn't matched. The subpatterns are indexed in order of their opening parentheses, 0 is the entire pattern, 1 is the first capturing subpattern, and so on. </p> <hr><a name="//apple_ref/occ/instm/AGRegexMatch/groupNamed:"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="groupNamed:">groupNamed:</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (NSString *)<B>groupNamed:</B>(NSString *)<I>name;</I> </tt><br> </pre></blockquote> <p>Returns the part of the target string that matched the subpattern of the given name or nil if it wasn't matched. </p> <hr><a name="//apple_ref/occ/instm/AGRegexMatch/range"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="range">range</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (NSRange)<B>range;</B> </tt><br> </pre></blockquote> <p>Returns the range of the target string that matched the pattern. </p> <hr><a name="//apple_ref/occ//AGRegexMatch/rangeAtIndex:"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="rangeAtIndex:">rangeAtIndex:</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (NSRange)<B>rangeAtIndex:</B>(int)<I>idx;</I> </tt><br> </pre></blockquote> <p>Returns the range of the target string that matched the subpattern at the given index or {NSNotFound, 0} if it wasn't matched. The subpatterns are indexed in order of their opening parentheses, 0 is the entire pattern, 1 is the first capturing subpattern, and so on. </p> <hr><a name="//apple_ref/occ//AGRegexMatch/rangeNamed:"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="rangeNamed:">rangeNamed:</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (NSRange)<B>rangeNamed:</B>(NSString *)<I>name;</I> </tt><br> </pre></blockquote> <p>Returns the range of the target string that matched the subpattern of the given name or {NSNotFound, 0} if it wasn't matched. </p> <hr><a name="//apple_ref/occ//AGRegexMatch/string"></a> <table border="0" cellpadding="2" cellspacing="2" width="300"><tr><td valign="top" height="12" colspan="5"><h2><a name="string">string</a></h2> </td></tr></table><hr><blockquote><pre><tt>- (NSString *)<B>string;</B> </tt><br> </pre></blockquote> <p>Returns the target string. </p> <p>(Last Updated 9/12/2003) </p></body></html>
{ "content_hash": "103f9ccb11e9702c5ceca3b37fb0d94a", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 274, "avg_line_length": 80.59649122807018, "alnum_prop": 0.6845885938180235, "repo_name": "edenwaith/Permanent-Eraser", "id": "22c7bc3729f8f31b0affa825221e59c2a121d3c0", "size": "4594", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "AGRegex/Documentation/AGRegex/Classes/AGRegexMatch/Methods/Methods.html", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "1514690" }, { "name": "C++", "bytes": "4335" }, { "name": "HTML", "bytes": "61085" }, { "name": "M4", "bytes": "22735" }, { "name": "Makefile", "bytes": "695366" }, { "name": "Objective-C", "bytes": "328350" }, { "name": "Roff", "bytes": "48214" }, { "name": "Shell", "bytes": "500154" } ], "symlink_target": "" }
namespace MediaNews.DbContext.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class AddMig : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(AddMig)); string IMigrationMetadata.Id { get { return "201706031619467_AddMig"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
{ "content_hash": "7e0e1eed392a000b1eb0ae710b4ad377", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 89, "avg_line_length": 28.107142857142858, "alnum_prop": 0.6149936467598475, "repo_name": "Kidoo96/MediaNews", "id": "73fc3757454be71a684664efa61a7731768a661c", "size": "809", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MediaNews/MediaNews.DbContext/Migrations/201706031619467_AddMig.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "C#", "bytes": "125226" }, { "name": "CSS", "bytes": "152822" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "11028" } ], "symlink_target": "" }
#ifndef _UAPI_LINUX_KD_H #define _UAPI_LINUX_KD_H #include <linux/types.h> #include <linux/compiler.h> #define GIO_FONT 0x4B60 #define PIO_FONT 0x4B61 #define GIO_FONTX 0x4B6B #define PIO_FONTX 0x4B6C struct consolefontdesc { unsigned short charcount; unsigned short charheight; char __user * chardata; }; #define PIO_FONTRESET 0x4B6D #define GIO_CMAP 0x4B70 #define PIO_CMAP 0x4B71 #define KIOCSOUND 0x4B2F #define KDMKTONE 0x4B30 #define KDGETLED 0x4B31 #define KDSETLED 0x4B32 #define LED_SCR 0x01 #define LED_NUM 0x02 #define LED_CAP 0x04 #define KDGKBTYPE 0x4B33 #define KB_84 0x01 #define KB_101 0x02 #define KB_OTHER 0x03 #define KDADDIO 0x4B34 #define KDDELIO 0x4B35 #define KDENABIO 0x4B36 #define KDDISABIO 0x4B37 #define KDSETMODE 0x4B3A #define KD_TEXT 0x00 #define KD_GRAPHICS 0x01 #define KD_TEXT0 0x02 #define KD_TEXT1 0x03 #define KDGETMODE 0x4B3B #define KDMAPDISP 0x4B3C #define KDUNMAPDISP 0x4B3D typedef char scrnmap_t; #define E_TABSZ 256 #define GIO_SCRNMAP 0x4B40 #define PIO_SCRNMAP 0x4B41 #define GIO_UNISCRNMAP 0x4B69 #define PIO_UNISCRNMAP 0x4B6A #define GIO_UNIMAP 0x4B66 struct unipair { unsigned short unicode; unsigned short fontpos; }; struct unimapdesc { unsigned short entry_ct; struct unipair __user * entries; }; #define PIO_UNIMAP 0x4B67 #define PIO_UNIMAPCLR 0x4B68 struct unimapinit { unsigned short advised_hashsize; unsigned short advised_hashstep; unsigned short advised_hashlevel; }; #define UNI_DIRECT_BASE 0xF000 #define UNI_DIRECT_MASK 0x01FF #define K_RAW 0x00 #define K_XLATE 0x01 #define K_MEDIUMRAW 0x02 #define K_UNICODE 0x03 #define K_OFF 0x04 #define KDGKBMODE 0x4B44 #define KDSKBMODE 0x4B45 #define K_METABIT 0x03 #define K_ESCPREFIX 0x04 #define KDGKBMETA 0x4B62 #define KDSKBMETA 0x4B63 #define K_SCROLLLOCK 0x01 #define K_NUMLOCK 0x02 #define K_CAPSLOCK 0x04 #define KDGKBLED 0x4B64 #define KDSKBLED 0x4B65 struct kbentry { unsigned char kb_table; unsigned char kb_index; unsigned short kb_value; }; #define K_NORMTAB 0x00 #define K_SHIFTTAB 0x01 #define K_ALTTAB 0x02 #define K_ALTSHIFTTAB 0x03 #define KDGKBENT 0x4B46 #define KDSKBENT 0x4B47 struct kbsentry { unsigned char kb_func; unsigned char kb_string[512]; }; #define KDGKBSENT 0x4B48 #define KDSKBSENT 0x4B49 struct kbdiacr { unsigned char diacr, base, result; }; struct kbdiacrs { unsigned int kb_cnt; struct kbdiacr kbdiacr[256]; }; #define KDGKBDIACR 0x4B4A #define KDSKBDIACR 0x4B4B struct kbdiacruc { unsigned int diacr, base, result; }; struct kbdiacrsuc { unsigned int kb_cnt; struct kbdiacruc kbdiacruc[256]; }; #define KDGKBDIACRUC 0x4BFA #define KDSKBDIACRUC 0x4BFB struct kbkeycode { unsigned int scancode, keycode; }; #define KDGETKEYCODE 0x4B4C #define KDSETKEYCODE 0x4B4D #define KDSIGACCEPT 0x4B4E struct kbd_repeat { int delay; int period; }; #define KDKBDREP 0x4B52 #define KDFONTOP 0x4B72 struct console_font_op { unsigned int op; unsigned int flags; unsigned int width, height; unsigned int charcount; unsigned char __user * data; }; struct console_font { unsigned int width, height; unsigned int charcount; unsigned char * data; }; #define KD_FONT_OP_SET 0 #define KD_FONT_OP_GET 1 #define KD_FONT_OP_SET_DEFAULT 2 #define KD_FONT_OP_COPY 3 #define KD_FONT_FLAG_DONT_RECALC 1 #endif
{ "content_hash": "c0b5b4295cbe1c200c5e86e70a0a4572", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 36, "avg_line_length": 22.655172413793103, "alnum_prop": 0.7726027397260274, "repo_name": "webos21/xbionic", "id": "2385037fe256327d4994b7d54c8842ffb9b7cf90", "size": "4259", "binary": false, "copies": "23", "ref": "refs/heads/master", "path": "platform_bionic-android-vts-12.0_r2/libc/kernel/uapi/linux/kd.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "27550310" }, { "name": "Batchfile", "bytes": "1921" }, { "name": "C", "bytes": "25898496" }, { "name": "C++", "bytes": "5400283" }, { "name": "HTML", "bytes": "28469" }, { "name": "M4", "bytes": "64774" }, { "name": "Makefile", "bytes": "439140" }, { "name": "Perl", "bytes": "189114" }, { "name": "Python", "bytes": "195280" }, { "name": "Rust", "bytes": "10937" }, { "name": "Shell", "bytes": "72173" }, { "name": "XSLT", "bytes": "415" } ], "symlink_target": "" }
(function (root, factory) { // Node. if(typeof module === 'object' && typeof module.exports === 'object') { exports = module.exports = factory(); } // AMD. if(typeof define === 'function' && define.amd) { define(["terraformer/terraformer"],factory); } // Browser Global. if(typeof root.navigator === "object") { if (typeof root.Terraformer === "undefined"){ root.Terraformer = {}; } root.Terraformer.GeoStore = factory().GeoStore; } }(this, function() { // super lightweight async to sync handling function Sync () { this._steps = [ ]; this._arguments = [ ]; this._current = 0; this._error = null; } Sync.prototype.next = function () { var args = Array.prototype.slice.call(arguments); this._steps.push(args.shift()); this._arguments[this._steps.length - 1] = args; return this; }; Sync.prototype.error = function (error) { this._error = error; return this; }; Sync.prototype.done = function (err) { this._current++; var args = Array.prototype.slice.call(arguments); // if there is an error, we are done if (err) { if (this._error) { this._error.apply(this, args); } } else { if (this._steps.length) { var next = this._steps.shift(); var a = this._arguments[this._current]; next.apply(this, this._arguments[this._current]); } else { if (this._callback) { this._callback(); } } } }; Sync.prototype.start = function (callback) { this._callback = callback; var start = this._steps.shift(); if (start) { var args = this._arguments[0]; start.apply(this, args); } else { if (this._callback) { this._callback(); } } }; var Stream = require('stream'); var exports = { }; var Terraformer; // Local Reference To Browser Global if(typeof this.navigator === "object") { Terraformer = this.Terraformer; } // Setup Node Dependencies if(typeof module === 'object' && typeof module.exports === 'object') { Terraformer = require('terraformer'); } // Setup AMD Dependencies if(arguments[0] && typeof define === 'function' && define.amd) { Terraformer = arguments[0]; } function bind(obj, fn) { var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null; return function () { return fn.apply(obj, args || arguments); }; } // The store object that ties everything together... /* OPTIONS { store: Terraformer.Store.Memory, index: Terraformer.RTree } */ function GeoStore(config){ if(!config.store || !config.index){ throw new Error("Terraformer.GeoStore requires an instace of a Terraformer.Store and a instance of Terraformer.RTree"); } this.index = config.index; this.store = config.store; this._stream = null; this._additional_indexes = [ ]; } // add the geojson object to the store // calculate the envelope and add it to the rtree // should return a deferred GeoStore.prototype.add = function(geojson, callback){ var bbox; if (!geojson.type.match(/Feature/)) { throw new Error("Terraform.GeoStore : only Features and FeatureCollections are supported"); } if(geojson.type === "Feature" && !geojson.id) { throw new Error("Terraform.GeoStore : Feature does not have an id property"); } // set a bounding box if(geojson.type === "FeatureCollection"){ for (var i = 0; i < geojson.features.length; i++) { var feature = geojson.features[i]; bbox = Terraformer.Tools.calculateBounds(feature); if(!feature.id) { throw new Error("Terraform.GeoStore : Feature does not have an id property"); } this.index.insert({ x: bbox[0], y: bbox[1], w: Math.abs(bbox[0] - bbox[2]), h: Math.abs(bbox[1] - bbox[3]) }, feature.id); } this.store.add(geojson, callback ); } else { bbox = Terraformer.Tools.calculateBounds(geojson); this.index.insert({ x: bbox[0], y: bbox[1], w: Math.abs(bbox[0] - bbox[2]), h: Math.abs(bbox[1] - bbox[3]) }, geojson.id); this.store.add(geojson, callback ); } // store the data (use the stores store method to decide how to do this.) }; GeoStore.prototype.remove = function(id, callback){ this.get(id, bind(this, function(error, geojson){ if ( error ){ callback("Could not get feature to remove", null); } else { this.index.remove(geojson, id, bind(this, function(error, leaf){ if(error){ callback("Could not remove from index", null); } else { this.store.remove(id, callback); } })); } })); }; GeoStore.prototype.contains = function(geojson){ var args = Array.prototype.slice.call(arguments); args.shift(); var callback = args.pop(); if (args.length) { var indexQuery = args[0]; } // make a new deferred var shape = new Terraformer.Primitive(geojson); // create our envelope var envelope = Terraformer.Tools.calculateEnvelope(shape); // search the index this.index.search(envelope, bind(this, function(err, found){ var results = []; var completed = 0; var errors = 0; var self = this; var sync = new Sync(); var set; var i; // should we do set elimination with additional indexes? if (indexQuery && self._additional_indexes.length) { // convert "found" to an object with keys set = { }; for (i = 0; i < found.length; i++) { set[found[i]] = true; } // iterate through the queries, find the correct indexes, and apply them var keys = Object.keys(indexQuery); for (var j = 0; j < keys.length; j++) { for (i = 0; i < self._additional_indexes.length; i++) { // index property matches query if (self._additional_indexes[i].property === keys[j]) { var which = indexQuery[keys[j]], index = self._additional_indexes[i].index; sync.next(function (index, which, set, id) { var next = this; eliminateForIndex(index, which, set, function (err, newSet) { set = newSet; next.done(err); }); }, index, which, set); } } } } sync.start(function () { // if we have a set, it is our new "found" if (set) { found = Object.keys(set); } // the function to evalute results from the index var evaluate = function(primitive){ completed++; if ( primitive ){ var geometry = new Terraformer.Primitive(primitive.geometry); if (shape.within(geometry)){ if (self._stream) { if (completed === found.length) { self._stream.emit("end", primitive); } else { self._stream.emit("data", primitive); } } else { results.push(primitive); } } if(completed >= found.length){ if(!errors){ if (self._stream) { self._stream = null; } else if (callback) { callback( null, results ); } } else { if (callback) { callback("Could not get all geometries", null); } } } } }; var error = function(){ completed++; errors++; if(completed >= found.length){ if (callback) { callback("Could not get all geometries", null); } } }; // for each result see if the polygon contains the point if(found && found.length){ var getCB = function(err, result){ if (err) { error(); } else { evaluate( result ); } }; for (var i = 0; i < found.length; i++) { self.get(found[i], getCB); } } else { if (callback) { callback(null, results); } } }); })); }; GeoStore.prototype.within = function(geojson){ var args = Array.prototype.slice.call(arguments); args.shift(); var callback = args.pop(); if (args.length) { var indexQuery = args[0]; } // make a new deferred var shape = new Terraformer.Primitive(geojson); // create our envelope var envelope = Terraformer.Tools.calculateEnvelope(shape); // search the index using within this.index.within(envelope, bind(this, function(err, found){ var results = []; var completed = 0; var errors = 0; var self = this; var sync = new Sync(); var set; var i; // should we do set elimination with additional indexes? if (indexQuery && self._additional_indexes.length) { // convert "found" to an object with keys set = { }; for (i = 0; i < found.length; i++) { set[found[i]] = true; } // iterate through the queries, find the correct indexes, and apply them var keys = Object.keys(indexQuery); for (var j = 0; j < keys.length; j++) { for (i = 0; i < self._additional_indexes.length; i++) { // index property matches query if (self._additional_indexes[i].property === keys[j]) { var which = indexQuery[keys[j]], index = self._additional_indexes[i].index; sync.next(function (index, which, set, id) { var next = this; eliminateForIndex(index, which, set, function (err, newSet) { set = newSet; next.done(err); }); }, index, which, set); } } } } sync.start(function () { // if we have a set, it is our new "found" if (set) { found = Object.keys(set); } // the function to evalute results from the index var evaluate = function(primitive){ completed++; if ( primitive ){ var geometry = new Terraformer.Primitive(primitive.geometry); if (geometry.within(shape)){ if (self._stream) { if (completed === found.length) { self._stream.emit("end", primitive); } else { self._stream.emit("data", primitive); } } else { results.push(primitive); } } if(completed >= found.length){ if(!errors){ if (self._stream) { self._stream = null; } else if (callback) { callback( null, results ); } } else { if (callback) { callback("Could not get all geometries", null); } } } } }; var error = function(){ completed++; errors++; if(completed >= found.length){ if (callback) { callback("Could not get all geometries", null); } } }; // for each result see if the polygon contains the point if(found && found.length){ var getCB = function(err, result){ if (err) { error(); } else { evaluate( result ); } }; for (var i = 0; i < found.length; i++) { self.get(found[i], getCB); } } else { if (callback) { callback(null, results); } } }); })); }; GeoStore.prototype.update = function(geojson, callback){ var feature = Terraformer.Primitive(geojson); if (feature.type !== "Feature") { throw new Error("Terraform.GeoStore : only Features and FeatureCollections are supported"); } if(!feature.id) { throw new Error("Terraform.GeoStore : Feature does not have an id property"); } this.get(feature.id, bind(this, function( error, oldFeatureGeoJSON ){ if ( error ){ callback("Could find feature", null); } else { var oldFeature = new Terraformer.Primitive(oldFeatureGeoJSON); this.index.remove(oldFeature.envelope(), oldFeature.id); this.index.insert(feature.envelope(), feature.id); this.store.update(feature, callback); } })); }; // gets an item by id GeoStore.prototype.get = function(id, callback){ this.store.get( id, callback ); }; GeoStore.prototype.createReadStream = function () { this._stream = new Stream(); return this._stream; }; // add an index GeoStore.prototype.addIndex = function(index) { this._additional_indexes.push(index); }; /* "crime": { "equals": "arson" } index -> specific index that references the property keyword query -> object containing the specific queries for the index set -> object containing keys of all of the id's matching currently callback -> object containing keys of all of the id's still matching: { 1: true, 23: true } TODO: add functionality for "crime": { "or": { "equals": "arson", "equals": "theft" } } */ function eliminateForIndex(index, query, set, callback) { var queryKeys = Object.keys(query); var count = 0; for (var i = 0; i < queryKeys.length; i++) { if (typeof index[queryKeys[i]] !== "function") { callback("Index does not have a method matching " + queryKeys[i]); return; } index[queryKeys[i]](query[i], function (err, data) { count++; if (err) { callback(err); // short-circuit the scan, we hit an error. this is fatal. count = queryKeys.length; return; } else { var setKeys = Object.keys(set); for (var j = 0; j < setKeys.length; j++) { if (!data[setKeys[j]]) { delete set[setKeys[j]]; } } } if (count === queryKeys.length) { callback(null, set); } }); } } exports.GeoStore = GeoStore; return exports; }));
{ "content_hash": "4a897a3a80bbbd96fcbdbe880faf7b0b", "timestamp": "", "source": "github", "line_count": 557, "max_line_length": 125, "avg_line_length": 26.283662477558348, "alnum_prop": 0.5253415300546448, "repo_name": "ecaldwell/Terraformer", "id": "8662d8b0a401e6dcc95b97092031b45a7e84020f", "size": "14640", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dist/node/GeoStore/index.js", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace ZF2EntityAudit; use Zend\Mvc\MvcEvent; use ZF2EntityAudit\Audit\Configuration; use ZF2EntityAudit\Audit\Manager ; use ZF2EntityAudit\EventListener\CreateSchemaListener; use ZF2EntityAudit\EventListener\LogRevisionsListener; use ZF2EntityAudit\View\Helper\DateTimeFormatter; use ZF2EntityAudit\View\Helper\EntityLabel; use ZF2EntityAudit\View\Helper\User as UserBlock; use ZF2EntityAudit\View\Helper\Dump ; use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface; use Zend\Console\Adapter\AdapterInterface as Console; class Module implements ConsoleUsageProviderInterface { public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function onBootstrap(MvcEvent $e) { // Initialize the audit manager by creating an instance of it $sm = $e->getApplication()->getServiceManager(); $sm->get('auditManager'); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getServiceConfig() { return array( 'factories' => array( 'auditConfig' => function($sm){ $config = $sm->get('Config'); $auditconfig = new Configuration(); $auditconfig->setAuditedEntityClasses($config['zf2-entity-audit']['entities']); $auditconfig->setZfcUserEntityClass($config['zf2-entity-audit']['zfcuser.entity_class']); if (!empty($config['zf2-entity-audit']['note'])) { $auditconfig->setNote($config['zf2-entity-audit']['note']); } if (!empty($config['zf2-entity-audit']['noteFormField'])) { $auditconfig->setNoteFormField($config['zf2-entity-audit']['noteFormField']); } return $auditconfig; }, 'auditManager' => function ($sm) { $config = $sm->get('Config'); $evm = $sm->get('doctrine.eventmanager.orm_default'); $auditconfig = $sm->get('auditConfig'); if ($config['zf2-entity-audit']['zfcuser.integration'] === true) { $auth = $sm->get('zfcuser_auth_service'); if ($auth->hasIdentity()) { $identity = $auth->getIdentity(); $auditconfig->setCurrentUser($identity); } /* need to handle the unauthenticated user action case, do it your own , 99% i will drop support for unauthenticated user auditing */ } $auditManager = new Manager($auditconfig); $evm->addEventSubscriber(new CreateSchemaListener($auditManager)); $evm->addEventSubscriber(new LogRevisionsListener($auditManager)); return $auditManager; }, 'auditReader' => function($sm) { $auditManager = $sm->get('auditManager'); $entityManager = $sm->get('doctrine.entitymanager.orm_default'); return $auditManager->createAuditReader($entityManager); }, ), ); } public function getViewHelperConfig() { return array( 'factories' => array( 'DateTimeFormatter' => function($sm) { $Servicelocator = $sm->getServiceLocator(); $config = $Servicelocator->get("Config"); $format = $config['zf2-entity-audit']['ui']['datetime.format']; $formatter = new DateTimeFormatter(); return $formatter->setDateTimeFormat($format); }, 'UserBlock' => function($sm){ $Servicelocator = $sm->getServiceLocator(); $em = $Servicelocator->get("doctrine.entitymanager.orm_default"); $config = $Servicelocator->get("Config"); $helper = new UserBlock(); $helper->setEntityManager($em); $helper->setZfcUserEntityClass($config['zf2-entity-audit']['zfcuser.entity_class']); return $helper ; }, 'EntityLabel' => function($sm){ $helper = new EntityLabel(); return $helper ; }, 'Dump' => function(){ $helper = new Dump(); return $helper; } ) ); } public function getConsoleUsage(Console $console) { return array( "update" => "update the database from 0.1 to be 0.2 compatibale ", "initialize-revisions <userEmail>" => "create initial revisions for all audited entities that do not have any revision" ); } }
{ "content_hash": "33a9a7a141e97231b92eb3a544192b59", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 159, "avg_line_length": 39.30075187969925, "alnum_prop": 0.5201836617562655, "repo_name": "tawfekov/ZF2EntityAudit", "id": "49f37c0cdce6531d516f263b5f8be634ea7b7093", "size": "5227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Module.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "16760" }, { "name": "PHP", "bytes": "98039" } ], "symlink_target": "" }
/* * This file ethmac.c represents the MAC layer source file * of the UDP/IP stack. * * Author : Marco Russi * * Evolution of the file: * 10/08/2015 - File created - Marco Russi * */ /* TODO LIST: 1) implement the Pattern match filter feature: see setPatternMatchRXFilter() function 2) only one TX buffer is used at the moment! see ETHMAC_getTXBufferPointer function and ETHMAC_UC_TX_NUM_OF_BUFFERS define 3) implement a watermark reached interrupt management if necessary: see FLOW_CTRL_RX_BUFF_FULL define 4) check the ETHSTAT register to see transfer result in sendPacket function 5) check a 32-bit alignment for RX buffer allocation 6) implement a de-init function to free TX and RX buffers 7) in ETHMAC_Init function, set bInitSuccess flag according to other results also */ /* ----------------- Inclusions files ----------------- */ #include <xc.h> #include <sys/attribs.h> #include "p32mx795f512l.h" #include "../fw_common.h" #include "ethmac.h" #include "../sal/ip/ipv4.h" /* only use to obtain IPv4 datagram octects length */ /* ---------------------- Local defines -------------------- */ /* if uncomment, configure MAC as loopback. If comment, lopback is disabled */ //#define CONFIGURE_MAC_LOOPBACK /* if uncomment, use SW defined MAC address. If comment, use the device defined one */ //#define USE_SW_MAC_ADDRESS #ifdef USE_SW_MAC_ADDRESS /* SW defined MAC address */ #define ULL_SW_MAC_ADDRESS ((uint64)0x0000218956435612) #endif /* this value is related to ETHMAC_st_DataDcpt struct; 2 descriptors used for each TX buffer */ #define UC_NUM_OF_TX_DCPT ((uint8)(ETHMAC_UC_TX_NUM_OF_BUFFERS * UC_2)) /* num of RX descriptors */ #define UC_NUM_OF_RX_DCPT (ETHMAC_UC_RX_NUM_OF_BUFFERS) /* length of each buffer in bytes */ #define US_DATA_BUFFER_LENGTH (IPV4_US_ACCEPTED_MIN_LENGTH) /* Back to back inter-packet gap defined as default register value */ #define BB_INTERPACKET_GAP_VALUE 0x15 /* Non back to back inter-packet gap defined as default register value */ #define NBB_INTERPACKET_GAP_VALUE1 0xC #define NBB_INTERPACKET_GAP_VALUE2 0x12 /* Collision window defined as default register value */ #define COLLISION_WINDOW_VALUE 0x37 /* Number of retransmission defined as default register value */ #define NUM_OF_RETX_VALUE 0xF /* Maximum MAC supported RX frame size. Any incoming ETH frame that's longer than this size will be discarded. The default value is 1536 (allows for VLAN tagged frames, although the VLAN tagged frames are discarded). Normally there's no need to touch this value unless you know exactly the maximum size of the frames you want to process or you need to control packets fragmentation (together with the EMAC_RX_BUFF_SIZE. Note: Always multiple of 16. */ #define MAC_RX_MAX_FRAME 1536 /* Flow control */ #define FLOW_CTRL_PTV 16 /* Flow control RX buffer full. Should be greater than FLOW_CTRL_RX_BUFF_EMPTY */ /* ATTENTION: this value should be equal to or lower than UC_NUM_OF_RX_DCPT */ #define FLOW_CTRL_RX_BUFF_FULL (6) /* value check */ #if FLOW_CTRL_RX_BUFF_FULL > UC_NUM_OF_RX_DCPT #error FLOW_CTRL_RX_BUFF_FULL define is greater than UC_NUM_OF_RX_DCPT #endif /* Flow control RX buffer empty. Should be lower than FLOW_CTRL_RX_BUFF_FULL */ #define FLOW_CTRL_RX_BUFF_EMPTY 0x00 /* ETH internet priority value */ #define ETH_PRIORITY 5 #define ETH_SUB_PRIORITY 2 /* ETHCON1 register */ #define ETHCON_PTV_BIT_POS 16 #define ETHCON_ON_BIT_POS 15 #define ETHCON_TXRTS_BIT_POS 9 #define ETHCON_RXEN_BIT_POS 8 #define ETHCON_AUTOFC_BIT_POS 7 #define ETHCON_MANFC_BIT_POS 4 #define ETHCON_BUFCDEC_BIT_POS 0 /* ETHCON2 register */ #define ETHCON2_RXBUFSZ_BIT_POS 4 /* EMAC1CFG1 register */ #define EMAC1_SOFTRESET_BIT_POS 15 #define LOOPBACK_BIT_POS 4 #define TXPAUSE_BIT_POS 3 #define RXPAUSE_BIT_POS 2 #define RXENABLE_BIT_POS 0 /* EMAC1CFG2 register */ #define EXCESSDER_BIT_POS 14 #define BPNOBKOFF_BIT_POS 13 #define NOBKOFF_BIT_POS 12 #define LONGPRE_BIT_POS 9 #define PUREPRE_BIT_POS 8 #define AUTOPAD_BIT_POS 7 #define VLANPAD_BIT_POS 6 #define PADENABLE_BIT_POS 5 #define CRCENABLE_BIT_POS 4 #define DELAYCRC_BIT_POS 3 #define HUGEFRM_BIT_POS 2 #define LENGTHCK_BIT_POS 1 #define FULLDPLX_BIT_POS 0 /* EMAC1IPGR register */ #define NB2BIPKTGP1_BIT_POS 8 #define NB2BIPKTGP2_BIT_POS 0 /* EMAC1CLRT register */ #define CWINDOW_BIT_POS 8 #define RETX_BIT_POS 0 /* ETHSTAT register */ #define ETHSTAT_BUFCNT_BIT_POS 16 #define ETHSTAT_BUSY_BIT_POS 7 /* ETHIRQ register */ #define ETHIRQ_TXBUSE_BIT_POS 14 #define ETHIRQ_RXBUSE_BIT_POS 13 #define ETHIRQ_FWMARK_BIT_POS 8 #define ETHIRQ_RXDONE_BIT_POS 7 #define ETHIRQ_TXDONE_BIT_POS 3 #define ETHIRQ_RXOVFLW_BIT_POS 0 /* ETHRXFC register */ #define ETHRXFC_NOTPM_BIT_POS 12 #define ETHRXFC_PMMODE_BIT_POS 8 #define ETHRXFC_CRCERREN_BIT_POS 7 #define ETHRXFC_CRCOKEN_BIT_POS 6 #define ETHRXFC_RUNTEN_BIT_POS 4 #define ETHRXFC_UCEN_BIT_POS 3 #define ETHRXFC_NOTMEEN_BIT_POS 2 #define ETHRXFC_MCEN_BIT_POS 1 #define ETHRXFC_BCEN_BIT_POS 0 /* ETHRXWM register */ #define ETHRXWM_RXFWM_BIT_POS 16 #define ETHRXWM_RXEWM_BIT_POS 0 /* ETHIEN register */ #define TXBUSEIE_BIT_POS 14 #define RXBUSEIE_BIT_POS 13 #define EWMARKIE_BIT_POS 9 #define FWMARKIE_BIT_POS 8 #define RXDONEIE_BIT_POS 7 #define PKTPENDIE_BIT_POS 6 #define RXACTIE_BIT_POS 5 #define TXDONEIE_BIT_POS 3 #define TXABORTIE_BIT_POS 2 #define RXBUFNAIE_BIT_POS 1 #define RXOVFLWIE_BIT_POS 0 /* IEC1 interrupt control register */ #define ETHIE_BIT_POS 28 /* IFS1 interrupt flag register */ #define ETHIF_BIT_POS 28 /* IPC12 interrupt priority register */ #define ETHPRI_BIT_POS 2 #define ETHSUBPRI_BIT_POS 0 /* ---------------- Local enums declaration -------------- */ /* RX filter pattern match mode */ typedef enum { MATCH_DISABLED, /* Disabled, pattern match is always unsuccessful */ NOTPM_XOR_CKS, /* NOTPM = 1 XOR Pattern Match Checksum matches */ NOTPM_XOR_CKS_AND_STAT_ADD, /* (NOTPM = 1 XOR Pattern Match Checksum matches) AND Destination Address = Station Address */ NOTPM_XOR_CKS_AND_UNIC_ADD, /* (NOTPM = 1 XOR Pattern Match Checksum matches) AND Destination Address = Unicast Address */ NOTPM_XOR_CKS_AND_BROAD_ADD, /* (NOTPM = 1 XOR Pattern Match Checksum matches) AND Destination Address = Broadcast Address */ NOTPM_XOR_CKS_AND_HASHT_ADD, /* (NOTPM = 1 XOR Pattern Match Checksum matches) AND Hash Table filter match */ NOTPM_XOR_CKS_AND_MAGIC_ADD /* (NOTPM = 1 XOR Pattern Match Checksum matches) AND Packet = Magic Packet */ } KE_FILTER_MATCH_MODE; /* --------------- Local structs defines -------------- */ /* Ethernet TX buffer descriptor */ typedef struct { volatile union { struct { unsigned: 7; unsigned EOWN: 1; unsigned NPV: 1; unsigned: 7; unsigned bCount: 11; unsigned: 3; unsigned EOP: 1; unsigned SOP: 1; }; unsigned int w; }hdr; unsigned char* pEDBuff; volatile unsigned long long stat; unsigned int next_ed; }__attribute__ ((__packed__)) st_TXEthDcpt; /* Ethernet RX buffer descriptor */ typedef struct { volatile union { struct { unsigned: 7; unsigned EOWN: 1; unsigned NPV: 1; unsigned: 7; unsigned bCount: 11; unsigned: 3; unsigned EOP: 1; unsigned SOP: 1; }flags; unsigned int w; }hdr; unsigned char* pEDBuff; volatile union { struct { unsigned PKT_Checksum: 16; unsigned: 8; unsigned RXF_RSV: 8; unsigned RSV: 32; }rxstat; unsigned long long s; }stat; unsigned int next_ed; }__attribute__ ((__packed__)) st_RXEthDcpt; /* -------------- Local macros declaration ----------- */ /* peripheral hardware macros */ #define ENABLE_ETH_INT() (IEC1SET = (1 << ETHIE_BIT_POS)) #define DISABLE_ETH_INT() (IEC1CLR = (1 << ETHIE_BIT_POS)) #define CLEAR_ETH_INT_FLAG() (IFS1CLR = (1 << ETHIF_BIT_POS)) #define ENABLE_ETH_MODULE() (ETHCON1SET = (1 << ETHCON_ON_BIT_POS)) #define DISABLE_ETH_MODULE() (ETHCON1CLR = (1 << ETHCON_ON_BIT_POS)) #define CHECK_ETH_IS_BUSY() ((ETHSTAT & (1 << ETHSTAT_BUSY_BIT_POS)) > 0) #define CHECK_TX_IS_DONE() ((ETHCON1 & (1 << ETHCON_TXRTS_BIT_POS)) > 0) /* Ethernet datagram related set macros */ #define SET_ETHERTYPE(x,y) ((x) = SWAP_BYTES_ORDER_16BIT_(y)) /* ----------- Exported variables declaration ------------ */ /* MAC address of this device */ EXPORTED uint64 ETHMAC_ui64MACAddress; /* --------------- Local variables declaration ------------ */ /* TX descriptors data buffers */ LOCAL uint8 *apui8TXDcptDataBuffers[(UC_NUM_OF_TX_DCPT / 2)]; /* RX descriptors data buffers */ LOCAL uint8 *apui8RXDcptDataBuffers[UC_NUM_OF_RX_DCPT]; /* Descriptors array */ LOCAL st_TXEthDcpt stTXArrayDcpt[UC_NUM_OF_TX_DCPT]; LOCAL st_RXEthDcpt stRXArrayDcpt[UC_NUM_OF_RX_DCPT]; /* RX descriptors counter. Used by ETHMAC_getNextRXDataBuffer function */ LOCAL uint8 ui8RXDcptCount; /* RX current descriptor pointer. Used by ETHMAC_getNextRXDataBuffer function */ LOCAL st_RXEthDcpt *stRXCurrEthDcpt; /* Pending RX descriptor to clear flag. Used by ETHMAC_getNextRXDataBuffer function */ LOCAL boolean bPrevPending; /* --------------- Local functions prototypes ---------------- */ LOCAL void setDestMACAddress (uint8 *, uint64); LOCAL void setSrcMACAddress (uint8 *, uint64); LOCAL void sendPacket (uint8 **, uint16 *, uint16); LOCAL void setRXPacket (uint8 **, uint16, uint16); LOCAL void resetEthController (void); LOCAL void resetMACModule (void); LOCAL void configureMACModule (void); LOCAL void initEthController (void); LOCAL void setPatternMatchRXFilter (KE_FILTER_MATCH_MODE, uint64, uint16, uint16, boolean); /* ------------- Exported functions implementation -------------------- */ /* Init ETHMAC module */ /* TODO: set bInitSuccess flag according to other results also */ EXPORTED boolean ETHMAC_Init( void ) { uint8 ui8BuffCount; boolean bInitSuccess; boolean bPHYInitSuccess = B_FALSE; /* init all RX descriptors buffers */ for(ui8BuffCount = UC_NULL; ui8BuffCount < UC_NUM_OF_RX_DCPT; ui8BuffCount++) { /* ATTENTION: it is necessary that IP header is always 32-bit aligned: * the 2 bytes are added in order to occupy 16 bytes with a 14-byte header, * the first 2 bytes are wasted */ apui8RXDcptDataBuffers[ui8BuffCount] = (uint8 *)MEM_MALLOC(US_DATA_BUFFER_LENGTH + UC_2) + UC_2; } /* init all RX descriptors buffers */ for(ui8BuffCount = UC_NULL; ui8BuffCount < (UC_NUM_OF_TX_DCPT / 2); ui8BuffCount++) { apui8TXDcptDataBuffers[ui8BuffCount] = (uint8 *)MEM_MALLOC(US_DATA_BUFFER_LENGTH); ALIGN_32BIT_OF_8BIT_PTR(apui8TXDcptDataBuffers[ui8BuffCount]); apui8TXDcptDataBuffers[ui8BuffCount] += (US_DATA_BUFFER_LENGTH - US_1); } /* no pending RX descriptors to clear */ bPrevPending = B_FALSE; /* --- Ethernet controller reset --- */ resetEthController(); /* --- MAC module reset --- */ resetMACModule(); /* enable ETH module */ /* ATTENTION: the ETH module should be turn on before any PHY operation */ ENABLE_ETH_MODULE(); /* --- EXT PHY module initialization --- */ bPHYInitSuccess = ETHPHY_Init(); /* if external PHY init is success */ if(B_TRUE == bPHYInitSuccess) { /* go on to config MAC and init ethernet controller */ /* --- MAC module configuration --- */ configureMACModule(); /* --- Ethernet controller initialisation --- */ initEthController(); /* init success */ bInitSuccess = B_TRUE; } else { /* init fail */ bInitSuccess = B_FALSE; } return bInitSuccess; } /* Function to get next received data pointer */ EXPORTED uint8 * ETHMAC_getNextRXDataBuffer( void ) { uint8 *pui8DataBufPtr = NULL; if(bPrevPending == B_TRUE) { /* restore previous descriptor */ stRXCurrEthDcpt->hdr.w = 0; /* clear all the fields */ stRXCurrEthDcpt->hdr.flags.NPV = 1; /* set next pointer valid */ stRXCurrEthDcpt->hdr.flags.EOWN = 1; /* set hardware ownership */ stRXCurrEthDcpt->stat.s = 0; /* clear stat field */ /* decrement received packet buffer count */ ETHCON1SET = (1 << ETHCON_BUFCDEC_BIT_POS); bPrevPending = B_FALSE; } else { /* if first call then start from first descriptor */ ui8RXDcptCount = UC_NUM_OF_RX_DCPT; stRXCurrEthDcpt = &stRXArrayDcpt[US_NULL]; } /* get next pointer */ while((ui8RXDcptCount > UC_NULL) && (stRXCurrEthDcpt->hdr.flags.EOWN == 1)) { /* decrement descriptor counter */ ui8RXDcptCount--; /* next descriptor */ stRXCurrEthDcpt++; } /* end of list reached */ if(ui8RXDcptCount == UC_NULL) { /* pointer is NULL */ pui8DataBufPtr = NULL; } else { /* check if SW ownership */ if(stRXCurrEthDcpt->hdr.flags.EOWN == 0) { /* get buffer pinter */ pui8DataBufPtr = (uint8 *)PA_TO_KVA1((uint32)stRXCurrEthDcpt->pEDBuff); bPrevPending = B_TRUE; } else { /* pointer is NULL */ pui8DataBufPtr = NULL; } } return pui8DataBufPtr; } /* send packet. Data buffers have been previously saved into the shared ETHMAC_stTXDataBuffer structure */ EXPORTED void ETHMAC_sendPacket( uint8 *pui8FramePtr, uint16 ui16DataLength, uint64 ui64HWSrcAdd, uint64 ui64HWDstAdd, uint16 ui16EthType ) { uint8 aui8EthernetHeader[ETHMAC_UC_ETH_HDR_LENGTH]; uint8 *apui8PtrsArray[UC_2]; uint16 aui16LengthArray[UC_2]; /* set ETH addresses and type */ setDestMACAddress(&aui8EthernetHeader[UC_0], ui64HWDstAdd); setSrcMACAddress(&aui8EthernetHeader[ETHMAC_UC_ETH_ADD_LENGTH], ui64HWSrcAdd); /* set ethernet type */ SET_ETHERTYPE(*((uint16 *)(&aui8EthernetHeader[(UC_2 * ETHMAC_UC_ETH_ADD_LENGTH)])), ui16EthType); /* 1 TX descriptor for the ethernet header */ apui8PtrsArray[UC_0] = aui8EthernetHeader; aui16LengthArray[UC_0] = ETHMAC_UC_ETH_HDR_LENGTH; /* 1 TX descriptor for the rest of the packet */ apui8PtrsArray[UC_1] = pui8FramePtr; aui16LengthArray[UC_1] = ui16DataLength; /* 2 TX descriptors are used for each TX packet */ sendPacket(apui8PtrsArray, aui16LengthArray, US_2); } /* Function to get next TX buffer pointer where upper layers write data. The pointer value is calculated according to required buffer length. */ EXPORTED uint8 * ETHMAC_getTXBufferPointer( uint16 ui16ReqBufLength ) { uint8 *pui8RetPtr; /* ATTENTION: only one buffer is used at the moment */ pui8RetPtr = (uint8 *)(apui8TXDcptDataBuffers[0] - ui16ReqBufLength); return pui8RetPtr; } /* ------------------ Local functions implementation --------------------- */ /* set destination MAC address */ LOCAL void setDestMACAddress(uint8 *pui8Frame, uint64 ui64MACAddress) { *pui8Frame++ = (uint8)((ui64MACAddress & 0x0000FF0000000000) >> ULL_SHIFT_40); *pui8Frame++ = (uint8)((ui64MACAddress & 0x000000FF00000000) >> ULL_SHIFT_32); *pui8Frame++ = (uint8)((ui64MACAddress & 0x00000000FF000000) >> ULL_SHIFT_24); *pui8Frame++ = (uint8)((ui64MACAddress & 0x0000000000FF0000) >> ULL_SHIFT_16); *pui8Frame++ = (uint8)((ui64MACAddress & 0x000000000000FF00) >> ULL_SHIFT_8); *pui8Frame = (uint8)(ui64MACAddress & 0x00000000000000FF); } /* set source MAC address */ LOCAL void setSrcMACAddress(uint8 *pui8Frame, uint64 ui64MACAddress) { *pui8Frame++ = (uint8)((ui64MACAddress & 0x0000FF0000000000) >> ULL_SHIFT_40); *pui8Frame++ = (uint8)((ui64MACAddress & 0x000000FF00000000) >> ULL_SHIFT_32); *pui8Frame++ = (uint8)((ui64MACAddress & 0x00000000FF000000) >> ULL_SHIFT_24); *pui8Frame++ = (uint8)((ui64MACAddress & 0x0000000000FF0000) >> ULL_SHIFT_16); *pui8Frame++ = (uint8)((ui64MACAddress & 0x000000000000FF00) >> ULL_SHIFT_8); *pui8Frame = (uint8)(ui64MACAddress & 0x00000000000000FF); } /* update TX descriptors fields and start transmission */ LOCAL void sendPacket( uint8 **pui8ArrayBuffers, uint16 *pui16ArraySizes, uint16 ui16ArrayItems ) { uint8 ui8BufferIndex; st_TXEthDcpt* pstCurrDcpt; st_TXEthDcpt* pstTailDcpt; /* init descriptors */ pstCurrDcpt = stTXArrayDcpt; /* init current descriptor with the first one */ pstTailDcpt = NULL; /* init tail descriptor with 0 */ /* set every descriptor with data buffers */ for(ui8BufferIndex = UC_NULL; ui8BufferIndex < ui16ArrayItems; ui8BufferIndex++, pstCurrDcpt++, pui8ArrayBuffers++, pui16ArraySizes++) { pstCurrDcpt->pEDBuff = (uint8*)KVA_TO_PA(*pui8ArrayBuffers); /* copy data buffer pointer */ pstCurrDcpt->hdr.w = 0; /* clear all the fields */ pstCurrDcpt->hdr.NPV = 1; /* set next pointer valid */ pstCurrDcpt->hdr.EOWN = 1; /* set hardware ownership */ pstCurrDcpt->hdr.bCount = *pui16ArraySizes; /* set proper size */ /* set tail descriptor */ if(NULL != pstTailDcpt) { pstTailDcpt->next_ed = KVA_TO_PA(pstCurrDcpt); } pstTailDcpt = pstCurrDcpt; } /* descriptors list end as circular buffer (set the first buffer as the next one) */ pstTailDcpt->next_ed = KVA_TO_PA(stTXArrayDcpt); /* anyway this is not used */ /* prepare descriptors array */ stTXArrayDcpt[0].hdr.SOP = 1; /* start of packet */ stTXArrayDcpt[(ui16ArrayItems - US_1)].hdr.EOP = 1; /* end of packet */ /* set the TX descriptors start address */ ETHTXST = KVA_TO_PA(stTXArrayDcpt); /* start transmission */ ETHCON1SET = (1 << ETHCON_TXRTS_BIT_POS); /* wait until packet is sent */ while(CHECK_TX_IS_DONE()); /* ATTENTION: maybe it is not necessary to wait... */ } /* update RX descriptors fields in order to receive packets */ LOCAL void setRXPacket( uint8** pui8ArrayBuffers, uint16 ui16ArraySize, uint16 ui16ArrayItems ) { uint8 ui8BufferIndex; st_RXEthDcpt* pstCurrDcpt; st_RXEthDcpt* pstTailDcpt; /* init descriptors */ pstCurrDcpt = stRXArrayDcpt; /* init current descriptor with the first one */ pstTailDcpt = NULL; /* init tail descriptor with 0 */ /* set the RX data buffer size */ ETHCON2 = ((ui16ArraySize / UL_16) << ETHCON2_RXBUFSZ_BIT_POS); /* set every descriptor with data buffers */ for(ui8BufferIndex = UC_NULL; ui8BufferIndex < ui16ArrayItems; ui8BufferIndex++, pstCurrDcpt++, pui8ArrayBuffers++) { pstCurrDcpt->pEDBuff = (uint8 *)KVA_TO_PA(*pui8ArrayBuffers); /* copy data buffer pointer */ pstCurrDcpt->hdr.w = 0; /* clear all the fields */ pstCurrDcpt->hdr.flags.NPV = 1; /* set next pointer valid */ pstCurrDcpt->hdr.flags.EOWN = 1; /* set hardware ownership */ /* set tail descriptor */ if(NULL != pstTailDcpt) { pstTailDcpt->next_ed = KVA_TO_PA(pstCurrDcpt); } pstTailDcpt = pstCurrDcpt; } /* connect first descriptor after last descriptor in the ring */ pstTailDcpt->next_ed = KVA_TO_PA(stRXArrayDcpt); /* set RX descriptors start address */ ETHRXST = KVA_TO_PA(stRXArrayDcpt); /* once RX enabled, the Ethernet Controller will receive frames and place them in the receive buffers we just programmed */ /* to check eventuals received packet check the BUFCNT (ETHSTAT<16:23>) or RXDONE (ETHIRQ<7>) */ } /* reset ETH controller */ LOCAL void resetEthController(void) { /* disable ethernet interrupt */ DISABLE_ETH_INT(); /* turn ethernet controller off */ ETHCON1CLR = (1 << ETHCON_ON_BIT_POS) | (1 << ETHCON_RXEN_BIT_POS) | (1 << ETHCON_TXRTS_BIT_POS); /* abort the Wait activity by polling ETHBUSY bit */ while(CHECK_ETH_IS_BUSY()); /* clear ethernet interrupt flag */ CLEAR_ETH_INT_FLAG(); /* disable ethernet controller interrupt generation */ ETHIEN = 0; /* clear eventual int events */ ETHIRQ = 0; /* clear ethernet TX and RX start addresses */ ETHTXST = 0; ETHRXST = 0; } /* reset MAC module */ LOCAL void resetMACModule (void) { /* reset MAC */ EMAC1CFG1SET = (1 << EMAC1_SOFTRESET_BIT_POS); asm("nop"); EMAC1CFG1CLR = (1 << EMAC1_SOFTRESET_BIT_POS); } /* configure MAC module registers */ LOCAL void configureMACModule (void) { /* enable MAC receive */ EMAC1CFG1SET = (1 << RXENABLE_BIT_POS); /* set MAC TX flow control */ EMAC1CFG1SET = (1 << TXPAUSE_BIT_POS); /* set MAC RX flow control */ EMAC1CFG1SET = (1 << RXPAUSE_BIT_POS); #ifdef CONFIGURE_MAC_LOOPBACK /* set MAC loopback */ EMAC1CFG1SET = (1 << LOOPBACK_BIT_POS); #endif /* Padding and CRC append are enabled by default */ #if 0 /* if this small frames will be not sent... maybe */ /* disable automatic padding generation */ EMAC1CFG2CLR = (1 << PADENABLE_BIT_POS); EMAC1CFG2CLR = (1 << VLANPAD_BIT_POS); EMAC1CFG2CLR = (1 << AUTOPAD_BIT_POS); /* disable automatic CRC generation and append */ EMAC1CFG2CLR = (1 << CRCENABLE_BIT_POS); #endif /* allow to tx and rx huge frames */ EMAC1CFG2SET = (1 << HUGEFRM_BIT_POS); /* ATTENTION: if following values are defined as default register values than it is not necessary to write them */ /* program back-to-back inter-packet gap */ EMAC1IPGT = BB_INTERPACKET_GAP_VALUE; /* program non back-to-back inter-packet gap */ EMAC1IPGRCLR = (0x7F << NB2BIPKTGP1_BIT_POS); EMAC1IPGRSET = ((NBB_INTERPACKET_GAP_VALUE1 & 0x7F) << NB2BIPKTGP1_BIT_POS); EMAC1IPGRCLR = (0x7F << NB2BIPKTGP2_BIT_POS); EMAC1IPGRSET = ((NBB_INTERPACKET_GAP_VALUE2 & 0x7F) << NB2BIPKTGP2_BIT_POS); /* set the collision window */ EMAC1CLRTCLR = (0x3F << CWINDOW_BIT_POS); EMAC1CLRTSET = ((COLLISION_WINDOW_VALUE & 0x3F) << CWINDOW_BIT_POS); /* set the maxinum number of retransmissions */ EMAC1CLRTCLR = (0x0F << RETX_BIT_POS); EMAC1CLRTSET = ((NUM_OF_RETX_VALUE & 0x0F) << RETX_BIT_POS); /* set maximum frame length */ EMAC1MAXF = MAC_RX_MAX_FRAME; /* Update SW defined MAC address */ #ifdef USE_SW_MAC_ADDRESS EMAC1SA0 = (uint16)ULL_SW_MAC_ADDRESS; EMAC1SA1 = (uint16)(ULL_SW_MAC_ADDRESS >> ULL_SHIFT_16); EMAC1SA2 = (uint16)(ULL_SW_MAC_ADDRESS >> ULL_SHIFT_32); /* most significant - first transmitted */ #endif /* prepare MAC address variable value */ ETHMAC_ui64MACAddress = ULL_NULL; ETHMAC_ui64MACAddress = (uint64)EMAC1SA0; ETHMAC_ui64MACAddress |= ((uint64)EMAC1SA1 << ULL_SHIFT_16); ETHMAC_ui64MACAddress |= ((uint64)EMAC1SA2 << ULL_SHIFT_32); } /* init ETH controller registers */ LOCAL void initEthController( void ) { /* stop an eventual transmit */ ETHCON1CLR = (1 << ETHCON_TXRTS_BIT_POS); /* set PTV value */ ETHCON1CLR = (0xFFFF << ETHCON_PTV_BIT_POS); ETHCON1SET = (FLOW_CTRL_PTV << ETHCON_PTV_BIT_POS); /* set RX buffer full watermark pointer */ ETHRXWMCLR = (0xFF << ETHRXWM_RXFWM_BIT_POS); ETHRXWMSET = (FLOW_CTRL_RX_BUFF_FULL << ETHRXWM_RXFWM_BIT_POS); /* set RX buffer empty watermark pointer */ ETHRXWMCLR = (0xFF << ETHRXWM_RXEWM_BIT_POS); ETHRXWMSET = (FLOW_CTRL_RX_BUFF_EMPTY << ETHRXWM_RXEWM_BIT_POS); /* disable manual flow control */ ETHCON1CLR = (1 << ETHCON_MANFC_BIT_POS); /* enable auto flow control */ ETHCON1SET = (1 << ETHCON_AUTOFC_BIT_POS); /* ATTENTION: set RX filters here */ /* enable RX filters */ // ETHRXFCSET = (1 << ETHRXFC_CRCERREN_BIT_POS); ETHRXFCSET = (1 << ETHRXFC_CRCOKEN_BIT_POS); ETHRXFCSET = (1 << ETHRXFC_RUNTEN_BIT_POS); ETHRXFCSET = (1 << ETHRXFC_UCEN_BIT_POS); ETHRXFCSET = (1 << ETHRXFC_NOTMEEN_BIT_POS); ETHRXFCSET = (1 << ETHRXFC_MCEN_BIT_POS); ETHRXFCSET = (1 << ETHRXFC_BCEN_BIT_POS); /* set RX pattern match filter */ /* ATTENTION: not supported yet! */ // setPatternMatchRXFilter(...); /* prepare RX packet */ setRXPacket(apui8RXDcptDataBuffers, US_DATA_BUFFER_LENGTH, UC_NUM_OF_RX_DCPT); /* set eth interrupts */ ETHIENSET = (1 << TXBUSEIE_BIT_POS); ETHIENSET = (1 << RXBUSEIE_BIT_POS); // ETHIENSET = (1 << FWMARKIE_BIT_POS); // ETHIENSET = (1 << RXDONEIE_BIT_POS); // ETHIENSET = (1 << TXDONEIE_BIT_POS); ETHIENSET = (1 << RXOVFLWIE_BIT_POS); /* set int priority */ IPC12SET = (ETH_PRIORITY << ETHPRI_BIT_POS); IPC12SET = (ETH_SUB_PRIORITY << ETHSUBPRI_BIT_POS); /* enable interrupt */ ENABLE_ETH_INT(); /* enable reception */ ETHCON1SET = (1 << ETHCON_RXEN_BIT_POS); } /* set pattern match filter registers */ LOCAL void setPatternMatchRXFilter( KE_FILTER_MATCH_MODE eMatchMode, uint64 ui64matchMask, uint16 ui16matchOffs, uint16 matchChecksum, boolean bmatchInvert) { /* clear PMMODE bits (pattern match mode) */ ETHRXFCCLR = (0xF << ETHRXFC_PMMODE_BIT_POS); /* set match mask */ ETHPMM0 = (uint32)ui64matchMask; ETHPMM1 = (uint32)(ui64matchMask >> ULL_SHIFT_32); /* set match offset */ ETHPMO = ui16matchOffs; /* set match checksum */ ETHPMCS = matchChecksum; /* update match invert */ if(B_TRUE == bmatchInvert) { ETHRXFCSET = (1 << ETHRXFC_NOTPM_BIT_POS); /* set NOTPM */ } else { ETHRXFCCLR = (1 << ETHRXFC_NOTPM_BIT_POS); /* clear NOTPM */ } /* set pattern match mode */ switch(eMatchMode) { case MATCH_DISABLED: { /* leave disabled */ break; } case NOTPM_XOR_CKS: { ETHRXFCSET = (0x1 << ETHRXFC_PMMODE_BIT_POS); break; } case NOTPM_XOR_CKS_AND_STAT_ADD: { ETHRXFCSET = (0x2 << ETHRXFC_PMMODE_BIT_POS); /* 0x3 is valid as well */ break; } case NOTPM_XOR_CKS_AND_UNIC_ADD: { ETHRXFCSET = (0x4 << ETHRXFC_PMMODE_BIT_POS); /* 0x5 is valid as well */ break; } case NOTPM_XOR_CKS_AND_BROAD_ADD: { ETHRXFCSET = (0x6 << ETHRXFC_PMMODE_BIT_POS); /* 0x7 is valid as well */ break; } case NOTPM_XOR_CKS_AND_HASHT_ADD: { ETHRXFCSET = (0x8 << ETHRXFC_PMMODE_BIT_POS); break; } case NOTPM_XOR_CKS_AND_MAGIC_ADD: { ETHRXFCSET = (0x9 << ETHRXFC_PMMODE_BIT_POS); break; } default: { /* leave disabled */ break; } } } /* ETH Interrupt service routine */ LOCAL void __ISR(_ETH_VECTOR, ipl5) Eth_IntHandler (void) { uint16 ui16EthFlags; // ETHMAC_st_DataDcpt *stDataDcpt; /* read interrupt flags */ ui16EthFlags = ETHIRQ; /* the sooner we acknowledge, the smaller the chance to miss another event of the same type because of a lengthy ISR */ /* acknowledge the interrupt flags */ ETHIRQCLR = ui16EthFlags; // if((ui16EthFlags & (1 << ETHIRQ_FWMARK_BIT_POS)) > 0) // if((ui16EthFlags & (1 << ETHIRQ_TXBUSE_BIT_POS)) > 0) // if((ui16EthFlags & (1 << ETHIRQ_RXBUSE_BIT_POS)) > 0) // if((ui16EthFlags & (1 << ETHIRQ_RXOVFLW_BIT_POS)) > 0) // if((ui16EthFlags & (1 << ETHIRQ_RXDONE_BIT_POS)) > 0) // if((ui16EthFlags & (1 << ETHIRQ_TXDONE_BIT_POS)) > 0) /* clear interrupt flag */ CLEAR_ETH_INT_FLAG(); } /* End of file */
{ "content_hash": "fa19027fd9623c82689ff8bd7dc8d8bb", "timestamp": "", "source": "github", "line_count": 914, "max_line_length": 156, "avg_line_length": 33.11706783369803, "alnum_prop": 0.5918266212957151, "repo_name": "marcorussi/minIP", "id": "1e76fe7305cfce541bf3c46cbb9e62ab1a8387a4", "size": "31433", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/hal/ethmac.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1941972" }, { "name": "C++", "bytes": "40165" } ], "symlink_target": "" }
const fs = require('fs'); const sourceTrace = require('source-trace'); const { promisify } = require('util'); const glob = promisify(require('glob')); const stat = promisify(fs.stat); module.exports = async mains => { if (typeof mains === 'string') { mains = [mains]; } const uniqueFiles = mains .reduce((prev, curr) => { return prev.concat(sourceTrace(curr)); }, []) .filter((val, idx, arr) => { return arr.indexOf(val) === idx; }); return await uniqueFiles.reduce(async (total, file) => { return (await total) + (await stat(file)).size; }, Promise.resolve(0)); };
{ "content_hash": "7820df7b07f3a4b70d55279d5721b13e", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 58, "avg_line_length": 25.666666666666668, "alnum_prop": 0.6055194805194806, "repo_name": "bramblejs/bramble", "id": "ef19d285f77f3b069f1635c0646a10a314e943ec", "size": "616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/size.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "280" }, { "name": "JavaScript", "bytes": "9779" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.flink</groupId> <artifactId>flink-end-to-end-tests</artifactId> <version>1.10-SNAPSHOT</version> <relativePath>..</relativePath> </parent> <artifactId>flink-dataset-fine-grained-recovery-test</artifactId> <name>flink-dataset-fine-grained-recovery-test</name> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-java</artifactId> <version>${project.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <executions> <execution> <id>dataset-fine-grained-recovery</id> <phase>test</phase> <goals> <goal>test</goal> </goals> <configuration> <includes> <include>**/*Test.*</include> </includes> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <executions> <execution> <id>DataSetFineGrainedRecoveryTestProgram</id> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <finalName>DataSetFineGrainedRecoveryTestProgram</finalName> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>org.apache.flink.batch.tests.DataSetFineGrainedRecoveryTestProgram</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "932dbce689bc408e8b381d5c3f7e8e5f", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 106, "avg_line_length": 31.415730337078653, "alnum_prop": 0.702074391988555, "repo_name": "mbode/flink", "id": "ecde754302e6cac2d3fc3ebe00e090c71e34a3e6", "size": "2796", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "flink-end-to-end-tests/flink-dataset-fine-grained-recovery-test/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5666" }, { "name": "CSS", "bytes": "18100" }, { "name": "Clojure", "bytes": "80170" }, { "name": "CoffeeScript", "bytes": "91220" }, { "name": "Dockerfile", "bytes": "9756" }, { "name": "HTML", "bytes": "86821" }, { "name": "Java", "bytes": "40396270" }, { "name": "JavaScript", "bytes": "8267" }, { "name": "Python", "bytes": "249644" }, { "name": "Scala", "bytes": "7495458" }, { "name": "Shell", "bytes": "388738" } ], "symlink_target": "" }
package testexecutionservice import ( "context" "errors" "github.com/census-ecosystem/opencensus-experiments/interoptest/src/testcoordinator/genproto" "sync" "google.golang.org/grpc" ) // Sender is the type that stores necessary information for making test requests, and sends // test execution request to each test server. type Sender struct { mu sync.RWMutex canDialInsecure bool reqID int64 reqName string serverAddr string hops []*interop.ServiceHop } var ( errAlreadyStarted = errors.New("already started") errSizeNotMatch = errors.New("sizes do not match") ) // NewUnstartedSender just creates a new Sender. // TODO: consider using options. func NewUnstartedSender( canDialInsecure bool, reqID int64, reqName string, serverAddr string, hops []*interop.ServiceHop) (*Sender, error) { s := &Sender{ canDialInsecure: canDialInsecure, reqID: reqID, reqName: reqName, serverAddr: serverAddr, hops: hops, } return s, nil } // Start transforms the request id, request name and Services into a TestRequest. // Then sends a TestRequest to the corresponding server, and returns the response // and error. func (s *Sender) Start() (*interop.TestResponse, error) { var resp *interop.TestResponse addr := s.serverAddr var err error if cc, err := s.dialToServer(addr); err == nil { resp, err = s.send(cc) } return resp, err } // TODO: send HTTP TestRequest func (s *Sender) send(cc *grpc.ClientConn) (*interop.TestResponse, error) { defer cc.Close() req := &interop.TestRequest{ Id: s.reqID, Name: s.reqName, ServiceHops: s.hops, } testSvcClient := interop.NewTestExecutionServiceClient(cc) return testSvcClient.Test(context.Background(), req) } func (s *Sender) dialToServer(addr string) (*grpc.ClientConn, error) { var dialOpts []grpc.DialOption if s.canDialInsecure { dialOpts = append(dialOpts, grpc.WithInsecure()) } return grpc.Dial(addr, dialOpts...) }
{ "content_hash": "b80746ae1226bbed846fef2b8f2b0723", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 94, "avg_line_length": 24.9, "alnum_prop": 0.7093373493975904, "repo_name": "census-ecosystem/opencensus-experiments", "id": "b99b787e87ff28048c08429f01ae73131bae4992", "size": "2589", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "interoptest/src/testcoordinator/testexecutionservice/request_sender.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "8479" }, { "name": "Dockerfile", "bytes": "5150" }, { "name": "Go", "bytes": "160963" }, { "name": "HTML", "bytes": "4460" }, { "name": "Java", "bytes": "106104" }, { "name": "JavaScript", "bytes": "105695" }, { "name": "Makefile", "bytes": "1231" }, { "name": "Python", "bytes": "33236" }, { "name": "Shell", "bytes": "15389" } ], "symlink_target": "" }
using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; namespace JsonApiDotNetCoreTests.IntegrationTests.ControllerActionResults; [UsedImplicitly(ImplicitUseTargetFlags.Members)] [Resource(ControllerNamespace = "JsonApiDotNetCoreTests.IntegrationTests.ControllerActionResults")] public sealed class Toothbrush : Identifiable<int> { [Attr] public bool IsElectric { get; set; } }
{ "content_hash": "50dbba789e7e5a7bf2b0bb8e21484c63", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 99, "avg_line_length": 34.15384615384615, "alnum_prop": 0.8355855855855856, "repo_name": "json-api-dotnet/JsonApiDotNetCore", "id": "4e6769756ab898bacc3642f7f179075c51b9b045", "size": "444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/JsonApiDotNetCoreTests/IntegrationTests/ControllerActionResults/Toothbrush.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3762090" }, { "name": "PowerShell", "bytes": "7865" }, { "name": "XSLT", "bytes": "1605" } ], "symlink_target": "" }
#ifndef NF_DATA_TRAIL_MODULE_H #define NF_DATA_TRAIL_MODULE_H #include "NFComm/NFPluginModule/NFIKernelModule.h" #include "NFComm/NFPluginModule/NFIPropertyModule.h" #include "NFComm/NFPluginModule/NFIElementModule.h" #include "NFComm/NFPluginModule/NFIClassModule.h" #include "NFComm/NFPluginModule/NFIPropertyConfigModule.h" #include "NFComm/NFPluginModule/NFIPluginManager.h" #include "NFComm/NFPluginModule/NFIDataTailModule.h" #include "NFComm/NFPluginModule/NFILogModule.h" class NFDataTailModule : public NFIDataTailModule { public: NFDataTailModule(NFIPluginManager* p) { pPluginManager = p; } virtual ~NFDataTailModule() {}; virtual bool Init(); virtual bool Shut(); virtual bool Execute(); virtual bool AfterInit(); virtual void LogObjectData(const NFGUID& self); virtual void StartTrail(const NFGUID& self); protected: void PrintStackTrace(); int TrailObjectData(const NFGUID& self); int OnClassObjectEvent(const NFGUID& self, const std::string& className, const CLASS_OBJECT_EVENT classEvent, const NFDataList& var); int OnObjectPropertyEvent(const NFGUID& self, const std::string& propertyName, const NFData& oldVar, const NFData& newVar, const NFINT64 reason); int OnObjectRecordEvent(const NFGUID& self, const RECORD_EVENT_DATA& eventData, const NFData& oldVar, const NFData& newVar); private: NFIKernelModule* m_pKernelModule; NFIElementModule* m_pElementModule; NFIClassModule* m_pClassModule; NFILogModule* m_pLogModule; }; #endif
{ "content_hash": "3c7385acc254eaa5b24590131fb82193", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 149, "avg_line_length": 29.22641509433962, "alnum_prop": 0.7579083279535184, "repo_name": "zh423328/NoahGameFrame", "id": "400e8bcb59dc274d12d27f77be335a9ec7c45f24", "size": "2507", "binary": false, "copies": "2", "ref": "refs/heads/dev-zh", "path": "NFComm/NFKernelPlugin/NFDataTailModule.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "138199" }, { "name": "Batchfile", "bytes": "7958" }, { "name": "C", "bytes": "2020464" }, { "name": "C#", "bytes": "1745561" }, { "name": "C++", "bytes": "2487462" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "1034" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Groff", "bytes": "7559" }, { "name": "HTML", "bytes": "143733" }, { "name": "Java", "bytes": "97959" }, { "name": "Lua", "bytes": "26149" }, { "name": "M4", "bytes": "1572" }, { "name": "Makefile", "bytes": "246301" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "Pascal", "bytes": "70297" }, { "name": "Perl", "bytes": "3895" }, { "name": "Protocol Buffer", "bytes": "79127" }, { "name": "Python", "bytes": "2980" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "11516" }, { "name": "Smalltalk", "bytes": "2796" }, { "name": "XSLT", "bytes": "82915" } ], "symlink_target": "" }
Article 2392 ---- Les droits du créancier titulaire d'un droit de gage immobilier s'éteignent notamment : 1° Par l'extinction de l'obligation principale ; 2° Par la restitution anticipée de l'immeuble à son propriétaire.
{ "content_hash": "7547b342e1234164de708fea455652bc", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 75, "avg_line_length": 27.875, "alnum_prop": 0.7802690582959642, "repo_name": "ultranaut/illacceptanything", "id": "c44807531b40294c85bbf6d20ddf024a6d406df0", "size": "230", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "data/france.code-civil/Livre IV/Titre II/Article 2392.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "AppleScript", "bytes": "61" }, { "name": "Arduino", "bytes": "709" }, { "name": "Assembly", "bytes": "2005" }, { "name": "Brainfuck", "bytes": "66542" }, { "name": "C", "bytes": "38598" }, { "name": "C#", "bytes": "55496" }, { "name": "C++", "bytes": "16638" }, { "name": "CMake", "bytes": "235" }, { "name": "CSS", "bytes": "97227" }, { "name": "Clojure", "bytes": "94838" }, { "name": "CoffeeScript", "bytes": "153782" }, { "name": "Common Lisp", "bytes": "1120" }, { "name": "Crystal", "bytes": "7261" }, { "name": "Dart", "bytes": "800" }, { "name": "Eagle", "bytes": "1297646" }, { "name": "Emacs Lisp", "bytes": "60" }, { "name": "Go", "bytes": "19658" }, { "name": "HTML", "bytes": "6432616" }, { "name": "Haskell", "bytes": "100" }, { "name": "JSONiq", "bytes": "536" }, { "name": "Java", "bytes": "14922" }, { "name": "JavaScript", "bytes": "5422014" }, { "name": "Julia", "bytes": "25" }, { "name": "KiCad", "bytes": "321244" }, { "name": "Lua", "bytes": "336811" }, { "name": "Makefile", "bytes": "1019" }, { "name": "OCaml", "bytes": "78" }, { "name": "Objective-C", "bytes": "3260" }, { "name": "PHP", "bytes": "1039" }, { "name": "Python", "bytes": "106335" }, { "name": "Racket", "bytes": "4918" }, { "name": "Ruby", "bytes": "18502" }, { "name": "Rust", "bytes": "42" }, { "name": "Shell", "bytes": "42068" }, { "name": "Swift", "bytes": "12055" }, { "name": "VimL", "bytes": "60880" }, { "name": "Visual Basic", "bytes": "1007" } ], "symlink_target": "" }
require 'spec_helper' describe Groups::CreateService, '#execute' do let!(:user) { create(:user) } let!(:group_params) { { path: "group_path", visibility_level: Gitlab::VisibilityLevel::PUBLIC } } subject { service.execute } describe 'visibility level restrictions' do let!(:service) { described_class.new(user, group_params) } context "create groups without restricted visibility level" do it { is_expected.to be_persisted } end context "cannot create group with restricted visibility level" do before do allow_any_instance_of(ApplicationSetting).to receive(:restricted_visibility_levels).and_return([Gitlab::VisibilityLevel::PUBLIC]) end it { is_expected.not_to be_persisted } end end describe 'creating a top level group' do let(:service) { described_class.new(user, group_params) } context 'when user can create a group' do before do user.update_attribute(:can_create_group, true) end it { is_expected.to be_persisted } end context 'when user can not create a group' do before do user.update_attribute(:can_create_group, false) end it { is_expected.not_to be_persisted } end end describe 'creating subgroup', :nested_groups do let!(:group) { create(:group) } let!(:service) { described_class.new(user, group_params.merge(parent_id: group.id)) } context 'as group owner' do before do group.add_owner(user) end it { is_expected.to be_persisted } context 'when nested groups feature is disabled' do it 'does not save group and returns an error' do allow(Group).to receive(:supports_nested_groups?).and_return(false) is_expected.not_to be_persisted expect(subject.errors[:parent_id]).to include('You don’t have permission to create a subgroup in this group.') expect(subject.parent_id).to be_nil end end end context 'when nested groups feature is enabled' do before do allow(Group).to receive(:supports_nested_groups?).and_return(true) end context 'as guest' do it 'does not save group and returns an error' do is_expected.not_to be_persisted expect(subject.errors[:parent_id].first).to eq('You don’t have permission to create a subgroup in this group.') expect(subject.parent_id).to be_nil end end context 'as owner' do before do group.add_owner(user) end it { is_expected.to be_persisted } end end end describe 'creating a mattermost team' do let!(:params) { group_params.merge(create_chat_team: "true") } let!(:service) { described_class.new(user, params) } before do stub_mattermost_setting(enabled: true) end it 'create the chat team with the group' do allow_any_instance_of(Mattermost::Team).to receive(:create) .and_return({ 'name' => 'tanuki', 'id' => 'lskdjfwlekfjsdifjj' }) expect { subject }.to change { ChatTeam.count }.from(0).to(1) end end end
{ "content_hash": "edbd27b5a31d59cf66bc897ac33dd587", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 137, "avg_line_length": 29.433962264150942, "alnum_prop": 0.642948717948718, "repo_name": "jirutka/gitlabhq", "id": "224e933bebc13b9a305bc64a2ef754d1bf1d238a", "size": "3124", "binary": false, "copies": "4", "ref": "refs/heads/11-3-stable", "path": "spec/services/groups/create_service_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "651536" }, { "name": "Clojure", "bytes": "79" }, { "name": "Dockerfile", "bytes": "1676" }, { "name": "HTML", "bytes": "1281244" }, { "name": "JavaScript", "bytes": "3887640" }, { "name": "Ruby", "bytes": "17664250" }, { "name": "Shell", "bytes": "30673" }, { "name": "Vue", "bytes": "967573" } ], "symlink_target": "" }
define(function(require, exports, module) { "use strict"; exports.snippetText = require("../requirejs/text!./jsx.snippets"); exports.scope = "jsx"; });
{ "content_hash": "a74890f96f7d2c1f45fec6cfa4e7fbc9", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 66, "avg_line_length": 23, "alnum_prop": 0.6645962732919255, "repo_name": "sxyseo/openbiz", "id": "6d439d1ca1bc0593ce8ee48651d126507378acde", "size": "161", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/vendor/ace/ace/snippets/jsx.js", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "163243" }, { "name": "JavaScript", "bytes": "520313" }, { "name": "Shell", "bytes": "1190" } ], "symlink_target": "" }
""" hyper/http20/bufsocket.py ~~~~~~~~~~~~~~~~~~~~~~~~~ This file implements a buffered socket wrapper. The purpose of this is to avoid the overhead of unnecessary syscalls while allowing small reads from the network. This represents a potentially massive performance optimisation at the cost of burning some memory in the userspace process. """ import select from .exceptions import ConnectionResetError, LineTooLongError # import logging # logger = logging.getLogger() # logger.setLevel(logging.DEBUG) class WriteBuffer(object): def __init__(self, s=None): if isinstance(s, str): self.string_len = len(s) self.buffer_list = [s] else: self.reset() def reset(self): self.buffer_list = [] self.string_len = 0 def __len__(self): return self.string_len def __add__(self, other): self.append(other) return self def insert(self, s): if isinstance(s, WriteBuffer): self.buffer_list = s.buffer_list + self.buffer_list self.string_len += s.string_len elif isinstance(s, str): self.buffer_list.insert(0, s) self.string_len += len(s) else: raise Exception("WriteBuffer append not string or StringBuffer") def append(self, s): if isinstance(s, WriteBuffer): self.buffer_list.extend(s.buffer_list) self.string_len += s.string_len elif isinstance(s, str): self.buffer_list.append(s) self.string_len += len(s) else: raise Exception("WriteBuffer append not string or StringBuffer") def __str__(self): return self.get_string() def get_string(self): return "".join(self.buffer_list) class BufferedSocket(object): """ A buffered socket wrapper. The purpose of this is to avoid the overhead of unnecessary syscalls while allowing small reads from the network. This represents a potentially massive performance optimisation at the cost of burning some memory in the userspace process. """ def __init__(self, sck, buffer_size=1000): """ Create the buffered socket. :param sck: The socket to wrap. :param buffer_size: The size of the backing buffer in bytes. This parameter should be set to an appropriate value for your use case. Small values of ``buffer_size`` increase the overhead of buffer management: large values cause more memory to be used. """ # The wrapped socket. self._sck = sck # The buffer we're using. self._backing_buffer = bytearray(buffer_size) self._buffer_view = memoryview(self._backing_buffer) # The size of the buffer. self._buffer_size = buffer_size # The start index in the memory view. self._index = 0 # The number of bytes in the buffer. self._bytes_in_buffer = 0 # following is define for send buffer # all send will be cache and send when flush called, # combine data to reduce the api call self.send_buffer = WriteBuffer() def send(self, buf, flush=True): self.send_buffer.append(buf) if len(self.send_buffer) > 1300 or flush: self.flush() def flush(self): if len(self.send_buffer): data = self.send_buffer.get_string() # logger.debug("buffer socket flush:%d", len(data)) self.send_buffer.reset() data_len = len(data) start = 0 while start < data_len: send_size = min(data_len - start, 65535) sended = self._sck.send(data[start:start+send_size]) start += sended @property def _remaining_capacity(self): """ The maximum number of bytes the buffer could still contain. """ return self._buffer_size - self._index @property def _buffer_end(self): """ The index of the first free byte in the buffer. """ return self._index + self._bytes_in_buffer @property def can_read(self): """ Whether or not there is more data to read from the socket. """ if self._bytes_in_buffer: return True read = select.select([self._sck], [], [], 0)[0] if read: return True return False @property def buffer(self): """ Get access to the buffer itself. """ return self._buffer_view[self._index:self._buffer_end] def advance_buffer(self, count): """ Advances the buffer by the amount of data consumed outside the socket. """ self._index += count self._bytes_in_buffer -= count def new_buffer(self): """ This method moves all the data in the backing buffer to the start of a new, fresh buffer. This gives the ability to read much more data. """ def read_all_from_buffer(): end = self._index + self._bytes_in_buffer return self._buffer_view[self._index:end] new_buffer = bytearray(self._buffer_size) new_buffer_view = memoryview(new_buffer) new_buffer_view[0:self._bytes_in_buffer] = read_all_from_buffer() self._index = 0 self._backing_buffer = new_buffer self._buffer_view = new_buffer_view return def recv(self, amt): """ Read some data from the socket. :param amt: The amount of data to read. :returns: A ``memoryview`` object containing the appropriate number of bytes. The data *must* be copied out by the caller before the next call to this function. """ # In this implementation you can never read more than the number of # bytes in the buffer. if amt > self._buffer_size: amt = self._buffer_size # If the amount of data we've been asked to read is less than the # remaining space in the buffer, we need to clear out the buffer and # start over. if amt > self._remaining_capacity: self.new_buffer() # If there's still some room in the buffer, opportunistically attempt # to read into it. # If we don't actually _need_ the data (i.e. there's enough in the # buffer to satisfy the request), use select to work out if the read # attempt will block. If it will, don't bother reading. If we need the # data, always do the read. if self._bytes_in_buffer >= amt: should_read = select.select([self._sck], [], [], 0)[0] else: should_read = True if ((self._remaining_capacity > self._bytes_in_buffer) and (should_read)): count = self._sck.recv_into(self._buffer_view[self._buffer_end:]) # The socket just got closed. We should throw an exception if we # were asked for more data than we can return. if not count and amt > self._bytes_in_buffer: raise ConnectionResetError() self._bytes_in_buffer += count # Read out the bytes and update the index. amt = min(amt, self._bytes_in_buffer) data = self._buffer_view[self._index:self._index+amt] self._index += amt self._bytes_in_buffer -= amt return data def fill(self): """ Attempts to fill the buffer as much as possible. It will block for at most the time required to have *one* ``recv_into`` call return. """ if not self._remaining_capacity: self.new_buffer() count = self._sck.recv_into(self._buffer_view[self._buffer_end:]) if not count: raise ConnectionResetError() self._bytes_in_buffer += count return def readline(self): """ Read up to a newline from the network and returns it. The implicit maximum line length is the buffer size of the buffered socket. Note that, unlike recv, this method absolutely *does* block until it can read the line. :returns: A ``memoryview`` object containing the appropriate number of bytes. The data *must* be copied out by the caller before the next call to this function. """ # First, check if there's anything in the buffer. This is one of those # rare circumstances where this will work correctly on all platforms. index = self._backing_buffer.find( b'\n', self._index, self._index + self._bytes_in_buffer ) if index != -1: length = index + 1 - self._index data = self._buffer_view[self._index:self._index+length] self._index += length self._bytes_in_buffer -= length return data # In this case, we didn't find a newline in the buffer. To fix that, # read some data into the buffer. To do our best to satisfy the read, # we should shunt the data down in the buffer so that it's right at # the start. We don't bother if we're already at the start of the # buffer. if self._index != 0: self.new_buffer() while self._bytes_in_buffer < self._buffer_size: count = self._sck.recv_into(self._buffer_view[self._buffer_end:]) if not count: raise ConnectionResetError() # We have some more data. Again, look for a newline in that gap. first_new_byte = self._buffer_end self._bytes_in_buffer += count index = self._backing_buffer.find( b'\n', first_new_byte, first_new_byte + count, ) if index != -1: # The length of the buffer is the index into the # buffer at which we found the newline plus 1, minus the start # index of the buffer, which really should be zero. assert not self._index length = index + 1 data = self._buffer_view[:length] self._index += length self._bytes_in_buffer -= length return data # If we got here, it means we filled the buffer without ever getting # a newline. Time to throw an exception. raise LineTooLongError() def __getattr__(self, name): return getattr(self._sck, name)
{ "content_hash": "8f35784e2fd581bca39ddf89602dfc26", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 82, "avg_line_length": 33.50316455696203, "alnum_prop": 0.5800510059506943, "repo_name": "qqzwc/XX-Net", "id": "62c79cf58c94b9ac5237b181365867ed50f9033f", "size": "10611", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "code/default/python27/1.0/lib/noarch/hyper/common/bufsocket.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "3884" }, { "name": "C", "bytes": "53301" }, { "name": "CSS", "bytes": "86883" }, { "name": "HTML", "bytes": "190128" }, { "name": "JavaScript", "bytes": "6524" }, { "name": "Python", "bytes": "15368059" }, { "name": "Shell", "bytes": "7812" }, { "name": "Visual Basic", "bytes": "1700" } ], "symlink_target": "" }
using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (int64_t)tx.nTime)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, false); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Zilbercoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64_t nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Zilbercoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript <hex string>\n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node if (!AcceptToMemoryPool(mempool, tx, NULL)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); SyncWithWallets(tx, NULL, true); } RelayTransaction(tx, hashTx); return hashTx.GetHex(); }
{ "content_hash": "2e34e2a430a908409b8f9c4ec9df0ea4", "timestamp": "", "source": "github", "line_count": 548, "max_line_length": 143, "avg_line_length": 36.14963503649635, "alnum_prop": 0.6017667844522968, "repo_name": "Zilbercoin/SRC", "id": "b69c25c608932d555f4a9d9513859b81f7a9fac9", "size": "20216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/rpcrawtransaction.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "34314" }, { "name": "C++", "bytes": "2671121" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "12822" }, { "name": "Objective-C", "bytes": "1052" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "33654" }, { "name": "Roff", "bytes": "30973" }, { "name": "Shell", "bytes": "7749" } ], "symlink_target": "" }
layout: media title: "Lip lick" excerpt: "PaperFaces portrait of @monaura0 drawn with Paper by 53 on an iPad." image: feature: paperfaces-monaura0-twitter-lg.jpg thumb: paperfaces-monaura0-twitter-150.jpg category: paperfaces tags: [portrait, illustration, paper by 53, black and white] --- PaperFaces portrait of [@monaura0](http://twitter.com/monaura0). {% include paperfaces-boilerplate-2.html %} <figure class="third"> <a href="{{ site.url }}/images/paperfaces-monaura0-process-1-lg.jpg"><img src="{{ site.url }}/images/paperfaces-monaura0-process-1-600.jpg" alt="Work in process screenshot"></a> <a href="{{ site.url }}/images/paperfaces-monaura0-process-2-lg.jpg"><img src="{{ site.url }}/images/paperfaces-monaura0-process-2-600.jpg" alt="Work in process screenshot"></a> <a href="{{ site.url }}/images/paperfaces-monaura0-process-3-lg.jpg"><img src="{{ site.url }}/images/paperfaces-monaura0-process-3-600.jpg" alt="Work in process screenshot"></a> <a href="{{ site.url }}/images/paperfaces-monaura0-process-4-lg.jpg"><img src="{{ site.url }}/images/paperfaces-monaura0-process-4-600.jpg" alt="Work in process screenshot"></a> <a href="{{ site.url }}/images/paperfaces-monaura0-process-5-lg.jpg"><img src="{{ site.url }}/images/paperfaces-monaura0-process-5-600.jpg" alt="Work in process screenshot"></a> <figcaption>Work in progress screen captures Made with Paper.</figcaption> </figure>
{ "content_hash": "69129d32cb30b4c1146277d922ad3434", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 178, "avg_line_length": 64.13636363636364, "alnum_prop": 0.7278525868178597, "repo_name": "mmistakes/made-mistakes", "id": "eeb65cafbe733945702dedce2132f0b5e2535221", "size": "1415", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "_posts/paperfaces/2014-04-22-monaura0-portrait.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "90685" }, { "name": "JavaScript", "bytes": "61809" }, { "name": "Ruby", "bytes": "8092" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>icharate: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.dev / icharate - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> icharate <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-08-11 14:39:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-11 14:39:01 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/icharate&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Icharate&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: Multimodal Categorial Grammars&quot; &quot;keyword: Syntax/Semantics Interface&quot; &quot;keyword: Higher Order Logic&quot; &quot;keyword: Meta-Linguistics&quot; &quot;category: Computer Science/Formal Languages Theory and Automata&quot; &quot;date: 2003-2006&quot; ] authors: [ &quot;Houda Anoun &lt;[email protected]&gt;&quot; &quot;Pierre Casteran &lt;[email protected]&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/icharate/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/icharate.git&quot; synopsis: &quot;Icharate: A logical Toolkit for Multimodal Categorial Grammars&quot; description: &quot;&quot;&quot; http://www.labri.fr/perso/anoun/Icharate The logical toolkit ICHARATE is built upon a formalization of multimodal categorial grammars in Coq proof assistant. This toolkit aims at facilitating the study of these complicated formalisms by allowing users to build interactively the syntactic derivations of different sentences, compute their semantic interpretations and also prove universal properties of entire classes of grammars using a collection of already established derived rules. Several tactics are defined to ease the interaction with users.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/icharate/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=c64866fc19d34cb8879374ce32012146&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-icharate.8.6.0 coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.dev). The following dependencies couldn&#39;t be met: - coq-icharate -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-icharate.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "c6d40cc7ac2782e4e63fd599e0f3ec2d", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 291, "avg_line_length": 43.81395348837209, "alnum_prop": 0.5676751592356688, "repo_name": "coq-bench/coq-bench.github.io", "id": "fd70b00377c47cd5311b49663d17da951783f210", "size": "7561", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/extra-dev/8.10.dev/icharate/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import { StackNavigator } from 'react-navigation'; import MineIndex from './MineIndex'; import Info from './Info'; const MineNavigator = StackNavigator( { // 页面跳转的钩子 MineIndex: { screen: MineIndex, key: 'MineIndex' }, info: {screen: Info, key: 'info'}, }); const defaultGetStateForAction = MineNavigator.router.getStateForAction; MineNavigator.router.getStateForAction = (action, state) => { if (state && action.type === 'PushTwoProfiles') { const routes = [ ...state.routes, {key: 'MineIndex', routeName: 'MineIndex'}, {key: 'info', routeName: 'info'}, ]; return { ...state, routes, index: routes.length - 1, }; } return defaultGetStateForAction(action, state); }; export default MineNavigator;
{ "content_hash": "afde41297b48ce4592e31c4971c31486", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 72, "avg_line_length": 23.96875, "alnum_prop": 0.6505867014341591, "repo_name": "nighthary/rn-cnodejs", "id": "d41fe7f154727ec121c3beea91f909e59fb33117", "size": "781", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/view/tab/MineNavigator.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "28484" }, { "name": "C++", "bytes": "1805" }, { "name": "Java", "bytes": "1311" }, { "name": "JavaScript", "bytes": "54068" }, { "name": "Makefile", "bytes": "530177" }, { "name": "Objective-C", "bytes": "373612" }, { "name": "Python", "bytes": "1722" }, { "name": "Shell", "bytes": "711" } ], "symlink_target": "" }