text
stringlengths
2
1.04M
meta
dict
echo ">> Since the test has failed" set -e source /opt/qnib/gocd/helpers/gocd-functions.sh # Create BUILD_IMG_NAME, which includes the git-hash and the revision of the pipeline assemble_build_img_name IMG_NAME=$(echo ${GO_PIPELINE_NAME} |awk -F'[\_\.]' '{print $1}') if [ -d docker ];then cd docker fi if [ -d test ];then cd test if [ -x stop.sh ];then ./stop.sh fi fi docker rmi ${BUILD_IMG_NAME} exit 1
{ "content_hash": "14322b5652de7fc918160bd9f74478a2", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 85, "avg_line_length": 18.91304347826087, "alnum_prop": 0.6436781609195402, "repo_name": "qnib/alpn-gocd-agent", "id": "a41f69601f64385e3806f380933ab75b56f4a380", "size": "447", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "opt/qnib/gocd/tasks/docker/faild_test.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "115" }, { "name": "Shell", "bytes": "9583" } ], "symlink_target": "" }
<?php namespace CentreonModule\Infrastructure\Source; use Psr\Container\ContainerInterface; use CentreonModule\Infrastructure\Entity\Module; use CentreonModule\Domain\Repository\ModulesInformationsRepository; use CentreonModule\Infrastructure\Source\SourceAbstract; use CentreonLegacy\ServiceProvider as ServiceProviderLegacy; class ModuleSource extends SourceAbstract { public const TYPE = 'module'; public const PATH = 'www/modules/'; public const PATH_WEB = 'modules/'; public const CONFIG_FILE = 'conf.php'; /** * @var array<string,mixed> */ protected $info; /** * Construct * * @param \Psr\Container\ContainerInterface $services */ public function __construct(ContainerInterface $services) { $this->installer = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_INSTALLER); $this->upgrader = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_UPGRADER); $this->remover = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_REMOVER); $this->license = $services->get(ServiceProviderLegacy::CENTREON_LEGACY_MODULE_LICENSE); parent::__construct($services); } public function initInfo(): void { $this->info = $this->db ->getRepository(ModulesInformationsRepository::class) ->getAllModuleVsVersion() ; } /** * {@inheritDoc} * * Install module * * @throws ModuleException */ public function install(string $id): ?Module { $this->installOrUpdateDependencies($id); return parent::install($id); } /** * {@inheritDoc} * * Remove module * * @throws ModuleException */ public function remove(string $id): void { $this->validateRemovalRequirementsOrFail($id); $recordId = $this->db ->getRepository(ModulesInformationsRepository::class) ->findIdByName($id) ; ($this->remover)($id, $recordId)->remove(); } /** * {@inheritDoc} * * Update module * * @throws ModuleException */ public function update(string $id): ?Module { $this->installOrUpdateDependencies($id); $recordId = $this->db ->getRepository(ModulesInformationsRepository::class) ->findIdByName($id) ; ($this->upgrader)($id, $recordId)->upgrade(); $this->initInfo(); return $this->getDetail($id); } /** * @param string|null $search * @param boolean|null $installed * @param boolean|null $updated * @return array<int,\CentreonModule\Infrastructure\Entity\Module> */ public function getList(string $search = null, bool $installed = null, bool $updated = null): array { $files = ($this->finder::create()) ->files() ->name(static::CONFIG_FILE) ->depth('== 1') ->sortByName() ->in($this->getPath()); $result = []; foreach ($files as $file) { $entity = $this->createEntityFromConfig($file->getPathName()); if (!$this->isEligible($entity, $search, $installed, $updated)) { continue; } $result[] = $entity; } return $result; } /** * @param string $id * @return Module|null */ public function getDetail(string $id): ?Module { $result = null; $path = $this->getPath() . $id; if (file_exists($path) === false) { return $result; } $files = ($this->finder::create()) ->files() ->name(static::CONFIG_FILE) ->depth('== 0') ->sortByName() ->in($path) ; foreach ($files as $file) { $result = $this->createEntityFromConfig($file->getPathName()); } return $result; } /** * @param string $configFile * @return Module */ public function createEntityFromConfig(string $configFile): Module { $module_conf = []; $module_conf = $this->getModuleConf($configFile); $info = current($module_conf); $entity = new Module(); $entity->setId(basename(dirname($configFile))); $entity->setPath(dirname($configFile)); $entity->setType(static::TYPE); $entity->setName($info['rname']); $entity->setAuthor($info['author']); $entity->setVersion($info['mod_release']); $entity->setDescription($info['infos']); $entity->setKeywords($entity->getId()); $entity->setLicense($this->processLicense($entity->getId(), $info)); if (array_key_exists('stability', $info) && $info['stability']) { $entity->setStability($info['stability']); } if (array_key_exists('last_update', $info) && $info['last_update']) { $entity->setLastUpdate($info['last_update']); } if (array_key_exists('release_note', $info) && $info['release_note']) { $entity->setReleaseNote($info['release_note']); } if (array_key_exists('images', $info) && $info['images']) { if (is_string($info['images'])) { $info['images'] = [$info['images']]; } foreach ($info['images'] as $image) { $entity->addImage(static::PATH_WEB . $entity->getId() . '/'. $image); } } if (array_key_exists('dependencies', $info) && is_array($info['dependencies'])) { $entity->setDependencies($info['dependencies']); } // load information about installed modules/widgets if ($this->info === null) { $this->initInfo(); } if (array_key_exists($entity->getId(), $this->info)) { $entity->setVersionCurrent($this->info[$entity->getId()]); $entity->setInstalled(true); $isUpdated = $this->isUpdated($this->info[$entity->getId()], $entity->getVersion()); $entity->setUpdated($isUpdated); } return $entity; } /** * @codeCoverageIgnore * @param string $configFile * @return array<mixed> */ protected function getModuleConf(string $configFile): array { $module_conf = []; require $configFile; return $module_conf; } /** * Process license check and return license information * @param string $moduleId the module id (slug) * @param array<string,mixed> $info the info of the module from conf.php * @return array<string,string|bool> the license information (required, expiration_date) */ protected function processLicense(string $moduleId, array $info): array { $license = [ 'required' => false ]; if (!empty($info['require_license']) && $info['require_license'] === true) { $license = [ 'required' => true, 'expiration_date' => $this->license->getLicenseExpiration($moduleId) ]; } return $license; } /** * Install or update module dependencies when needed * * @param string $moduleId * * @throws ModuleException */ private function installOrUpdateDependencies(string $moduleId): void { $sortedDependencies = $this->getSortedDependencies($moduleId); foreach ($sortedDependencies as $dependency) { $dependencyDetails = $this->getDetail($dependency); if ($dependencyDetails === null) { throw ModuleException::cannotFindModuleDetails($dependency); } if (! $dependencyDetails->isInstalled()) { $this->install($dependency); } elseif (! $dependencyDetails->isUpdated()) { $this->update($dependency); } } } /** * Sort module dependencies * * @param string $moduleId (example: centreon-license-manager) * @param string[] $alreadyProcessed * @return string[] * * @throws ModuleException */ private function getSortedDependencies( string $moduleId, array $alreadyProcessed = [] ) { $dependencies = []; if (in_array($moduleId, $alreadyProcessed)) { return $dependencies; } $alreadyProcessed[] = $moduleId; $moduleDetails = $this->getDetail($moduleId); if ($moduleDetails === null) { throw ModuleException::moduleIsMissing($moduleId); } foreach ($moduleDetails->getDependencies() as $dependency) { $dependencies[] = $dependency; $dependencyDetails = $this->getDetail($dependency); $dependencies = array_unique([ ...$this->getSortedDependencies($dependencyDetails->getId(), $alreadyProcessed), ...$dependencies, ]); } return $dependencies; } /** * Validate requirements before remove (dependencies) * * @param string $moduleId (example: centreon-license-manager) * * @throws ModuleException */ private function validateRemovalRequirementsOrFail(string $moduleId): void { $dependenciesToRemove = []; $modules = $this->getList(); foreach ($modules as $module) { if ($module->isInstalled() && in_array($moduleId, $module->getDependencies())) { $dependenciesToRemove[] = $module->getName(); } } if (! empty($dependenciesToRemove)) { throw ModuleException::modulesNeedToBeRemovedFirst($dependenciesToRemove); } } }
{ "content_hash": "da40241ed95746658c548ed14c94282a", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 103, "avg_line_length": 28.074498567335244, "alnum_prop": 0.5593998775260257, "repo_name": "centreon/centreon", "id": "f7555ccad6a72c8a75de19823784844a22630362", "size": "10473", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "centreon/src/CentreonModule/Infrastructure/Source/ModuleSource.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "210043" }, { "name": "Gherkin", "bytes": "174313" }, { "name": "HTML", "bytes": "1276734" }, { "name": "JavaScript", "bytes": "865312" }, { "name": "Makefile", "bytes": "25883" }, { "name": "NewLisp", "bytes": "621" }, { "name": "PHP", "bytes": "15602217" }, { "name": "Perl", "bytes": "1866808" }, { "name": "Python", "bytes": "32748" }, { "name": "Raku", "bytes": "122" }, { "name": "Shell", "bytes": "473416" }, { "name": "Smarty", "bytes": "42689" }, { "name": "TypeScript", "bytes": "1698281" }, { "name": "XSLT", "bytes": "124586" } ], "symlink_target": "" }
#include "config.h" #include "bindings/core/v8/V8ErrorHandler.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8ErrorEvent.h" #include "bindings/core/v8/V8HiddenValue.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "core/dom/ExecutionContext.h" #include "core/events/ErrorEvent.h" #include "core/frame/LocalFrame.h" namespace blink { V8ErrorHandler::V8ErrorHandler(bool isInline, ScriptState* scriptState) : V8EventListener(isInline, scriptState) { } v8::Local<v8::Value> V8ErrorHandler::callListenerFunction(ScriptState* scriptState, v8::Local<v8::Value> jsEvent, Event* event) { ASSERT(!jsEvent.IsEmpty()); if (!event->hasInterface(EventNames::ErrorEvent)) return V8EventListener::callListenerFunction(scriptState, jsEvent, event); ErrorEvent* errorEvent = static_cast<ErrorEvent*>(event); if (errorEvent->world() && errorEvent->world() != &world()) return v8::Null(isolate()); v8::Local<v8::Object> listener = getListenerObject(scriptState->executionContext()); if (listener.IsEmpty() || !listener->IsFunction()) return v8::Null(isolate()); v8::Local<v8::Function> callFunction = v8::Local<v8::Function>::Cast(listener); v8::Local<v8::Object> thisValue = scriptState->context()->Global(); v8::Local<v8::Object> eventObject; if (!jsEvent->ToObject(scriptState->context()).ToLocal(&eventObject)) return v8::Null(isolate()); v8::Local<v8::Value> error = V8HiddenValue::getHiddenValue(scriptState, eventObject, V8HiddenValue::error(isolate())); if (error.IsEmpty()) error = v8::Null(isolate()); v8::Local<v8::Value> parameters[5] = { v8String(isolate(), errorEvent->message()), v8String(isolate(), errorEvent->filename()), v8::Integer::New(isolate(), errorEvent->lineno()), v8::Integer::New(isolate(), errorEvent->colno()), error }; v8::TryCatch tryCatch(isolate()); tryCatch.SetVerbose(true); v8::MaybeLocal<v8::Value> result; if (scriptState->executionContext()->isWorkerGlobalScope()) { result = V8ScriptRunner::callFunction(callFunction, scriptState->executionContext(), thisValue, WTF_ARRAY_LENGTH(parameters), parameters, isolate()); } else { result = ScriptController::callFunction(scriptState->executionContext(), callFunction, thisValue, WTF_ARRAY_LENGTH(parameters), parameters, isolate()); } v8::Local<v8::Value> returnValue; if (!result.ToLocal(&returnValue)) return v8::Null(isolate()); return returnValue; } // static void V8ErrorHandler::storeExceptionOnErrorEventWrapper(ScriptState* scriptState, ErrorEvent* event, v8::Local<v8::Value> data, v8::Local<v8::Object> creationContext) { v8::Local<v8::Value> wrappedEvent = toV8(event, creationContext, scriptState->isolate()); if (!wrappedEvent.IsEmpty()) { ASSERT(wrappedEvent->IsObject()); V8HiddenValue::setHiddenValue(scriptState, v8::Local<v8::Object>::Cast(wrappedEvent), V8HiddenValue::error(scriptState->isolate()), data); } } bool V8ErrorHandler::shouldPreventDefault(v8::Local<v8::Value> returnValue) { return returnValue->IsBoolean() && returnValue.As<v8::Boolean>()->Value(); } } // namespace blink
{ "content_hash": "ccf247e899b66f4192c621009b456fd6", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 241, "avg_line_length": 42.25974025974026, "alnum_prop": 0.7098955132145052, "repo_name": "Workday/OpenFrame", "id": "ff6942afdc9b846a1c799a27d592ad488b8a5c2f", "size": "4816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/bindings/core/v8/V8ErrorHandler.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */ /*global define, $, brackets, window */ /** * Initializes the default brackets menu items. */ define(function (require, exports, module) { "use strict"; var AppInit = require("utils/AppInit"), Commands = require("command/Commands"), EditorManager = require("editor/EditorManager"), Menus = require("command/Menus"), Strings = require("strings"); AppInit.htmlReady(function () { /* * File menu */ var menu; menu = Menus.addMenu(Strings.FILE_MENU, Menus.AppMenuBar.FILE_MENU); menu.addMenuItem(Commands.FILE_NEW); menu.addMenuItem(Commands.FILE_NEW_FOLDER); menu.addMenuItem(Commands.FILE_OPEN); menu.addMenuItem(Commands.FILE_OPEN_FOLDER); menu.addMenuItem(Commands.FILE_CLOSE); menu.addMenuItem(Commands.FILE_CLOSE_ALL); menu.addMenuDivider(); menu.addMenuItem(Commands.FILE_SAVE); menu.addMenuItem(Commands.FILE_SAVE_ALL); menu.addMenuDivider(); menu.addMenuItem(Commands.FILE_LIVE_FILE_PREVIEW); menu.addMenuItem(Commands.FILE_LIVE_HIGHLIGHT); menu.addMenuItem(Commands.FILE_PROJECT_SETTINGS); menu.addMenuDivider(); menu.addMenuItem(Commands.FILE_EXTENSION_MANAGER); // supress redundant quit menu item on mac if (brackets.platform !== "mac" && !brackets.inBrowser) { menu.addMenuDivider(); menu.addMenuItem(Commands.FILE_QUIT); } /* * Edit menu */ menu = Menus.addMenu(Strings.EDIT_MENU, Menus.AppMenuBar.EDIT_MENU); menu.addMenuItem(Commands.EDIT_UNDO); menu.addMenuItem(Commands.EDIT_REDO); menu.addMenuDivider(); menu.addMenuItem(Commands.EDIT_CUT); menu.addMenuItem(Commands.EDIT_COPY); menu.addMenuItem(Commands.EDIT_PASTE); menu.addMenuDivider(); menu.addMenuItem(Commands.EDIT_SELECT_ALL); menu.addMenuItem(Commands.EDIT_SELECT_LINE); menu.addMenuDivider(); menu.addMenuItem(Commands.EDIT_FIND); menu.addMenuItem(Commands.EDIT_FIND_IN_FILES); menu.addMenuItem(Commands.EDIT_FIND_NEXT); menu.addMenuItem(Commands.EDIT_FIND_PREVIOUS); menu.addMenuDivider(); menu.addMenuItem(Commands.EDIT_REPLACE); menu.addMenuDivider(); menu.addMenuItem(Commands.EDIT_INDENT); menu.addMenuItem(Commands.EDIT_UNINDENT); menu.addMenuItem(Commands.EDIT_DUPLICATE); menu.addMenuItem(Commands.EDIT_DELETE_LINES); menu.addMenuItem(Commands.EDIT_LINE_UP); menu.addMenuItem(Commands.EDIT_LINE_DOWN); menu.addMenuDivider(); menu.addMenuItem(Commands.EDIT_LINE_COMMENT); menu.addMenuItem(Commands.EDIT_BLOCK_COMMENT); menu.addMenuDivider(); menu.addMenuItem(Commands.SHOW_CODE_HINTS); menu.addMenuDivider(); menu.addMenuItem(Commands.TOGGLE_CLOSE_BRACKETS); /* * View menu */ menu = Menus.addMenu(Strings.VIEW_MENU, Menus.AppMenuBar.VIEW_MENU); menu.addMenuItem(Commands.VIEW_HIDE_SIDEBAR); menu.addMenuDivider(); menu.addMenuItem(Commands.VIEW_INCREASE_FONT_SIZE); menu.addMenuItem(Commands.VIEW_DECREASE_FONT_SIZE); menu.addMenuItem(Commands.VIEW_RESTORE_FONT_SIZE); menu.addMenuDivider(); menu.addMenuItem(Commands.TOGGLE_ACTIVE_LINE); menu.addMenuItem(Commands.TOGGLE_LINE_NUMBERS); menu.addMenuItem(Commands.TOGGLE_WORD_WRAP); /* * Navigate menu */ menu = Menus.addMenu(Strings.NAVIGATE_MENU, Menus.AppMenuBar.NAVIGATE_MENU); menu.addMenuItem(Commands.NAVIGATE_QUICK_OPEN); menu.addMenuItem(Commands.NAVIGATE_GOTO_LINE); menu.addMenuItem(Commands.NAVIGATE_GOTO_DEFINITION); menu.addMenuItem(Commands.NAVIGATE_JUMPTO_DEFINITION); menu.addMenuDivider(); menu.addMenuItem(Commands.NAVIGATE_NEXT_DOC); menu.addMenuItem(Commands.NAVIGATE_PREV_DOC); menu.addMenuDivider(); menu.addMenuItem(Commands.NAVIGATE_SHOW_IN_FILE_TREE); menu.addMenuDivider(); menu.addMenuItem(Commands.TOGGLE_QUICK_EDIT); menu.addMenuItem(Commands.QUICK_EDIT_PREV_MATCH); menu.addMenuItem(Commands.QUICK_EDIT_NEXT_MATCH); menu.addMenuDivider(); menu.addMenuItem(Commands.TOGGLE_QUICK_DOCS); /* * Help menu */ menu = Menus.addMenu(Strings.HELP_MENU, Menus.AppMenuBar.HELP_MENU); menu.addMenuItem(Commands.HELP_CHECK_FOR_UPDATE); menu.addMenuDivider(); if (brackets.config.how_to_use_url) { menu.addMenuItem(Commands.HELP_HOW_TO_USE_BRACKETS); } if (brackets.config.forum_url) { menu.addMenuItem(Commands.HELP_FORUM); } if (brackets.config.release_notes_url) { menu.addMenuItem(Commands.HELP_RELEASE_NOTES); } if (brackets.config.report_issue_url) { menu.addMenuItem(Commands.HELP_REPORT_AN_ISSUE); } menu.addMenuDivider(); menu.addMenuItem(Commands.HELP_SHOW_EXT_FOLDER); var hasAboutItem = (brackets.platform !== "mac" || brackets.inBrowser); // Add final divider only if we have a twitter URL or about item if (hasAboutItem || brackets.config.twitter_url) { menu.addMenuDivider(); } if (brackets.config.twitter_url) { menu.addMenuItem(Commands.HELP_TWITTER); } // supress redundant about menu item in mac shell if (hasAboutItem) { menu.addMenuItem(Commands.HELP_ABOUT); } /* * Context Menus */ var project_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.PROJECT_MENU); project_cmenu.addMenuItem(Commands.FILE_NEW); project_cmenu.addMenuItem(Commands.FILE_NEW_FOLDER); project_cmenu.addMenuItem(Commands.FILE_RENAME); project_cmenu.addMenuItem(Commands.FILE_DELETE); project_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_OS); project_cmenu.addMenuDivider(); project_cmenu.addMenuItem(Commands.EDIT_FIND_IN_SUBTREE); project_cmenu.addMenuDivider(); project_cmenu.addMenuItem(Commands.FILE_REFRESH); var working_set_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.WORKING_SET_MENU); working_set_cmenu.addMenuItem(Commands.FILE_CLOSE); working_set_cmenu.addMenuItem(Commands.FILE_SAVE); working_set_cmenu.addMenuItem(Commands.FILE_RENAME); working_set_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_FILE_TREE); working_set_cmenu.addMenuItem(Commands.NAVIGATE_SHOW_IN_OS); working_set_cmenu.addMenuDivider(); working_set_cmenu.addMenuItem(Commands.EDIT_FIND_IN_SUBTREE); working_set_cmenu.addMenuDivider(); working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_ADDED); working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_NAME); working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_BY_TYPE); working_set_cmenu.addMenuDivider(); working_set_cmenu.addMenuItem(Commands.SORT_WORKINGSET_AUTO); var editor_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.EDITOR_MENU); // editor_cmenu.addMenuItem(Commands.NAVIGATE_JUMPTO_DEFINITION); editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_EDIT); editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_DOCS); editor_cmenu.addMenuItem(Commands.EDIT_SELECT_ALL); var inline_editor_cmenu = Menus.registerContextMenu(Menus.ContextMenuIds.INLINE_EDITOR_MENU); inline_editor_cmenu.addMenuItem(Commands.TOGGLE_QUICK_EDIT); inline_editor_cmenu.addMenuItem(Commands.EDIT_SELECT_ALL); inline_editor_cmenu.addMenuDivider(); inline_editor_cmenu.addMenuItem(Commands.QUICK_EDIT_PREV_MATCH); inline_editor_cmenu.addMenuItem(Commands.QUICK_EDIT_NEXT_MATCH); /** * Context menu for code editors (both full-size and inline) * Auto selects the word the user clicks if the click does not occur over * an existing selection */ $("#editor-holder").on("contextmenu", function (e) { if ($(e.target).parents(".CodeMirror-gutter").length !== 0) { return; } // Note: on mousedown before this event, CodeMirror automatically checks mouse pos, and // if not clicking on a selection moves the cursor to click location. When triggered // from keyboard, no pre-processing occurs and the cursor/selection is left as is. var editor = EditorManager.getFocusedEditor(), inlineWidget = EditorManager.getFocusedInlineWidget(); if (editor) { // If there's just an insertion point select the word token at the cursor pos so // it's more clear what the context menu applies to. if (!editor.hasSelection()) { editor.selectWordAt(editor.getCursorPos()); // Prevent menu from overlapping text by moving it down a little // Temporarily backout this change for now to help mitigate issue #1111, // which only happens if mouse is not over context menu. Better fix // requires change to bootstrap, which is too risky for now. //e.pageY += 6; } // Inline text editors have a different context menu (safe to assume it's not some other // type of inline widget since we already know an Editor has focus) if (inlineWidget) { inline_editor_cmenu.open(e); } else { editor_cmenu.open(e); } } }); /** * Context menus for folder tree & working set list */ $("#project-files-container").on("contextmenu", function (e) { project_cmenu.open(e); }); $("#open-files-container").on("contextmenu", function (e) { working_set_cmenu.open(e); }); // Prevent the browser context menu since Brackets creates a custom context menu $(window).contextmenu(function (e) { e.preventDefault(); }); /* * General menu event processing */ // Prevent clicks on top level menus and menu items from taking focus $(window.document).on("mousedown", ".dropdown", function (e) { e.preventDefault(); }); // Switch menus when the mouse enters an adjacent menu // Only open the menu if another one has already been opened // by clicking $(window.document).on("mouseenter", "#titlebar .dropdown", function (e) { var open = $(this).siblings(".open"); if (open.length > 0) { open.removeClass("open"); $(this).addClass("open"); } }); }); });
{ "content_hash": "acad3ee431bc6924c4a82c591d9648a7", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 104, "avg_line_length": 41.667883211678834, "alnum_prop": 0.6178505737058771, "repo_name": "ybayer/brackets", "id": "6a055d39cd8006a314cb750fb6e973d0e494250c", "size": "12587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/command/DefaultMenus.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/nearby_sharing/sharesheet/nearby_share_action.h" #include <memory> #include <vector> #include "base/files/file_path.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/ash/file_manager/app_id.h" #include "chrome/browser/ash/file_manager/fileapi_util.h" #include "chrome/browser/nearby_sharing/attachment.h" #include "chrome/browser/nearby_sharing/file_attachment.h" #include "chrome/browser/nearby_sharing/logging/logging.h" #include "chrome/browser/nearby_sharing/nearby_sharing_service.h" #include "chrome/browser/nearby_sharing/nearby_sharing_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/sharesheet/sharesheet_types.h" #include "chrome/browser/ui/webui/nearby_share/nearby_share_dialog_ui.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/generated_resources.h" #include "components/services/app_service/public/cpp/intent_util.h" #include "storage/browser/file_system/file_system_context.h" #include "storage/browser/file_system/file_system_url.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/rounded_corners_f.h" #include "ui/gfx/geometry/size.h" #include "ui/views/controls/webview/webview.h" #include "url/gurl.h" #include "url/url_constants.h" namespace { std::vector<base::FilePath> ResolveFileUrls( Profile* profile, const std::vector<apps::IntentFilePtr>& files) { std::vector<base::FilePath> file_paths; storage::FileSystemContext* fs_context = file_manager::util::GetFileManagerFileSystemContext(profile); DCHECK(fs_context); for (const auto& file : files) { // Only supports filesystem: type URLs, for paths managed by file_manager // (e.g. MyFiles). DCHECK(file->url.SchemeIsFileSystem()); const storage::FileSystemURL fs_url = fs_context->CrackURLInFirstPartyContext(file->url); if (fs_url.is_valid()) { file_paths.push_back(fs_url.path()); } } return file_paths; } std::string GetFirstFilenameFromFileUrls( Profile* profile, const std::vector<apps::IntentFilePtr>& file_urls) { if (file_urls.empty()) { return std::string(); } auto file_paths = ResolveFileUrls(profile, file_urls); return file_paths.size() == 1u ? file_paths[0].BaseName().AsUTF8Unsafe() : std::string(); } std::vector<std::unique_ptr<Attachment>> CreateTextAttachmentFromIntent( Profile* profile, const apps::IntentPtr& intent) { // TODO(crbug.com/1186730): Detect address and phone number text shares and // apply the correct |TextAttachment::Type|. TextAttachment::Type type = intent->share_text ? TextAttachment::Type::kText : TextAttachment::Type::kUrl; std::string title = intent->share_title ? *intent->share_title : GetFirstFilenameFromFileUrls( profile, intent->files); std::string text; if (intent->share_text) text = *intent->share_text; else if (intent->url) text = intent->url->spec(); else if (intent->drive_share_url) text = intent->drive_share_url->spec(); if (text.empty()) { NS_LOG(WARNING) << "Failed to create TextAttachment from sharesheet intent"; return std::vector<std::unique_ptr<Attachment>>(); } std::vector<std::unique_ptr<Attachment>> attachments; attachments.push_back( std::make_unique<TextAttachment>(type, text, title, intent->mime_type)); return attachments; } std::vector<std::unique_ptr<Attachment>> CreateFileAttachmentsFromIntent( Profile* profile, const apps::IntentPtr& intent) { std::vector<base::FilePath> file_paths = ResolveFileUrls(profile, intent->files); std::vector<std::unique_ptr<Attachment>> attachments; for (auto& file_path : file_paths) { attachments.push_back( std::make_unique<FileAttachment>(std::move(file_path))); } return attachments; } } // namespace namespace { constexpr int kCornerRadius = 12; gfx::Size ComputeSize() { // TODO(vecore): compute expected size based on screen size return {/*width=*/512, /*height=*/420}; } } // namespace NearbyShareAction::NearbyShareAction(Profile* profile) : profile_(profile) {} NearbyShareAction::~NearbyShareAction() = default; const std::u16string NearbyShareAction::GetActionName() { return l10n_util::GetStringUTF16(IDS_NEARBY_SHARE_FEATURE_NAME); } const gfx::VectorIcon& NearbyShareAction::GetActionIcon() { return kNearbyShareIcon; } void NearbyShareAction::LaunchAction( sharesheet::SharesheetController* controller, views::View* root_view, apps::IntentPtr intent) { gfx::Size size = ComputeSize(); controller->SetBubbleSize(size.width(), size.height()); auto view = std::make_unique<views::WebView>(profile_); // If this is not done, we don't see anything in our view. view->SetPreferredSize(size); views::WebView* web_view = root_view->AddChildView(std::move(view)); // TODO(vecore): Query this from the container view web_view->holder()->SetCornerRadii(gfx::RoundedCornersF(kCornerRadius)); // load chrome://nearby into the webview web_view->LoadInitialURL(GURL(chrome::kChromeUINearbyShareURL)); // Without requesting focus, the sharesheet will launch in an unfocused state // which raises accessibility issues with the "Device name" input. web_view->RequestFocus(); auto* webui = web_view->GetWebContents()->GetWebUI(); DCHECK(webui != nullptr); auto* nearby_ui = webui->GetController()->GetAs<nearby_share::NearbyShareDialogUI>(); DCHECK(nearby_ui != nullptr); nearby_ui->SetSharesheetController(controller); nearby_ui->SetAttachments( CreateAttachmentsFromIntent(profile_, std::move(intent))); nearby_ui->SetWebView(web_view); } bool NearbyShareAction::HasActionView() { // Return true so that the Nearby UI is shown after it has been selected. return true; } bool NearbyShareAction::ShouldShowAction(const apps::IntentPtr& intent, bool contains_hosted_document) { bool valid_file_share = intent && intent->IsShareIntent() && !intent->files.empty() && !intent->share_text && !intent->url && !intent->drive_share_url && !contains_hosted_document; bool valid_text_share = intent->action == apps_util::kIntentActionSend && intent->share_text && intent->files.empty(); bool valid_url_share = intent->action == apps_util::kIntentActionView && intent->url && intent->url->is_valid() && !intent->share_text; // Disallow sharing multiple drive files at once. There isn't a valid // |drive_share_url| in this case. bool valid_drive_share = intent->action == apps_util::kIntentActionSend && intent->drive_share_url && intent->drive_share_url->is_valid() && intent->files.size() == 1u && !intent->share_text; return (valid_file_share || valid_text_share || valid_url_share || valid_drive_share) && !IsNearbyShareDisabledByPolicy(); } bool NearbyShareAction::IsNearbyShareDisabledByPolicy() { if (nearby_share_disabled_by_policy_for_testing_.has_value()) { return *nearby_share_disabled_by_policy_for_testing_; } NearbySharingService* nearby_sharing_service = NearbySharingServiceFactory::GetForBrowserContext(profile_); if (!nearby_sharing_service) { return false; } return nearby_sharing_service->GetSettings()->IsDisabledByPolicy(); } std::vector<std::unique_ptr<Attachment>> NearbyShareAction::CreateAttachmentsFromIntent(Profile* profile, apps::IntentPtr intent) { if (intent->share_text || intent->url || intent->drive_share_url) { return CreateTextAttachmentFromIntent(profile, intent); } else { // Only create a file attachment if there is no text or URL. Google docs may // have associated file paths, but are still treated as text shares. return CreateFileAttachmentsFromIntent(profile, intent); } } bool NearbyShareAction::OnAcceleratorPressed( const ui::Accelerator& accelerator) { // This is overridden because the default case returns false // which means the accelerator has not been handled by the ShareAction. In // that case, the sharesheet handles it by closing the UI. We return true // instead to indicate we will handle the accelerator ourselves, which // prevents the UI from being closed by the sharesheet. return true; } void NearbyShareAction::SetActionCleanupCallbackForArc( base::OnceCallback<void()> callback) { if (callback.is_null()) { return; } NearbySharingService* nearby_sharing_service = NearbySharingServiceFactory::GetForBrowserContext(profile_); if (!nearby_sharing_service) { std::move(callback).Run(); return; } nearby_sharing_service->SetArcTransferCleanupCallback(std::move(callback)); }
{ "content_hash": "d5d531187cdcca7c751dadf0ae2d2cbe", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 80, "avg_line_length": 37.288, "alnum_prop": 0.68783522849174, "repo_name": "nwjs/chromium.src", "id": "d8f523c3da078e07954fc61b5f34e616e2b2305b", "size": "9322", "binary": false, "copies": "1", "ref": "refs/heads/nw70", "path": "chrome/browser/nearby_sharing/sharesheet/nearby_share_action.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/** * Author: chenboxiang * Date: 14-6-13 * Time: 下午8:42 */ 'use strict' var _ = require('lodash') var Tracker = require('./tracker') var EventEmitter = require('events').EventEmitter var util = require('util') var logger = require('./logger') var fs = require('fs') var is = require('is-type-of') var path = require('path') var helpers = require('./helpers') var protocol = require('./protocol') var defaults = { charset: 'utf8', trackers: [], // 默认超时时间10s timeout: 10000, // 默认后缀 // 当获取不到文件后缀时使用 defaultExt: 'txt' } function FdfsClient(config) { EventEmitter.call(this) // config global logger if (config.logger) { logger.setLogger(config.logger) } this.config = _.extend({}, defaults, config) this._checkConfig() this._init() this._errorHandle() } // extends from EventEmitter util.inherits(FdfsClient, EventEmitter) // ------------- private methods /** * 确认配置是否合法 * @private */ FdfsClient.prototype._checkConfig = function() { // ------------- 验证trackers是否合法 if (!this.config.trackers) { throw new Error('you must specify "trackers" in config.') } if (!Array.isArray(this.config.trackers)) { this.config.trackers = [this.config.trackers] } if (this.config.trackers.length === 0) { throw new Error('"trackers" in config is empty.') } this.config.trackers.forEach(function(tracker) { if (!tracker.host || !tracker.port) { throw new Error('"trackers" in config is invalid, every tracker must all have "host" and "port".') } }) } FdfsClient.prototype._init = function() { // --------- init trackers var self = this this._trackers = [] this.config.trackers.forEach(function(tc) { tc.timeout = self.config.timeout tc.charset = self.config.charset var tracker = new Tracker(tc) self._trackers.push(tracker) tracker.on('error', function(err) { logger.error(err) // 将有错误的tracker剔除 self._trackers.splice(self._trackers.indexOf(tracker), 1) // 检查是否还有可用的tracker if (self._trackers.length === 0) { self.emit('error', new Error('There are no available trackers, please check your tracker config or your tracker server.')); } }) }) } FdfsClient.prototype._errorHandle = function() { // 1. 当没有tracker可用时触发 // 2. 当连接storage错误时触发 this.on('error', function(err) { logger.error(err) }) } /** * 按顺序获取可用的tracker * @private */ FdfsClient.prototype._getTracker = function() { if (null == this._trackerIndex) { this._trackerIndex = 0 return this._trackers[0] } else { this._trackerIndex++ if (this._trackerIndex >= this._trackers.length) { this._trackerIndex = 0 } return this._trackers[this._trackerIndex] } } FdfsClient.prototype._upload = function(file, options, callback) { var tracker = this._getTracker() tracker.getStoreStorage(options.group, function(err, storage) { if (null != err) { callback(err) return } storage.upload(file, options, callback) }) } FdfsClient.prototype._uploadAppenderFile = function(file, options, callback) { var tracker = this._getTracker() tracker.getStoreStorage(options.group, function(err, storage) { if (null != err) { callback(err) return } storage.uploadAppenderFile(file, options, callback) }) } FdfsClient.prototype._appendFile = function(file, options, callback) { var tracker = this._getTracker() tracker.getStoreStorage(options.group, function(err, storage) { if (null != err) { callback(err) return } storage.appendFile(file, options, callback) }) } FdfsClient.prototype._modifyFile = function(file, options, callback) { var tracker = this._getTracker() tracker.getStoreStorage(options.group, function(err, storage) { if (null != err) { callback(err) return } storage.appendFile(file, options, callback) }) } // ------------- public methods /** * 上传文件 * @param file absolute file path or Buffer or ReadableStream * @param options * options.group: 指定要上传的group, 不指定则由tracker server分配 * options.size: file size, file参数为ReadableStream时必须指定 * options.ext: 上传文件的后缀,不指定则获取file参数的后缀,不含(.) * @param callback */ FdfsClient.prototype.upload = function(file, options, callback) { var self = this if (is.function(options)) { callback = options options = {} } else { if (!options) { options = {} } } _normalizeUploadParams(file, options, function(err) { if (err) { callback(err) return } if (!options.ext) { options.ext = self.defaultExt } self._upload(file, options, callback) }) } FdfsClient.prototype.uploadAppenderFile = function(file, options, callback) { var self = this if (is.function(options)) { callback = options options = {} } else { if (!options) { options = {} } } _normalizeUploadParams(file, options, function(err) { if (err) { callback(err) return } if (!options.ext) { options.ext = self.defaultExt } self._uploadAppenderFile(file, options, callback) }) } FdfsClient.prototype.appendFile = function(file, options, callback) { var self = this if (is.function(options)) { callback = options options = {} } else { if (!options) { options = {} } } _normalizeUploadParams(file, options, function(err) { if (err) { callback(err) return } self._appendFile(file, options, callback) }) } FdfsClient.prototype.modifyFile = function(file, options, callback) { var self = this if (is.function(options)) { callback = options options = {} } else { if (!options) { options = {} } } _normalizeUploadParams(file, options, function(err) { if (err) { callback(err) return } self._appendFile(file, options, callback) }) } /** * 下载文件 * @param fileId * @param options options可以直接传options.target * options.target 下载的文件流将被写入到这里,可以是本地文件名,也可以是WritableStream,如果为空则每次服务器返回数据的时候都会回调callback * options.offset和options.bytes: 当只想下载文件中的某1片段时指定 * @param callback 若未指定options.target,服务器每次数据的返回都会回调,若指定了options.target,则只在结束时回调一次 */ FdfsClient.prototype.download = function(fileId, options, callback) { if (!options || is.function(options)) { callback(new Error('options.target is not specified')) return } // 直接传入target if (!options.target) { var ori = options options = {} options.target = ori } if (!(is.string(options.target) || is.writableStream(options.target))) { callback(new Error('options.target is invalid, it\'s type must be String or WritableStream')) } if (is.string(options.target)) { options.target = fs.createWriteStream(options.target) } this._getTracker().getFetchStorage(fileId, function(err, storage) { storage.download(fileId, options, callback) }) } /** * 删除fileId指定的文件 * @param fileId * @param callback */ FdfsClient.prototype.del = function(fileId, callback) { this._getTracker().getUpdateStorage(fileId, function(err, storage) { if (null != err) { callback(err) return } storage.del(fileId, callback) }) } FdfsClient.prototype.remove = FdfsClient.prototype.del /** * @param fileId * @param metaData {key1: value1, key2: value2} * @param flag 'O' for overwrite all old metadata (default) 'M' for merge, insert when the meta item not exist, otherwise update it * @param callback */ FdfsClient.prototype.setMetaData = function(fileId, metaData, flag, callback) { if (is.function(flag)) { callback = flag flag = 'O' } this._getTracker().getUpdateStorage(fileId, function(err, storage) { if (null != err) { callback(err) return } storage.setMetaData(fileId, metaData, flag, callback) }) } /** * 获取指定fileId的meta data * @param fileId * @param callback */ FdfsClient.prototype.getMetaData = function(fileId, callback) { this._getTracker().getUpdateStorage(fileId, function(err, storage) { if (null != err) { callback(err) return } storage.getMetaData(fileId, callback) }) } /** * 获取指定fileId的信息 * fileInfo会传给回调,结构如下 * { * // 文件大小 * size: * // 文件创建的UTC时间戳,单位为秒 * timestamp: * crc32: * // 最初上传到的storage server的ip * addr: * } * @param fileId * @param callback */ FdfsClient.prototype.getFileInfo = function(fileId, callback) { this._getTracker().getUpdateStorage(fileId, function(err, storage) { if (err) { callback(err) return } storage.getFileInfo(fileId, callback) }) } // -------------- helpers /** * 验证file参数是否合法,同时补充一些必要的参数 * 若为String,则需验证是否存在 * 若为ReadableStream,则需验证options.size是否存在 * @param file * @param options * @param callback * @private */ function _normalizeUploadParams(file, options, callback) { if (!file) { callback(new Error('The "file" parameter is empty.')) return } if (!(is.string(file) || is.buffer(file) || is.readableStream(file))) { callback(new Error('The "file" parameter is invalid, it must be a String, Buffer, or ReadableStream')) return } if (is.string(file)) { fs.stat(file, function(err, stats) { if (err || !stats) { callback(new Error('File [' + file + '] is not exists!')) return } options.size = stats.size if (!options.ext) { options.ext = path.extname(file) if (options.ext) { // 去掉. options.ext = options.ext.substring(1) } } callback(null) }) return } if (is.readableStream(file) && !options.size) { callback(new Error('when the "file" parameter\'s is ReadableStream, options.size must specified')) return } if (is.buffer(file)) { options.size = file.length } callback(null) } // expose module.exports = FdfsClient
{ "content_hash": "ace5707c0f6359a77c12d0b1e54e34df", "timestamp": "", "source": "github", "line_count": 440, "max_line_length": 139, "avg_line_length": 24.547727272727272, "alnum_prop": 0.5822609017683548, "repo_name": "ymyang/fdfs-client", "id": "2b205ad46e56c699841217ac7aa6d04cb45cebd4", "size": "11471", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/fdfs.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "189825" }, { "name": "JavaScript", "bytes": "65959" }, { "name": "Makefile", "bytes": "459" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers; use App\Page; use Illuminate\Http\Request; class PageController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function store(Request $request) { $page = new Page(); $page->title = $request->input('title'); $page->raw = $request->input('raw'); $page->parse(); $page->save(); \Flash::success('Page created.'); return redirect()->to('/wiki/'.$page->id); } /** * Display the specified resource. * * @param int $id * * @return \Illuminate\Http\Response */ public function show($id) { $page = Page::find($id); return view('show')->with('page', $page); } /** * Show the form for editing the specified resource. * * @param int $id * * @return \Illuminate\Http\Response */ public function edit($id) { $page = Page::findOrFail($id); return view('edit')->with('page', $page); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $page = \App\Page::findOrFail($id); $page->title = $request->input('title'); $page->raw = $request->input('raw'); $page->parse(); $page->save(); \Flash::success('Page edited.'); return redirect()->to('/wiki/'.$id); } /** * Remove the specified resource from storage. * * @param int $id * * @return \Illuminate\Http\Response */ public function destroy($id) { $page = Page::findOrFail($id); $page->delete(); \Flash::success('Page deleted.'); return redirect()->to('/'); } public function refresh($id) { $page = Page::findOrFail($id); $page->parse(); $page->save(); \Flash::success('Page refreshed. The latest HTML has been rebuilt.'); return redirect()->to('/wiki/'.$id); } }
{ "content_hash": "a0b02dc8c136bb7cb55598548c1391cd", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 77, "avg_line_length": 21.62295081967213, "alnum_prop": 0.5200909780136467, "repo_name": "Faore/SimpleWiki", "id": "c69e64526d3764127338ec4a521e9a76e03ec412", "size": "2638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Http/Controllers/PageController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "41287" }, { "name": "JavaScript", "bytes": "250217" }, { "name": "PHP", "bytes": "80943" } ], "symlink_target": "" }
package com.datastax.driver.spark.demo import org.apache.spark.{SparkConf, SparkContext} object BasicReadWriteDemo extends App { import com.datastax.driver.spark._ val sparkMasterHost = "127.0.0.1" val cassandraHost = "127.0.0.1" val keyspace = "test" val table = "kv" // Tell Spark the address of one Cassandra node: val conf = new SparkConf(true).set("cassandra.connection.host", cassandraHost) // Connect to the Spark cluster: val sc = new SparkContext("spark://" + sparkMasterHost + ":7077", "demo-program", conf) // Read table test.kv and print its contents: val rdd = sc.cassandraTable("test", "kv").select("key", "value") rdd.toArray().foreach(println) // Write two rows to the test.kv table: val col = sc.parallelize(Seq((1, "value 1"), (2, "value 2"))) col.saveToCassandra("test", "kv", Seq("key", "value")) sc.stop() }
{ "content_hash": "f1a1a253ca70821dbfdcc617e7de9473", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 89, "avg_line_length": 29.1, "alnum_prop": 0.6804123711340206, "repo_name": "bovigny/cassandra-driver-spark", "id": "a3ec2200e2a2330d79bdfc6c667a42291642a02e", "size": "873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scala/com/datastax/driver/spark/demo/BasicReadWriteDemo.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "224618" } ], "symlink_target": "" }
Phiber's Command Line Tool v0.6.5 Usage: myo <comand> <flag> [[--option1 value][--option2 = value]...] -- arg1 arg2 ... Flags: -i Preserve case otherwise files will always be created in lowercase -g Generate entity files when used with myo entity Commands: version Prints the version number app Creates a new Phiber application Usage: myo app <appname> Options: --app-path Specify the application path entity Creates an entity file or generate entities from db with -g Usage: myo entity <entity name> Creates an empty entity file myo entity -g Generates entity files from the database with no options it will use your config to access the db and put the files into the entity folder options: --db-driver The driver of your database (defaults to mysql) --db-dsn The dsn of your db --db-host Database host --db-name Database name, overides --db-dsn --db-user Database username --db-pass Database password --entity-path The folder to put generated files in ext Creates myo extensions. Usage: myo ext <extension name> The new extension will be used as a command: myo <extension name> help Provides more information about commands. Usage: myo help <command> mvc Creates different parts of the MVC layout. mvc <flag> [option] Options: --module <module name> Creates a module and defaults to module 'default' --controller <controller name> Creates a controller and defaults to 'index' --model <model name> Creates a model --action <action name> Creates an action for a given controller version Prints the current version of Myo
{ "content_hash": "643f55f55a194b3ce7a01044e49a68ef", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 80, "avg_line_length": 17.62135922330097, "alnum_prop": 0.6484848484848484, "repo_name": "ghousseyn/phiber-myo", "id": "8d40598663b1ffe3cfbb59ceaa08a091269acc43", "size": "1816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "229" }, { "name": "C", "bytes": "799" }, { "name": "PHP", "bytes": "36361" } ], "symlink_target": "" }
@class NSString; @protocol XCUILocalDeviceScreenshotIPCInterface; @interface XCUILocalDeviceScreenDataSource : NSObject <XCUIScreenDataSource> { id <XCUILocalDeviceScreenshotIPCInterface> _screenshotIPCInterface; } - (void).cxx_destruct; @property(retain, nonatomic) id <XCUILocalDeviceScreenshotIPCInterface> screenshotIPCInterface; // @synthesize screenshotIPCInterface=_screenshotIPCInterface; - (id)_clippedScreenshotFromImage:(id)arg1 encoding:(id)arg2 rect:(struct CGRect)arg3; - (void)requestScreenshotOfScreenWithID:(long long)arg1 withRect:(struct CGRect)arg2 encoding:(id)arg3 withReply:(CDUnknownBlockType)arg4; - (void)requestScaleForScreenWithIdentifier:(long long)arg1 completion:(CDUnknownBlockType)arg2; - (void)requestScreenIdentifiersWithCompletion:(CDUnknownBlockType)arg1; @property(readonly, nonatomic) _Bool supportsHEICImageEncoding; - (id)initWithScreenshotIPCInterface:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
{ "content_hash": "f93cc420eeb9c3d044f1960c54cb0ca0", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 158, "avg_line_length": 45.12, "alnum_prop": 0.8289007092198581, "repo_name": "linkedin/bluepill", "id": "9c4def21a9926a58849ff3b229a6dc659cbc0225", "size": "1348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bp/src/PrivateHeaders/XCTest/XCUILocalDeviceScreenDataSource.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "3119" }, { "name": "HTML", "bytes": "13423" }, { "name": "Objective-C", "bytes": "820220" }, { "name": "Python", "bytes": "6253" }, { "name": "Ruby", "bytes": "689" }, { "name": "Shell", "bytes": "7389" }, { "name": "Starlark", "bytes": "5932" }, { "name": "Swift", "bytes": "666" } ], "symlink_target": "" }
// ZipStorer, by Jaime Olivares // Website: zipstorer.codeplex.com // Version: 2.35 (March 14, 2010) using System.Collections.Generic; using System.Text; namespace System.IO.Compression { /// <summary> /// Unique class for compression/decompression file. Represents a Zip file. /// </summary> public class ZipStorer : IDisposable { /// <summary> /// Compression method enumeration /// </summary> public enum Compression : ushort { /// <summary>Uncompressed storage</summary> Store = 0, /// <summary>Deflate compression method</summary> Deflate = 8 } /// <summary> /// Represents an entry in Zip file directory /// </summary> public struct ZipFileEntry { /// <summary>Compression method</summary> public Compression Method; /// <summary>Full path and filename as stored in Zip</summary> public string FilenameInZip; /// <summary>Original file size</summary> public uint FileSize; /// <summary>Compressed file size</summary> public uint CompressedSize; /// <summary>Offset of header information inside Zip storage</summary> public uint HeaderOffset; /// <summary>Offset of file inside Zip storage</summary> public uint FileOffset; /// <summary>Size of header information</summary> public uint HeaderSize; /// <summary>32-bit checksum of entire file</summary> public uint Crc32; /// <summary>Last modification time of file</summary> public DateTime ModifyTime; /// <summary>User comment for file</summary> public string Comment; /// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary> public bool EncodeUTF8; /// <summary>Overriden method</summary> /// <returns>Filename in Zip</returns> public override string ToString() { return this.FilenameInZip; } } #region Public fields /// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary> public bool EncodeUTF8 = false; /// <summary>Force deflate algotithm even if it inflates the stored file. Off by default.</summary> public bool ForceDeflating = false; #endregion #region Private fields // List of files to store private List<ZipFileEntry> Files = new List<ZipFileEntry>(); // Filename of storage file private string FileName; // Stream object of storage file private Stream ZipFileStream; // General comment private string Comment = ""; // Central dir image private byte[] CentralDirImage = null; // Existing files in zip private ushort ExistingFiles = 0; // File access for Open method private FileAccess Access; // Static CRC32 Table private static UInt32[] CrcTable = null; // Default filename encoder private static Encoding DefaultEncoding = Encoding.GetEncoding(437); #endregion #region Public methods // Static constructor. Just invoked once in order to create the CRC32 lookup table. static ZipStorer() { // Generate CRC32 table CrcTable = new UInt32[256]; for (int i = 0; i < CrcTable.Length; i++) { UInt32 c = (UInt32)i; for (int j = 0; j < 8; j++) { if ((c & 1) != 0) c = 3988292384 ^ (c >> 1); else c >>= 1; } CrcTable[i] = c; } } /// <summary> /// Method to create a new storage file /// </summary> /// <param name="_filename">Full path of Zip file to create</param> /// <param name="_comment">General comment for Zip file</param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Create(string _filename, string _comment) { Stream stream = new FileStream(_filename, FileMode.Create, FileAccess.ReadWrite); ZipStorer zip = Create(stream, _comment); zip.Comment = _comment; zip.FileName = _filename; return zip; } /// <summary> /// Method to create a new zip storage in a stream /// </summary> /// <param name="_stream"></param> /// <param name="_comment"></param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Create(Stream _stream, string _comment) { ZipStorer zip = new ZipStorer(); zip.Comment = _comment; zip.ZipFileStream = _stream; zip.Access = FileAccess.Write; return zip; } /// <summary> /// Method to open an existing storage file /// </summary> /// <param name="_filename">Full path of Zip file to open</param> /// <param name="_access">File access mode as used in FileStream constructor</param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Open(string _filename, FileAccess _access) { Stream stream = (Stream)new FileStream(_filename, FileMode.Open, _access == FileAccess.Read ? FileAccess.Read : FileAccess.ReadWrite); ZipStorer zip = Open(stream, _access); zip.FileName = _filename; return zip; } /// <summary> /// Method to open an existing storage from stream /// </summary> /// <param name="_stream">Already opened stream with zip contents</param> /// <param name="_access">File access mode for stream operations</param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Open(Stream _stream, FileAccess _access) { if (!_stream.CanSeek && _access != FileAccess.Read) throw new InvalidOperationException("Stream cannot seek"); ZipStorer zip = new ZipStorer(); //zip.FileName = _filename; zip.ZipFileStream = _stream; zip.Access = _access; if (zip.ReadFileInfo()) return zip; throw new System.IO.InvalidDataException(); } /// <summary> /// Add full contents of a file into the Zip storage /// </summary> /// <param name="_method">Compression method</param> /// <param name="_pathname">Full path of file to add to Zip storage</param> /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param> /// <param name="_comment">Comment for stored file</param> public void AddFile(Compression _method, string _pathname, string _filenameInZip, string _comment) { if (Access == FileAccess.Read) throw new InvalidOperationException("Writing is not alowed"); FileStream stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read); AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment); stream.Close(); } /// <summary> /// Add full contents of a stream into the Zip storage /// </summary> /// <param name="_method">Compression method</param> /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param> /// <param name="_source">Stream object containing the data to store in Zip</param> /// <param name="_modTime">Modification time of the data to store</param> /// <param name="_comment">Comment for stored file</param> public void AddStream(Compression _method, string _filenameInZip, Stream _source, DateTime _modTime, string _comment) { if (Access == FileAccess.Read) throw new InvalidOperationException("Writing is not alowed"); long offset; if (this.Files.Count==0) offset = 0; else { ZipFileEntry last = this.Files[this.Files.Count-1]; offset = last.HeaderOffset + last.HeaderSize; } // Prepare the fileinfo ZipFileEntry zfe = new ZipFileEntry(); zfe.Method = _method; zfe.EncodeUTF8 = this.EncodeUTF8; zfe.FilenameInZip = NormalizedFilename(_filenameInZip); zfe.Comment = (_comment == null ? "" : _comment); // Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc. zfe.Crc32 = 0; // to be updated later zfe.HeaderOffset = (uint)this.ZipFileStream.Position; // offset within file of the start of this local record zfe.ModifyTime = _modTime; // Write local header WriteLocalHeader(ref zfe); zfe.FileOffset = (uint)this.ZipFileStream.Position; // Write file to zip (store) Store(ref zfe, _source); _source.Close(); this.UpdateCrcAndSizes(ref zfe); Files.Add(zfe); } /// <summary> /// Updates central directory (if pertinent) and close the Zip storage /// </summary> /// <remarks>This is a required step, unless automatic dispose is used</remarks> public void Close() { if(this.ZipFileStream == null) return; if (this.Access != FileAccess.Read) { uint centralOffset = (uint)this.ZipFileStream.Position; uint centralSize = 0; if (this.CentralDirImage != null) this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length); for (int i = 0; i < Files.Count; i++) { long pos = this.ZipFileStream.Position; this.WriteCentralDirRecord(Files[i]); centralSize += (uint)(this.ZipFileStream.Position - pos); } if (this.CentralDirImage != null) this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset); else this.WriteEndRecord(centralSize, centralOffset); } if (this.ZipFileStream != null) { this.ZipFileStream.Flush(); this.ZipFileStream.Dispose(); this.ZipFileStream = null; } } /// <summary> /// Read all the file records in the central directory /// </summary> /// <returns>List of all entries in directory</returns> public List<ZipFileEntry> ReadCentralDir() { if (this.CentralDirImage == null) throw new InvalidOperationException("Central directory currently does not exist"); List<ZipFileEntry> result = new List<ZipFileEntry>(); for (int pointer = 0; pointer < this.CentralDirImage.Length; ) { uint signature = BitConverter.ToUInt32(CentralDirImage, pointer); if (signature != 0x02014b50) break; bool encodeUTF8 = (BitConverter.ToUInt16(CentralDirImage, pointer + 8) & 0x0800) != 0; ushort method = BitConverter.ToUInt16(CentralDirImage, pointer + 10); uint modifyTime = BitConverter.ToUInt32(CentralDirImage, pointer + 12); uint crc32 = BitConverter.ToUInt32(CentralDirImage, pointer + 16); uint comprSize = BitConverter.ToUInt32(CentralDirImage, pointer + 20); uint fileSize = BitConverter.ToUInt32(CentralDirImage, pointer + 24); ushort filenameSize = BitConverter.ToUInt16(CentralDirImage, pointer + 28); ushort extraSize = BitConverter.ToUInt16(CentralDirImage, pointer + 30); ushort commentSize = BitConverter.ToUInt16(CentralDirImage, pointer + 32); uint headerOffset = BitConverter.ToUInt32(CentralDirImage, pointer + 42); uint headerSize = (uint)( 46 + filenameSize + extraSize + commentSize); Encoding encoder = encodeUTF8 ? Encoding.UTF8 : DefaultEncoding; ZipFileEntry zfe = new ZipFileEntry(); zfe.Method = (Compression)method; zfe.FilenameInZip = encoder.GetString(CentralDirImage, pointer + 46, filenameSize); zfe.FileOffset = GetFileOffset(headerOffset); zfe.FileSize = fileSize; zfe.CompressedSize = comprSize; zfe.HeaderOffset = headerOffset; zfe.HeaderSize = headerSize; zfe.Crc32 = crc32; zfe.ModifyTime = DosTimeToDateTime(modifyTime); if (commentSize > 0) zfe.Comment = encoder.GetString(CentralDirImage, pointer + 46 + filenameSize + extraSize, commentSize); result.Add(zfe); pointer += (46 + filenameSize + extraSize + commentSize); } return result; } /// <summary> /// Copy the contents of a stored file into a physical file /// </summary> /// <param name="_zfe">Entry information of file to extract</param> /// <param name="_filename">Name of file to store uncompressed data</param> /// <returns>True if success, false if not.</returns> /// <remarks>Unique compression methods are Store and Deflate</remarks> public bool ExtractFile(ZipFileEntry _zfe, string _filename) { // Make sure the parent directory exist string path = System.IO.Path.GetDirectoryName(_filename); if (!Directory.Exists(path)) Directory.CreateDirectory(path); // Check it is directory. If so, do nothing if (Directory.Exists(_filename)) return true; Stream output = new FileStream(_filename, FileMode.Create, FileAccess.Write); bool result = ExtractFile(_zfe, output); if (result) output.Close(); File.SetCreationTime(_filename, _zfe.ModifyTime); File.SetLastWriteTime(_filename, _zfe.ModifyTime); return result; } /// <summary> /// Copy the contents of a stored file into an opened stream /// </summary> /// <param name="_zfe">Entry information of file to extract</param> /// <param name="_stream">Stream to store the uncompressed data</param> /// <returns>True if success, false if not.</returns> /// <remarks>Unique compression methods are Store and Deflate</remarks> public bool ExtractFile(ZipFileEntry _zfe, Stream _stream) { if (!_stream.CanWrite) throw new InvalidOperationException("Stream cannot be written"); // check signature byte[] signature = new byte[4]; this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin); this.ZipFileStream.Read(signature, 0, 4); if (BitConverter.ToUInt32(signature, 0) != 0x04034b50) return false; // Select input stream for inflating or just reading Stream inStream; if (_zfe.Method == Compression.Store) inStream = this.ZipFileStream; else if (_zfe.Method == Compression.Deflate) inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true); else return false; // Buffered copy byte[] buffer = new byte[16384]; this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin); uint bytesPending = _zfe.FileSize; while (bytesPending > 0) { int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length)); _stream.Write(buffer, 0, bytesRead); bytesPending -= (uint)bytesRead; } _stream.Flush(); if (_zfe.Method == Compression.Deflate) inStream.Dispose(); return true; } /// <summary> /// Removes one of many files in storage. It creates a new Zip file. /// </summary> /// <param name="_zip">Reference to the current Zip object</param> /// <param name="_zfes">List of Entries to remove from storage</param> /// <returns>True if success, false if not</returns> /// <remarks>This method only works for storage of type FileStream</remarks> public static bool RemoveEntries(ref ZipStorer _zip, List<ZipFileEntry> _zfes) { if (!(_zip.ZipFileStream is FileStream)) throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream"); //Get full list of entries List<ZipFileEntry> fullList = _zip.ReadCentralDir(); //In order to delete we need to create a copy of the zip file excluding the selected items string tempZipName = Path.GetTempFileName(); string tempEntryName = Path.GetTempFileName(); try { ZipStorer tempZip = ZipStorer.Create(tempZipName, string.Empty); foreach (ZipFileEntry zfe in fullList) { if (!_zfes.Contains(zfe)) { if (_zip.ExtractFile(zfe, tempEntryName)) { tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment); } } } _zip.Close(); tempZip.Close(); File.Delete(_zip.FileName); File.Move(tempZipName, _zip.FileName); _zip = ZipStorer.Open(_zip.FileName, _zip.Access); } catch { return false; } finally { if (File.Exists(tempZipName)) File.Delete(tempZipName); if (File.Exists(tempEntryName)) File.Delete(tempEntryName); } return true; } #endregion #region Private methods // Calculate the file offset by reading the corresponding local header private uint GetFileOffset(uint _headerOffset) { byte[] buffer = new byte[2]; this.ZipFileStream.Seek(_headerOffset + 26, SeekOrigin.Begin); this.ZipFileStream.Read(buffer, 0, 2); ushort filenameSize = BitConverter.ToUInt16(buffer, 0); this.ZipFileStream.Read(buffer, 0, 2); ushort extraSize = BitConverter.ToUInt16(buffer, 0); return (uint)(30 + filenameSize + extraSize + _headerOffset); } /* Local file header: local file header signature 4 bytes (0x04034b50) version needed to extract 2 bytes general purpose bit flag 2 bytes compression method 2 bytes last mod file time 2 bytes last mod file date 2 bytes crc-32 4 bytes compressed size 4 bytes uncompressed size 4 bytes filename length 2 bytes extra field length 2 bytes filename (variable size) extra field (variable size) */ private void WriteLocalHeader(ref ZipFileEntry _zfe) { long pos = this.ZipFileStream.Position; Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding; byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip); this.ZipFileStream.Write(new byte[] { 80, 75, 3, 4, 20, 0}, 0, 6); // No extra header this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time this.ZipFileStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); // unused CRC, un/compressed size, updated later this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length); _zfe.HeaderSize = (uint)(this.ZipFileStream.Position - pos); } /* Central directory's File header: central file header signature 4 bytes (0x02014b50) version made by 2 bytes version needed to extract 2 bytes general purpose bit flag 2 bytes compression method 2 bytes last mod file time 2 bytes last mod file date 2 bytes crc-32 4 bytes compressed size 4 bytes uncompressed size 4 bytes filename length 2 bytes extra field length 2 bytes file comment length 2 bytes disk number start 2 bytes internal file attributes 2 bytes external file attributes 4 bytes relative offset of local header 4 bytes filename (variable size) extra field (variable size) file comment (variable size) */ private void WriteCentralDirRecord(ZipFileEntry _zfe) { Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding; byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip); byte[] encodedComment = encoder.GetBytes(_zfe.Comment); this.ZipFileStream.Write(new byte[] { 80, 75, 1, 2, 23, 0xB, 20, 0 }, 0, 8); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // file CRC this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // compressed file size this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // uncompressed file size this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0 this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable) this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.HeaderOffset), 0, 4); // Offset of header this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length); this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length); } /* End of central dir record: end of central dir signature 4 bytes (0x06054b50) number of this disk 2 bytes number of the disk with the start of the central directory 2 bytes total number of entries in the central dir on this disk 2 bytes total number of entries in the central dir 2 bytes size of the central directory 4 bytes offset of start of central directory with respect to the starting disk number 4 bytes zipfile comment length 2 bytes zipfile comment (variable size) */ private void WriteEndRecord(uint _size, uint _offset) { Encoding encoder = this.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding; byte[] encodedComment = encoder.GetBytes(this.Comment); this.ZipFileStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2); this.ZipFileStream.Write(BitConverter.GetBytes(_size), 0, 4); this.ZipFileStream.Write(BitConverter.GetBytes(_offset), 0, 4); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2); this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length); } // Copies all source file into storage file private void Store(ref ZipFileEntry _zfe, Stream _source) { byte[] buffer = new byte[16384]; int bytesRead; uint totalRead = 0; Stream outStream; long posStart = this.ZipFileStream.Position; long sourceStart = _source.Position; if (_zfe.Method == Compression.Store) outStream = this.ZipFileStream; else outStream = new DeflateStream(this.ZipFileStream, CompressionMode.Compress, true); _zfe.Crc32 = 0 ^ 0xffffffff; do { bytesRead = _source.Read(buffer, 0, buffer.Length); totalRead += (uint)bytesRead; if (bytesRead > 0) { outStream.Write(buffer, 0, bytesRead); for (uint i = 0; i < bytesRead; i++) { _zfe.Crc32 = ZipStorer.CrcTable[(_zfe.Crc32 ^ buffer[i]) & 0xFF] ^ (_zfe.Crc32 >> 8); } } } while (bytesRead == buffer.Length); outStream.Flush(); if (_zfe.Method == Compression.Deflate) outStream.Dispose(); _zfe.Crc32 ^= 0xffffffff; _zfe.FileSize = totalRead; _zfe.CompressedSize = (uint)(this.ZipFileStream.Position - posStart); // Verify for real compression if (_zfe.Method == Compression.Deflate && !this.ForceDeflating && _source.CanSeek && _zfe.CompressedSize > _zfe.FileSize) { // Start operation again with Store algorithm _zfe.Method = Compression.Store; this.ZipFileStream.Position = posStart; this.ZipFileStream.SetLength(posStart); _source.Position = sourceStart; this.Store(ref _zfe, _source); } } /* DOS Date and time: MS-DOS date. The date is a packed value with the following format. Bits Description 0-4 Day of the month (1–31) 5-8 Month (1 = January, 2 = February, and so on) 9-15 Year offset from 1980 (add 1980 to get actual year) MS-DOS time. The time is a packed value with the following format. Bits Description 0-4 Second divided by 2 5-10 Minute (0–59) 11-15 Hour (0–23 on a 24-hour clock) */ private uint DateTimeToDosTime(DateTime _dt) { return (uint)( (_dt.Second / 2) | (_dt.Minute << 5) | (_dt.Hour << 11) | (_dt.Day<<16) | (_dt.Month << 21) | ((_dt.Year - 1980) << 25)); } private DateTime DosTimeToDateTime(uint _dt) { return new DateTime( (int)(_dt >> 25) + 1980, (int)(_dt >> 21) & 15, (int)(_dt >> 16) & 31, (int)(_dt >> 11) & 31, (int)(_dt >> 5) & 63, (int)(_dt & 31) * 2); } /* CRC32 algorithm The 'magic number' for the CRC is 0xdebb20e3. The proper CRC pre and post conditioning is used, meaning that the CRC register is pre-conditioned with all ones (a starting value of 0xffffffff) and the value is post-conditioned by taking the one's complement of the CRC residual. If bit 3 of the general purpose flag is set, this field is set to zero in the local header and the correct value is put in the data descriptor and in the central directory. */ private void UpdateCrcAndSizes(ref ZipFileEntry _zfe) { long lastPos = this.ZipFileStream.Position; // remember position this.ZipFileStream.Position = _zfe.HeaderOffset + 8; this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method this.ZipFileStream.Position = _zfe.HeaderOffset + 14; this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // Update CRC this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // Compressed size this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // Uncompressed size this.ZipFileStream.Position = lastPos; // restore position } // Replaces backslashes with slashes to store in zip header private string NormalizedFilename(string _filename) { string filename = _filename.Replace('\\', '/'); int pos = filename.IndexOf(':'); if (pos >= 0) filename = filename.Remove(0, pos + 1); return filename.Trim('/'); } // Reads the end-of-central-directory record private bool ReadFileInfo() { if (this.ZipFileStream.Length < 22) return false; try { this.ZipFileStream.Seek(-17, SeekOrigin.End); BinaryReader br = new BinaryReader(this.ZipFileStream); do { this.ZipFileStream.Seek(-5, SeekOrigin.Current); UInt32 sig = br.ReadUInt32(); if (sig == 0x06054b50) { this.ZipFileStream.Seek(6, SeekOrigin.Current); UInt16 entries = br.ReadUInt16(); Int32 centralSize = br.ReadInt32(); UInt32 centralDirOffset = br.ReadUInt32(); UInt16 commentSize = br.ReadUInt16(); // check if comment field is the very last data in file if (this.ZipFileStream.Position + commentSize != this.ZipFileStream.Length) return false; // Copy entire central directory to a memory buffer this.ExistingFiles = entries; this.CentralDirImage = new byte[centralSize]; this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin); this.ZipFileStream.Read(this.CentralDirImage, 0, centralSize); // Leave the pointer at the begining of central dir, to append new files this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin); return true; } } while (this.ZipFileStream.Position > 0); } catch { } return false; } #endregion #region IDisposable Members /// <summary> /// Closes the Zip file stream /// </summary> public void Dispose() { this.Close(); } #endregion } }
{ "content_hash": "e31d36da22dab54dbdfaf7c9bb5e9e7c", "timestamp": "", "source": "github", "line_count": 748, "max_line_length": 146, "avg_line_length": 44.2620320855615, "alnum_prop": 0.5576597801135678, "repo_name": "oktykrk/hidroanaUI", "id": "6a0b9fc3c404810eb988f7ded72751fcd285fb27", "size": "33108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GMap.NET.Core/GMap.NET/ZipStorer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1076090" } ], "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_13) on Tue Apr 16 14:41:02 BST 2013 --> <title>Unit</title> <meta name="date" content="2013-04-16"> <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="Unit"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Unit.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../logic/Sword.html" title="class in logic"><span class="strong">Prev Class</span></a></li> <li><a href="../logic/UnitComparator.html" title="class in logic"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?logic/Unit.html" target="_top">Frames</a></li> <li><a href="Unit.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">logic</div> <h2 title="Class Unit" class="title">Class Unit</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../logic/WorldObject.html" title="class in logic">logic.WorldObject</a></li> <li> <ul class="inheritance"> <li>logic.Unit</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable</dd> </dl> <dl> <dt>Direct Known Subclasses:</dt> <dd><a href="../logic/Dragon.html" title="class in logic">Dragon</a>, <a href="../logic/Eagle.html" title="class in logic">Eagle</a>, <a href="../logic/Hero.html" title="class in logic">Hero</a>, <a href="../logic/Sword.html" title="class in logic">Sword</a></dd> </dl> <hr> <br> <pre>public abstract class <span class="strong">Unit</span> extends <a href="../logic/WorldObject.html" title="class in logic">WorldObject</a></pre> <div class="block">Base class for all living objects</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../serialized-form.html#logic.Unit">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#_alive">_alive</a></strong></code> <div class="block">Is alive?</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../logic/Direction.html" title="enum in logic">Direction</a></code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#_direction">_direction</a></strong></code> <div class="block">The direction between last position and unit position.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private static long</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#serialVersionUID">serialVersionUID</a></strong></code> <div class="block">The Constant serialVersionUID.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../logic/UnitType.html" title="enum in logic">UnitType</a></code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#Type">Type</a></strong></code> <div class="block">The unit type.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_logic.WorldObject"> <!-- --> </a> <h3>Fields inherited from class&nbsp;logic.<a href="../logic/WorldObject.html" title="class in logic">WorldObject</a></h3> <code><a href="../logic/WorldObject.html#_position">_position</a>, <a href="../logic/WorldObject.html#DEFAULT_POSITION">DEFAULT_POSITION</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../logic/Unit.html#Unit(logic.UnitType)">Unit</a></strong>(<a href="../logic/UnitType.html" title="enum in logic">UnitType</a>&nbsp;type)</code> <div class="block">Instantiates a new unit.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../logic/Direction.html" title="enum in logic">Direction</a></code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#GetDirection()">GetDirection</a></strong>()</code> <div class="block">Gets the direction.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>abstract void</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#HandleEvent(logic.Maze, logic.Event)">HandleEvent</a></strong>(<a href="../logic/Maze.html" title="class in logic">Maze</a>&nbsp;maze, <a href="../logic/Event.html" title="class in logic">Event</a>&nbsp;ev)</code> <div class="block">Handle event.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#Is(logic.UnitType)">Is</a></strong>(<a href="../logic/UnitType.html" title="enum in logic">UnitType</a>&nbsp;type)</code> <div class="block">Checks if is unit type.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#IsAlive()">IsAlive</a></strong>()</code> <div class="block">Checks if is alive.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#IsDragon()">IsDragon</a></strong>()</code> <div class="block">Checks if is dragon.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#IsEagle()">IsEagle</a></strong>()</code> <div class="block">Checks if is eagle.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#IsHero()">IsHero</a></strong>()</code> <div class="block">Checks if is hero.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#IsSameType(logic.Unit)">IsSameType</a></strong>(<a href="../logic/Unit.html" title="class in logic">Unit</a>&nbsp;other)</code> <div class="block">Checks if is same type.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#IsSword()">IsSword</a></strong>()</code> <div class="block">Checks if is sword.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#Kill()">Kill</a></strong>()</code> <div class="block">Kill.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#OnMovement(logic.Unit, logic.Direction)">OnMovement</a></strong>(<a href="../logic/Unit.html" title="class in logic">Unit</a>&nbsp;other, <a href="../logic/Direction.html" title="enum in logic">Direction</a>&nbsp;dir)</code> <div class="block">Method called when an unit in maze moves</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../logic/Dragon.html" title="class in logic">Dragon</a></code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#ToDragon()">ToDragon</a></strong>()</code> <div class="block">Cast to dragon.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../logic/Eagle.html" title="class in logic">Eagle</a></code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#ToEagle()">ToEagle</a></strong>()</code> <div class="block">Cast to eagle.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../logic/Hero.html" title="class in logic">Hero</a></code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#ToHero()">ToHero</a></strong>()</code> <div class="block">Cast to hero.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../logic/Sword.html" title="class in logic">Sword</a></code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#ToSword()">ToSword</a></strong>()</code> <div class="block">Cast to sword.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../logic/Unit.html#Update(logic.Maze)">Update</a></strong>(<a href="../logic/Maze.html" title="class in logic">Maze</a>&nbsp;maze)</code> <div class="block">Method called each iteration.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_logic.WorldObject"> <!-- --> </a> <h3>Methods inherited from class&nbsp;logic.<a href="../logic/WorldObject.html" title="class in logic">WorldObject</a></h3> <code><a href="../logic/WorldObject.html#GetId()">GetId</a>, <a href="../logic/WorldObject.html#GetPosition()">GetPosition</a>, <a href="../logic/WorldObject.html#GetSymbol()">GetSymbol</a>, <a href="../logic/WorldObject.html#IsInanimatedObject()">IsInanimatedObject</a>, <a href="../logic/WorldObject.html#IsUnit()">IsUnit</a>, <a href="../logic/WorldObject.html#SetPosition(model.Position)">SetPosition</a>, <a href="../logic/WorldObject.html#ToInanimatedObject()">ToInanimatedObject</a>, <a href="../logic/WorldObject.html#toString()">toString</a>, <a href="../logic/WorldObject.html#ToUnit()">ToUnit</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="serialVersionUID"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>serialVersionUID</h4> <pre>private static final&nbsp;long serialVersionUID</pre> <div class="block">The Constant serialVersionUID.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../constant-values.html#logic.Unit.serialVersionUID">Constant Field Values</a></dd></dl> </li> </ul> <a name="Type"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Type</h4> <pre>public final&nbsp;<a href="../logic/UnitType.html" title="enum in logic">UnitType</a> Type</pre> <div class="block">The unit type.</div> </li> </ul> <a name="_alive"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>_alive</h4> <pre>protected&nbsp;boolean _alive</pre> <div class="block">Is alive?</div> </li> </ul> <a name="_direction"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>_direction</h4> <pre>protected&nbsp;<a href="../logic/Direction.html" title="enum in logic">Direction</a> _direction</pre> <div class="block">The direction between last position and unit position.</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Unit(logic.UnitType)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Unit</h4> <pre>public&nbsp;Unit(<a href="../logic/UnitType.html" title="enum in logic">UnitType</a>&nbsp;type)</pre> <div class="block">Instantiates a new unit.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>type</code> - the type</dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="GetDirection()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>GetDirection</h4> <pre>public&nbsp;<a href="../logic/Direction.html" title="enum in logic">Direction</a>&nbsp;GetDirection()</pre> <div class="block">Gets the direction.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the direction</dd></dl> </li> </ul> <a name="IsAlive()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IsAlive</h4> <pre>public&nbsp;boolean&nbsp;IsAlive()</pre> <div class="block">Checks if is alive.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>true, if successful</dd></dl> </li> </ul> <a name="Kill()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Kill</h4> <pre>public&nbsp;void&nbsp;Kill()</pre> <div class="block">Kill.</div> </li> </ul> <a name="Update(logic.Maze)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Update</h4> <pre>public&nbsp;void&nbsp;Update(<a href="../logic/Maze.html" title="class in logic">Maze</a>&nbsp;maze)</pre> <div class="block">Method called each iteration.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>maze</code> - the maze</dd></dl> </li> </ul> <a name="OnMovement(logic.Unit, logic.Direction)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>OnMovement</h4> <pre>public&nbsp;void&nbsp;OnMovement(<a href="../logic/Unit.html" title="class in logic">Unit</a>&nbsp;other, <a href="../logic/Direction.html" title="enum in logic">Direction</a>&nbsp;dir)</pre> <div class="block">Method called when an unit in maze moves</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>other</code> - the unit that moved</dd><dd><code>dir</code> - the direction it moved</dd></dl> </li> </ul> <a name="IsHero()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IsHero</h4> <pre>public&nbsp;boolean&nbsp;IsHero()</pre> <div class="block">Checks if is hero.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>true, if successful</dd></dl> </li> </ul> <a name="IsDragon()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IsDragon</h4> <pre>public&nbsp;boolean&nbsp;IsDragon()</pre> <div class="block">Checks if is dragon.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>true, if successful</dd></dl> </li> </ul> <a name="IsSword()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IsSword</h4> <pre>public&nbsp;boolean&nbsp;IsSword()</pre> <div class="block">Checks if is sword.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>true, if successful</dd></dl> </li> </ul> <a name="IsEagle()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IsEagle</h4> <pre>public&nbsp;boolean&nbsp;IsEagle()</pre> <div class="block">Checks if is eagle.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>true, if successful</dd></dl> </li> </ul> <a name="IsSameType(logic.Unit)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>IsSameType</h4> <pre>public&nbsp;boolean&nbsp;IsSameType(<a href="../logic/Unit.html" title="class in logic">Unit</a>&nbsp;other)</pre> <div class="block">Checks if is same type.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>other</code> - the other</dd> <dt><span class="strong">Returns:</span></dt><dd>true, if successful</dd></dl> </li> </ul> <a name="Is(logic.UnitType)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Is</h4> <pre>public&nbsp;boolean&nbsp;Is(<a href="../logic/UnitType.html" title="enum in logic">UnitType</a>&nbsp;type)</pre> <div class="block">Checks if is unit type.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>type</code> - the type</dd> <dt><span class="strong">Returns:</span></dt><dd>true, if successful</dd></dl> </li> </ul> <a name="ToHero()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ToHero</h4> <pre>public&nbsp;<a href="../logic/Hero.html" title="class in logic">Hero</a>&nbsp;ToHero()</pre> <div class="block">Cast to hero.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the hero</dd></dl> </li> </ul> <a name="ToDragon()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ToDragon</h4> <pre>public&nbsp;<a href="../logic/Dragon.html" title="class in logic">Dragon</a>&nbsp;ToDragon()</pre> <div class="block">Cast to dragon.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the dragon</dd></dl> </li> </ul> <a name="ToSword()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ToSword</h4> <pre>public&nbsp;<a href="../logic/Sword.html" title="class in logic">Sword</a>&nbsp;ToSword()</pre> <div class="block">Cast to sword.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the sword</dd></dl> </li> </ul> <a name="ToEagle()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ToEagle</h4> <pre>public&nbsp;<a href="../logic/Eagle.html" title="class in logic">Eagle</a>&nbsp;ToEagle()</pre> <div class="block">Cast to eagle.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>the eagle</dd></dl> </li> </ul> <a name="HandleEvent(logic.Maze, logic.Event)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>HandleEvent</h4> <pre>public abstract&nbsp;void&nbsp;HandleEvent(<a href="../logic/Maze.html" title="class in logic">Maze</a>&nbsp;maze, <a href="../logic/Event.html" title="class in logic">Event</a>&nbsp;ev)</pre> <div class="block">Handle event.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>maze</code> - the maze</dd><dd><code>ev</code> - the event to handle</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Unit.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../logic/Sword.html" title="class in logic"><span class="strong">Prev Class</span></a></li> <li><a href="../logic/UnitComparator.html" title="class in logic"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?logic/Unit.html" target="_top">Frames</a></li> <li><a href="Unit.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "097303cdbdc3bf0a0a0cb2c5fdacc8c4", "timestamp": "", "source": "github", "line_count": 641, "max_line_length": 619, "avg_line_length": 35.82683307332293, "alnum_prop": 0.6441976921402134, "repo_name": "DDuarte/feup-lpoo-maze_and_bombermen", "id": "dd893ebebdb8c4581ddba07819fc8e7b57d96d7e", "size": "22965", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "maze/doc/logic/Unit.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "Java", "bytes": "413746" }, { "name": "Shell", "bytes": "155" } ], "symlink_target": "" }
<!DOCTYPE HTML> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="UTF-8"> <title>PropertyHelper example</title> <script src="../../shared-config.js"></script> <script id="sap-ui-bootstrap" type="text/javascript" src="../../../../../../resources/sap-ui-core.js" data-sap-ui-libs="sap.m, sap.ui.layout, sap.ui.codeeditor" data-sap-ui-compatVersion="edge" data-sap-ui-xx-bindingSyntax="complex"> </script> <style> #content { display: flex; flex-direction: column; } #main { flex: 1 1 auto; } #main > :first-child { height: 100%; } #log { max-height: 500px; overflow: auto; } #log:not(:empty) { border: 2px solid red; } #log > .error { color: red; } #log > .warning { color: darkorange; } </style> <script> sap.ui.require([ "sap/base/Log", "sap/ui/model/json/JSONModel", "sap/ui/layout/cssgrid/CSSGrid", "sap/ui/codeeditor/CodeEditor", "sap/m/TextArea", "sap/m/Input", "sap/m/Title", "sap/m/Text", "sap/m/OverflowToolbar", "sap/m/ToolbarSpacer", "sap/m/Button", "sap/m/CheckBox", "sap/ui/model/type/String" ], function(Log, JSONModel, CSSGrid, CodeEditor, TextArea, Input, Title, Text, OverflowToolbar, ToolbarSpacer, Button, CheckBox, StringType ) { sap.ui.getCore().attachInit(function() { var aInitialPropertyInfos = [ { name: "PropertyA", label: "Property A" }, { name: "PropertyB", label: "Property B", visible: false, path: "blub", typeConfig: { baseType: "String", className: "sap.ui.model.type.String", typeInstance: new StringType() }, maxConditions: 2, group: "groupA", groupLabel: "Group A", filterable: false, sortable: true }, { name: "ComplexPropertyA", label: "Complex property A", propertyInfos: ["PropertyA", "PropertyB"] } ]; var mInitialAdditionalAttributesMetadata = { filterable: true, sortable: true, propertyInfos: true, additionalAttribute: {type: "string", "default": {value: "default value"}} }; var oSettings = new JSONModel({helperSettingsEnabled: true}); var oPropertyInfosInput = new CodeEditor({ type: "json" }).setValue(stringify(aInitialPropertyInfos)); var oInputLayout = new CSSGrid({ items: [ new OverflowToolbar({ content: [ new Title({text: "Property info input"}), new ToolbarSpacer(), new Button({ text: "Reset", press: function() { oPropertyInfosInput.setValue(stringify(aInitialPropertyInfos)); savePropertyInfos(); } }), new Button({ text: "Save", press: function() { savePropertyInfos(); }, enabled: false }) ] }), oPropertyInfosInput ], gridTemplateRows: "auto 1fr" }); var oPropertyHelperClassInput = new Input({ value: "sap.ui.mdc.util.PropertyHelper", placeholder: "Path to PropertyHelper module", liveChange: function(oEvent) { var sValue = oEvent.getParameter("value"); oSettings.setProperty("/helperSettingsEnabled", sValue === "sap.ui.mdc.util.PropertyHelper"); } }); var oAdditionalAttributesInput = new CodeEditor({ type: "json", visible: "{/helperSettingsEnabled}" }).setValue(stringify(mInitialAdditionalAttributesMetadata)); var oSettingsLayout = new CSSGrid({ items: [ new OverflowToolbar({ content: [ new Title({text: "PropertyHelper settings"}), new ToolbarSpacer(), new Button({ text: "Reset", press: function() { oPropertyHelperClassInput.setValue("sap.ui.mdc.util.PropertyHelper"); oAdditionalAttributesInput.setValue(stringify(mInitialAdditionalAttributesMetadata)); oSettings.setProperty("/helperSettingsEnabled", true); savePropertyHelperSettings(); } }), new Button({ text: "Save", press: function() { savePropertyHelperSettings(); }, enabled: false }) ] }), new Text({text: "Class"}), oPropertyHelperClassInput, new Text({text: "Additional attribute metadata", visible: "{/helperSettingsEnabled}"}), oAdditionalAttributesInput, ], gridTemplateRows: "auto auto auto auto 1fr" }); var oPropertyOutput = new CodeEditor({ type: "json", editable: false }); var oFullOutputCheckBox = new CheckBox({ text: "Including non-enumerable" }); var oOutputLayout = new CSSGrid({ items: [ new OverflowToolbar({ content: [ new Title({text: "PropertyHelper#getProperties"}), oFullOutputCheckBox, new ToolbarSpacer(), new Button({ text: "Update", press: function() { update(); } }) ] }), oPropertyOutput ], gridTemplateRows: "auto 1fr" }); new CSSGrid({ items: [oInputLayout, oSettingsLayout, oOutputLayout], gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gridAutoRows: "1fr", models: oSettings }).placeAt("main"); function update() { var sPropertyInfos = oPropertyInfosInput.getValue(); var sAdditionalAttributes = oAdditionalAttributesInput.getValue(); var bFullOutput = oFullOutputCheckBox.getSelected(); var aPropertyInfos = sPropertyInfos ? JSON.parse(sPropertyInfos) : undefined; var mAdditionalAttributesMetadata = sAdditionalAttributes ? JSON.parse(sAdditionalAttributes) : undefined; var aLogEntries = []; var oLogListener = { onLogEntry: function(oLogEntry) { if (oLogEntry.message.indexOf("Invalid property definition") === 0) { aLogEntries.push(oLogEntry); } } }; clearLog(); sap.ui.require([ oPropertyHelperClassInput.getValue().trim().replace(/\./g, "/") ], function(PropertyHelper) { try { Log.addLogListener(oLogListener); if (oSettings.getProperty("/helperSettingsEnabled")) { oPropertyHelper = new PropertyHelper(aPropertyInfos, null, mAdditionalAttributesMetadata); } else { oPropertyHelper = new PropertyHelper(aPropertyInfos); } Log.removeLogListener(oLogListener); if (bFullOutput) { oPropertyOutput.setValue(stringify(oPropertyHelper.getProperties().map(getFullPropertyJSON))); } else { oPropertyOutput.setValue(stringify(oPropertyHelper.getProperties())); } oPropertyHelper.destroy(); } catch (e) { oPropertyOutput.setValue(); writeLogEntry(e.message, Log.Level.ERROR); } aLogEntries.forEach(function(oEntry) { if (oEntry.message.indexOf("Invalid property definition") === 0) { writeLogEntry(oEntry.message, oEntry.level); } }) }, function(e) { writeLogEntry(e.message, Log.Level.ERROR); }); } function getFullPropertyJSON(oProperty) { var oJSON = {}; var aFunctionKeys = []; var aReferenceKeys = []; var aOrderedKeys = []; Object.getOwnPropertyNames(oProperty).forEach(function(sKey) { if (typeof oProperty[sKey] === "function") { aFunctionKeys.push(sKey); } else if (sKey.startsWith("_")) { aReferenceKeys.push(sKey); } else { aOrderedKeys.push(sKey); } }); aReferenceKeys.forEach(function(sKey) { aOrderedKeys.splice(aOrderedKeys.indexOf(sKey.substring(1)) + 1, 0, sKey); }); aOrderedKeys.forEach(function(sKey) { oJSON[sKey] = oProperty[sKey]; }); aFunctionKeys.forEach(function(sKey) { oJSON[sKey + "()"] = oProperty[sKey](); }) return oJSON; } function clearLog() { document.getElementById("log").innerText = ""; } function writeLogEntry(sMessage, iLevel) { var oLogElement = document.getElementById("log"); var oLogEntryElement = document.createElement("div"); oLogEntryElement.innerText = sMessage.split("\n")[0]; switch (iLevel) { case Log.Level.ERROR: oLogEntryElement.classList.add("error"); break; case Log.Level.WARNING: oLogEntryElement.classList.add("warning"); break; default: } oLogElement.appendChild(oLogEntryElement); } function savePropertyInfos() { } function savePropertyHelperSettings() { } update(); }); }); function stringify(vValue) { return JSON.stringify(vValue, null, 4) } </script> </head> <body class="sapUiBody sapUiSizeCompact"> <div id="content" style="height: 100vh;"> <div id="main"></div> <div id="log"></div> </div> </body> </html>
{ "content_hash": "a2707d1c15a1580a60bcce393c37e7e8", "timestamp": "", "source": "github", "line_count": 342, "max_line_length": 110, "avg_line_length": 25.149122807017545, "alnum_prop": 0.6271363794907568, "repo_name": "SAP/openui5", "id": "25b96cf5a870ef1f9aca8ed51d39999ab5721a2e", "size": "8601", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sap.ui.mdc/test/sap/ui/mdc/sample/util/PropertyHelper.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "294216" }, { "name": "Gherkin", "bytes": "17201" }, { "name": "HTML", "bytes": "6443688" }, { "name": "Java", "bytes": "83398" }, { "name": "JavaScript", "bytes": "109546491" }, { "name": "Less", "bytes": "8741757" }, { "name": "TypeScript", "bytes": "20918" } ], "symlink_target": "" }
DNS API ======= For details on how to use dns, see :doc:`/user/guides/dns` .. automodule:: openstack.dns.v2._proxy The DNS Class ------------- The dns high-level interface is available through the ``dns`` member of a :class:`~openstack.connection.Connection` object. The ``dns`` member will only be added if the service is detected. DNS Zone Operations ^^^^^^^^^^^^^^^^^^^ .. autoclass:: openstack.dns.v2._proxy.Proxy :noindex: :members: create_zone, delete_zone, get_zone, find_zone, zones, abandon_zone, xfr_zone Recordset Operations ^^^^^^^^^^^^^^^^^^^^ .. autoclass:: openstack.dns.v2._proxy.Proxy :noindex: :members: create_recordset, update_recordset, get_recordset, delete_recordset, recordsets Zone Import Operations ^^^^^^^^^^^^^^^^^^^^^^ .. autoclass:: openstack.dns.v2._proxy.Proxy :noindex: :members: zone_imports, create_zone_import, get_zone_import, delete_zone_import Zone Export Operations ^^^^^^^^^^^^^^^^^^^^^^ .. autoclass:: openstack.dns.v2._proxy.Proxy :noindex: :members: zone_exports, create_zone_export, get_zone_export, get_zone_export_text, delete_zone_export FloatingIP Operations ^^^^^^^^^^^^^^^^^^^^^ .. autoclass:: openstack.dns.v2._proxy.Proxy :noindex: :members: floating_ips, get_floating_ip, update_floating_ip Zone Transfer Operations ^^^^^^^^^^^^^^^^^^^^^^^^ .. autoclass:: openstack.dns.v2._proxy.Proxy :noindex: :members: zone_transfer_requests, get_zone_transfer_request, create_zone_transfer_request, update_zone_transfer_request, delete_zone_transfer_request, zone_transfer_accepts, get_zone_transfer_accept, create_zone_transfer_accept
{ "content_hash": "f407244bcf7e03b59916b94408ef474a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 71, "avg_line_length": 27.467741935483872, "alnum_prop": 0.6512037580739871, "repo_name": "stackforge/python-openstacksdk", "id": "e85db5dbdda8812fa394a90ed936e30f5c9d6ddb", "size": "1703", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/source/user/proxies/dns.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "1138292" }, { "name": "Shell", "bytes": "1792" } ], "symlink_target": "" }
package es.carm.mydom.servlet; import java.util.Hashtable; import org.apache.naming.resources.FileDirContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MydomDirContext extends FileDirContext { private FileDirContext secondary; private String secondaryDocBase; public MydomDirContext() { super(); this.secondary = new FileDirContext(); } public MydomDirContext(Hashtable<String, Object> env) { super(env); this.secondary = new FileDirContext(env); } public String getSecondaryDocBase() { return secondaryDocBase; } public void setSecondaryDocBase(String secondaryDocBase) { this.secondaryDocBase = secondaryDocBase; } }
{ "content_hash": "b4864e18c3f36e690f4fdaee8150ef7a", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 59, "avg_line_length": 21.3125, "alnum_prop": 0.7727272727272727, "repo_name": "maltimor/mydom-server", "id": "37a681db661bf8201e3866eb77912cce5d2934b2", "size": "682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/es/carm/mydom/servlet/MydomDirContext.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "335523" } ], "symlink_target": "" }
package org.projectfloodlight.openflow.protocol.ver14; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFActionIdCopyTtlInVer14 implements OFActionIdCopyTtlIn { private static final Logger logger = LoggerFactory.getLogger(OFActionIdCopyTtlInVer14.class); // version: 1.4 final static byte WIRE_VERSION = 5; final static int LENGTH = 4; // OF message fields // // Immutable default instance final static OFActionIdCopyTtlInVer14 DEFAULT = new OFActionIdCopyTtlInVer14( ); final static OFActionIdCopyTtlInVer14 INSTANCE = new OFActionIdCopyTtlInVer14(); // private empty constructor - use shared instance! private OFActionIdCopyTtlInVer14() { } // Accessors for OF message fields @Override public OFActionType getType() { return OFActionType.COPY_TTL_IN; } @Override public OFVersion getVersion() { return OFVersion.OF_14; } // no data members - do not support builder public OFActionIdCopyTtlIn.Builder createBuilder() { throw new UnsupportedOperationException("OFActionIdCopyTtlInVer14 has no mutable properties -- builder unneeded"); } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFActionIdCopyTtlIn> { @Override public OFActionIdCopyTtlIn readFrom(ChannelBuffer bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property type == 12 short type = bb.readShort(); if(type != (short) 0xc) throw new OFParseError("Wrong type: Expected=OFActionType.COPY_TTL_IN(12), got="+type); int length = U16.f(bb.readShort()); if(length != 4) throw new OFParseError("Wrong length: Expected=4(4), got="+length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); if(logger.isTraceEnabled()) logger.trace("readFrom - returning shared instance={}", INSTANCE); return INSTANCE; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFActionIdCopyTtlInVer14Funnel FUNNEL = new OFActionIdCopyTtlInVer14Funnel(); static class OFActionIdCopyTtlInVer14Funnel implements Funnel<OFActionIdCopyTtlInVer14> { private static final long serialVersionUID = 1L; @Override public void funnel(OFActionIdCopyTtlInVer14 message, PrimitiveSink sink) { // fixed value property type = 12 sink.putShort((short) 0xc); // fixed value property length = 4 sink.putShort((short) 0x4); } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFActionIdCopyTtlInVer14> { @Override public void write(ChannelBuffer bb, OFActionIdCopyTtlInVer14 message) { // fixed value property type = 12 bb.writeShort((short) 0xc); // fixed value property length = 4 bb.writeShort((short) 0x4); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFActionIdCopyTtlInVer14("); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; return true; } @Override public int hashCode() { int result = 1; return result; } }
{ "content_hash": "ff4b1fac119aa2d4aaade6071990765f", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 122, "avg_line_length": 33.16326530612245, "alnum_prop": 0.6646153846153846, "repo_name": "o3project/openflowj-otn", "id": "b557f287bf90b637648497a368304201cee4bd12", "size": "5293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/projectfloodlight/openflow/protocol/ver14/OFActionIdCopyTtlInVer14.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "21028252" } ], "symlink_target": "" }
""" Nyaa.eu Feed Updater Sample Usage Faiz Ilham (faizilham.com) 2013 Check torrent updates and download if applicable. """ from nyaa_parser import fetch, download from nyaa_db import NyaaSQLiteDB # checker, viewer, and prompter def checkUpdate(res): links = [] updates = {} for key, val in res.items(): ret = fetch(val[0], val[1]) if (ret): n = 0 while(n < len(ret) and ret[n]['name'] != val[2]): links.append((ret[n]['link'], ret[n]['name'] + ".torrent")) n = n + 1 if (n == 0): print key, "is already updated" else: updates[key] = [None, None, ret[0]['name']] print key, "has", n, "new update(s)!" for i in range(n): print ret[i]['name'] else: print "Connection error on checking", key print return links, updates # create and load database object to be checked db = NyaaSQLiteDB() links, updates = checkUpdate(db.load()) n = len(links) # download available torrent(s) if applicable if n > 0: print "Download all", n, "torrent(s)? [y/n]", var = raw_input() if var=="y": for e in links: try: download(e[0],e[1]) print "Downloaded", e[1] except IOError: print "Connection Error" db.update(updates)
{ "content_hash": "dfa18975da836ab989e2597275fb2f85", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 63, "avg_line_length": 23.098039215686274, "alnum_prop": 0.633276740237691, "repo_name": "faizilham/nyaaupdater", "id": "79afb5185650e6a086118625d1c46e5fcd24b08f", "size": "1200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nyaa_check2.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "15454" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Hendersonia microphylla Cooke ### Remarks null
{ "content_hash": "76f58d2339244e738f1a60473b4690f5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 29, "avg_line_length": 10.307692307692308, "alnum_prop": 0.7238805970149254, "repo_name": "mdoering/backbone", "id": "ef7025ce8f65cd10b0bdcbfc3dec57b75921804e", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phaeosphaeriaceae/Hendersonia/Hendersonia microphylla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#include "prrtnavdemoMain.h" #include "CIniEditor.h" //(*InternalHeaders(CIniEditor) #include <wx/settings.h> #include <wx/font.h> #include <wx/intl.h> #include <wx/string.h> //*) //(*IdInit(CIniEditor) const long CIniEditor::ID_BUTTON1 = wxNewId(); const long CIniEditor::ID_BUTTON2 = wxNewId(); const long CIniEditor::ID_TEXTCTRL1 = wxNewId(); //*) BEGIN_EVENT_TABLE(CIniEditor,wxDialog) //(*EventTable(CIniEditor) //*) END_EVENT_TABLE() CIniEditor::CIniEditor(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size) { //(*Initialize(CIniEditor) wxFlexGridSizer* FlexGridSizer2; wxFlexGridSizer* FlexGridSizer1; Create(parent, id, _("Edit "), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER, _T("id")); SetClientSize(wxDefaultSize); Move(wxDefaultPosition); FlexGridSizer1 = new wxFlexGridSizer(0, 1, 0, 0); FlexGridSizer1->AddGrowableCol(0); FlexGridSizer1->AddGrowableRow(1); FlexGridSizer2 = new wxFlexGridSizer(0, 2, 0, 0); btnOK = new wxButton(this, ID_BUTTON1, _("OK"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1")); FlexGridSizer2->Add(btnOK, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); btnCancel = new wxButton(this, ID_BUTTON2, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2")); FlexGridSizer2->Add(btnCancel, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); FlexGridSizer1->Add(FlexGridSizer2, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0); edText = new wxTextCtrl(this, ID_TEXTCTRL1, _("// Configuration block for the PRRT Navigator\n// ------------------------------------------------\n[prrt-navigator]\n\n\n// 2D-robot for collision detection:\nrobot_shape = [-0.2 0.2 0.2 -0.2; -0.1 -0.1 0.1 0.1]\n"), wxDefaultPosition, wxSize(516,372), wxTE_MULTILINE|wxHSCROLL|wxVSCROLL, wxDefaultValidator, _T("ID_TEXTCTRL1")); wxFont edTextFont = wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT); if ( !edTextFont.Ok() ) edTextFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); edTextFont.SetPointSize((int)(edTextFont.GetPointSize() * 1.000000)); edText->SetFont(edTextFont); FlexGridSizer1->Add(edText, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); SetSizer(FlexGridSizer1); FlexGridSizer1->Fit(this); FlexGridSizer1->SetSizeHints(this); Center(); Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CIniEditor::OnbtnOKClick); Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CIniEditor::OnbtnCancelClick); //*) } CIniEditor::~CIniEditor() { //(*Destroy(CIniEditor) //*) } void CIniEditor::OnbtnCancelClick(wxCommandEvent& event) { EndModal( 0 ); } void CIniEditor::OnbtnOKClick(wxCommandEvent& event) { EndModal( 1 ); }
{ "content_hash": "5bad2c3f6002628244b1c5935653713b", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 378, "avg_line_length": 38.657534246575345, "alnum_prop": 0.7360028348688873, "repo_name": "samuelpfchoi/mrpt", "id": "2d734cc5e09b85bb05864763abd79dcb7d5fba24", "size": "3472", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apps/prrt-navigator-demo/CIniEditor.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.horntail.music.tmp3.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.horntail.music.tmp3.R; /** * A simple {@link Fragment} subclass. */ public class MainGenreFragment extends Fragment { public MainGenreFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_main_genre, container, false); } }
{ "content_hash": "3f09c0d5a6b4a7e372eea038e31b527e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 80, "avg_line_length": 23.666666666666668, "alnum_prop": 0.7070422535211267, "repo_name": "sayan7848/MusicPlayer", "id": "2f7678099a172aa58aa34f916521fa0beb230eb5", "size": "710", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TMP3/app/src/main/java/com/horntail/music/tmp3/fragments/MainGenreFragment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "47852" } ], "symlink_target": "" }
body { margin-top: 15px; margin-bottom: 15px; /*padding-top: 20px;*/ /*padding-bottom: 20px;*/ max-width: 800px; margin-right: auto; margin-left: auto; } /* Set padding to keep content from hitting the edges */ .body-content { padding-left: 15px; padding-right: 15px; } .navbar { background-color: #b1daae; border-radius: 5px; border-color: transparent; margin-right: 15px; margin-left: 15px; } /* Shady fix of admin nav bar */ .navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:hover { background-color: #b1daae; } a.thumbnail { white-space: normal; text-decoration: none; } a.thumbnail:hover { border-color: #adadad; } /* styles for validation helpers */ .field-validation-error { color: #b94a48; } .field-validation-valid { display: none; } input.input-validation-error { border: 1px solid #b94a48; } input[type="checkbox"].input-validation-error { border: 0 none; } .validation-summary-errors { color: #b94a48; } .validation-summary-valid { display: none; } .panel-btn { min-width: 90px; } .field_error_list { list-style-type: none; padding-left: 0; } .field_error_list div { width: auto; } .flashes { list-style-type: none; padding-left: 0; width: auto; }
{ "content_hash": "c3c8ee5a2484f324be0811a58bc13a13", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 56, "avg_line_length": 16.759493670886076, "alnum_prop": 0.6389728096676737, "repo_name": "szeestraten/kidsakoder-minecraft", "id": "e0371d8509223645d514999050403daefb085340", "size": "1326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flask_app/static/content/site.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33699" }, { "name": "HCL", "bytes": "8283" }, { "name": "HTML", "bytes": "130314" }, { "name": "JavaScript", "bytes": "300387" }, { "name": "Python", "bytes": "44478" }, { "name": "SaltStack", "bytes": "16074" }, { "name": "Scheme", "bytes": "959" }, { "name": "Shell", "bytes": "11442" } ], "symlink_target": "" }
/** * Blockly Apps: NetLogo Blocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Blocks for NetLogo extension to Blockly * @author dweintrop@u.northwestern.edu */ 'use strict'; Blockly.Blocks['netlogo_controls_if'] = { /** * Block for if/elseif/else condition. * @this Blockly.Block */ init: function() { this.setHelpUrl(Blockly.Msg.CONTROLS_IF_HELPURL); this.setColour(210); this.appendValueInput('IF0') .setCheck('Boolean') .appendField(Blockly.Msg.CONTROLS_IF_MSG_IF); this.appendStatementInput('DO0') .appendField(Blockly.Msg.CONTROLS_IF_MSG_THEN); this.setPreviousStatement(true); this.setNextStatement(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { if (!thisBlock.elseifCount_ && !thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_1; } else if (!thisBlock.elseifCount_ && thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_2; } else if (thisBlock.elseifCount_ && !thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_3; } else if (thisBlock.elseifCount_ && thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_4; } return ''; }); this.elseifCount_ = 0; this.elseCount_ = 0; }, /** * Store pointers to any connected child blocks. * @param {!Blockly.Block} containerBlock Root block in mutator. * @this Blockly.Block */ saveConnections: function(containerBlock) { var clauseBlock = containerBlock.getInputTargetBlock('STACK'); var x = 1; while (clauseBlock) { switch (clauseBlock.type) { case 'controls_if_elseif': var inputIf = this.getInput('IF' + x); var inputDo = this.getInput('DO' + x); clauseBlock.valueConnection_ = inputIf && inputIf.connection.targetConnection; clauseBlock.statementConnection_ = inputDo && inputDo.connection.targetConnection; x++; break; case 'controls_if_else': var inputDo = this.getInput('ELSE'); clauseBlock.statementConnection_ = inputDo && inputDo.connection.targetConnection; break; default: throw 'Unknown block type.'; } clauseBlock = clauseBlock.nextConnection && clauseBlock.nextConnection.targetBlock(); } } }; Blockly.Blocks['netlogo_controls_if_else'] = { /** * Block for if/elseif/else condition. * @this Blockly.Block */ init: function() { this.setHelpUrl(Blockly.Msg.CONTROLS_IF_HELPURL); this.setColour(210); this.appendValueInput('IF0') .setCheck('Boolean') .appendField(Blockly.Msg.CONTROLS_IF_MSG_IF); this.appendStatementInput('DO0') .appendField(Blockly.Msg.CONTROLS_IF_MSG_THEN); this.appendStatementInput('ELSE') .appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE) this.setPreviousStatement(true); this.setNextStatement(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { if (!thisBlock.elseifCount_ && !thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_1; } else if (!thisBlock.elseifCount_ && thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_2; } else if (thisBlock.elseifCount_ && !thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_3; } else if (thisBlock.elseifCount_ && thisBlock.elseCount_) { return Blockly.Msg.CONTROLS_IF_TOOLTIP_4; } return ''; }); this.elseifCount_ = 0; this.elseCount_ = 0; }, /** * Store pointers to any connected child blocks. * @param {!Blockly.Block} containerBlock Root block in mutator. * @this Blockly.Block */ saveConnections: function(containerBlock) { var clauseBlock = containerBlock.getInputTargetBlock('STACK'); var x = 1; while (clauseBlock) { switch (clauseBlock.type) { case 'controls_if_elseif': var inputIf = this.getInput('IF' + x); var inputDo = this.getInput('DO' + x); clauseBlock.valueConnection_ = inputIf && inputIf.connection.targetConnection; clauseBlock.statementConnection_ = inputDo && inputDo.connection.targetConnection; x++; break; case 'controls_if_else': var inputDo = this.getInput('ELSE'); clauseBlock.statementConnection_ = inputDo && inputDo.connection.targetConnection; break; default: throw 'Unknown block type.'; } clauseBlock = clauseBlock.nextConnection && clauseBlock.nextConnection.targetBlock(); } } };
{ "content_hash": "eff20a4d5b2bb19af4369910e1e0eefc", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 75, "avg_line_length": 34.583333333333336, "alnum_prop": 0.6417052826691381, "repo_name": "dweintrop/blockly-NetLogo", "id": "0795bbee8c2136346c4c0b9eae8ae1b875cb4f67", "size": "5395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/tortoise/blocks.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17549" }, { "name": "JavaScript", "bytes": "3630631" }, { "name": "Python", "bytes": "64570" } ], "symlink_target": "" }
package com.amazonaws.services.gamelift.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.gamelift.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * EC2InstanceCountsMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class EC2InstanceCountsMarshaller { private static final MarshallingInfo<Integer> DESIRED_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("DESIRED").build(); private static final MarshallingInfo<Integer> MINIMUM_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("MINIMUM").build(); private static final MarshallingInfo<Integer> MAXIMUM_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("MAXIMUM").build(); private static final MarshallingInfo<Integer> PENDING_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("PENDING").build(); private static final MarshallingInfo<Integer> ACTIVE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ACTIVE").build(); private static final MarshallingInfo<Integer> IDLE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("IDLE").build(); private static final MarshallingInfo<Integer> TERMINATING_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TERMINATING").build(); private static final EC2InstanceCountsMarshaller instance = new EC2InstanceCountsMarshaller(); public static EC2InstanceCountsMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(EC2InstanceCounts eC2InstanceCounts, ProtocolMarshaller protocolMarshaller) { if (eC2InstanceCounts == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(eC2InstanceCounts.getDESIRED(), DESIRED_BINDING); protocolMarshaller.marshall(eC2InstanceCounts.getMINIMUM(), MINIMUM_BINDING); protocolMarshaller.marshall(eC2InstanceCounts.getMAXIMUM(), MAXIMUM_BINDING); protocolMarshaller.marshall(eC2InstanceCounts.getPENDING(), PENDING_BINDING); protocolMarshaller.marshall(eC2InstanceCounts.getACTIVE(), ACTIVE_BINDING); protocolMarshaller.marshall(eC2InstanceCounts.getIDLE(), IDLE_BINDING); protocolMarshaller.marshall(eC2InstanceCounts.getTERMINATING(), TERMINATING_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "eda71b2837f52327e88ab9edc9688144", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 159, "avg_line_length": 51.83870967741935, "alnum_prop": 0.7554449284380834, "repo_name": "aws/aws-sdk-java", "id": "b01986ec903399cbd062f6ee58c89d7848726047", "size": "3794", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/transform/EC2InstanceCountsMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@implementation JavaClassMetadata @synthesize version; @synthesize typeName; @synthesize packageName; @synthesize enclosingName; @synthesize fieldCount; @synthesize methodCount; @synthesize modifiers; - (instancetype)initWithMetadata:(J2ObjcClassInfo *)metadata { if (self = [super init]) { data_ = metadata; switch (data_->version) { // Add future versions here as case statements. default: version = 1; break; } NSStringEncoding defaultEncoding = [NSString defaultCStringEncoding]; typeName = [[NSString alloc] initWithCString:metadata->typeName encoding:defaultEncoding]; if (metadata->packageName) { packageName = [[NSString alloc] initWithCString:metadata->packageName encoding:defaultEncoding]; } if (metadata->enclosingName) { enclosingName = [[NSString alloc] initWithCString:metadata->enclosingName encoding:defaultEncoding]; } fieldCount = metadata->fieldCount; methodCount = metadata->methodCount; modifiers = metadata->modifiers; } return self; } - (NSString *)qualifiedName { NSMutableString *qName = [NSMutableString string]; if ([packageName length] > 0) { [qName appendString:packageName]; [qName appendString:@"."]; } if (enclosingName) { [qName appendString:enclosingName]; [qName appendString:@"$"]; } [qName appendString:typeName]; return qName; } - (const J2ObjcMethodInfo *)findMethodInfo:(NSString *)methodName { const char *name = [methodName cStringUsingEncoding:[NSString defaultCStringEncoding]]; for (int i = 0; i < data_->methodCount; i++) { if (strcmp(name, data_->methods[i].selector) == 0) { return &data_->methods[i]; } } return nil; } - (JavaMethodMetadata *)findMethodMetadata:(NSString *)methodName { const J2ObjcMethodInfo *info = [self findMethodInfo:methodName]; return info ? AUTORELEASE([[JavaMethodMetadata alloc] initWithMetadata:info]) : nil; } static jint countArgs(char *s) { jint count = 0; while (*s) { if (*s++ == ':') { ++count; } } return count; } - (JavaMethodMetadata *)findMethodMetadataWithJavaName:(NSString *)javaName argCount:(jint)argCount { const char *name = [javaName cStringUsingEncoding:[NSString defaultCStringEncoding]]; for (int i = 0; i < data_->methodCount; i++) { const char *cname = data_->methods[i].javaName; if (cname && strcmp(name, cname) == 0 && argCount == countArgs((char *)data_->methods[i].selector)) { // Skip leading matches followed by "With", which follow the standard selector // pattern using typed parameters. This method is for resolving mapped methods // which don't follow that pattern, and thus need help from metadata. char buffer[256]; strcpy(buffer, cname); strcat(buffer, "With"); if (strncmp(buffer, data_->methods[i].selector, strlen(buffer)) != 0) { return [[JavaMethodMetadata alloc] initWithMetadata:&data_->methods[i]]; } } } return nil; } - (const J2ObjcFieldInfo *)findFieldInfo:(const char *)fieldName { for (int i = 0; i < data_->fieldCount; i++) { const J2ObjcFieldInfo *fieldInfo = &data_->fields[i]; if (fieldInfo->javaName && strcmp(fieldName, fieldInfo->javaName) == 0) { return fieldInfo; } if (strcmp(fieldName, fieldInfo->name) == 0) { return fieldInfo; } // See if field name has trailing underscore added. size_t max = strlen(fieldInfo->name) - 1; if (fieldInfo->name[max] == '_' && strlen(fieldName) == max && strncmp(fieldName, fieldInfo->name, max) == 0) { return fieldInfo; } } return nil; } - (JavaFieldMetadata *)findFieldMetadata:(const char *)fieldName { const J2ObjcFieldInfo *info = [self findFieldInfo:fieldName]; return info ? AUTORELEASE([[JavaFieldMetadata alloc] initWithMetadata:info]) : nil; } - (IOSObjectArray *)getSuperclassTypeArguments { uint16_t size = data_->superclassTypeArgsCount; if (size == 0) { return nil; } IOSObjectArray *result = [IOSObjectArray arrayWithLength:size type:JavaLangReflectType_class_()]; for (int i = 0; i < size; i++) { IOSObjectArray_Set(result, i, JreTypeForString(data_->superclassTypeArgs[i])); } return result; } - (IOSObjectArray *)allFields { IOSObjectArray *result = [IOSObjectArray arrayWithLength:data_->fieldCount type:NSObject_class_()]; J2ObjcFieldInfo *fields = (J2ObjcFieldInfo *) data_->fields; for (int i = 0; i < data_->fieldCount; i++) { [result replaceObjectAtIndex:i withObject:[[JavaFieldMetadata alloc] initWithMetadata:fields++]]; } return result; } - (IOSObjectArray *)allMethods { IOSObjectArray *result = [IOSObjectArray arrayWithLength:data_->methodCount type:NSObject_class_()]; J2ObjcMethodInfo *methods = (J2ObjcMethodInfo *) data_->methods; for (int i = 0; i < data_->methodCount; i++) { [result replaceObjectAtIndex:i withObject:[[JavaMethodMetadata alloc] initWithMetadata:methods++]]; } return result; } - (NSString *)description { return [NSString stringWithFormat:@"{ typeName=%@ packageName=%@ modifiers=0x%x }", typeName, packageName, modifiers]; } - (void)dealloc { if (attributes) { free(attributes); } #if ! __has_feature(objc_arc) [typeName release]; [packageName release]; [enclosingName release]; [super dealloc]; #endif } @end @implementation JavaFieldMetadata - (instancetype)initWithMetadata:(const J2ObjcFieldInfo *)metadata { if (self = [super init]) { data_ = metadata; } return self; } - (NSString *)name { return data_->javaName ? [NSString stringWithUTF8String:data_->javaName] : [NSString stringWithUTF8String:data_->name]; } - (NSString *)iosName { return [NSString stringWithUTF8String:data_->name]; } - (NSString *)javaName { return data_->javaName ? [NSString stringWithUTF8String:data_->javaName] : nil; } - (int)modifiers { return data_->modifiers; } - (id<JavaLangReflectType>)type { return JreTypeForString(data_->type); } - (const void *)staticRef { return data_->staticRef; } - (const J2ObjcRawValue * const)getConstantValue { return &data_->constantValue; } @end @implementation JavaMethodMetadata - (instancetype)initWithMetadata:(const J2ObjcMethodInfo *)metadata { if (self = [super init]) { data_ = metadata; } return self; } - (SEL)selector { return sel_registerName(data_->selector); } - (NSString *)name { return data_->javaName ? [NSString stringWithUTF8String:data_->javaName] : [NSString stringWithUTF8String:data_->selector]; } - (NSString *)javaName { return data_->javaName ? [NSString stringWithUTF8String:data_->javaName] : nil; } - (NSString *)objcName { return [NSString stringWithUTF8String:data_->selector]; } - (int)modifiers { return data_->modifiers; } - (id<JavaLangReflectType>)returnType { return JreTypeForString(data_->returnType); } - (IOSObjectArray *)exceptionTypes { NSString *exceptionsStr = [NSString stringWithUTF8String:data_->exceptions]; NSArray *exceptionsArray = [exceptionsStr componentsSeparatedByString:@";"]; // The last string is empty, due to the trailing semi-colon of the last exception. NSUInteger n = [exceptionsArray count] - 1; IOSObjectArray *result = [IOSObjectArray arrayWithLength:(jint)n type:IOSClass_class_()]; jint count = 0; for (NSUInteger i = 0; i < n; i++) { // Strip off leading 'L'. NSString *thrownException = [[exceptionsArray objectAtIndex:i] substringFromIndex:1]; IOSObjectArray_Set(result, count++, [IOSClass forName:thrownException]); } return result; } - (BOOL)isConstructor { const char *name = data_->javaName ? data_->javaName : data_->selector; return strcmp(name, "init") == 0 || strstr(name, "initWith") == name; } @end
{ "content_hash": "f8f17411b92f7f099c0ab095299ee4de", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 99, "avg_line_length": 29.395522388059703, "alnum_prop": 0.6769484640771769, "repo_name": "jiachenning/j2objc", "id": "d06b7e6dc1e17ce79039081ae48ed43c92130f21", "size": "8612", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jre_emul/Classes/JavaMetadata.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "561283" }, { "name": "C++", "bytes": "93021" }, { "name": "Java", "bytes": "21499836" }, { "name": "Makefile", "bytes": "179647" }, { "name": "Objective-C", "bytes": "531366" }, { "name": "Python", "bytes": "725" }, { "name": "Shell", "bytes": "7914" } ], "symlink_target": "" }
// // UIView+PRJProjection.h // Projection // // Created by Mikey Lintz on 2/1/15. // Copyright (c) 2015 Mikey Lintz. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @class PRJMapping; @class PRJRect; typedef void (^PRJConfigurationBlock)(PRJMapping * __nonnull mapping, PRJRect * __nonnull viewBounds); /** Convenience category for applying layout to a view's children. These methods automatically create an empty PRJMapping and a fully defined PRJRect representing the receivers frame pass, them to a client-provided PRJConfigurationBlock to fill out the mapping, and then invokes [mapping apply]. The following two examples are equivalent: // Without category method PRJMapping *mapping = [[PRJMapping alloc] init]; PRJRect *viewBounds = [[PRJRect alloc] init]; viewBounds.bounds = superView.bounds; mapping[subview1].topLeft = viewBounds.topLeft; mapping[subview1].size = CGSizeMake(10, 10); mapping[subview2].bottomRight = viewBounds.bottomRight; mapping[subview2].size = mapping[subview1].size; [mapping apply]; // With category method [viewBounds prj_applyProjection:^(PRJMapping *mapping, PRJRect *viewBounds) { mapping[subview1].topLeft = viewBounds.topLeft; mapping[subview1].size = CGSizeMake(10, 10); mapping[subview2].bottomRight = viewBounds.bottomRight; mapping[subview2].size = mapping[subview1].size; }]; */ @interface UIView (PRJConvenience) NS_ASSUME_NONNULL_BEGIN - (void)prj_applyProjection:(__attribute__((noescape)) PRJConfigurationBlock)configurationBlock; - (void)prj_applyProjectionWithSize:(CGSize)size configuration:(__attribute__((noescape)) PRJConfigurationBlock)configurationBlock; - (void)prj_applyProjectionWithBounds:(CGRect)bounds configuration:(__attribute__((noescape)) PRJConfigurationBlock)configurationBlock; NS_ASSUME_NONNULL_END @end
{ "content_hash": "bab65ac26a7687d7e2703ac71ff483c0", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 106, "avg_line_length": 32.483333333333334, "alnum_prop": 0.7301180092355054, "repo_name": "mlintz/Projection", "id": "f2f1d5218b4350991152a83eb1617b3b3c04da80", "size": "1949", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Projection/UIView+PRJConvenience.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "38019" }, { "name": "Ruby", "bytes": "1011" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Devsense.PHP.Syntax; using Devsense.PHP.Syntax.Ast; using Devsense.PHP.Text; using Microsoft.CodeAnalysis; using Pchp.CodeAnalysis; using Pchp.CodeAnalysis.Symbols; namespace Peachpie.CodeAnalysis.Syntax { /// <summary> /// Provides nodes instantiation for underlaying parser /// and collects instantiated nodes. /// </summary> sealed class NodesFactory : BasicNodesFactory { /// <summary> /// Gets constructed lambda nodes. /// </summary> public List<LambdaFunctionExpr> Lambdas => _lambdas; List<LambdaFunctionExpr> _lambdas; /// <summary> /// Gets constructed type declaration nodes. /// </summary> public List<TypeDecl> Types => _types; List<TypeDecl> _types; /// <summary> /// Gets constructed function declaration nodes. /// </summary> public List<FunctionDecl> Functions => _functions; List<FunctionDecl> _functions; /// <summary> /// Gets constructed global code (ast root). /// </summary> public GlobalCode Root { get; private set; } /// <summary> /// Gets constructed yield extpressions. /// </summary> public List<LangElement> YieldNodes => _yieldNodes; List<LangElement> _yieldNodes; /// <summary> /// Adds node to the list and returns the node. /// </summary> static T AddAndReturn<T>(ref List<T> list, T node) { if (list == null) { list = new List<T>(); } list.Add(node); return node; } public void AddAnnotation(int position, object obj) { AddAndReturn(ref _annotations, (position, obj)); } List<(int, object)> _annotations; // list of parsed custom attributes, will be taken and used for the next declaration /// <summary> /// Gets an additional annotation if any. /// </summary> /// <typeparam name="T">Annotation type.</typeparam> /// <param name="position">Position of the annotation.</param> /// <param name="obj">Resulting object.</param> /// <returns>Wtehher the annotation was found.</returns> bool TryGetAnotation<T>(int position, out T obj) { // check Span contains position => add to Properties if (_annotations != null) { for (int i = _annotations.Count - 1; i >= 0; i--) { if (_annotations[i].Item1 == position && _annotations[i].Item2 is T value) { _annotations.RemoveAt(i); obj = value; return true; } } } // obj = default; return false; } /// <summary> /// If applicable, annotates the element with previously parsed <see cref="SourceCustomAttribute"/>. /// </summary> T WithCustomAttributes<T>(T element) where T : LangElement { while (TryGetAnotation<AttributeData>(element.Span.Start, out var attr)) { element.AddCustomAttribute(attr); } // return element; } TypeRef WithGenericTypes(TypeRef tref) { return TryGetAnotation<List<TypeRef>>(tref.Span.End, out var generics) ? new GenericTypeRef(tref.Span, tref, generics) : tref; } FunctionCall WithGenericTypes(FunctionCall call, Span nameSpan) { if (TryGetAnotation<List<TypeRef>>(nameSpan.End, out var generics)) { call.SetGenericParams(generics); } return call; } public override LangElement GlobalCode(Span span, IEnumerable<LangElement> statements, NamingContext context) { Debug.Assert(_annotations == null || _annotations.Count == 0, $"file {this.SourceUnit.FilePath} contains CLR annotations we did not consume! Probably a bogus in AdditionalSyntaxProvider."); // all parsed custom annotations have to be consumed return Root = (GlobalCode)base.GlobalCode(span, statements, context); } public override LangElement Function(Span span, bool conditional, bool aliasReturn, PhpMemberAttributes attributes, TypeRef returnType, Name name, Span nameSpan, IEnumerable<FormalTypeParam> typeParamsOpt, IEnumerable<FormalParam> formalParams, Span formalParamsSpan, LangElement body) { return AddAndReturn(ref _functions, WithCustomAttributes((FunctionDecl)base.Function(span, conditional, aliasReturn, attributes, returnType, name, nameSpan, typeParamsOpt, formalParams, formalParamsSpan, body))); } public override LangElement Type(Span span, Span headingSpan, bool conditional, PhpMemberAttributes attributes, Name name, Span nameSpan, IEnumerable<FormalTypeParam> typeParamsOpt, INamedTypeRef baseClassOpt, IEnumerable<INamedTypeRef> implements, IEnumerable<LangElement> members, Span bodySpan) { var tref = (TypeDecl)base.Type(span, headingSpan, conditional, attributes, name, nameSpan, typeParamsOpt, baseClassOpt, implements, members, bodySpan); return AddAndReturn(ref _types, WithCustomAttributes(tref)); } public override LangElement DeclList(Span span, PhpMemberAttributes attributes, IList<LangElement> decls, TypeRef type) { return WithCustomAttributes(base.DeclList(span, attributes, decls, type)); } public override LangElement Method(Span span, bool aliasReturn, PhpMemberAttributes attributes, TypeRef returnType, Span returnTypeSpan, string name, Span nameSpan, IEnumerable<FormalTypeParam> typeParamsOpt, IEnumerable<FormalParam> formalParams, Span formalParamsSpan, IEnumerable<ActualParam> baseCtorParams, LangElement body) { return WithCustomAttributes( base.Method(span, aliasReturn, attributes, returnType, returnTypeSpan, name, nameSpan, typeParamsOpt, formalParams, formalParamsSpan, baseCtorParams, body)); } public override TypeRef AnonymousTypeReference(Span span, Span headingSpan, bool conditional, PhpMemberAttributes attributes, IEnumerable<FormalTypeParam> typeParamsOpt, INamedTypeRef baseClassOpt, IEnumerable<INamedTypeRef> implements, IEnumerable<LangElement> members, Span bodySpan) { var tref = (AnonymousTypeRef)base.AnonymousTypeReference(span, headingSpan, conditional, attributes, typeParamsOpt, baseClassOpt, implements, members, bodySpan); AddAndReturn(ref _types, tref.TypeDeclaration); return tref; } public override LangElement Lambda(Span span, Span headingSpan, bool aliasReturn, TypeRef returnType, IEnumerable<FormalParam> formalParams, Span formalParamsSpan, IEnumerable<FormalParam> lexicalVars, LangElement body) { return AddAndReturn(ref _lambdas, (LambdaFunctionExpr)base.Lambda(span, headingSpan, aliasReturn, returnType, formalParams, formalParamsSpan, lexicalVars, body)); } public override LangElement ArrowFunc(Span span, Span headingSpan, bool aliasReturn, TypeRef returnType, IEnumerable<FormalParam> formalParams, Span formalParamsSpan, LangElement expression) { return AddAndReturn(ref _lambdas, (ArrowFunctionExpr)base.ArrowFunc(span, headingSpan, aliasReturn, returnType, formalParams, formalParamsSpan, expression)); } public override LangElement Yield(Span span, LangElement keyOpt, LangElement valueOpt) { return AddAndReturn(ref _yieldNodes, base.Yield(span, keyOpt, valueOpt)); } public override LangElement YieldFrom(Span span, LangElement fromExpr) { return AddAndReturn(ref _yieldNodes, base.YieldFrom(span, fromExpr)); } public Literal Literal(Span span, long lvalue) => new LongIntLiteral(span, lvalue); // overload to avoid boxing public Literal Literal(Span span, double dvalue) => new DoubleLiteral(span, dvalue); // overload to avoid boxing public override LangElement Literal(Span span, object value, string originalValue) { return base.Literal(span, value, originalValue: null); // discard the original value string, not needed, free some memory } public override LangElement EncapsedExpression(Span span, LangElement expression, Tokens openDelimiter) => expression; public override LangElement StringEncapsedExpression(Span span, LangElement expression, Tokens openDelimiter) => expression; public override LangElement HeredocExpression(Span span, LangElement expression, Tokens quoteStyle, string label) => expression; public override LangElement Call(Span span, Name name, Span nameSpan, CallSignature signature, TypeRef typeRef) { var call = (FunctionCall)base.Call(span, name, nameSpan, signature, typeRef); return WithGenericTypes(call, nameSpan); } public override LangElement Call(Span span, TranslatedQualifiedName name, CallSignature signature, LangElement memberOfOpt) { var call = (FunctionCall)base.Call(span, name, signature, memberOfOpt); return WithGenericTypes(call, name.Span); } public override TypeRef TypeReference(Span span, QualifiedName className) { return WithGenericTypes(base.TypeReference(span, className)); } public NodesFactory(SourceUnit sourceUnit) : base(sourceUnit) { } } internal static class FunctionCallExtensions { public static void SetGenericParams(this FunctionCall call, IList<TypeRef> types) { if (types == null || types.Count == 0) { RemoveGenericParams(call); } else { call.Properties.SetProperty<IList<TypeRef>>(types); } } public static void RemoveGenericParams(this FunctionCall call) { call.Properties.RemoveProperty<IList<TypeRef>>(); } public static IList<TypeRef> GetGenericParams(this FunctionCall call) { return call.Properties.GetProperty<IList<TypeRef>>() ?? Array.Empty<TypeRef>(); } } }
{ "content_hash": "b4f8141fd98e43c5e45c9d8a357d31cd", "timestamp": "", "source": "github", "line_count": 254, "max_line_length": 337, "avg_line_length": 42.28346456692913, "alnum_prop": 0.6424581005586593, "repo_name": "iolevel/peachpie", "id": "6be49528e11b47bfe35e4d2e44908698cd4340f5", "size": "10742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Peachpie.CodeAnalysis/Syntax/NodesFactory.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "353" }, { "name": "C#", "bytes": "6677736" }, { "name": "Lex", "bytes": "19063" }, { "name": "PHP", "bytes": "90462" }, { "name": "PowerShell", "bytes": "2885" }, { "name": "Shell", "bytes": "2888" }, { "name": "Yacc", "bytes": "2990" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Anemone flavescens Zucc. ### Remarks null
{ "content_hash": "277fbafeef192306dedb4be9fcf8f864", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 11.23076923076923, "alnum_prop": 0.726027397260274, "repo_name": "mdoering/backbone", "id": "90da131fd1c617326049a8cc60875acef76a3d65", "size": "230", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Ranunculaceae/Anemone/Pulsatilla angustifolia/Pulsatilla angustifolia flavescens/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import * as React from "react"; import NotebookPreview from "@nteract/notebook-preview"; import Markdown from "@nteract/markdown"; import { Styles, Source } from "@nteract/presentational-components"; import { standardTransforms, standardDisplayOrder, registerTransform } from "@nteract/transforms"; import { VegaLite1, VegaLite2, Vega2, Vega3 } from "@nteract/transform-vega"; // import DataResourceTransform from "@nteract/transform-dataresource"; import { PlotlyNullTransform, PlotlyTransform } from "../../transforms"; import DirectoryListing from "./directory-listing"; import HTMLView from "./html"; import JSONView from "./json"; import CSVView from "./csv"; const jquery = require("jquery"); // HACK: Temporarily provide jquery for others to use... global.jquery = jquery; global.$ = jquery; // Order is important here. The last transform in the array will have order `0`. const { transforms, displayOrder } = [ // DataResourceTransform, PlotlyNullTransform, PlotlyTransform, VegaLite1, VegaLite2, Vega2, Vega3 ].reduce(registerTransform, { transforms: standardTransforms, displayOrder: standardDisplayOrder }); const suffixRegex = /(?:\.([^.]+))?$/; class File extends React.Component<*> { shouldComponentUpdate() { return false; } render() { const name = this.props.entry.name; const presuffix = suffixRegex.exec(name); if (!presuffix) { return null; } const suffix = (presuffix[1] || "").toLowerCase(); switch (suffix) { case "html": return <HTMLView entry={this.props.entry} />; case "json": return <JSONView entry={this.props.entry} />; case "csv": return <CSVView entry={this.props.entry} />; case "md": case "markdown": case "rmd": return <Markdown source={this.props.entry.content} />; case "js": return ( <Source language="javascript">{this.props.entry.content}</Source> ); case "py": case "pyx": return <Source language="python">{this.props.entry.content}</Source>; case "gif": case "jpeg": case "jpg": case "png": return ( <img src={`/files/${this.props.pathname}`} alt={this.props.pathname} /> ); default: if (this.props.entry.format === "text") { return ( <Source language="text/plain">{this.props.entry.content}</Source> ); } return <a href={`/files/${this.props.pathname}`}>Download raw file</a>; } } } type EntryProps = { entry: JupyterApi$Content, pathname: string, basepath: string }; export const Entry = (props: EntryProps) => { if (props.entry.content === null) { return null; } switch (props.entry.type) { case "directory": // Dynamic type check on content being an Array if (Array.isArray(props.entry.content)) { return ( <DirectoryListing contents={props.entry.content} basepath={"/view"} /> ); } return null; case "file": // TODO: Case off various file types (by extension, mimetype) return <File entry={props.entry} pathname={props.pathname} />; case "notebook": return ( <Styles> <NotebookPreview notebook={props.entry.content} displayOrder={displayOrder} transforms={transforms} /> </Styles> ); default: return <pre>{JSON.stringify(props.entry.content)}</pre>; } };
{ "content_hash": "6fb7df7eca87dd90ab068461fdd05a98", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 80, "avg_line_length": 26.795454545454547, "alnum_prop": 0.6135142776364151, "repo_name": "rgbkrk/nteract", "id": "31e8ca7878b80e13a00f9eff959242abb20abb34", "size": "3546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "applications/commuter/components/contents/index.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "472" }, { "name": "CSS", "bytes": "7634" }, { "name": "Dockerfile", "bytes": "242" }, { "name": "HTML", "bytes": "10431" }, { "name": "JavaScript", "bytes": "464357" }, { "name": "Jupyter Notebook", "bytes": "211986" }, { "name": "Python", "bytes": "43513" }, { "name": "Shell", "bytes": "6075" }, { "name": "TypeScript", "bytes": "859762" } ], "symlink_target": "" }
/* @flow */ import React from 'react'; import styled from 'styled-components'; import { Field, reduxForm } from 'redux-form'; // internal import Button from '@boldr/ui/Button'; import { Form, TextFormField } from '@boldr/ui/Form'; type Props = { handleSubmit?: Function, reset?: Function, submitting?: boolean, pristine?: boolean, }; const FormBottom = styled.div` justify-content: center; display: flex; width: 100%; font-size: 14px; text-align: center; `; const MediaForm = (props: Props) => { const { handleSubmit, reset, submitting, pristine } = props; return ( <Form onSubmit={handleSubmit} className="boldr-form__fileeditor"> <Field id="name" name="name" type="text" label="File name" component={TextFormField} /> <Field id="description" name="fileDescription" type="text" label="Description" component={TextFormField} /> <FormBottom> <Button htmlType="submit" kind="primary" disabled={submitting || pristine}> Save </Button> <Button onClick={reset} outline> Reset </Button> </FormBottom> </Form> ); }; export default reduxForm({ form: 'mediaForm', })(MediaForm);
{ "content_hash": "10b86bbbc41a01c24446e91e9503cf9e", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 93, "avg_line_length": 24.6, "alnum_prop": 0.6268292682926829, "repo_name": "boldr/boldr", "id": "643114cb6f8011ed4a2bec2421a8840bde88407d", "size": "1230", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "project/src/scenes/Admin/Media/MediaManager/components/MediaForm/MediaForm.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33159" }, { "name": "JavaScript", "bytes": "1820797" }, { "name": "Makefile", "bytes": "877" } ], "symlink_target": "" }
import * as moment from 'moment' export interface ISourceOptions{ id: number; name: string; size: number; mimeType?: string; dateCreated?: string | moment.Moment; dateUpdated?: string | moment.Moment; version?: number; } export class Source { private id: number; public name: string; public size: number; public mimeType: string; public dateCreated: string | moment.Moment; public dateUpdated: string | moment.Moment; public version: number; constructor(options: ISourceOptions) { // Required this.id = options.id this.name = options.name this.size = options.size // Optional this.mimeType = options.mimeType || "application/unknown" this.dateCreated = options.dateCreated || moment() this.dateUpdated = options.dateUpdated || moment() this.version = options.version || 1 } }
{ "content_hash": "314aa92c8c342034295da9acda1ca56f", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 65, "avg_line_length": 25.72972972972973, "alnum_prop": 0.6186974789915967, "repo_name": "aheinrich/simple-finance-ng2", "id": "34c4953199240dd499130ec7631a107ebded43d7", "size": "952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/transactions/models/source.model.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "920" }, { "name": "HTML", "bytes": "9978" }, { "name": "JavaScript", "bytes": "1615" }, { "name": "TypeScript", "bytes": "27832" } ], "symlink_target": "" }
package smtestutil import ( "bytes" "fmt" "runtime" "strings" "sync" "testing" "unsafe" ) // An adapter around testing.T that allows finer grain control of stack frame logging. // Generally you would wrap this in another type that exposes the desired logging interface. type TestLogger interface { // Logs the given message to the test log, skipping the desired number of stack frames. DoLog(s string, skipFrames int) } // Adapt a testing.T to expose its inner logging with better stack frame handling. func AdaptTestLogger(t *testing.T) TestLogger { // Just cast the internal type to our look-alike type. return (*logger)(unsafe.Pointer(t)) } // Lookalike copy of testing.T/testing.common, so we can access the bits directly. // Sadly, there's no other way to get the right call stack depth handling. type logger struct { mu sync.RWMutex output []byte } func (t *logger) DoLog(s string, skipFrames int) { t.mu.Lock() defer t.mu.Unlock() msg := t.decorate(s, skipFrames+1) t.output = append(t.output, msg...) } // decorate prefixes the string with the file and line of the call site // and inserts the final newline if needed and indentation tabs for formatting. // Almost a direct copy of the internal testing.common -> decorate() func (t *logger) decorate(s string, skipFrames int) string { _, file, line, ok := runtime.Caller(skipFrames) // decorate + log + public function. if ok { // Truncate file name at last file name separator. if index := strings.LastIndex(file, "/"); index >= 0 { file = file[index+1:] } else if index = strings.LastIndex(file, "\\"); index >= 0 { file = file[index+1:] } } else { file = "???" line = 1 } buf := new(bytes.Buffer) // Every line is indented at least one tab. buf.WriteByte('\t') fmt.Fprintf(buf, "%s:%d: ", file, line) lines := strings.Split(s, "\n") if l := len(lines); l > 1 && lines[l-1] == "" { lines = lines[:l-1] } for i, line := range lines { if i > 0 { // Second and subsequent lines are indented an extra tab. buf.WriteString("\n\t\t") } buf.WriteString(line) } buf.WriteByte('\n') return buf.String() }
{ "content_hash": "d0be1ad9ae65690c47d9cd371c0f92d5", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 92, "avg_line_length": 29.17808219178082, "alnum_prop": 0.680281690140845, "repo_name": "fullstorydev/gosolr", "id": "e8e4601e842b7f0b1857d42a1644124a5d32a151", "size": "2719", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "smtestutil/testlogger.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "185379" }, { "name": "Shell", "bytes": "185" } ], "symlink_target": "" }
package org.jivesoftware.openfire.auth; /** * This is the interface the used to provide default defualt authorization * ID's when none was selected by the client. * <p> * Users that wish to integrate with their own authorization * system must implement this interface. * Register the class with Openfire in the {@code openfire.xml} * file. An entry in that file would look like the following: * </p> * <pre> * &lt;provider&gt; * &lt;authorizationMapping&gt; * &lt;classlist&gt;com.foo.auth.CustomProvider&lt;/classlist&gt; * &lt;/authorizationMapping&gt; * &lt;/provider&gt;</pre> * * @author Jay Kline */ public interface AuthorizationMapping { /** * Returns true if the principal is explicity authorized to the JID * * @param principal The autheticated principal requesting authorization. * @return The name of the default username to use. */ String map( String principal ); /** * Returns the short name of the Policy * * @return The short name of the Policy */ String name(); /** * Returns a description of the Policy * * @return The description of the Policy. */ String description(); }
{ "content_hash": "f494f52b35e3a063c4d467beb6e89859", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 76, "avg_line_length": 26.58695652173913, "alnum_prop": 0.6590351594439902, "repo_name": "GregDThomas/Openfire", "id": "c1bab6b5ada30ce10968666f0f206edd78b351c2", "size": "1850", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "xmppserver/src/main/java/org/jivesoftware/openfire/auth/AuthorizationMapping.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3430" }, { "name": "C", "bytes": "3814" }, { "name": "CSS", "bytes": "66351" }, { "name": "Dockerfile", "bytes": "1580" }, { "name": "HTML", "bytes": "312602" }, { "name": "Java", "bytes": "8282211" }, { "name": "JavaScript", "bytes": "178921" }, { "name": "Makefile", "bytes": "1266" }, { "name": "Objective-C", "bytes": "6879" }, { "name": "Shell", "bytes": "45527" }, { "name": "TSQL", "bytes": "123538" } ], "symlink_target": "" }
<?php namespace Horus\SiteBundle\Repository; use Doctrine\ORM\EntityRepository; /** * Class CommercialRepository * @package Horus\SiteBundle\Repository */ class CommercialRepository extends EntityRepository { /** * Get Active Commercials * @return \Doctrine\ORM\QueryBuilder */ public function getActiveCommercialQueryBuilder() { $queryBuilder = $this->getEntityManager() ->createQueryBuilder() ->select('m') ->from('Horus\SiteBundle\Entity\Commercial', 'm') ->orderBy('m.id', 'DESC'); return $queryBuilder; } /** * Get articles by Category * @param Category $category * @return mixed */ public function getCommercialIsDesactive() { $query = $this->getEntityManager() ->createQuery("SELECT COUNT(a.id) FROM HorusSiteBundle:Commercial a WHERE a.isVisible = :visible") ->setParameter('visible', false); return $query->getSingleScalarResult(); } /** * Get articles by Category * @param Category $category * @return mixed */ public function getCommercialSoonBegin() { $query = $this->getEntityManager() ->createQuery("SELECT COUNT(a.id) FROM HorusSiteBundle:Commercial a WHERE DATE_DIFF(a.datePublication,:dateend) <= 3 AND DATE_DIFF(a.datePublication,:dateend) >= 0 AND a.isVisible = :visible") ->setParameter('dateend', new \Datetime('now')) ->setParameter('visible', true); return $query->getSingleScalarResult(); } /** * Get articles by Category * @param Category $category * @return mixed */ public function getCommercialSoonEnd() { $query = $this->getEntityManager() ->createQuery("SELECT COUNT(a.id) FROM HorusSiteBundle:Commercial a WHERE DATE_DIFF(a.dateFinPublication,:dateend) <= 3 AND DATE_DIFF(a.dateFinPublication,:dateend) >= 0 AND a.isVisible = :visible") ->setParameter('dateend', new \Datetime('now')) ->setParameter('visible', true); return $query->getSingleScalarResult(); } }
{ "content_hash": "14cc3d2166447c05ed4857ece97262da", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 211, "avg_line_length": 28.407894736842106, "alnum_prop": 0.6215840666975452, "repo_name": "HorusCMF/Shop", "id": "1834180a8763fc606c6cc95d9ce9fb043f89f228", "size": "2159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Horus/SiteBundle/Repository/CommercialRepository.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1049193" }, { "name": "CoffeeScript", "bytes": "11178" }, { "name": "JavaScript", "bytes": "1728581" }, { "name": "PHP", "bytes": "8579493" }, { "name": "Perl", "bytes": "9275" }, { "name": "Python", "bytes": "154728" }, { "name": "Ruby", "bytes": "19" }, { "name": "Shell", "bytes": "60" } ], "symlink_target": "" }
package com.lufs.preresearch.webflux.service; import com.lufs.preresearch.webflux.domain.User; import com.lufs.preresearch.webflux.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Service public class UserService { private UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public Flux<User> getUsers() { return Flux.fromIterable(userRepository.selectAll()); } public Mono<User> getUserById(String id) { return Mono.justOrEmpty(userRepository.getUserById(id)); } }
{ "content_hash": "d97186cac24ed66c180d906efd43fa65", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 64, "avg_line_length": 28.555555555555557, "alnum_prop": 0.7639429312581063, "repo_name": "pink-lucifer/preresearch", "id": "304243800a23f4d9133d49d0db21e481dc6e3357", "size": "771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "springboot-webflux-rx/src/main/java/com/lufs/preresearch/webflux/service/UserService.java", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "816" }, { "name": "CMake", "bytes": "1715" }, { "name": "CSS", "bytes": "111" }, { "name": "Go", "bytes": "18461" }, { "name": "HTML", "bytes": "275" }, { "name": "Java", "bytes": "668209" }, { "name": "JavaScript", "bytes": "31723" }, { "name": "Python", "bytes": "444" } ], "symlink_target": "" }
template <typename _return_type> class CScriptCallbackEx; class CActor; //class CUIActorSleepVideoPlayer; class CActorCondition: public CEntityCondition { private: typedef CEntityCondition inherited; enum { eCriticalPowerReached =(1<<0), eCriticalMaxPowerReached =(1<<1), eCriticalBleedingSpeed =(1<<2), eCriticalSatietyReached =(1<<3), eCriticalRadiationReached =(1<<4), eWeaponJammedReached =(1<<5), ePhyHealthMinReached =(1<<6), eCantWalkWeight =(1<<7), }; Flags16 m_condition_flags; private: CActor* m_object; void UpdateTutorialThresholds (); void UpdateSatiety (); public: CActorCondition (CActor *object); virtual ~CActorCondition (void); virtual void LoadCondition (LPCSTR section); virtual void reinit (); virtual CWound* ConditionHit (SHit* pHDS); virtual void UpdateCondition (); virtual void ChangeAlcohol (float value); virtual void ChangeSatiety (float value); // õðîìàíèå ïðè ïîòåðå ñèë è çäîðîâüÿ virtual bool IsLimping () const; virtual bool IsCantWalk () const; virtual bool IsCantWalkWeight (); virtual bool IsCantSprint () const; void ConditionJump (float weight); void ConditionWalk (float weight, bool accel, bool sprint); void ConditionStand (float weight); float xr_stdcall GetAlcohol () {return m_fAlcohol;} float xr_stdcall GetPsy () {return 1.0f-GetPsyHealth();} float GetSatiety () {return m_fSatiety;} public: IC CActor &object () const { VERIFY (m_object); return (*m_object); } virtual void save (NET_Packet &output_packet); virtual void load (IReader &input_packet); protected: float m_fAlcohol; float m_fV_Alcohol; //-- float m_fSatiety; float m_fV_Satiety; float m_fV_SatietyPower; float m_fV_SatietyHealth; //-- float m_fPowerLeakSpeed; float m_fJumpPower; float m_fStandPower; float m_fWalkPower; float m_fJumpWeightPower; float m_fWalkWeightPower; float m_fOverweightWalkK; float m_fOverweightJumpK; float m_fAccelK; float m_fSprintK; float m_MaxWalkWeight; mutable bool m_bLimping; mutable bool m_bCantWalk; mutable bool m_bCantSprint; //ïîðîã ñèëû è çäîðîâüÿ ìåíüøå êîòîðîãî àêòåð íà÷èíàåò õðîìàòü float m_fLimpingPowerBegin; float m_fLimpingPowerEnd; float m_fCantWalkPowerBegin; float m_fCantWalkPowerEnd; float m_fCantSprintPowerBegin; float m_fCantSprintPowerEnd; float m_fLimpingHealthBegin; float m_fLimpingHealthEnd; };
{ "content_hash": "3ab056ef82f315d9f7fa6d51ab484a5a", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 66, "avg_line_length": 25.37, "alnum_prop": 0.7000394166338195, "repo_name": "OLR-xray/XRay-NEW", "id": "617546ef5ab2c47987e2ed52fdb2acf12ef1c2dd", "size": "2653", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XRay/xr_3da/xrGame/ActorCondition.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "62738" }, { "name": "Batchfile", "bytes": "7939" }, { "name": "C", "bytes": "24706439" }, { "name": "C++", "bytes": "42161717" }, { "name": "Groff", "bytes": "287360" }, { "name": "HTML", "bytes": "67830" }, { "name": "Lua", "bytes": "96997" }, { "name": "Makefile", "bytes": "16534" }, { "name": "Objective-C", "bytes": "175957" }, { "name": "Pascal", "bytes": "1259032" }, { "name": "Perl", "bytes": "9355" }, { "name": "PostScript", "bytes": "115918" }, { "name": "Shell", "bytes": "962" }, { "name": "TeX", "bytes": "2421274" }, { "name": "xBase", "bytes": "99233" } ], "symlink_target": "" }
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import TestSCons test = TestSCons.TestSCons() test.write('SConstruct', "") test.option_not_yet_implemented('-r', '.') test.option_not_yet_implemented('--no-builtin-rules', '.') test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
{ "content_hash": "364e0ef07d857dbbe06e9f2396d1fad2", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 61, "avg_line_length": 19.526315789473685, "alnum_prop": 0.6657681940700808, "repo_name": "azverkan/scons", "id": "a3c3911d3adb462d6ba85d8d0ae5e02448de8580", "size": "1473", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "test/option-r.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "259" }, { "name": "JavaScript", "bytes": "17316" }, { "name": "Perl", "bytes": "45214" }, { "name": "Python", "bytes": "6727715" }, { "name": "Shell", "bytes": "2535" } ], "symlink_target": "" }
(function() { document.addEventListener("deviceready", function() { init(); }, false); if($development) init(); })();
{ "content_hash": "9ba5ff78315cd7847b9fc416c4b7b0d3", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 55, "avg_line_length": 16.875, "alnum_prop": 0.5703703703703704, "repo_name": "snk7891/mobster", "id": "e10376bf07efddef5963b1eba9cf7ddf99f97a0c", "size": "135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/cordova-boilerplate.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "323" }, { "name": "HTML", "bytes": "1737" }, { "name": "JavaScript", "bytes": "9037" }, { "name": "Shell", "bytes": "106" } ], "symlink_target": "" }
describe('certificates', function () { var fs = require('fs'), path = require('path'), CertificateList = require('postman-collection').CertificateList, https = require('https'), certificateId = 'test-certificate', server, testrun; describe('valid', function () { before(function (done) { var port = 9090, certDataPath = path.join(__dirname, '..', '..', 'integration-legacy', 'data'), clientKeyPath = path.join(certDataPath, 'client1-key.pem'), clientCertPath = path.join(certDataPath, 'client1-crt.pem'), serverKeyPath = path.join(certDataPath, 'server-key.pem'), serverCertPath = path.join(certDataPath, 'server-crt.pem'), serverCaPath = path.join(certDataPath, 'ca-crt.pem'), certificateList = new CertificateList({}, [{ id: certificateId, matches: ['https://localhost:' + port + '/*'], key: {src: clientKeyPath}, cert: {src: clientCertPath} }]); server = https.createServer({ key: fs.readFileSync(serverKeyPath), cert: fs.readFileSync(serverCertPath), ca: fs.readFileSync(serverCaPath), requestCert: true }); server.on('request', function (req, res) { if (req.client.authorized) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('authorized\n'); } else { res.writeHead(401, {'Content-Type': 'text/plain'}); res.end('unauthorized\n'); } }); server.listen(port, 'localhost'); this.run({ collection: { item: { request: 'https://localhost:' + port + '/' } }, requester: { strictSSL: false }, fileResolver: fs, certificates: certificateList }, function (err, results) { testrun = results; done(err); }); }); it('must have started and completed the test run', function () { expect(testrun).be.ok(); expect(testrun.done.calledOnce).be.ok(); expect(testrun.start.calledOnce).be.ok(); }); it('must receive response from https server', function () { var response = testrun.request.getCall(0).args[2]; expect(response.text()).to.eql('authorized\n'); }); it('must have certificate attached to request', function () { var request = testrun.request.getCall(0).args[3].toJSON(); expect(request.certificate.id).to.eql(certificateId); }); after(function () { server.close(); }); }); describe('invalid', function () { before(function (done) { var port = 9090, certDataPath = path.join(__dirname, '..', '..', 'integration-legacy', 'data'), clientKeyPath = path.join('/tmp/non-existent/', 'client1-key.pem'), clientCertPath = path.join('/tmp/non-existent/', 'client1-crt.pem'), serverKeyPath = path.join(certDataPath, 'server-key.pem'), serverCertPath = path.join(certDataPath, 'server-crt.pem'), serverCaPath = path.join(certDataPath, 'ca-crt.pem'), certificateList = new CertificateList({}, [{ id: certificateId, matches: ['https://localhost:' + port + '/*'], key: {src: clientKeyPath}, cert: {src: clientCertPath} }]); server = https.createServer({ key: fs.readFileSync(serverKeyPath), cert: fs.readFileSync(serverCertPath), ca: fs.readFileSync(serverCaPath) }); server.on('request', function (req, res) { if (req.client.authorized) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('authorized\n'); } else { res.writeHead(401, {'Content-Type': 'text/plain'}); res.end('unauthorized\n'); } }); server.listen(port, 'localhost'); this.run({ collection: { item: { request: 'https://localhost:' + port + '/' } }, requester: { strictSSL: false }, fileResolver: fs, certificates: certificateList }, function (err, results) { testrun = results; done(err); }); }); it('must have started and completed the test run', function () { expect(testrun).be.ok(); expect(testrun.done.calledOnce).be.ok(); expect(testrun.start.calledOnce).be.ok(); }); it('must not throw an error', function () { expect(testrun.request.calledOnce).be.ok(); var err = testrun.request.firstCall.args[0], request = testrun.request.firstCall.args[3]; expect(err).to.not.be.ok(); expect(request).to.not.have.property('certificate'); }); it('must trigger a console warning', function () { expect(testrun.console.calledOnce).to.be.ok(); var call = testrun.console.firstCall.args; expect(call[0]).to.have.property('ref'); expect(call[1]).to.eql('warn'); expect(call[2]).to.match(/^certificate load error:/); }); after(function () { server.close(); }); }); });
{ "content_hash": "1c23bdcaad32311819ceda3114a5f211", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 94, "avg_line_length": 35.10919540229885, "alnum_prop": 0.4727451301358651, "repo_name": "jhelbig/postman-linux-app", "id": "87dcdf7ac66f8f184f8537956f64855c202b1ccb", "size": "6109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/resources/app/node_modules/postman-runtime/test/integration/sanity/certificate.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1575004" }, { "name": "HTML", "bytes": "1811491" }, { "name": "JavaScript", "bytes": "29034800" }, { "name": "Shell", "bytes": "553" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <html><body class="spl" id="spl"> <div class="DocumentTitle"> <p class="DocumentTitle"><strong>MEDIPLAST- salicylic acid plaster </strong><br>Medline Industries, Inc<br></p> <p class="disclaimer">Disclaimer: Most OTC drugs are not reviewed and approved by FDA, however they may be marketed if they comply with applicable regulations and policies. FDA has not evaluated whether this product complies.</p> </div> <h1>Drug Facts</h1> <div class="Contents"> <div class="Section" data-sectionCode="48780-1"> <a name="section-1"></a><p></p> </div> <div class="Section" data-sectionCode="55106-9"> <a name="i4i_OTC_Active_Ingredient_id_d1ee12e2-d2c9-47a1-b3fe-8812b01ccaf8"></a><a name="section-1"></a><p></p> <h1>Active ingredient</h1> <p class="First">40% Salicylic Acid</p> </div> <div class="Section" data-sectionCode="55105-1"> <a name="i4i_OTC_Purpose_id_5d7dca17-a0d2-4a2e-b67c-b27f64588fcb"></a><a name="section-2"></a><p></p> <h1>Purpose</h1> <p class="First">Corn, Callus, and <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">Wart</span> Remover</p> </div> <div class="Section" data-sectionCode="34067-9"> <a name="i4i_indications_id_ee705042-7a43-4230-8480-ab8271a902cd"></a><a name="section-3"></a><p></p> <h1>Uses</h1> <p class="First">For the removal of</p> <ul> <li>corns</li> <li>calluses</li> <li>common <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">warts</span></li> </ul> </div> <div class="Section" data-sectionCode="34071-1"> <a name="i4i_warnings_id_6480d86d-ea31-4609-b276-979b41fc1196"></a><a name="section-4"></a><p></p> <h1>Warnings</h1> <p class="First"><span class="Bold">For external use only. </span>This product contains natural rubber, which may cause <span class="product-label-link" type="condition" conceptid="4084167" conceptname="Acute allergic reaction">allergic reactions</span>. </p> <div class="Section" data-sectionCode="50570-1"> <a name="i4i_OTC_Do_not_use_id_d7a1141f-af86-4401-8481-62ee071b98b6"></a><a name="section-4.1"></a><p></p> <h2>Do not use</h2> <ul> <li>if you are diabetic or have poor blood circulation</li> <li>on irritated skin or on any area that is infected or reddened</li> <li>on moles, birthmarks, or <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">warts</span> with hair growing from them, <span class="product-label-link" type="condition" conceptid="198075" conceptname="Condyloma acuminatum">genital warts</span>, <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">warts</span> on the face, <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">warts</span> on mucous membranes such as <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">warts</span> inside the mouth, nose, anus, genitals or lips. </li> </ul> </div> <div class="Section" data-sectionCode="50565-1"> <a name="i4i_OTC_Keep_Away_Children_id_b6e46033-6318-4db9-956e-8c3af26a5cb4"></a><a name="section-4.2"></a><p></p> <h2>Keep this and all drugs out of reach of children.</h2> <p class="First">In case of accidental ingestion, seek professional assistance or contact a Poison Control center immediately.</p> </div> <div class="Section" data-sectionCode="50566-9"> <a name="i4i_OTC_Stop_Use_id_729ecc7d-51f7-4faf-b59f-3c8155cda34a"></a><a name="section-4.3"></a><p></p> <h2>Stop using this product and see your doctor</h2> <p class="First">if <span class="product-label-link" type="condition" conceptid="4090431" conceptname="Discomfort">discomfort</span> persists. </p> </div> </div> <div class="Section" data-sectionCode="34068-7"> <a name="i4i_dosage_admin_id_ddf243c1-b3b4-4b2f-baff-3927b01302e7"></a><a name="section-5"></a><p></p> <h1>Directions</h1> <p class="First">Wash affected area. May soak corn, callus or <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">wart</span> in warm water for 5 minutes. Dry area thoroughly. Cut pad to fit corn, callus or <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">wart</span>. Apply medicated pad to area. Remove medicated pad after 48 hours. Repeat procedure every 48 hours for up to 14 days for corn/callus removal and up to 12 weeks for <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">warts</span>, until the problem has cleared. </p> </div> <div class="Section" data-sectionCode="51727-6"> <a name="i4i_inactive_ingredients_id_60876ace-e055-47c7-b7d7-38c445d4f550"></a><a name="section-6"></a><p></p> <h1>Inactive ingredients</h1> <p class="First">O-Cresol, Lanolin, Myroxylon pereirae (Balsam Peru), Phenol, Talc, Terpineol.</p> <p>Bandage: Flannel (99.7% cotton), Colophonium, Rubber Latex, 0.3% Polyurethane</p> </div> <div class="Section" data-sectionCode="51945-4"> <a name="i4i_Principal_display_panel_id_c5920e2c-e92a-430d-b483-1cbdb2c5bba3"></a><a name="section-7"></a><p></p> <h1>Package/Label Principal Display Panel</h1> <p class="First"><img alt="Mediplast Corn, Callus &amp; <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">Wart</span> Remover Packet Principal Display Panel" src="http://dailymed.nlm.nih.gov/dailymed/image.cfm?setid=35bd29f9-cf49-404b-826b-72d1269d4f19&amp;name=a925113e-347e-4051-b092-f947b8252d74-01.jpg"></p> <p>NDC: 53329-410-09</p> <p>CURAD</p> <p>WE HELP HEAL</p> <p><span class="Bold">MEDIPLAST</span></p> <p>Corn, Callus &amp; <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">Wart</span> Remover</p> <ul> <li>Active Ingredient: 40% Salicylic Acid</li> <li>2" x 3" Pad (Cut-to-Fit)</li> </ul> <p>Made in Germany</p> <p>Distributed by Medline Industries, Inc. Mundelein, IL 60060</p> <p>This Product Contains Dry Natural Rubber</p> </div> <div class="Section" data-sectionCode="51945-4"> <a name="i4i_Principal_display_panel_id_9e9f50e8-d693-4b82-8573-983737a250f5"></a><a name="section-8"></a><p></p> <h1>Package Label/Drug Facts</h1> <div class="Figure"><img alt="Mediplast Corn, Callus &amp; <span class="product-label-link" type="condition" conceptid="140641" conceptname="Verruca vulgaris">Wart</span> Remover Packet Drug Facts" src="http://dailymed.nlm.nih.gov/dailymed/image.cfm?setid=35bd29f9-cf49-404b-826b-72d1269d4f19&amp;name=a925113e-347e-4051-b092-f947b8252d74-02.jpg"></div> </div> <div class="Section" data-sectionCode="51945-4"> <a name="i4i_Principal_display_panel_id_e6596832-13d6-461f-a825-b1ccd4e47084"></a><a name="section-9"></a><p></p> <h1>Box Label / Principal Display Panel</h1> <div class="Figure"><img alt="Box Label / Principal Display Panel" src="http://dailymed.nlm.nih.gov/dailymed/image.cfm?setid=35bd29f9-cf49-404b-826b-72d1269d4f19&amp;name=a925113e-347e-4051-b092-f947b8252d74-03.jpg"></div> </div> <div class="Section" data-sectionCode="51945-4"> <a name="i4i_Principal_display_panel_id_dfba936f-7371-414f-8399-ffd78e10ec0d"></a><a name="section-10"></a><p></p> <h1>Box Label / Back and Top</h1> <div class="Figure"><img alt="Box Label / Top and Back" src="http://dailymed.nlm.nih.gov/dailymed/image.cfm?setid=35bd29f9-cf49-404b-826b-72d1269d4f19&amp;name=a925113e-347e-4051-b092-f947b8252d74-04.jpg"></div> </div> </div> <div class="DataElementsTables"> <table class="contentTablePetite" cellSpacing="0" cellPadding="3" width="100%"><tbody> <tr><td class="contentTableTitle"> <strong>MEDIPLAST  </strong><br><span class="contentTableReg">salicylic acid plaster</span> </td></tr> <tr><td><table width="100%" cellpadding="5" cellspacing="0" class="formTablePetite"> <tr><td colspan="4" class="formHeadingTitle">Product Information</td></tr> <tr class="formTableRowAlt"> <td class="formLabel">Product Type</td> <td class="formItem">HUMAN OTC DRUG LABEL</td> <td class="formLabel">Item Code (Source)</td> <td class="formItem">NDC:53329-410</td> </tr> <tr class="formTableRow"> <td width="30%" class="formLabel">Route of Administration</td> <td class="formItem">TOPICAL</td> <td width="30%" class="formLabel">DEA Schedule</td> <td class="formItem">     </td> </tr> </table></td></tr> <tr><td><table width="100%" cellpadding="3" cellspacing="0" class="formTablePetite"> <tr><td colspan="3" class="formHeadingTitle">Active Ingredient/Active Moiety</td></tr> <tr> <th class="formTitle" scope="col">Ingredient Name</th> <th class="formTitle" scope="col">Basis of Strength</th> <th class="formTitle" scope="col">Strength</th> </tr> <tr class="formTableRowAlt"> <td class="formItem"> <strong>SALICYLIC ACID</strong> (SALICYLIC ACID) </td> <td class="formItem">SALICYLIC ACID</td> <td class="formItem">40 g  in 100 g</td> </tr> </table></td></tr> <tr><td><table width="100%" cellpadding="3" cellspacing="0" class="formTablePetite"> <tr><td colspan="2" class="formHeadingTitle">Inactive Ingredients</td></tr> <tr> <th class="formTitle" scope="col">Ingredient Name</th> <th class="formTitle" scope="col">Strength</th> </tr> <tr class="formTableRowAlt"> <td class="formItem"><strong>LANOLIN</strong></td> <td class="formItem"> </td> </tr> <tr class="formTableRow"> <td class="formItem"><strong>NATURAL LATEX RUBBER</strong></td> <td class="formItem"> </td> </tr> <tr class="formTableRowAlt"> <td class="formItem"><strong>BALSAM PERU</strong></td> <td class="formItem"> </td> </tr> <tr class="formTableRow"> <td class="formItem"><strong>ROSIN</strong></td> <td class="formItem"> </td> </tr> <tr class="formTableRowAlt"> <td class="formItem"><strong>TALC</strong></td> <td class="formItem"> </td> </tr> <tr class="formTableRow"> <td class="formItem"><strong>TERPINEOL</strong></td> <td class="formItem"> </td> </tr> </table></td></tr> <tr><td></td></tr> <tr><td><table width="100%" cellpadding="3" cellspacing="0" class="formTablePetite"> <tr><td colspan="5" class="formHeadingTitle">Packaging</td></tr> <tr> <th scope="col" width="1" class="formTitle">#</th> <th scope="col" class="formTitle">Item Code</th> <th scope="col" class="formTitle">Package Description</th> <th scope="col" class="formTitle">Marketing Start Date</th> <th scope="col" class="formTitle">Marketing End Date</th> </tr> <tr class="formTableRowAlt"> <th scope="row" class="formItem">1</th> <td class="formItem">NDC:53329-410-59</td> <td class="formItem">25 in 1 BOX</td> <td class="formItem"></td> <td class="formItem"></td> </tr> <tr class="formTableRowAlt"> <th scope="row" class="formItem">1</th> <td class="formItem">NDC:53329-410-09</td> <td class="formItem">1 in 1 PACKET</td> <td class="formItem"></td> <td class="formItem"></td> </tr> <tr class="formTableRowAlt"> <th scope="row" class="formItem">1</th> <td class="formItem"></td> <td class="formItem">1.4 g in 1 APPLICATOR</td> <td class="formItem"></td> <td class="formItem"></td> </tr> </table></td></tr> <tr><td></td></tr> <tr><td class="normalizer"><table width="100%" cellpadding="3" cellspacing="0" class="formTableMorePetite"> <tr><td colspan="4" class="formHeadingReg"><span class="formHeadingTitle">Marketing Information</span></td></tr> <tr> <th scope="col" class="formTitle">Marketing Category</th> <th scope="col" class="formTitle">Application Number or Monograph Citation</th> <th scope="col" class="formTitle">Marketing Start Date</th> <th scope="col" class="formTitle">Marketing End Date</th> </tr> <tr class="formTableRowAlt"> <td class="formItem">OTC monograph final</td> <td class="formItem">part358F</td> <td class="formItem">08/01/2008</td> <td class="formItem"></td> </tr> </table></td></tr> </tbody></table> <table width="100%" cellpadding="3" cellspacing="0" class="formTableMorePetite"><tr><td colspan="4" class="formHeadingReg"> <span class="formHeadingTitle">Labeler - </span>Medline Industries, Inc (025460908) </td></tr></table> </div> <p><div class="EffectiveDate">Revised: 11/2012<div class="DocumentMetadata"> <div> <a href="javascript:toggleMixin();">Document Id: </a>a925113e-347e-4051-b092-f947b8252d74</div> <div>Set id: 35bd29f9-cf49-404b-826b-72d1269d4f19</div> <div>Version: 3</div> <div>Effective Time: 20121130</div> </div> </div> <div class="DistributorName">Medline Industries, Inc</div></p> </body></html>
{ "content_hash": "bbb50aa0157337b1ea8e13f121b818ea", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 730, "avg_line_length": 53.86026200873363, "alnum_prop": 0.715907248256851, "repo_name": "OHDSI/Penelope", "id": "963240c0f7b56070bec876e390de6e264cd962ef", "size": "12353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/js/spl/35bd29f9-cf49-404b-826b-72d1269d4f19.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "44224" }, { "name": "HTML", "bytes": "276095058" }, { "name": "JavaScript", "bytes": "282967" } ], "symlink_target": "" }
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="#"><img src="img/logo.png" style="display: inline-block; height: 100px; width: 100px;"></a> <a class="navbar-brand" href="#">Ricks Interdimensional Shop</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Shop <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="over.php">Over</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="#" role="button" data-toggle="modal" data-target="#login-modal">Login</a> </ul> </div> </div> </nav>;
{ "content_hash": "8e03f853ddd6e85a2b8359747c0ea9dc", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 194, "avg_line_length": 47.03703703703704, "alnum_prop": 0.5598425196850394, "repo_name": "mathijs196/RIS", "id": "23cd9d28ee5952d0261497f6a11cadbd9f74c664", "size": "1271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "page/layout_nav.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5767" }, { "name": "JavaScript", "bytes": "5216" }, { "name": "PHP", "bytes": "26567" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a09a5226ea84e6429544ce2261e2e0df", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "0fbf3a6ae0dc33eb72977d35a55629dd504b7152", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Albizia/Albizia tenuiflora/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>likeness.helpers.Joker)unnamed_49~summary documentation</title> <link rel="stylesheet" type="text/css" href="../../../../../../../../../../index.css" /> <link rel="stylesheet" type="text/css" href="../../../../../../../../../../highlight.css" /> <script type="text/javascript" src="../../../../../../../../../../index.js"></script> </head> <body class="spare" id="component_2127"> <div id="outer"> <div id="header"> <a class="ctype" href="../../../../../../../../../../index.html">spare</a> <span></span> <span class="breadcrumbs"> <span class="delimiter">:</span><a href="../../../../../../../../index.html" class="breadcrumb module">likeness</a><span class="delimiter">.</span><a href="../../../../../../index.html" class="breadcrumb property">helpers</a><span class="delimiter">.</span><a href="../../../../index.html" class="breadcrumb property">Joker</a><span class="delimiter">)</span><a href="../../index.html" class="breadcrumb returns"></a><span class="delimiter">~</span><a href="index.html" class="breadcrumb spare">summary</a> </span> </div> <div id="content"> <!-- basic document info --> <div id="details"> <div class="markdown"><p>New pre-configured likeness.</p> </div> <div class="clear"></div> </div> <div class="children"> </div> </div> </div> <div id="footer"> This document was generated with <a href="https://github.com/shenanigans/node-doczar">doczar</a> at <span class="time">3:55pm</span> on <span class="date">8/14/2015</span> </div> </body> </html>
{ "content_hash": "59a78c185513978ee44332a33ab1e8fa", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 522, "avg_line_length": 45.05, "alnum_prop": 0.5099889012208657, "repo_name": "shenanigans/node-sublayer", "id": "6dd707c623cf31dd2532e979ad0dbea6739ca1ba", "size": "1802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/docs/generated/module/likeness/property/helpers/property/joker/returns/unnamed_49/spare/summary/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19097" }, { "name": "HTML", "bytes": "7637111" }, { "name": "JavaScript", "bytes": "2783424" } ], "symlink_target": "" }
<?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>io.trino</groupId> <artifactId>trino-root</artifactId> <version>368-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <artifactId>trino-google-sheets</artifactId> <description>Trino - Google Sheets Connector</description> <packaging>trino-plugin</packaging> <properties> <air.main.basedir>${project.parent.basedir}</air.main.basedir> </properties> <dependencies> <dependency> <groupId>io.trino</groupId> <artifactId>trino-plugin-toolkit</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>bootstrap</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>configuration</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>json</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>log</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>units</artifactId> </dependency> <!-- gsheets deps --> <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>1.23.0</version> <exclusions> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> <exclusion> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-sheets</artifactId> <version>v4-rev516-1.23.0</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client</artifactId> <version>1.35.0</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-jackson2</artifactId> <version>1.23.0</version> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> </dependency> <dependency> <groupId>com.google.oauth-client</groupId> <artifactId>google-oauth-client</artifactId> <version>1.31.0</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> <!-- Trino SPI --> <dependency> <groupId>io.trino</groupId> <artifactId>trino-spi</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>slice</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.openjdk.jol</groupId> <artifactId>jol-core</artifactId> <scope>provided</scope> </dependency> <!-- for testing --> <dependency> <groupId>io.trino</groupId> <artifactId>trino-main</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.trino</groupId> <artifactId>trino-testing</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>http-server</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>node</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>testing</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "14be68793583e35e5fcde845e24c78ff", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 204, "avg_line_length": 30.6, "alnum_prop": 0.5446034269563681, "repo_name": "ebyhr/presto", "id": "04c702fe8db7cf82de87b41c46b4248d4d222912", "size": "5661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugin/trino-google-sheets/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "26917" }, { "name": "CSS", "bytes": "12957" }, { "name": "HTML", "bytes": "28832" }, { "name": "Java", "bytes": "31247929" }, { "name": "JavaScript", "bytes": "211244" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "PLpgSQL", "bytes": "11504" }, { "name": "Python", "bytes": "7811" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29857" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
package ch.uzh.ifi.attempto.acerules.help.page.error; import ch.uzh.ifi.attempto.acerules.help.HelpWindow; import ch.uzh.ifi.attempto.acerules.help.page.Page; public class PrioritiesNotSupported extends Page { public PrioritiesNotSupported(HelpWindow helpWindow) { super(helpWindow, "Priorities are not supported", "Errors"); addText("Priority definitions (i.e. 'overrides' statements) are only allowed in courteous mode."); addHelpLink("Modes"); addGap(); addHeading("Suggestions"); addParagraph("Switch to another mode that allows priorities."); addParagraph("Or remove your priority definition from your program."); } }
{ "content_hash": "6e2b30b940081b74eed89564727995be", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 100, "avg_line_length": 33.94736842105263, "alnum_prop": 0.7674418604651163, "repo_name": "TeamSPoon/logicmoo_workspace", "id": "b0c8433d83ef50878669355225957827ed8ae1c9", "size": "1385", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packs_sys/logicmoo_nlu/ext/AceRules/webapp/src/ch/uzh/ifi/attempto/acerules/help/page/error/PrioritiesNotSupported.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "342" }, { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "CSS", "bytes": "126627" }, { "name": "HTML", "bytes": "839172" }, { "name": "Java", "bytes": "11116" }, { "name": "JavaScript", "bytes": "238700" }, { "name": "PHP", "bytes": "42253" }, { "name": "Perl 6", "bytes": "23" }, { "name": "Prolog", "bytes": "440882" }, { "name": "PureBasic", "bytes": "1334" }, { "name": "Rich Text Format", "bytes": "3436542" }, { "name": "Roff", "bytes": "42" }, { "name": "Shell", "bytes": "61603" }, { "name": "TeX", "bytes": "99504" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>io-system: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.2 / io-system - 2.4.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> io-system <small> 2.4.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-24 22:37:17 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-24 22:37:17 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;dev@clarus.me&quot; homepage: &quot;https://github.com/clarus/io-system&quot; dev-repo: &quot;git+https://github.com/clarus/io-system.git&quot; bug-reports: &quot;https://github.com/clarus/io-system/issues&quot; authors: [&quot;Guillaume Claret&quot;] license: &quot;MIT&quot; build: [ [&quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.4pl4&quot;} &quot;coq-function-ninjas&quot; &quot;coq-list-string&quot; {&gt;= &quot;2.0.0&quot;} &quot;coq-io&quot; {&gt;= &quot;3.2.0&quot; &amp; &lt; &quot;4&quot;} &quot;coq-io-system-ocaml&quot; {&gt;= &quot;2.2.0&quot;} ] tags: [ &quot;date:2015-07-04&quot; &quot;keyword:effects&quot; &quot;keyword:extraction&quot; &quot;logpath:Io.System&quot; ] synopsis: &quot;System effects for Coq&quot; url { src: &quot;https://github.com/coq-io/system/archive/2.4.0.tar.gz&quot; checksum: &quot;md5=750547991abee194c99bd32ea93e46b2&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-io-system.2.4.0 coq.8.13.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.2). The following dependencies couldn&#39;t be met: - coq-io-system -&gt; coq-io (&gt;= 3.2.0 &amp; &lt; 4) -&gt; coq &lt; 8.6~ -&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-io 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-io-system.2.4.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": "ed2523b8666a667e12e7964999a01d69", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 159, "avg_line_length": 39.64, "alnum_prop": 0.5333717745423093, "repo_name": "coq-bench/coq-bench.github.io", "id": "de81791371541dbdddd4fab4ffc0e74f53638196", "size": "6962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.13.2/io-system/2.4.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#ifndef SQUID_BASE_INSTANCE_ID_H #define SQUID_BASE_INSTANCE_ID_H #include <iosfwd> /** Identifier for class instances * - unique IDs for a large number of concurrent instances, but may wrap; * - useful for debugging and insecure request/response matching; * - sequential IDs within a class except when wrapping; * - always positive IDs. * \todo: add storage type parameter to support configurable Value types? * \todo: add creation/destruction debugging? */ template <class Class> class InstanceId { public: typedef unsigned int Value; ///< id storage type; \todo: parameterize? InstanceId(): value(++Last ? Last : ++Last) {} operator Value() const { return value; } bool operator ==(const InstanceId &o) const { return value == o.value; } bool operator !=(const InstanceId &o) const { return !(*this == o); } void change() {value = ++Last ? Last : ++Last;} /// prints Prefix followed by ID value; \todo: use HEX for value printing? std::ostream &print(std::ostream &os) const; public: static const char *Prefix; ///< Class shorthand string for debugging Value value; ///< instance identifier private: InstanceId(const InstanceId& right); ///< not implemented; IDs are unique InstanceId& operator=(const InstanceId &right); ///< not implemented private: static Value Last; ///< the last used ID value }; /// convenience macro to instantiate Class-specific stuff in .cc files #define InstanceIdDefinitions(Class, prefix) \ template<> const char *InstanceId<Class>::Prefix = prefix; \ template<> InstanceId<Class>::Value InstanceId<Class>::Last = 0; \ template<> std::ostream & \ InstanceId<Class>::print(std::ostream &os) const { \ return os << Prefix << value; \ } /// print the id template <class Class> inline std::ostream &operator <<(std::ostream &os, const InstanceId<Class> &id) { return id.print(os); } #endif /* SQUID_BASE_INSTANCE_ID_H */
{ "content_hash": "121ea5fbd4cb28554690cff2d91116d0", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 78, "avg_line_length": 33.23728813559322, "alnum_prop": 0.6807751147373788, "repo_name": "spaceify/spaceify", "id": "d948b5cd08cfb88df4b6557d51a16ba316c8b1b7", "size": "1961", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "squid/squid3-3.3.8.spaceify/src/base/InstanceId.h", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "5027" }, { "name": "C", "bytes": "6727964" }, { "name": "C++", "bytes": "7435855" }, { "name": "CSS", "bytes": "9138" }, { "name": "CoffeeScript", "bytes": "10353" }, { "name": "Groff", "bytes": "253204" }, { "name": "HTML", "bytes": "67045" }, { "name": "JavaScript", "bytes": "559321" }, { "name": "M4", "bytes": "241674" }, { "name": "Makefile", "bytes": "5753890" }, { "name": "Objective-C", "bytes": "1898" }, { "name": "Perl", "bytes": "152532" }, { "name": "Python", "bytes": "60106" }, { "name": "Shell", "bytes": "3088278" } ], "symlink_target": "" }
 #pragma once #include <aws/machinelearning/MachineLearning_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace MachineLearning { namespace Model { /** * <p> Represents the output of a <code>DeleteBatchPrediction</code> operation.</p> * <p>You can use the <code>GetBatchPrediction</code> operation and check the value * of the <code>Status</code> parameter to see whether a * <code>BatchPrediction</code> is marked as <code>DELETED</code>.</p> */ class AWS_MACHINELEARNING_API DeleteBatchPredictionResult { public: DeleteBatchPredictionResult(); DeleteBatchPredictionResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); DeleteBatchPredictionResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>A user-supplied ID that uniquely identifies the <code>BatchPrediction</code>. * This value should be identical to the value of the * <code>BatchPredictionID</code> in the request.</p> */ inline const Aws::String& GetBatchPredictionId() const{ return m_batchPredictionId; } /** * <p>A user-supplied ID that uniquely identifies the <code>BatchPrediction</code>. * This value should be identical to the value of the * <code>BatchPredictionID</code> in the request.</p> */ inline void SetBatchPredictionId(const Aws::String& value) { m_batchPredictionId = value; } /** * <p>A user-supplied ID that uniquely identifies the <code>BatchPrediction</code>. * This value should be identical to the value of the * <code>BatchPredictionID</code> in the request.</p> */ inline void SetBatchPredictionId(Aws::String&& value) { m_batchPredictionId = value; } /** * <p>A user-supplied ID that uniquely identifies the <code>BatchPrediction</code>. * This value should be identical to the value of the * <code>BatchPredictionID</code> in the request.</p> */ inline void SetBatchPredictionId(const char* value) { m_batchPredictionId.assign(value); } /** * <p>A user-supplied ID that uniquely identifies the <code>BatchPrediction</code>. * This value should be identical to the value of the * <code>BatchPredictionID</code> in the request.</p> */ inline DeleteBatchPredictionResult& WithBatchPredictionId(const Aws::String& value) { SetBatchPredictionId(value); return *this;} /** * <p>A user-supplied ID that uniquely identifies the <code>BatchPrediction</code>. * This value should be identical to the value of the * <code>BatchPredictionID</code> in the request.</p> */ inline DeleteBatchPredictionResult& WithBatchPredictionId(Aws::String&& value) { SetBatchPredictionId(value); return *this;} /** * <p>A user-supplied ID that uniquely identifies the <code>BatchPrediction</code>. * This value should be identical to the value of the * <code>BatchPredictionID</code> in the request.</p> */ inline DeleteBatchPredictionResult& WithBatchPredictionId(const char* value) { SetBatchPredictionId(value); return *this;} private: Aws::String m_batchPredictionId; }; } // namespace Model } // namespace MachineLearning } // namespace Aws
{ "content_hash": "39fd37a5961876079b7fec1235db0d56", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 133, "avg_line_length": 37.91111111111111, "alnum_prop": 0.708968347010551, "repo_name": "ambasta/aws-sdk-cpp", "id": "a8960a24d145700222c6b4873d1a52ca33f3365a", "size": "3985", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-machinelearning/include/aws/machinelearning/model/DeleteBatchPredictionResult.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2305" }, { "name": "C++", "bytes": "74273816" }, { "name": "CMake", "bytes": "412257" }, { "name": "Java", "bytes": "229873" }, { "name": "Python", "bytes": "62933" } ], "symlink_target": "" }
"""Tests for non_semantic_speech_benchmark.eval_embedding.sklearn.sklearn_to_savedmodel.""" from absl.testing import absltest import numpy as np from sklearn import linear_model import tensorflow as tf from non_semantic_speech_benchmark.export_model import trill_and_sklearn_to_one_savedmodel class SklearnToSavedmodelTest(absltest.TestCase): def test_sklearn_logistic_regression_to_keras(self): np.random.seed(9521) for i in range(10): m = linear_model.LogisticRegression() n_samples, n_features = 10, 2048 m.fit(np.random.rand(n_samples, n_features), [1] * 5 + [0] * 5) k = trill_and_sklearn_to_one_savedmodel.sklearn_logistic_regression_to_keras( m) for j in range(20): rng = np.random.RandomState(i * j) data = rng.lognormal(size=n_features).reshape([1, -1]) sklearn_prob = m.predict_proba(data) keras_prob = k(data) np.testing.assert_almost_equal(sklearn_prob, keras_prob.numpy(), 6) if __name__ == '__main__': tf.compat.v1.enable_v2_behavior() assert tf.executing_eagerly() absltest.main()
{ "content_hash": "d9b51e27c6d25a50dc6e496413d93d83", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 91, "avg_line_length": 31.485714285714284, "alnum_prop": 0.6833030852994555, "repo_name": "google-research/google-research", "id": "6565050198d483a64711a5146345cf17b63ad378", "size": "1710", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "non_semantic_speech_benchmark/export_model/trill_and_sklearn_to_one_savedmodel_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "9817" }, { "name": "C++", "bytes": "4166670" }, { "name": "CMake", "bytes": "6412" }, { "name": "CSS", "bytes": "27092" }, { "name": "Cuda", "bytes": "1431" }, { "name": "Dockerfile", "bytes": "7145" }, { "name": "Gnuplot", "bytes": "11125" }, { "name": "HTML", "bytes": "77599" }, { "name": "ImageJ Macro", "bytes": "50488" }, { "name": "Java", "bytes": "487585" }, { "name": "JavaScript", "bytes": "896512" }, { "name": "Julia", "bytes": "67986" }, { "name": "Jupyter Notebook", "bytes": "71290299" }, { "name": "Lua", "bytes": "29905" }, { "name": "MATLAB", "bytes": "103813" }, { "name": "Makefile", "bytes": "5636" }, { "name": "NASL", "bytes": "63883" }, { "name": "Perl", "bytes": "8590" }, { "name": "Python", "bytes": "53790200" }, { "name": "R", "bytes": "101058" }, { "name": "Roff", "bytes": "1208" }, { "name": "Rust", "bytes": "2389" }, { "name": "Shell", "bytes": "730444" }, { "name": "Smarty", "bytes": "5966" }, { "name": "Starlark", "bytes": "245038" } ], "symlink_target": "" }
import os from PyQt5.QtGui import QTextCursor, QColor from ui_generated.console_widget_ui import Ui_ConsoleWidget from threading import Thread from time import sleep class LoggingThread(Thread): def __init__(self, pipe, write): super().__init__() self.daemon = True self.pipe = pipe self.write = write def run(self): while True: self.write(self.drain_pipe()) sleep(0.1) def drain_pipe(self): return os.read(self.pipe, 1024).decode() class ConsoleWidget(Ui_ConsoleWidget): def __init__(self, out_pipe, normal_color, warning_color, error_color): self.normal_color = normal_color self.warning_color = warning_color self.error_color = error_color self.out_pipe = out_pipe def initialize(self): self.stdout_logger = LoggingThread(self.out_pipe, self.write) self.stdout_logger.start() self.clear_btn.clicked.connect(self.flush) def write(self, message): self.text_edit.setTextColor(self.normal_color) self.text_edit.insertPlainText(message) self.text_edit.moveCursor(QTextCursor.End) def warning(self, message): self.text_edit.setTextColor(self.warning_color) self.text_edit.insertPlainText(message) self.text_edit.moveCursor(QTextCursor.End) def error(self, message): self.text_edit.setTextColor(self.error_color) self.text_edit.insertPlainText(message) self.text_edit.moveCursor(QTextCursor.End) def flush(self): self.text_edit.clear()
{ "content_hash": "1e316b244c113fde9c96f1b5fd81e7da", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 75, "avg_line_length": 28.410714285714285, "alnum_prop": 0.6561910747957259, "repo_name": "stolyaroleh/renderer", "id": "76f28ea709adfdab42dfc8a212b796426990c7a6", "size": "1591", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/python/ui/console_widget.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "889" }, { "name": "C++", "bytes": "10151" }, { "name": "CMake", "bytes": "1818" }, { "name": "Python", "bytes": "327388" } ], "symlink_target": "" }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit.TestFramework { using System; using System.Collections.Concurrent; using System.Linq; using System.Reflection; public class InterfaceReflectionCache { readonly ConcurrentDictionary<Type, ConcurrentDictionary<Type, Type>> _cache; public InterfaceReflectionCache() { _cache = new ConcurrentDictionary<Type, ConcurrentDictionary<Type, Type>>(); } public Type GetGenericInterface(Type type, Type interfaceType) { if (!interfaceType.GetTypeInfo().IsGenericTypeDefinition) { throw new ArgumentException( "The interface must be a generic interface definition: " + interfaceType.Name, nameof(interfaceType)); } // our contract states that we will not return generic interface definitions without generic type arguments if (type == interfaceType) return null; if (type.GetTypeInfo().IsGenericType) { if (type.GetGenericTypeDefinition() == interfaceType) return type; } Type[] interfaces = type.GetTypeInfo().ImplementedInterfaces.ToArray(); return interfaces.Where(t => t.GetTypeInfo().IsGenericType) .FirstOrDefault(t => t.GetGenericTypeDefinition() == interfaceType); } public Type Get(Type type, Type interfaceType) { ConcurrentDictionary<Type, Type> typeCache = _cache.GetOrAdd(type, x => new ConcurrentDictionary<Type, Type>()); return typeCache.GetOrAdd(interfaceType, x => GetInterfaceInternal(type, interfaceType)); } Type GetInterfaceInternal(Type type, Type interfaceType) { if (interfaceType.GetTypeInfo().IsGenericTypeDefinition) return GetGenericInterface(type, interfaceType); Type[] interfaces = type.GetTypeInfo().ImplementedInterfaces.ToArray(); return interfaces.FirstOrDefault(t => t == interfaceType); } } }
{ "content_hash": "e1b4263b23a29b9dd02051b690a54601", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 124, "avg_line_length": 40.34285714285714, "alnum_prop": 0.6310198300283286, "repo_name": "jacobpovar/MassTransit", "id": "1b293ba684fc335be1b527783ac336832353f449", "size": "2826", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/MassTransit.TestFramework/InterfaceReflectionCache.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "506" }, { "name": "C#", "bytes": "6856642" }, { "name": "F#", "bytes": "3272" }, { "name": "HTML", "bytes": "15611" }, { "name": "PowerShell", "bytes": "5322" } ], "symlink_target": "" }
package org.moe.parser import scala.util.parsing.combinator._ import org.moe.ast._ trait MoeProductions extends MoeLiterals with JavaTokenParsers with PackratParsers { /** ********************************************************************* * This part of the parser deals mostly with * Ternary, Unary and Binary operations and * implements the precedance ordering. ********************************************************************* */ lazy val expression: PackratParser[AST] = matchOp | assignOp // TODO: left or xor // TODO: left and // TODO: right not // TODO: nonassoc list operators (rightward) // TODO: left , => // TODO: right = += -= *= etc. // right = (assignment) lazy val assignOp: PackratParser[AST] = lvalue ~ "=" ~ assignOp ^^ { case left ~ "=" ~ right => BinaryOpNode(left, "=", right) } | ternaryOp // right ?: lazy val ternaryOp: PackratParser[AST] = logicalOrOp ~ "?" ~ ternaryOp ~ ":" ~ ternaryOp ^^ { case cond ~ "?" ~ trueExpr ~ ":" ~ falseExpr => TernaryOpNode(cond, trueExpr, falseExpr) } | logicalOrOp // left || TODO: // lazy val logicalOrOp: PackratParser[AST] = logicalOrOp ~ """\|\||//""".r ~ logicalAndOp ^^ { case left ~ op ~ right => ShortCircuitBinaryOpNode(left, op, right) } | logicalAndOp // left && lazy val logicalAndOp: PackratParser[AST] = logicalAndOp ~ "&&" ~ bitOrOp ^^ { case left ~ op ~ right => ShortCircuitBinaryOpNode(left, op, right) } | bitOrOp // left | ^ lazy val bitOrOp: PackratParser[AST] = bitOrOp ~ "[|^]".r ~ bitAndOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | bitAndOp // left & lazy val bitAndOp: PackratParser[AST] = bitAndOp ~ "&" ~ eqOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | eqOp // nonassoc == != eq ne cmp ~~ lazy val eqOp: PackratParser[AST] = eqOp ~ "[!=]=|<=>|eq|ne|cmp".r ~ relOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | relOp // nonassoc < > <= >= lt gt le ge lazy val relOp: PackratParser[AST] = relOp ~ "[<>]=?|lt|gt|le|ge".r ~ bitShiftOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | bitShiftOp // TODO: nonassoc named unary operators // left << >> lazy val bitShiftOp: PackratParser[AST] = bitShiftOp ~ "<<|>>".r ~ addOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | addOp // left + - ~ lazy val addOp: PackratParser[AST] = addOp ~ "[-+~]".r ~ mulOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | mulOp // left * / % x lazy val mulOp: PackratParser[AST] = mulOp ~ "[*/%x]".r ~ expOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | expOp // TODO: right ! ~ \ and unary + and - // This one is right-recursive (associative) instead of left // right ** lazy val expOp: PackratParser[AST] = coerceOp ~ "**" ~ expOp ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } | coerceOp // Symbolic unary -- left + (num), ? (bool), ~ (str) // used for explicit coercion // (see: http://perlcabal.org/syn/S03.html#Symbolic_unary_precedence) lazy val coerceOp: PackratParser[AST] = "[+?~]".r ~ fileTestOps ^^ { case op ~ expr => PrefixUnaryOpNode(expr, op) } | fileTestOps // TODO: nonassoc ++ -- lazy val fileTestOps: PackratParser[AST] = "-[erwx]".r ~ applyOp ^^ { case op ~ expr => PrefixUnaryOpNode(expr, op) } | applyOp /** ********************************************************************* * Here we have method and subroutine calling * both of which are still expressions. ********************************************************************* */ // left . lazy val applyOp: PackratParser[AST] = (applyOp <~ ".") ~ identifier ~ ("(" ~> repsep(expression, ",") <~ ")").? ^^ { case invocant ~ method ~ Some(args) => MethodCallNode(invocant, method, args) case invocant ~ method ~ None => MethodCallNode(invocant, method, List()) } | quoteExpression | subroutineCall lazy val subroutineCall: PackratParser[AST] = namespacedIdentifier ~ ("(" ~> repsep(expression, ",") <~ ")") ^^ { case sub ~ args => SubroutineCallNode(sub, args) } | anonCodeCall def anonCodeInvocant: PackratParser[AST] = ( variable | attribute ) lazy val anonCodeCall: PackratParser[AST] = anonCodeInvocant ~ "." ~ ("(" ~> repsep(expression, ",") <~ ")") ^^ { case anonCode ~ _ ~ args => MethodCallNode(anonCode, "call", args) } | listOpLeftward // left terms and list operators (leftward) lazy val listOpLeftward: PackratParser[AST] = namespacedIdentifier ~ rep1sep(expression, ",") ^^ { case sub ~ args => SubroutineCallNode(sub, args) } | simpleExpression /** ********************************************************************* * Now build our set of simpleExpressions * which are not Unary, Binary or Ternay * This includes much of what comes after * it in this file. ********************************************************************* */ lazy val simpleExpression: PackratParser[AST] = ( quoteExpression | arrayIndex | hashIndex | hash | array | pair | range | code | literalValue | classAccess | variable | attribute | specialVariable | expressionParens | signedExpressionParens ) def expressionParens: Parser[AST] = "(" ~> expression <~ ")" def signedExpressionParens: PackratParser[AST] = "[-+!]".r ~ expressionParens ^^ { case "+" ~ expr => expr case "-" ~ expr => PrefixUnaryOpNode(expr, "-") case "!" ~ expr => PrefixUnaryOpNode(expr, "!") } /** ********************************************************************* * Now we get into a lot of creation of * complex literal values such as Hash, * Pair, Array, Code, etc ********************************************************************* */ // List/Array Literals def list: Parser[List[AST]] = (literal(",").? ~> repsep(expression, ",") <~ literal(",").?) def array: Parser[ArrayLiteralNode] = "[" ~> list <~ "]" ^^ ArrayLiteralNode // Pair Literals def pair: Parser[PairLiteralNode] = (hashKey <~ "=>") ~ expression ^^ { case k ~ v => PairLiteralNode(k, v) } // Hash Literals def barehashKey: Parser[StringLiteralNode] = """[0-9\w_]+""".r ^^ StringLiteralNode def hashKey: Parser[AST] = variable | arrayIndex | hashIndex | literalValue | barehashKey def hashContent: Parser[List[PairLiteralNode]] = repsep(pair, ",") def hash: Parser[HashLiteralNode] = "{" ~> hashContent <~ "}" ^^ HashLiteralNode // Range Literals def range: Parser[RangeLiteralNode] = simpleExpression ~ ".." ~ simpleExpression ^^ { case s ~ _ ~ e => RangeLiteralNode(s, e) } /** ********************************************************************* * This section begins to deal with variable * declaration and access. ********************************************************************* */ def identifier = """[a-zA-Z_][a-zA-Z0-9_]*""".r def namespaceSeparator = "::" def namespacedIdentifier = rep1sep(identifier, namespaceSeparator) ^^ { _.mkString(namespaceSeparator) } // access def variableName = """[$@%&][a-zA-Z_][a-zA-Z0-9_]*""".r ^^ { v => VariableNameNode(v) } def variable = variableName ^^ { case VariableNameNode(v) => VariableAccessNode(v) } def specialVariableName = ("""[$@%&][?*][A-Z_]+""".r | "$!") ^^ { v => VariableNameNode(v) } def specialVariable = specialVariableName ^^ { case VariableNameNode(v) => VariableAccessNode(v) } def attributeName = """[$@%&]![a-zA-Z_][a-zA-Z0-9_]*""".r ^^ { a => AttributeNameNode(a) } def attribute = attributeName ^^ { case AttributeNameNode(a) => AttributeAccessNode(a) } def parameterName = """([$@%&])([a-zA-Z_][a-zA-Z0-9_]*)""".r def classAccess = namespacedIdentifier ^^ ClassAccessNode // declaration def arrayVariableName = """@[a-zA-Z_][a-zA-Z0-9_]*""".r def hashVariableName = """%[a-zA-Z_][a-zA-Z0-9_]*""".r def array_index_rule = arrayVariableName ~ ( "[" ~> expression <~ "]" ).+ ^^ { case a ~ i => ArrayElementNameNode(a, i) } def hash_index_rule = hashVariableName ~ ( "{" ~> expression <~ "}" ).+ ^^ { case h ~ k => HashElementNameNode(h, k) } def arrayIndex = array_index_rule ^^ { case ArrayElementNameNode(i, exprs) => ArrayElementAccessNode(i, exprs) } def hashIndex = hash_index_rule ^^ { case HashElementNameNode(h, exprs) => HashElementAccessNode(h, exprs) } def lvalue: Parser[AST] = ( array_index_rule | hash_index_rule | attributeName | variableName | specialVariableName ) // assignment def variableDeclaration = "my" ~> variableName ~ ("=" ~> expression).? ^^ { case VariableNameNode(v) ~ expr => VariableDeclarationNode(v, expr.getOrElse(UndefLiteralNode())) } private def zipEm (x: List[String], y: List[AST], f: ((String, AST)) => AST): List[AST] = { if (y.isEmpty) x.map(f(_, UndefLiteralNode())) else if (x.isEmpty) List() else f(x.head, y.headOption.getOrElse(UndefLiteralNode())) :: zipEm(x.tail, y.tail, f) } def multiVariableDeclaration = "my" ~> ("(" ~> repsep(variableName, ",") <~ ")") ~ ("=" ~> "(" ~> repsep(expression, ",") <~ ")").? ^^ { case vars ~ None => StatementsNode( vars.map( { case VariableNameNode(v) => VariableDeclarationNode(v, UndefLiteralNode()) } ) ) case vars ~ Some(exprs) => StatementsNode( zipEm(vars.map( { case VariableNameNode(v) => v } ), exprs, (p) => VariableDeclarationNode(p._1, p._2)) ) } def multiVariableAssignment = ("(" ~> repsep(variableName, ",") <~ ")") ~ "=" ~ ("(" ~> repsep(expression, ",") <~ ")") ^^ { case vars ~ _ ~ exprs => MultiVariableAssignmentNode( vars.map( { case VariableNameNode(vname) => vname } ), exprs ) } def multiAttributeAssignment = ("(" ~> repsep(attributeName, ",") <~ ")") ~ "=" ~ ("(" ~> repsep(expression, ",") <~ ")") ^^ { case vars ~ _ ~ exprs => MultiAttributeAssignmentNode(vars.map({case AttributeNameNode(aname) => aname}), exprs) } /** * regex match/substitution etc */ lazy val regexModifiers: Parser[AST] = """[igsmx]*""".r ^^ { flags => StringLiteralNode(flags) } def matchExpression: Parser[AST] = (("m" ~> quotedString) | quoted('/')) ~ opt(regexModifiers) ^^ { case pattern ~ None => MatchExpressionNode(RegexLiteralNode(pattern), StringLiteralNode("")) case pattern ~ Some(flags) => MatchExpressionNode(RegexLiteralNode(pattern), flags) } def substExpression_1: Parser[AST] = ("s" ~> quotedPair('/')) ~ opt(regexModifiers) ^^ { case (pattern, replacement) ~ None => SubstExpressionNode(RegexLiteralNode(pattern), StringLiteralNode(replacement), StringLiteralNode("")) case (pattern, replacement) ~ Some(flags) => SubstExpressionNode(RegexLiteralNode(pattern), StringLiteralNode(replacement), flags) } def substExpression_2: Parser[AST] = ("s" ~> bracketedString) ~ bracketedString ~ opt(regexModifiers) ^^ { case pattern ~ replacement ~ None => SubstExpressionNode(RegexLiteralNode(pattern), StringLiteralNode(replacement), StringLiteralNode("")) case pattern ~ replacement ~ Some(flags) => SubstExpressionNode(RegexLiteralNode(pattern), StringLiteralNode(replacement), flags) } private def splitString(str: String) = str.split(" ").map(s => StringLiteralNode(s)).toList def quoteOp = "q[qwx]?".r ~ quotedString ^^ { case "qq" ~ expr => MoeStringParser.interpolateStr(expr) case "qw" ~ expr => ArrayLiteralNode(splitString(expr)) // this is naive; doesn't handle embedded spaces in args case "qx" ~ expr => ExecuteCommandNode(MoeStringParser.interpolateStr(expr)) case "q" ~ expr => StringLiteralNode(expr) } def quoteRegexOp = "qr" ~ quotedString ~ opt(regexModifiers) ^^ { case "qr" ~ expr ~ Some(flags) => MatchExpressionNode(RegexLiteralNode(expr), flags) case "qr" ~ expr ~ None => MatchExpressionNode(RegexLiteralNode(expr), StringLiteralNode("")) } // TODO: tr (transliteration) operator lazy val transModifiers: Parser[AST] = """[cdsr]*""".r ^^ StringLiteralNode def transExpression_1 = ("tr" ~> quotedPair('/')) ~ opt(transModifiers) ^^ { case (search, replacement) ~ None => TransExpressionNode(StringLiteralNode(search), StringLiteralNode(replacement), StringLiteralNode("")) case (search, replacement) ~ Some(flags) => TransExpressionNode(StringLiteralNode(search), StringLiteralNode(replacement), flags) } def transExpression_2 = ("tr" ~> bracketedString) ~ bracketedString ~ opt(transModifiers) ^^ { case search ~ replacement ~ None => TransExpressionNode(StringLiteralNode(search), StringLiteralNode(replacement), StringLiteralNode("")) case search ~ replacement ~ Some(flags) => TransExpressionNode(StringLiteralNode(search), StringLiteralNode(replacement), flags) } def quoteExpression = ( substExpression_1 | substExpression_2 | matchExpression | transExpression_1 | transExpression_2 | quoteOp | quoteRegexOp ) def matchOp = simpleExpression ~ "=~" ~ expression ^^ { case left ~ op ~ right => BinaryOpNode(left, op, right) } /** ********************************************************************* * Now we are getting into statements, * however the line is a little blurred * here by the "code" production because * it is referenced above in "simpleExpressions" ********************************************************************* */ def statementDelim: Parser[List[String]] = rep1(";") def statements: Parser[StatementsNode] = rep(( blockStatement | declarationStatement | terminatedStatement | statement | scopeBlock )) ~ opt(statement) ^^ { case stmts ~ Some(lastStmt) => StatementsNode(stmts ++ List(lastStmt)) case stmts ~ None => StatementsNode(stmts) } def block: Parser[StatementsNode] = ("{" ~> statements <~ "}") def doBlock: Parser[StatementsNode] = "do".r ~> block def scopeBlock: Parser[ScopeNode] = block ^^ { ScopeNode(_) } // versions and authority def versionDecl = """[0-9]+(\.[0-9]+)*""".r def authorityDecl = """[a-z]+\:\S*""".r // Parameters def parameter = ("[*:]".r).? ~ parameterName ~ "?".? ~ opt("=" ~> expression) ^^ { case None ~ a ~ None ~ None => ParameterNode(a) case None ~ a ~ Some("?") ~ None => ParameterNode(a, optional = true) case Some(":") ~ a ~ None ~ None => ParameterNode(a, named = true) case Some("*") ~ a ~ None ~ None => { a.take(1) match { case "@" => ParameterNode(a, slurpy = true) case "%" => ParameterNode(a, slurpy = true, named = true) case _ => throw new Exception("slurpy parameters must be either arrays or hashes") } } case None ~ a ~ None ~ defVal => ParameterNode(a, default = defVal) } // Code literals def code: Parser[CodeLiteralNode] = ("->" ~> ("(" ~> repsep(parameter, ",") <~ ")").?) ~ block ^^ { case Some(p) ~ b => CodeLiteralNode(SignatureNode(p), b) case None ~ b => CodeLiteralNode(SignatureNode(List(ParameterNode("@_", slurpy = true))), b) } // Packages def packageDecl = ("package" ~> namespacedIdentifier ~ ("-" ~> versionDecl).? ~ ("-" ~> authorityDecl).?) ~ block ^^ { case p ~ None ~ None ~ b => PackageDeclarationNode(p, b) case p ~ v ~ None ~ b => PackageDeclarationNode(p, b, version = v) case p ~ None ~ a ~ b => PackageDeclarationNode(p, b, authority = a) case p ~ v ~ a ~ b => PackageDeclarationNode(p, b, version = v, authority = a) } def subroutineDecl: Parser[SubroutineDeclarationNode] = ("sub" ~> identifier ~ ("(" ~> repsep(parameter, ",") <~ ")").?) ~ rep("is" ~> identifier).? ~ block ^^ { case n ~ Some(p) ~ t ~ b => SubroutineDeclarationNode(n, SignatureNode(p), b, t) case n ~ None ~ t ~ b => SubroutineDeclarationNode(n, SignatureNode(List()), b, t) } // Classes def attributeDecl = "has" ~> attributeName ~ ("=" ~> expression).? ^^ { case AttributeNameNode(v) ~ expr => AttributeDeclarationNode(v, expr.getOrElse(UndefLiteralNode())) } def methodDecl: Parser[MethodDeclarationNode] = ("method" ~> identifier ~ ("(" ~> repsep(parameter, ",") <~ ")").?) ~ block ^^ { case n ~ Some(p) ~ b => MethodDeclarationNode(n, SignatureNode(p), b) case n ~ None ~ b => MethodDeclarationNode(n, SignatureNode(List()), b) } def submethodDecl: Parser[SubMethodDeclarationNode] = ("submethod" ~> identifier ~ ("(" ~> repsep(parameter, ",") <~ ")").?) ~ block ^^ { case n ~ Some(p) ~ b => SubMethodDeclarationNode(n, SignatureNode(p), b) case n ~ None ~ b => SubMethodDeclarationNode(n, SignatureNode(List()), b) } def classBodyParts: Parser[AST] = ( methodDecl | submethodDecl | (attributeDecl <~ statementDelim) | attributeDecl ) def classBodyContent : Parser[StatementsNode] = rep(classBodyParts) ^^ StatementsNode def classBody : Parser[StatementsNode] = "{" ~> classBodyContent <~ "}" def classDecl = ("class" ~> identifier ~ ("-" ~> versionDecl).? ~ ("-" ~> authorityDecl).?) ~ ("extends" ~> namespacedIdentifier).? ~ classBody ^^ { case c ~ None ~ None ~ s ~ b => ClassDeclarationNode(c, s, b) case c ~ v ~ None ~ s ~ b => ClassDeclarationNode(c, s, b, version = v) case c ~ None ~ a ~ s ~ b => ClassDeclarationNode(c, s, b, authority = a) case c ~ v ~ a ~ s ~ b => ClassDeclarationNode(c, s, b, version = v, authority = a) } /** ********************************************************************* * From here on out it is mostly about * control statements. ********************************************************************* */ def useStatement: Parser[UseStatement] = ("use" ~> namespacedIdentifier) ^^ UseStatement def elseBlock: Parser[IfStruct] = "else" ~> block ^^ { case body => new IfStruct(BooleanLiteralNode(true), body) } def elsifBlock: Parser[IfStruct] = "elsif" ~> ("(" ~> expression <~ ")") ~ block ~ (elsifBlock | elseBlock).? ^^ { case cond ~ body ~ None => new IfStruct(cond, body) case cond ~ body ~ more => new IfStruct(cond, body, more) } def ifElseBlock: Parser[AST] = "if" ~> ("(" ~> expression <~ ")") ~ block ~ (elsifBlock | elseBlock).? ^^ { case if_cond ~ if_body ~ None => IfNode(new IfStruct(if_cond,if_body)) case if_cond ~ if_body ~ Some(_else) => IfNode(new IfStruct(if_cond,if_body, Some(_else))) } def unlessElseBlock: Parser[AST] = "unless" ~> ("(" ~> expression <~ ")") ~ block ~ (elsifBlock | elseBlock).? ^^ { case unless_cond ~ unless_body ~ None => UnlessNode(new UnlessStruct(unless_cond, unless_body)) case unless_cond ~ unless_body ~ Some(_else) => UnlessNode(new UnlessStruct(unless_cond, unless_body, Some(_else))) } def whileBlock: Parser[WhileNode] = "while" ~> ("(" ~> expression <~ ")") ~ block ^^ { case cond ~ body => WhileNode(cond, body) } def untilBlock: Parser[WhileNode] = "until" ~> ("(" ~> expression <~ ")") ~ block ^^ { case cond ~ body => WhileNode(PrefixUnaryOpNode(cond, "!"), body) } def topicVariable = ("my".? ~> variableName) ^^ { case VariableNameNode(v) => VariableDeclarationNode(v, UndefLiteralNode()) } def foreachBlock = "for(each)?".r ~> opt(topicVariable) ~ ("(" ~> expression <~ ")") ~ block ^^ { case Some(topic) ~ list ~ block => ForeachNode(topic, list, block) case None ~ list ~ block => ForeachNode(VariableDeclarationNode("$_", UndefLiteralNode()), list, block) } def forBlock = "for" ~> (("(" ~> variableDeclaration) <~ ";") ~ (expression <~ ";") ~ (statement <~ ")") ~ block ^^ { case init ~ termCond ~ step ~ block => ForNode(init, termCond, step, block) } def tryBlock: Parser[TryNode] = ("try" ~> block) ~ rep(catchBlock) ~ rep(finallyBlock) ^^ { case a ~ b ~ c => TryNode(a, b, c) } def catchBlock: Parser[CatchNode] = ("catch" ~ "(") ~> namespacedIdentifier ~ variableName ~ (")" ~> block) ^^ { case a ~ VariableNameNode(b) ~ c => CatchNode(a, b, c) } def finallyBlock: Parser[FinallyNode] = "finally" ~> block ^^ FinallyNode /** ********************************************************************* * Lastly, wrap it up with a general "statements" * production that encompasess much of the above ********************************************************************* */ lazy val blockStatement: Parser[AST] = ( ifElseBlock | unlessElseBlock | whileBlock | untilBlock | foreachBlock | forBlock | doBlock | tryBlock ) <~ opt(statementDelim) lazy val declarationStatement: Parser[AST] = ( packageDecl | subroutineDecl | classDecl ) <~ opt(statementDelim) lazy val simpleStatement: Parser[AST] = ( variableDeclaration | multiVariableDeclaration | useStatement | expression | multiVariableAssignment | multiAttributeAssignment ) /** * Statement modifiers */ lazy val modifiedStatement: Parser[AST] = simpleStatement ~ "if|unless|for(each)?|while|until".r ~ expression ^^ { case stmt ~ "if" ~ cond => IfNode(new IfStruct(cond, StatementsNode(List(stmt)))) case stmt ~ "unless" ~ cond => UnlessNode(new UnlessStruct(cond, StatementsNode(List(stmt)))) case stmt ~ "foreach" ~ list => ForeachNode(VariableDeclarationNode("$_", UndefLiteralNode()), list, StatementsNode(List(stmt))) case stmt ~ "for" ~ list => ForeachNode(VariableDeclarationNode("$_", UndefLiteralNode()), list, StatementsNode(List(stmt))) case stmt ~ "while" ~ cond => WhileNode(cond, StatementsNode(List(stmt))) case stmt ~ "until" ~ cond => WhileNode(PrefixUnaryOpNode(cond, "!"), StatementsNode(List(stmt))) } lazy val statement: Parser[AST] = ( modifiedStatement | simpleStatement ) lazy val terminatedStatement: Parser[AST] = statement <~ statementDelim }
{ "content_hash": "e5eb9883c4b5cb9767b1d7f4c30cac67", "timestamp": "", "source": "github", "line_count": 570, "max_line_length": 164, "avg_line_length": 39.271929824561404, "alnum_prop": 0.5806566897475989, "repo_name": "MoeOrganization/moe", "id": "5de7df9ee20da14ce5dfb0a16a98219398f28a0e", "size": "22385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/org/moe/parser/MoeProductions.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Perl", "bytes": "221671" }, { "name": "Racket", "bytes": "57" }, { "name": "Scala", "bytes": "489025" } ], "symlink_target": "" }
package com.a200fang.wozai; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
{ "content_hash": "e4d554c1f0bdb7594fe79cceb0d37c21", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 81, "avg_line_length": 23.294117647058822, "alnum_prop": 0.6893939393939394, "repo_name": "xumorden/WoZai", "id": "a1f3fdb4d117717cf4f6fa36eabb9e870cfcfbe5", "size": "396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/test/java/com/a200fang/wozai/ExampleUnitTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1039138" }, { "name": "Shell", "bytes": "608" } ], "symlink_target": "" }
const char *kWDContextKey = "wd_context"; @implementation WDCoreDataWatchdog - (void)setup { if (WDCoreDataWatchdogMonitorOptionsContexts & self.options) { [self setupContextMonitoring]; } if (WDCoreDataWatchdogMonitorOptionsObjects & self.options) { [self setupObjectMonitoring]; } if (WDCoreDataWatchdogMonitorOptionsCoordinators & self.options) { [self setupCoordinatorMonitoring]; } } - (void)setupContextMonitoring { IMP originalSaveImplementation = NULL; IMP originalInitImplementation = NULL; Ivar privateQueueIvar = NULL; Class MOCClass = [NSManagedObjectContext class]; Method saveMethod = class_getInstanceMethod(MOCClass, @selector(save:)); Method initMethod = class_getInstanceMethod(MOCClass, @selector(initWithConcurrencyType:)); originalSaveImplementation = method_getImplementation(saveMethod); originalInitImplementation = method_getImplementation(initMethod); privateQueueIvar = class_getInstanceVariable(MOCClass, "_dispatchQueue"); method_setImplementation(saveMethod, imp_implementationWithBlock(^BOOL(id context, NSError **errorBackPointer) { // SEL is ommited, it's not an error, it's an implementation detail of this runtime functionality dispatch_queue_t contextQueue = object_getIvar(context, privateQueueIvar); BOOL isAccessCorrect = ((!contextQueue || contextQueue == dispatch_get_main_queue()) && [NSThread isMainThread]) || (dispatch_get_specific(kWDContextKey) == (__bridge void *)context); if (!isAccessCorrect) { [self raiseErrorCode:WDErrorCodesCoreData.unwrappedSave forObject:context method:@selector(save:)]; } return ((BOOL (*)(id, SEL, NSError**))originalSaveImplementation)(context, @selector(save:), errorBackPointer); })); method_setImplementation(initMethod, imp_implementationWithBlock(^id(id context, NSManagedObjectContextConcurrencyType type) { // SEL is ommited, it's not an error, it's an implementation detail of this runtime functionality context = ((id (*)(id, SEL, NSManagedObjectContextConcurrencyType))originalInitImplementation)(context, @selector(initWithConcurrencyType:), type); if (type == NSPrivateQueueConcurrencyType) { dispatch_queue_t contextQueue = object_getIvar(context, privateQueueIvar); dispatch_queue_set_specific(contextQueue, kWDContextKey, (__bridge void *)(context), NULL); } return context; })); } - (void)setupObjectMonitoring { IMP originalResolveInstanceMethodImplementation = NULL; Ivar privateQueueIvar = NULL; Class MOClass = [NSManagedObject class]; Class MOCClass = [NSManagedObjectContext class]; Method resolveMethod = class_getClassMethod(MOClass, @selector(resolveInstanceMethod:)); privateQueueIvar = class_getInstanceVariable(MOCClass, "_dispatchQueue"); originalResolveInstanceMethodImplementation = method_getImplementation(resolveMethod); method_setImplementation(resolveMethod, imp_implementationWithBlock(^BOOL(Class class, SEL selector) { // SEL is ommited, it's not an error, it's an implementation detail of this runtime functionality. This selector is not a resolveInstanceMethod: but it's paramether. BOOL result = ((BOOL (*)(Class, SEL, SEL))originalResolveInstanceMethodImplementation)(class, @selector(resolveInstanceMethod:), selector); if (result) { static NSRegularExpression *regex = nil; if (!regex) { regex = [NSRegularExpression regularExpressionWithPattern:@"\\:" options:0 error:NULL]; } NSString *selectorString = NSStringFromSelector(selector); NSUInteger numberOfArguments = [regex numberOfMatchesInString:selectorString options:0 range:NSMakeRange(0, [selectorString length])]; Method methodToHook = class_getInstanceMethod(class, selector); IMP implementationToHook = method_getImplementation(methodToHook); char returnType[32]; const char objectEncoding[] = @encode(id); method_getReturnType(methodToHook, returnType, 32); BOOL isObjectReturned = strstr(returnType, objectEncoding) == returnType; if (numberOfArguments == 0) { void(^verifierBlock)(id, SEL) = ^(id SELF, SEL callingSelector) { id context = ((NSManagedObject *)SELF).managedObjectContext; dispatch_queue_t contextQueue = object_getIvar(context, privateQueueIvar); BOOL isAccessCorrect = ((!contextQueue || contextQueue == dispatch_get_main_queue()) && [NSThread isMainThread]) || (dispatch_get_specific(kWDContextKey) == (__bridge void *)context); if (!isAccessCorrect) { [self raiseErrorCode:WDErrorCodesCoreData.unwrappedGetter forObject:SELF method:callingSelector]; } }; if (isObjectReturned) { method_setImplementation(methodToHook, imp_implementationWithBlock(^id(id SELF) { verifierBlock(SELF, selector); return ((id (*)(id, SEL))implementationToHook)(SELF, selector); })); } else { method_setImplementation(methodToHook, imp_implementationWithBlock(^NSInteger(id SELF) { verifierBlock(SELF, selector); return ((NSInteger (*)(id, SEL))implementationToHook)(SELF, selector); })); } } else if (numberOfArguments == 1) { method_setImplementation(methodToHook, imp_implementationWithBlock(^void(id SELF, id argument) { id context = ((NSManagedObject *)SELF).managedObjectContext; dispatch_queue_t contextQueue = object_getIvar(context, privateQueueIvar); BOOL isAccessCorrect = ((!contextQueue || contextQueue == dispatch_get_main_queue()) && [NSThread isMainThread]) || (dispatch_get_specific(kWDContextKey) == (__bridge void *)context); if (!isAccessCorrect) { [self raiseErrorCode:WDErrorCodesCoreData.unwrappedSetter forObject:SELF method:selector]; } return ((void (*)(id, SEL, id))implementationToHook)(SELF, selector, argument); })); } else { NSAssert(NO, @"Unexpected selector resolve: %@", selectorString); } } return result; })); } - (void)setupCoordinatorMonitoring { // To be done } - (NSString *)errorDomain { return WDErrorDomain.coreData; } - (NSString *)descriptionForErrorCode:(NSInteger)code { return mapCoreDataErrorCodeToDescription(code); } @end #endif
{ "content_hash": "b92b65492d89a8bea74b63129485fdb5", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 272, "avg_line_length": 50.048611111111114, "alnum_prop": 0.6309143887886777, "repo_name": "soxjke/WatchDogs", "id": "cb5a2ea4e1a4ad44fda8722dcf0cad192e9783cb", "size": "8542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WatchDogs/Classes/CoreData/WDCoreDataWatchdog.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "44984" }, { "name": "Ruby", "bytes": "987" } ], "symlink_target": "" }
<component name="ProjectDictionaryState"> <dictionary name="hckhanh"> <words> <w>richtext</w> <w>turbolinks</w> </words> </dictionary> </component>
{ "content_hash": "a3ca6a0bf0af923bccdc696f54441923", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 41, "avg_line_length": 21.375, "alnum_prop": 0.6257309941520468, "repo_name": "hckhanh/bloggrails", "id": "76fa68e885ef0819de0204bb6a836d54252191fe", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/dictionaries/hckhanh.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "145222" }, { "name": "HTML", "bytes": "23100" }, { "name": "JavaScript", "bytes": "5103" }, { "name": "Ruby", "bytes": "41704" } ], "symlink_target": "" }
 #pragma once #include <aws/s3/S3_EXPORTS.h> #include <aws/s3/S3Request.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/s3/model/EncodingType.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <utility> namespace Aws { namespace Http { class URI; } //namespace Http namespace S3 { namespace Model { /** */ class AWS_S3_API ListObjectVersionsRequest : public S3Request { public: ListObjectVersionsRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "ListObjectVersions"; } Aws::String SerializePayload() const override; void AddQueryStringParameters(Aws::Http::URI& uri) const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The bucket name that contains the objects. </p> */ inline const Aws::String& GetBucket() const{ return m_bucket; } /** * <p>The bucket name that contains the objects. </p> */ inline bool BucketHasBeenSet() const { return m_bucketHasBeenSet; } /** * <p>The bucket name that contains the objects. </p> */ inline void SetBucket(const Aws::String& value) { m_bucketHasBeenSet = true; m_bucket = value; } /** * <p>The bucket name that contains the objects. </p> */ inline void SetBucket(Aws::String&& value) { m_bucketHasBeenSet = true; m_bucket = std::move(value); } /** * <p>The bucket name that contains the objects. </p> */ inline void SetBucket(const char* value) { m_bucketHasBeenSet = true; m_bucket.assign(value); } /** * <p>The bucket name that contains the objects. </p> */ inline ListObjectVersionsRequest& WithBucket(const Aws::String& value) { SetBucket(value); return *this;} /** * <p>The bucket name that contains the objects. </p> */ inline ListObjectVersionsRequest& WithBucket(Aws::String&& value) { SetBucket(std::move(value)); return *this;} /** * <p>The bucket name that contains the objects. </p> */ inline ListObjectVersionsRequest& WithBucket(const char* value) { SetBucket(value); return *this;} /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline const Aws::String& GetDelimiter() const{ return m_delimiter; } /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline bool DelimiterHasBeenSet() const { return m_delimiterHasBeenSet; } /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline void SetDelimiter(const Aws::String& value) { m_delimiterHasBeenSet = true; m_delimiter = value; } /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline void SetDelimiter(Aws::String&& value) { m_delimiterHasBeenSet = true; m_delimiter = std::move(value); } /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline void SetDelimiter(const char* value) { m_delimiterHasBeenSet = true; m_delimiter.assign(value); } /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline ListObjectVersionsRequest& WithDelimiter(const Aws::String& value) { SetDelimiter(value); return *this;} /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline ListObjectVersionsRequest& WithDelimiter(Aws::String&& value) { SetDelimiter(std::move(value)); return *this;} /** * <p>A delimiter is a character that you specify to group keys. All keys that * contain the same string between the <code>prefix</code> and the first occurrence * of the delimiter are grouped under a single result element in CommonPrefixes. * These groups are counted as one result against the max-keys limitation. These * keys are not returned elsewhere in the response.</p> */ inline ListObjectVersionsRequest& WithDelimiter(const char* value) { SetDelimiter(value); return *this;} inline const EncodingType& GetEncodingType() const{ return m_encodingType; } inline bool EncodingTypeHasBeenSet() const { return m_encodingTypeHasBeenSet; } inline void SetEncodingType(const EncodingType& value) { m_encodingTypeHasBeenSet = true; m_encodingType = value; } inline void SetEncodingType(EncodingType&& value) { m_encodingTypeHasBeenSet = true; m_encodingType = std::move(value); } inline ListObjectVersionsRequest& WithEncodingType(const EncodingType& value) { SetEncodingType(value); return *this;} inline ListObjectVersionsRequest& WithEncodingType(EncodingType&& value) { SetEncodingType(std::move(value)); return *this;} /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline const Aws::String& GetKeyMarker() const{ return m_keyMarker; } /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline bool KeyMarkerHasBeenSet() const { return m_keyMarkerHasBeenSet; } /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline void SetKeyMarker(const Aws::String& value) { m_keyMarkerHasBeenSet = true; m_keyMarker = value; } /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline void SetKeyMarker(Aws::String&& value) { m_keyMarkerHasBeenSet = true; m_keyMarker = std::move(value); } /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline void SetKeyMarker(const char* value) { m_keyMarkerHasBeenSet = true; m_keyMarker.assign(value); } /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline ListObjectVersionsRequest& WithKeyMarker(const Aws::String& value) { SetKeyMarker(value); return *this;} /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline ListObjectVersionsRequest& WithKeyMarker(Aws::String&& value) { SetKeyMarker(std::move(value)); return *this;} /** * <p>Specifies the key to start with when listing objects in a bucket.</p> */ inline ListObjectVersionsRequest& WithKeyMarker(const char* value) { SetKeyMarker(value); return *this;} /** * <p>Sets the maximum number of keys returned in the response. By default the API * returns up to 1,000 key names. The response might contain fewer keys but will * never contain more. If additional keys satisfy the search criteria, but were not * returned because max-keys was exceeded, the response contains * &lt;isTruncated&gt;true&lt;/isTruncated&gt;. To return the additional keys, see * key-marker and version-id-marker.</p> */ inline int GetMaxKeys() const{ return m_maxKeys; } /** * <p>Sets the maximum number of keys returned in the response. By default the API * returns up to 1,000 key names. The response might contain fewer keys but will * never contain more. If additional keys satisfy the search criteria, but were not * returned because max-keys was exceeded, the response contains * &lt;isTruncated&gt;true&lt;/isTruncated&gt;. To return the additional keys, see * key-marker and version-id-marker.</p> */ inline bool MaxKeysHasBeenSet() const { return m_maxKeysHasBeenSet; } /** * <p>Sets the maximum number of keys returned in the response. By default the API * returns up to 1,000 key names. The response might contain fewer keys but will * never contain more. If additional keys satisfy the search criteria, but were not * returned because max-keys was exceeded, the response contains * &lt;isTruncated&gt;true&lt;/isTruncated&gt;. To return the additional keys, see * key-marker and version-id-marker.</p> */ inline void SetMaxKeys(int value) { m_maxKeysHasBeenSet = true; m_maxKeys = value; } /** * <p>Sets the maximum number of keys returned in the response. By default the API * returns up to 1,000 key names. The response might contain fewer keys but will * never contain more. If additional keys satisfy the search criteria, but were not * returned because max-keys was exceeded, the response contains * &lt;isTruncated&gt;true&lt;/isTruncated&gt;. To return the additional keys, see * key-marker and version-id-marker.</p> */ inline ListObjectVersionsRequest& WithMaxKeys(int value) { SetMaxKeys(value); return *this;} /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline const Aws::String& GetPrefix() const{ return m_prefix; } /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline bool PrefixHasBeenSet() const { return m_prefixHasBeenSet; } /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline void SetPrefix(const Aws::String& value) { m_prefixHasBeenSet = true; m_prefix = value; } /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline void SetPrefix(Aws::String&& value) { m_prefixHasBeenSet = true; m_prefix = std::move(value); } /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline void SetPrefix(const char* value) { m_prefixHasBeenSet = true; m_prefix.assign(value); } /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline ListObjectVersionsRequest& WithPrefix(const Aws::String& value) { SetPrefix(value); return *this;} /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline ListObjectVersionsRequest& WithPrefix(Aws::String&& value) { SetPrefix(std::move(value)); return *this;} /** * <p>Use this parameter to select only those keys that begin with the specified * prefix. You can use prefixes to separate a bucket into different groupings of * keys. (You can think of using prefix to make groups in the same way you'd use a * folder in a file system.) You can use prefix with delimiter to roll up numerous * objects into a single result under CommonPrefixes. </p> */ inline ListObjectVersionsRequest& WithPrefix(const char* value) { SetPrefix(value); return *this;} /** * <p>Specifies the object version you want to start listing from.</p> */ inline const Aws::String& GetVersionIdMarker() const{ return m_versionIdMarker; } /** * <p>Specifies the object version you want to start listing from.</p> */ inline bool VersionIdMarkerHasBeenSet() const { return m_versionIdMarkerHasBeenSet; } /** * <p>Specifies the object version you want to start listing from.</p> */ inline void SetVersionIdMarker(const Aws::String& value) { m_versionIdMarkerHasBeenSet = true; m_versionIdMarker = value; } /** * <p>Specifies the object version you want to start listing from.</p> */ inline void SetVersionIdMarker(Aws::String&& value) { m_versionIdMarkerHasBeenSet = true; m_versionIdMarker = std::move(value); } /** * <p>Specifies the object version you want to start listing from.</p> */ inline void SetVersionIdMarker(const char* value) { m_versionIdMarkerHasBeenSet = true; m_versionIdMarker.assign(value); } /** * <p>Specifies the object version you want to start listing from.</p> */ inline ListObjectVersionsRequest& WithVersionIdMarker(const Aws::String& value) { SetVersionIdMarker(value); return *this;} /** * <p>Specifies the object version you want to start listing from.</p> */ inline ListObjectVersionsRequest& WithVersionIdMarker(Aws::String&& value) { SetVersionIdMarker(std::move(value)); return *this;} /** * <p>Specifies the object version you want to start listing from.</p> */ inline ListObjectVersionsRequest& WithVersionIdMarker(const char* value) { SetVersionIdMarker(value); return *this;} /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline const Aws::String& GetExpectedBucketOwner() const{ return m_expectedBucketOwner; } /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline bool ExpectedBucketOwnerHasBeenSet() const { return m_expectedBucketOwnerHasBeenSet; } /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline void SetExpectedBucketOwner(const Aws::String& value) { m_expectedBucketOwnerHasBeenSet = true; m_expectedBucketOwner = value; } /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline void SetExpectedBucketOwner(Aws::String&& value) { m_expectedBucketOwnerHasBeenSet = true; m_expectedBucketOwner = std::move(value); } /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline void SetExpectedBucketOwner(const char* value) { m_expectedBucketOwnerHasBeenSet = true; m_expectedBucketOwner.assign(value); } /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline ListObjectVersionsRequest& WithExpectedBucketOwner(const Aws::String& value) { SetExpectedBucketOwner(value); return *this;} /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline ListObjectVersionsRequest& WithExpectedBucketOwner(Aws::String&& value) { SetExpectedBucketOwner(std::move(value)); return *this;} /** * <p>The account id of the expected bucket owner. If the bucket is owned by a * different account, the request will fail with an HTTP <code>403 (Access * Denied)</code> error.</p> */ inline ListObjectVersionsRequest& WithExpectedBucketOwner(const char* value) { SetExpectedBucketOwner(value); return *this;} inline const Aws::Map<Aws::String, Aws::String>& GetCustomizedAccessLogTag() const{ return m_customizedAccessLogTag; } inline bool CustomizedAccessLogTagHasBeenSet() const { return m_customizedAccessLogTagHasBeenSet; } inline void SetCustomizedAccessLogTag(const Aws::Map<Aws::String, Aws::String>& value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag = value; } inline void SetCustomizedAccessLogTag(Aws::Map<Aws::String, Aws::String>&& value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag = std::move(value); } inline ListObjectVersionsRequest& WithCustomizedAccessLogTag(const Aws::Map<Aws::String, Aws::String>& value) { SetCustomizedAccessLogTag(value); return *this;} inline ListObjectVersionsRequest& WithCustomizedAccessLogTag(Aws::Map<Aws::String, Aws::String>&& value) { SetCustomizedAccessLogTag(std::move(value)); return *this;} inline ListObjectVersionsRequest& AddCustomizedAccessLogTag(const Aws::String& key, const Aws::String& value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag.emplace(key, value); return *this; } inline ListObjectVersionsRequest& AddCustomizedAccessLogTag(Aws::String&& key, const Aws::String& value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag.emplace(std::move(key), value); return *this; } inline ListObjectVersionsRequest& AddCustomizedAccessLogTag(const Aws::String& key, Aws::String&& value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag.emplace(key, std::move(value)); return *this; } inline ListObjectVersionsRequest& AddCustomizedAccessLogTag(Aws::String&& key, Aws::String&& value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag.emplace(std::move(key), std::move(value)); return *this; } inline ListObjectVersionsRequest& AddCustomizedAccessLogTag(const char* key, Aws::String&& value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag.emplace(key, std::move(value)); return *this; } inline ListObjectVersionsRequest& AddCustomizedAccessLogTag(Aws::String&& key, const char* value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag.emplace(std::move(key), value); return *this; } inline ListObjectVersionsRequest& AddCustomizedAccessLogTag(const char* key, const char* value) { m_customizedAccessLogTagHasBeenSet = true; m_customizedAccessLogTag.emplace(key, value); return *this; } private: Aws::String m_bucket; bool m_bucketHasBeenSet; Aws::String m_delimiter; bool m_delimiterHasBeenSet; EncodingType m_encodingType; bool m_encodingTypeHasBeenSet; Aws::String m_keyMarker; bool m_keyMarkerHasBeenSet; int m_maxKeys; bool m_maxKeysHasBeenSet; Aws::String m_prefix; bool m_prefixHasBeenSet; Aws::String m_versionIdMarker; bool m_versionIdMarkerHasBeenSet; Aws::String m_expectedBucketOwner; bool m_expectedBucketOwnerHasBeenSet; Aws::Map<Aws::String, Aws::String> m_customizedAccessLogTag; bool m_customizedAccessLogTagHasBeenSet; }; } // namespace Model } // namespace S3 } // namespace Aws
{ "content_hash": "6861e720bb92e756b07ed5caddf9d9cb", "timestamp": "", "source": "github", "line_count": 499, "max_line_length": 232, "avg_line_length": 46.1503006012024, "alnum_prop": 0.7019844543836032, "repo_name": "jt70471/aws-sdk-cpp", "id": "7bc20248a064fff61822c734bcdaa0762607224d", "size": "23148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-s3/include/aws/s3/model/ListObjectVersionsRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.dao.jena; import static org.junit.Assert.*; import edu.cornell.mannlib.vitro.testing.AbstractTestClass; import org.junit.Test; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; public class ObjectPropertyStatementDaoJenaTest extends AbstractTestClass { /** * Test if jena lib can parse N3 that it generates. * owl:sameAs has been a problem when it is represetned * in N3 with the character = */ @Test public void testN3WithSameAs() { String n3WithSameAs = " <http://example.com/bob> = <http://example.com/robert> ."; try{ Model m = ModelFactory.createDefaultModel(); m.read(n3WithSameAs, null, "N3"); fail( "If this test fails it means that jena now correctly parses = when reading N3."); }catch(Exception ex ){ } } }
{ "content_hash": "6c51b44d23dd98da1f829687c216114a", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 99, "avg_line_length": 28.17142857142857, "alnum_prop": 0.6713995943204868, "repo_name": "vivo-project/Vitro", "id": "6488a107b6155823147f2837a789b72d8c4b3d3e", "size": "986", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "api/src/test/java/edu/cornell/mannlib/vitro/webapp/dao/jena/ObjectPropertyStatementDaoJenaTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "22844" }, { "name": "CSS", "bytes": "155404" }, { "name": "FreeMarker", "bytes": "373347" }, { "name": "HTML", "bytes": "61363" }, { "name": "Java", "bytes": "7485398" }, { "name": "JavaScript", "bytes": "2110935" }, { "name": "Shell", "bytes": "913" }, { "name": "XSLT", "bytes": "4546" } ], "symlink_target": "" }
(function () { 'use strict'; angular.module('socialbook') .factory('newsFeedService', ['$q', 'friendsListService', newsFeedService]); function newsFeedService($q, friendsListService) { return { getNewsFeed: getNewsFeed }; // simply returns a random subset (half) of the 'friends' array from the 'friendsListService' function getNewsFeed() { return $q(function(resolve, reject) { friendsListService.getFriends() .then(function (response) { var originalFriends = response.data, randomizedFriends = randomizeArray(originalFriends); resolve({ data: randomizedFriends.slice(0, Math.floor(randomizedFriends.length / 2)) }); }); }); } } function randomizeArray(arr) { var sortedArray = [], len = arr.length; while(len > 0) { var j = Math.floor(Math.random() * arr.length); var randomItem = arr.splice(j, 1); sortedArray.push(randomItem[0]); len = arr.length; } return sortedArray; } })();
{ "content_hash": "4cd42c55946caed0c2d7f70ec615c6ff", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 95, "avg_line_length": 24.923076923076923, "alnum_prop": 0.6656378600823045, "repo_name": "jvnicholson/socialbook", "id": "5ca31f1b3be2ec336f8533ade161255bc1e84f10", "size": "972", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/news-feed/news-feed-service.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2918" }, { "name": "HTML", "bytes": "4637" }, { "name": "JavaScript", "bytes": "16077" } ], "symlink_target": "" }
class ChromeBrowserState; // Controller for the UI that allows the user to block popups. @interface BlockPopupsTableViewController : SettingsRootTableViewController // The designated initializer. |browserState| must not be nil. - (instancetype)initWithBrowserState:(ChromeBrowserState*)browserState NS_DESIGNATED_INITIALIZER; - (instancetype)initWithStyle:(UITableViewStyle)style NS_UNAVAILABLE; @end #endif // IOS_CHROME_BROWSER_UI_SETTINGS_BLOCK_POPUPS_TABLE_VIEW_CONTROLLER_H_
{ "content_hash": "9f8f3e55cbf3bff590002456d6f6154d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 79, "avg_line_length": 35, "alnum_prop": 0.8122448979591836, "repo_name": "endlessm/chromium-browser", "id": "725c011cea195ac9aa3ac798180463a1da243c14", "size": "891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ios/chrome/browser/ui/settings/block_popups_table_view_controller.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
.class Lcom/mediatek/hdmi/MtkHdmiManagerService$6; .super Ljava/lang/Object; .source "MtkHdmiManagerService.java" # interfaces .implements Ljava/lang/Runnable; # annotations .annotation system Ldalvik/annotation/EnclosingMethod; value = Lcom/mediatek/hdmi/MtkHdmiManagerService;->initial()V .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService; # direct methods .method constructor <init>(Lcom/mediatek/hdmi/MtkHdmiManagerService;)V .locals 0 .prologue .line 513 iput-object p1, p0, Lcom/mediatek/hdmi/MtkHdmiManagerService$6;->this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService; invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public run()V .locals 3 .prologue .line 517 sget-boolean v0, Lcom/mediatek/hdmi/MtkHdmiManagerService$FeatureOption;->MTK_DRM_KEY_MNG_SUPPORT:Z if-eqz v0, :cond_0 .line 518 const-string v0, "MtkHdmiService" new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string v2, "setDrmKey: " invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 iget-object v2, p0, Lcom/mediatek/hdmi/MtkHdmiManagerService$6;->this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService; # invokes: Lcom/mediatek/hdmi/MtkHdmiManagerService;->setDrmKey()Z invoke-static {v2}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$2000(Lcom/mediatek/hdmi/MtkHdmiManagerService;)Z move-result v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 # invokes: Lcom/mediatek/hdmi/MtkHdmiManagerService;->log(Ljava/lang/String;Ljava/lang/Object;)V invoke-static {v0, v1}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$000(Ljava/lang/String;Ljava/lang/Object;)V .line 522 :goto_0 return-void .line 520 :cond_0 const-string v0, "MtkHdmiService" new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string v2, "setHdcpKey: " invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 iget-object v2, p0, Lcom/mediatek/hdmi/MtkHdmiManagerService$6;->this$0:Lcom/mediatek/hdmi/MtkHdmiManagerService; # invokes: Lcom/mediatek/hdmi/MtkHdmiManagerService;->setHdcpKey()Z invoke-static {v2}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$2100(Lcom/mediatek/hdmi/MtkHdmiManagerService;)Z move-result v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 # invokes: Lcom/mediatek/hdmi/MtkHdmiManagerService;->log(Ljava/lang/String;Ljava/lang/Object;)V invoke-static {v0, v1}, Lcom/mediatek/hdmi/MtkHdmiManagerService;->access$000(Ljava/lang/String;Ljava/lang/Object;)V goto :goto_0 .end method
{ "content_hash": "319ac128cae840364ffc188bc32369c5", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 122, "avg_line_length": 29.189655172413794, "alnum_prop": 0.7362669816893089, "repo_name": "hexiaoshuai/Flyme_device_ZTE_A1", "id": "1f36b496606a986cf7ac07a78142aa2c5e9815a4", "size": "3386", "binary": false, "copies": "1", "ref": "refs/heads/C880AV1.0.0B06", "path": "services.jar.out/smali/com/mediatek/hdmi/MtkHdmiManagerService$6.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "1500" }, { "name": "HTML", "bytes": "10195" }, { "name": "Makefile", "bytes": "11258" }, { "name": "Python", "bytes": "924" }, { "name": "Shell", "bytes": "2734" }, { "name": "Smali", "bytes": "234274633" } ], "symlink_target": "" }
include $(srctree)/drivers/misc/mediatek/Makefile.custom obj-$(CONFIG_MTK_VIBRATOR) := vibrator_drv.o obj-y += $(subst ",,$(CONFIG_MTK_PLATFORM))/ #ccflags-y := -Idrivers/staging/android/
{ "content_hash": "f4305cf87e3c7ea6214a34db25571843", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 56, "avg_line_length": 27.285714285714285, "alnum_prop": 0.7068062827225131, "repo_name": "zhengdejin/X1_Code", "id": "7443743ad3cc5899e7a2c6e6b6427797c9418c3a", "size": "191", "binary": false, "copies": "91", "ref": "refs/heads/master", "path": "kernel-3.10/drivers/misc/mediatek/vibrator/Makefile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "4528" }, { "name": "Assembly", "bytes": "10107915" }, { "name": "Awk", "bytes": "18681" }, { "name": "Batchfile", "bytes": "144" }, { "name": "C", "bytes": "519266172" }, { "name": "C++", "bytes": "11700846" }, { "name": "GDB", "bytes": "18113" }, { "name": "Lex", "bytes": "47705" }, { "name": "M4", "bytes": "3388" }, { "name": "Makefile", "bytes": "1619668" }, { "name": "Objective-C", "bytes": "2963724" }, { "name": "Perl", "bytes": "570279" }, { "name": "Perl 6", "bytes": "3727" }, { "name": "Python", "bytes": "92743" }, { "name": "Roff", "bytes": "55837" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "185922" }, { "name": "SourcePawn", "bytes": "2711" }, { "name": "UnrealScript", "bytes": "6113" }, { "name": "XS", "bytes": "1240" }, { "name": "Yacc", "bytes": "92226" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="150dp" android:gravity="center" android:horizontalSpacing="5dp" android:numColumns="auto_fit" android:stretchMode="columnWidth" android:padding="5dp" android:verticalSpacing="5dp" > </GridView>
{ "content_hash": "124c4c197aa3eaaae6ccab09e1d7d3c6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 68, "avg_line_length": 33.57142857142857, "alnum_prop": 0.6872340425531915, "repo_name": "ixiyang/ImagePicker", "id": "e1b621710d3db2a1408c5a62ff71ab76903336a8", "size": "470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/layout/gallery.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "26451" } ], "symlink_target": "" }
SMTP_SETTINGS = { address: ENV.fetch('SMTP_ADDRESS'), # example: "smtp.sendgrid.net" authentication: :login, domain: ENV.fetch('SMTP_DOMAIN'), # example: "heroku.com" enable_starttls_auto: true, password: ENV.fetch('SMTP_PASSWORD'), port: '587', user_name: ENV.fetch('SMTP_USERNAME') }.freeze
{ "content_hash": "8a00ba8097f24d9ff974d19e1dee4755", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 68, "avg_line_length": 34.111111111111114, "alnum_prop": 0.6840390879478827, "repo_name": "welaika/welaika-suspenders", "id": "5fc933785ab67c3dbd70ca3b32697690e3517a2a", "size": "338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/smtp.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "52" }, { "name": "HTML", "bytes": "7711" }, { "name": "Ruby", "bytes": "84481" }, { "name": "Shell", "bytes": "2309" } ], "symlink_target": "" }
#include "tensorflow/compiler/xla/service/pattern_matcher.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/hlo_parser.h" #include "tensorflow/core/platform/test.h" namespace xla { namespace { TEST(PatternMatcherTest, AddOp) { constexpr char kModuleStr[] = R"(HloModule two_plus_two_module ENTRY %two_plus_two_computation () -> f32[] { %two = f32[] constant(2) ROOT %two_plus_two = f32[] add(f32[] %two, f32[] %two) } )"; TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, ParseHloString(kModuleStr)); const HloInstruction* matched_inst; HloInstruction* matched_operand; Shape* matched_shape; Layout* matched_layout; ASSERT_TRUE(Match( hlo_module->entry_computation()->root_instruction(), match::Op(&matched_inst) .WithName("two_plus_two") .WithOpcode(HloOpcode::kAdd) .WithShape( match::Shape(&matched_shape) .WithLayout(match::Layout(&matched_layout).WithDenseFormat())) .WithOperand( 0, match::Op(&matched_operand).WithOpcode(HloOpcode::kConstant)))); ASSERT_NE(matched_inst, nullptr); EXPECT_EQ(matched_inst->name(), "two_plus_two"); EXPECT_EQ(matched_inst->opcode(), HloOpcode::kAdd); EXPECT_TRUE(Match(hlo_module->entry_computation()->root_instruction(), match::Add(match::Constant(), match::Constant()))); EXPECT_FALSE(Match(hlo_module->entry_computation()->root_instruction(), match::Op().WithName("bad_name"))); matched_inst = nullptr; EXPECT_FALSE(Match(hlo_module->entry_computation()->root_instruction(), match::Multiply(&matched_inst, match::Op(), match::Op()))); } TEST(PatternMatcherTest, ScalarShape) { auto scalar_shape = ShapeUtil::MakeShape(F32, {}); Shape* matched_shape; EXPECT_TRUE(Match(&scalar_shape, match::Shape(&matched_shape).IsScalar())); EXPECT_EQ(matched_shape, &scalar_shape); EXPECT_TRUE(Match(&scalar_shape, match::Shape().IsArray())); EXPECT_TRUE(Match(&scalar_shape, match::Shape().IsDenseArray())); EXPECT_FALSE(Match(&scalar_shape, match::Shape().IsTuple())); EXPECT_TRUE(Match(&scalar_shape, match::Shape().WithElementType(F32))); EXPECT_TRUE(Match(&scalar_shape, match::Shape().WithRank(0))); EXPECT_FALSE(Match( &scalar_shape, match::Shape().WithSubshape({0}, match::Shape()).WithElementType(F32))); } TEST(PatternMatcherTest, DenseArrayShape) { auto array_shape = ShapeUtil::MakeShape(F32, {2, 3, 4}); Shape* matched_shape; EXPECT_TRUE(Match(&array_shape, match::Shape(&matched_shape).IsArray())); EXPECT_EQ(matched_shape, &array_shape); EXPECT_TRUE(Match(&array_shape, match::Shape().IsDenseArray())); EXPECT_FALSE(Match(&array_shape, match::Shape().IsSparseArray())); EXPECT_FALSE(Match(&array_shape, match::Shape().IsScalar())); EXPECT_FALSE(Match(&array_shape, match::Shape().IsTuple())); EXPECT_TRUE(Match(&array_shape, match::Shape().WithElementType(F32))); EXPECT_TRUE(Match(&array_shape, match::Shape().WithRank(3))); EXPECT_FALSE( Match(&array_shape, match::Shape().WithSubshape({0}, match::Shape()))); Layout* matched_layout; EXPECT_FALSE(Match(&array_shape, match::Shape().WithLayout( match::Layout(&matched_layout).WithSparseFormat()))); EXPECT_TRUE(Match(&array_shape, match::Shape().WithLayout( match::Layout(&matched_layout).WithDenseFormat()))); EXPECT_EQ(matched_layout, &array_shape.layout()); } TEST(PatternMatcherTest, SparseArrayShape) { auto array_shape = ShapeUtil::MakeShapeWithSparseLayout(F32, {2, 3, 4}, 10); Shape* matched_shape; EXPECT_TRUE(Match(&array_shape, match::Shape(&matched_shape).IsArray())); EXPECT_EQ(matched_shape, &array_shape); EXPECT_FALSE(Match(&array_shape, match::Shape().IsDenseArray())); EXPECT_TRUE(Match(&array_shape, match::Shape().IsSparseArray())); EXPECT_FALSE(Match(&array_shape, match::Shape().IsScalar())); EXPECT_FALSE(Match(&array_shape, match::Shape().IsTuple())); EXPECT_TRUE(Match(&array_shape, match::Shape().WithElementType(F32))); EXPECT_TRUE(Match(&array_shape, match::Shape().WithRank(3))); EXPECT_FALSE( Match(&array_shape, match::Shape().WithSubshape({0}, match::Shape()))); Layout* matched_layout; EXPECT_FALSE(Match(&array_shape, match::Shape().WithLayout( match::Layout(&matched_layout).WithDenseFormat()))); EXPECT_TRUE(Match(&array_shape, match::Shape().WithLayout( match::Layout(&matched_layout).WithSparseFormat()))); EXPECT_EQ(matched_layout, &array_shape.layout()); } TEST(PatternMatcherTest, TupleShape) { auto tuple_shape = ShapeUtil::MakeTupleShape({ ShapeUtil::MakeShape(F32, {1, 2, 3}), ShapeUtil::MakeShape(S32, {4, 5}), }); EXPECT_TRUE(Match(&tuple_shape, match::Shape().IsTuple())); EXPECT_FALSE(Match(&tuple_shape, match::Shape().IsArray())); EXPECT_FALSE(Match(&tuple_shape, match::Shape().IsScalar())); Shape* subshape; ASSERT_TRUE(Match( &tuple_shape, match::Shape().WithSubshape( {0}, match::Shape(&subshape).WithElementType(F32).WithRank(3)))); ASSERT_NE(subshape, nullptr); EXPECT_TRUE( ShapeUtil::Equal(*subshape, ShapeUtil::GetSubshape(tuple_shape, {0}))); EXPECT_TRUE(Match(&tuple_shape, match::Shape().WithSubshape( {0}, match::Shape().EqualTo( &ShapeUtil::GetSubshape(tuple_shape, {0}))))); EXPECT_FALSE(Match(&tuple_shape, match::Shape().WithSubshape( {0}, match::Shape().EqualTo( &ShapeUtil::GetSubshape(tuple_shape, {1}))))); ASSERT_TRUE(Match( &tuple_shape, match::Shape().WithSubshape( {1}, match::Shape(&subshape).WithElementType(S32).WithRank(2)))); ASSERT_NE(subshape, nullptr); EXPECT_TRUE( ShapeUtil::Equal(*subshape, ShapeUtil::GetSubshape(tuple_shape, {1}))); EXPECT_TRUE(Match(&tuple_shape, match::Shape().WithSubshape( {1}, match::Shape().EqualTo( &ShapeUtil::GetSubshape(tuple_shape, {1}))))); EXPECT_FALSE(Match(&tuple_shape, match::Shape().WithSubshape( {1}, match::Shape().EqualTo( &ShapeUtil::GetSubshape(tuple_shape, {0}))))); EXPECT_FALSE( Match(&tuple_shape, match::Shape().WithSubshape({2}, match::Shape()))); EXPECT_FALSE( Match(&tuple_shape, match::Shape().WithSubshape({0, 0}, match::Shape()))); } TEST(PatternMatcherTest, FusionKind) { constexpr char kModuleStr[] = R"( HloModule test_module fused_computation { ROOT fp0 = f32[] parameter(0) } ENTRY while.v11 { p0 = f32[] parameter(0) ROOT fusion = f32[] fusion(p0), kind=kLoop, calls=fused_computation })"; TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, ParseHloString(kModuleStr)); auto* root = hlo_module->entry_computation()->root_instruction(); EXPECT_TRUE(Match( root, match::Op().WithFusionKind(HloInstruction::FusionKind::kLoop))); EXPECT_FALSE(Match( root, match::Op().WithFusionKind(HloInstruction::FusionKind::kInput))); EXPECT_FALSE(Match(root->operand(0), match::Op().WithFusionKind( HloInstruction::FusionKind::kLoop))); } TEST(PatternMatcherTest, GetTupleElement) { constexpr char kModuleStr[] = R"( HloModule test_module ENTRY while.v11 { p0 = (f32[], f32[], f32[]) parameter(0) ROOT gte = f32[] get-tuple-element(p0), index=1 })"; TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, ParseHloString(kModuleStr)); auto* root = hlo_module->entry_computation()->root_instruction(); EXPECT_FALSE(Match(root, match::Op().WithTupleIndex(0))); EXPECT_TRUE(Match(root, match::Op().WithTupleIndex(1))); EXPECT_FALSE(Match(root, match::Op().WithTupleIndex(2))); EXPECT_FALSE(Match(root, match::GetTupleElement(match::Op(), 0))); EXPECT_TRUE(Match(root, match::GetTupleElement(match::Op(), 1))); } TEST(PatternMatcherTest, AnyOf) { constexpr char kModuleStr[] = R"( HloModule test_module ENTRY test { ROOT constant = f16[] constant(1) })"; TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, ParseHloString(kModuleStr)); auto* root = hlo_module->entry_computation()->root_instruction(); EXPECT_TRUE( Match(root, match::AnyOf<HloInstruction>(match::ConstantScalar(0), match::ConstantScalar(1)))); EXPECT_TRUE( Match(root, match::AnyOf<HloInstruction>(match::ConstantScalar(1), match::ConstantScalar(0)))); EXPECT_FALSE( Match(root, match::AnyOf<HloInstruction>(match::ConstantScalar(0), match::ConstantScalar(2)))); } TEST(PatternMatcherTest, ConstantScalar) { constexpr char kModuleStr[] = R"( HloModule test_module ENTRY test { ROOT constant = f16[] constant(42) })"; TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, ParseHloString(kModuleStr)); auto* root = hlo_module->entry_computation()->root_instruction(); EXPECT_TRUE(Match(root, match::ConstantScalar(42))); EXPECT_FALSE(Match(root, match::ConstantScalar(41))); EXPECT_FALSE(Match(root, match::ConstantScalar(0))); } TEST(PatternMatcherTest, MultiplyAnyOrder) { using match::ConstantScalar; using match::MultiplyAnyOrder; constexpr char kModuleStr[] = R"( HloModule test_module ENTRY test { lhs = f16[] constant(42) rhs = f16[] constant(52) ROOT multiply = f16[] multiply(lhs, rhs) })"; TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, ParseHloString(kModuleStr)); auto* root = hlo_module->entry_computation()->root_instruction(); const HloInstruction* instr; EXPECT_TRUE(Match( root, MultiplyAnyOrder(&instr, ConstantScalar(42), ConstantScalar(52)))); EXPECT_TRUE(Match( root, MultiplyAnyOrder(&instr, ConstantScalar(52), ConstantScalar(42)))); } TEST(PatternMatcherTest, AnyOfShortCircuit) { using match::AnyOf; using match::Multiply; using match::Op; constexpr char kModuleStr[] = R"( HloModule test_module ENTRY test { lhs = f16[] constant(42) rhs = f16[] constant(52) ROOT multiply = f16[] multiply(lhs, rhs) })"; TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, ParseHloString(kModuleStr)); auto* root = hlo_module->entry_computation()->root_instruction(); { const HloInstruction* mul = nullptr; const HloInstruction* any = nullptr; ASSERT_TRUE(Match( root, AnyOf<HloInstruction>(Multiply(&mul, Op(), Op()), Op(&any)))); EXPECT_NE(nullptr, mul); EXPECT_EQ(nullptr, any); } { const HloInstruction* mul = nullptr; const HloInstruction* any = nullptr; ASSERT_TRUE(Match( root, AnyOf<HloInstruction>(Op(&any), Multiply(&mul, Op(), Op())))); EXPECT_NE(nullptr, any); EXPECT_EQ(nullptr, mul); } } } // namespace } // namespace xla
{ "content_hash": "1122be38b2eaac6cea0e35607d1552b0", "timestamp": "", "source": "github", "line_count": 286, "max_line_length": 80, "avg_line_length": 39.2972027972028, "alnum_prop": 0.6372453065219326, "repo_name": "xodus7/tensorflow", "id": "b3a2c954b38e00ff4083266a499f4d223c0c42ad", "size": "11907", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/compiler/xla/service/pattern_matcher_test.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1286" }, { "name": "Batchfile", "bytes": "9258" }, { "name": "C", "bytes": "340946" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "48861698" }, { "name": "CMake", "bytes": "195699" }, { "name": "Dockerfile", "bytes": "36400" }, { "name": "Go", "bytes": "1240309" }, { "name": "HTML", "bytes": "4681865" }, { "name": "Java", "bytes": "834061" }, { "name": "Jupyter Notebook", "bytes": "2604756" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "52618" }, { "name": "Objective-C", "bytes": "15650" }, { "name": "Objective-C++", "bytes": "99243" }, { "name": "PHP", "bytes": "1357" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "40952138" }, { "name": "Ruby", "bytes": "553" }, { "name": "Shell", "bytes": "459258" }, { "name": "Smarty", "bytes": "6976" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_43) on Wed May 22 21:49:31 UTC 2013 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.hbase.mapreduce.MultiTableInputFormat (HBase 0.94.8 API) </TITLE> <META NAME="date" CONTENT="2013-05-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.hbase.mapreduce.MultiTableInputFormat (HBase 0.94.8 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/hbase/mapreduce/MultiTableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/hbase/mapreduce//class-useMultiTableInputFormat.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MultiTableInputFormat.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.hbase.mapreduce.MultiTableInputFormat</B></H2> </CENTER> No usage of org.apache.hadoop.hbase.mapreduce.MultiTableInputFormat <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/hbase/mapreduce/MultiTableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/hbase/mapreduce//class-useMultiTableInputFormat.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MultiTableInputFormat.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2013 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "bd18958ae23360e43fa0ddde58ae08e8", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 248, "avg_line_length": 43.737931034482756, "alnum_prop": 0.6217281614632608, "repo_name": "algarecu/hbase-0.94.8-qod", "id": "5f498f909e91dfbf96d0551a87e32ca00be0c616", "size": "6342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/apidocs/org/apache/hadoop/hbase/mapreduce/class-use/MultiTableInputFormat.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "19836" }, { "name": "CSS", "bytes": "20794" }, { "name": "HTML", "bytes": "139288" }, { "name": "Java", "bytes": "24259991" }, { "name": "Makefile", "bytes": "2514" }, { "name": "PHP", "bytes": "14700" }, { "name": "Perl", "bytes": "17334" }, { "name": "Python", "bytes": "29070" }, { "name": "Ruby", "bytes": "779544" }, { "name": "Shell", "bytes": "175912" }, { "name": "Thrift", "bytes": "69092" }, { "name": "XSLT", "bytes": "8758" } ], "symlink_target": "" }
import { pool } from "db/pool"; import { PWCEvents } from "controllers/Events"; const events = new PWCEvents(); const errorMessage = "Could not retrieve events"; const expectedError = new Error(errorMessage); jest.mock("db/pool"); afterEach(() => { jest.clearAllMocks(); }); test("Could not retrieve any events", async () => { (pool as any).query.mockRejectedValueOnce(expectedError); expect.assertions(1); await expect(events.getAllEvents()).resolves.toEqual(expectedError); });
{ "content_hash": "a86db4f4e557c29907b404d5dce0cecb", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 70, "avg_line_length": 24.7, "alnum_prop": 0.7125506072874493, "repo_name": "Tokyo-Buffalo/pow-wow-calendar", "id": "eff9a49cf7941651af2f3f1ca2df32a91ec9220a", "size": "494", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "server/controllers/__tests__/Events.test.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "157" }, { "name": "JavaScript", "bytes": "584" }, { "name": "Shell", "bytes": "87" }, { "name": "TSQL", "bytes": "2887" }, { "name": "TypeScript", "bytes": "25909" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Valsa ribesia P. Karst. ### Remarks null
{ "content_hash": "4b81ed1243d525270edc185ff684b00d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.846153846153847, "alnum_prop": 0.6875, "repo_name": "mdoering/backbone", "id": "c0daa21ccc79e0c3815ac41dae19205d0fb770ca", "size": "175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Valsaceae/Valsa/Valsa ribesia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highstock]] */ package com.highstock.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>series&lt;mappoint&gt;-states-hover-marker</code> */ @js.annotation.ScalaJSDefined class SeriesMappointStatesHoverMarker extends com.highcharts.HighchartsGenericObject { /** * <p>The width of the point marker&#39;s outline.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-fillcolor/">2px blue marker</a> */ val lineWidth: js.UndefOr[Double] = js.undefined /** * <p>The color of the point marker&#39;s outline. When <code>undefined</code>, the * series&#39; or point&#39;s color is used.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-fillcolor/">Inherit from series color (undefined)</a> */ val lineColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>The threshold for how dense the point markers should be before they * are hidden, given that <code>enabled</code> is not defined. The number indicates * the horizontal distance between the two closest points in the series, * as multiples of the <code>marker.radius</code>. In other words, the default * value of 2 means points are hidden if overlapping horizontally.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-enabledthreshold">A higher threshold</a> * @since 6.0.5 */ val enabledThreshold: js.UndefOr[Double] = js.undefined /** * <p>The radius of the point marker.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-radius/">Bigger markers</a> */ val radius: js.UndefOr[Double] = js.undefined /** * <p>States for a single point marker.</p> */ val states: js.Any = js.undefined /** * <p>The fill color of the point marker. When <code>undefined</code>, the series&#39; or * point&#39;s color is used.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-fillcolor/">White fill</a> */ val fillColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>Enable or disable the point marker. If <code>undefined</code>, the markers are * hidden when the data is dense, and shown for more widespread data * points.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-enabled/">Disabled markers</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-enabled-false/">Disabled in normal state but enabled on hover</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/stock/plotoptions/series-marker/">Enabled markers</a> */ val enabled: js.UndefOr[Boolean] = js.undefined /** * <p>Image markers only. Set the image width explicitly. When using this * option, a <code>width</code> must also be set.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a> * @since 4.0.4 */ val height: js.UndefOr[Double] = js.undefined /** * <p>A predefined shape or symbol for the marker. When undefined, the * symbol is pulled from options.symbols. Other possible values are * &quot;circle&quot;, &quot;square&quot;, &quot;diamond&quot;, &quot;triangle&quot; and &quot;triangle-down&quot;.</p> * <p>Additionally, the URL to a graphic can be given on this form: * &quot;url(graphic.png)&quot;. Note that for the image to be applied to exported * charts, its URL needs to be accessible by the export server.</p> * <p>Custom callbacks for symbol path generation can also be added to * <code>Highcharts.SVGRenderer.prototype.symbols</code>. The callback is then * used by its method name, as shown in the demo.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-symbol/">Predefined, graphic and custom markers</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-symbol/">Predefined, graphic and custom markers</a> */ val symbol: js.UndefOr[String] = js.undefined /** * <p>Image markers only. Set the image width explicitly. When using this * option, a <code>height</code> must also be set.</p> * @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a> <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-marker-width-height/">Fixed width and height</a> * @since 4.0.4 */ val width: js.UndefOr[Double] = js.undefined } object SeriesMappointStatesHoverMarker { /** * @param lineWidth <p>The width of the point marker&#39;s outline.</p> * @param lineColor <p>The color of the point marker&#39;s outline. When <code>undefined</code>, the. series&#39; or point&#39;s color is used.</p> * @param enabledThreshold <p>The threshold for how dense the point markers should be before they. are hidden, given that <code>enabled</code> is not defined. The number indicates. the horizontal distance between the two closest points in the series,. as multiples of the <code>marker.radius</code>. In other words, the default. value of 2 means points are hidden if overlapping horizontally.</p> * @param radius <p>The radius of the point marker.</p> * @param states <p>States for a single point marker.</p> * @param fillColor <p>The fill color of the point marker. When <code>undefined</code>, the series&#39; or. point&#39;s color is used.</p> * @param enabled <p>Enable or disable the point marker. If <code>undefined</code>, the markers are. hidden when the data is dense, and shown for more widespread data. points.</p> * @param height <p>Image markers only. Set the image width explicitly. When using this. option, a <code>width</code> must also be set.</p> * @param symbol <p>A predefined shape or symbol for the marker. When undefined, the. symbol is pulled from options.symbols. Other possible values are. &quot;circle&quot;, &quot;square&quot;, &quot;diamond&quot;, &quot;triangle&quot; and &quot;triangle-down&quot;.</p>. <p>Additionally, the URL to a graphic can be given on this form:. &quot;url(graphic.png)&quot;. Note that for the image to be applied to exported. charts, its URL needs to be accessible by the export server.</p>. <p>Custom callbacks for symbol path generation can also be added to. <code>Highcharts.SVGRenderer.prototype.symbols</code>. The callback is then. used by its method name, as shown in the demo.</p> * @param width <p>Image markers only. Set the image width explicitly. When using this. option, a <code>height</code> must also be set.</p> */ def apply(lineWidth: js.UndefOr[Double] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, enabledThreshold: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, states: js.UndefOr[js.Any] = js.undefined, fillColor: js.UndefOr[String | js.Object] = js.undefined, enabled: js.UndefOr[Boolean] = js.undefined, height: js.UndefOr[Double] = js.undefined, symbol: js.UndefOr[String] = js.undefined, width: js.UndefOr[Double] = js.undefined): SeriesMappointStatesHoverMarker = { val lineWidthOuter: js.UndefOr[Double] = lineWidth val lineColorOuter: js.UndefOr[String | js.Object] = lineColor val enabledThresholdOuter: js.UndefOr[Double] = enabledThreshold val radiusOuter: js.UndefOr[Double] = radius val statesOuter: js.Any = states val fillColorOuter: js.UndefOr[String | js.Object] = fillColor val enabledOuter: js.UndefOr[Boolean] = enabled val heightOuter: js.UndefOr[Double] = height val symbolOuter: js.UndefOr[String] = symbol val widthOuter: js.UndefOr[Double] = width com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesMappointStatesHoverMarker { override val lineWidth: js.UndefOr[Double] = lineWidthOuter override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter override val enabledThreshold: js.UndefOr[Double] = enabledThresholdOuter override val radius: js.UndefOr[Double] = radiusOuter override val states: js.Any = statesOuter override val fillColor: js.UndefOr[String | js.Object] = fillColorOuter override val enabled: js.UndefOr[Boolean] = enabledOuter override val height: js.UndefOr[Double] = heightOuter override val symbol: js.UndefOr[String] = symbolOuter override val width: js.UndefOr[Double] = widthOuter }) } }
{ "content_hash": "7b06542816efcf95aff591b1ba606cea", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 682, "avg_line_length": 67.7872340425532, "alnum_prop": 0.7282904373299853, "repo_name": "Karasiq/scalajs-highcharts", "id": "b6b240aa1cb57aa3f70087619af2e7fba50c4ff6", "size": "9558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/highstock/config/SeriesMappointStatesHoverMarker.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "131509301" } ], "symlink_target": "" }
{ debug: true, flushInterval: 2000, percentThreshold: [95, 99], backends: ["statsd-zabbix-backend"], zabbixHost: "localhost", //zabbixTargetHostname: "hostname.example.com" }
{ "content_hash": "becee64b122264b8e2a8856a665a47df", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 48, "avg_line_length": 23.375, "alnum_prop": 0.6951871657754011, "repo_name": "parkerd/statsd-zabbix-backend", "id": "f00069440218fccdd0d0a9ce234e545975b518ba", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/local.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "12689" }, { "name": "Shell", "bytes": "384" } ], "symlink_target": "" }
class Notification{ constructor() { this._system=null; } notify(msg,level) { this._system.addNotification({ message: msg, level: level, position:'br' }); } success(msg) { this.notify(msg,"success") } error(msg) { this.notify(msg,"error") } warning (msg) { this.notify(msg,"warning") } info(msg) { this.notify(msg,"info") } } export default (new Notification);
{ "content_hash": "4670abbbda9409c191bfb4751b7e6747", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 34, "avg_line_length": 17.884615384615383, "alnum_prop": 0.535483870967742, "repo_name": "2cats/webserial", "id": "13d53d4b398ea27fb06a6e4f6bb4c3e06f8cac8d", "size": "465", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/js/Notification.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1427898" }, { "name": "Go", "bytes": "6206" }, { "name": "HTML", "bytes": "352" }, { "name": "JavaScript", "bytes": "5604099" }, { "name": "Makefile", "bytes": "448" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:2.0.50727.8009 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace MsgPack.Serialization.GeneratedSerializers.MapBased { [System.CodeDom.Compiler.GeneratedCodeAttribute("MsgPack.Serialization.CodeDomSerializers.CodeDomSerializerBuilder", "0.6.0.0")] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public class MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructorSerializer : MsgPack.Serialization.MessagePackSerializer<MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor> { private MsgPack.Serialization.MessagePackSerializer<string> _serializer0; public MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructorSerializer(MsgPack.Serialization.SerializationContext context) : base(context) { MsgPack.Serialization.PolymorphismSchema schema0 = default(MsgPack.Serialization.PolymorphismSchema); schema0 = null; this._serializer0 = context.GetSerializer<string>(schema0); } protected internal override void PackToCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor objectTree) { packer.PackMapHeader(1); this._serializer0.PackTo(packer, "String"); this._serializer0.PackTo(packer, objectTree.String); } protected internal override MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor UnpackFromCore(MsgPack.Unpacker unpacker) { MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor result = default(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor); if (unpacker.IsArrayHeader) { int unpacked = default(int); int itemsCount = default(int); itemsCount = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); string ctorArg0 = default(string); ctorArg0 = null; string nullable = default(string); if ((unpacked < itemsCount)) { nullable = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor), "System.String String"); } if (((nullable == null) == false)) { ctorArg0 = nullable; } unpacked = (unpacked + 1); result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor(ctorArg0); } else { int itemsCount0 = default(int); itemsCount0 = MsgPack.Serialization.UnpackHelpers.GetItemsCount(unpacker); string ctorArg00 = default(string); ctorArg00 = null; for (int i = 0; (i < itemsCount0); i = (i + 1)) { string key = default(string); string nullable0 = default(string); nullable0 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor), "MemberName"); if (((nullable0 == null) == false)) { key = nullable0; } else { throw MsgPack.Serialization.SerializationExceptions.NewNullIsProhibited("MemberName"); } if ((key == "String")) { string nullable1 = default(string); nullable1 = MsgPack.Serialization.UnpackHelpers.UnpackStringValue(unpacker, typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor), "System.String String"); if (((nullable1 == null) == false)) { ctorArg00 = nullable1; } } else { unpacker.Skip(); } } result = new MsgPack.Serialization.PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructor(ctorArg00); } return result; } private static T @__Conditional<T>(bool condition, T whenTrue, T whenFalse) { if (condition) { return whenTrue; } else { return whenFalse; } } } }
{ "content_hash": "5b7ba39c6338710f8166501c0cb9691e", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 263, "avg_line_length": 54.463157894736845, "alnum_prop": 0.5956706609972942, "repo_name": "luyikk/ZYSOCKET", "id": "e60089efb634c21458a08dc82fe721b97682ceb8", "size": "5348", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "msgpack-cli-master/test/MsgPack.UnitTest.Net35/gen/map/MsgPack_Serialization_PolymorphicMemberTypeKnownType_Normal_StringReadOnlyFieldAndConstructorSerializer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "348" }, { "name": "C", "bytes": "451" }, { "name": "C#", "bytes": "32978903" }, { "name": "C++", "bytes": "86396" }, { "name": "HTML", "bytes": "38474" }, { "name": "Java", "bytes": "1864" }, { "name": "PowerShell", "bytes": "4676" }, { "name": "Protocol Buffer", "bytes": "192" }, { "name": "Python", "bytes": "5096" }, { "name": "Shell", "bytes": "206" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in in Braun & Crous, Fungal Diversity 26(1): 66 (2007) #### Original name Stenella leucothoës U. Braun ### Remarks null
{ "content_hash": "294cc0dbc4d2e3ddcfc16ba18720b834", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 13.846153846153847, "alnum_prop": 0.7, "repo_name": "mdoering/backbone", "id": "a65a373d92e19d5a94da5904eb075d5f4c3fcde7", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Stenella/Stenella leucothoës/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
SYNONYM #### According to IUCN Red List of Threatened Species #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5b426630321f7d177bac1f7c6ac919c8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 35, "avg_line_length": 9.923076923076923, "alnum_prop": 0.6976744186046512, "repo_name": "mdoering/backbone", "id": "1823f01dffa290a62039e7cbb6b68e90376575ea", "size": "185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Dipterocarpaceae/Shorea/Shorea disticha/ Syn. Doona oblonga/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <!--[if IE]><![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Class ListCommandHandler | FTP Server documentation </title> <meta name="viewport" content="width=device-width"> <meta name="title" content="Class ListCommandHandler | FTP Server documentation "> <meta name="generator" content="docfx 2.43.2.0"> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="../styles/docfx.vendor.css"> <link rel="stylesheet" href="../styles/docfx.css"> <link rel="stylesheet" href="../styles/main.css"> <meta property="docfx:navrel" content="../toc.html"> <meta property="docfx:tocrel" content="toc.html"> <meta property="docfx:rel" content="../"> </head> <body data-spy="scroll" data-target="#affix" data-offset="120"> <div id="wrapper"> <header> <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> <img id="logo" class="svg" src="../logo.svg" alt=""> </a> </div> <div class="collapse navbar-collapse" id="navbar"> <form class="navbar-form navbar-right" role="search" id="search"> <div class="form-group"> <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off"> </div> </form> </div> </div> </nav> <div class="subnav navbar navbar-default"> <div class="container hide-when-search" id="breadcrumb"> <ul class="breadcrumb"> <li></li> </ul> </div> </div> </header> <div class="container body-content"> <div id="search-results"> <div class="search-list"></div> <div class="sr-items"> <p><i class="glyphicon glyphicon-refresh index-loading"></i></p> </div> <ul id="pagination"></ul> </div> </div> <div role="main" class="container body-content hide-when-search"> <div class="sidenav hide-when-search"> <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a> <div class="sidetoggle collapse" id="sidetoggle"> <div id="sidetoc"></div> </div> </div> <div class="article row grid-right"> <div class="col-md-10"> <article class="content wrap" id="_content" data-uid="FubarDev.FtpServer.CommandHandlers.ListCommandHandler"> <h1 id="FubarDev_FtpServer_CommandHandlers_ListCommandHandler" data-uid="FubarDev.FtpServer.CommandHandlers.ListCommandHandler" class="text-break">Class ListCommandHandler </h1> <div class="markdown level0 summary"><p>Implements the <code>LIST</code> and <code>NLST</code> commands.</p> </div> <div class="markdown level0 conceptual"></div> <div class="inheritance"> <h5>Inheritance</h5> <div class="level0"><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object">Object</a></div> <div class="level1"><a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html">FtpCommandHandler</a></div> <div class="level2"><span class="xref">ListCommandHandler</span></div> </div> <div classs="implements"> <h5>Implements</h5> <div><a class="xref" href="FubarDev.FtpServer.IFtpCommandHandler.html">IFtpCommandHandler</a></div> <div><a class="xref" href="FubarDev.FtpServer.IFtpCommandBase.html">IFtpCommandBase</a></div> <div><a class="xref" href="FubarDev.FtpServer.IFeatureHost.html">IFeatureHost</a></div> </div> <div class="inheritedMembers"> <h5>Inherited Members</h5> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_Names">FtpCommandHandler.Names</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_IsLoginRequired">FtpCommandHandler.IsLoginRequired</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_IsAbortable">FtpCommandHandler.IsAbortable</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_CommandContext">FtpCommandHandler.CommandContext</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_FtpContext">FtpCommandHandler.FtpContext</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_Connection">FtpCommandHandler.Connection</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_Data">FtpCommandHandler.Data</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_ServerMessages">FtpCommandHandler.ServerMessages</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_GetSupportedFeatures_FubarDev_FtpServer_IFtpConnection_">FtpCommandHandler.GetSupportedFeatures(IFtpConnection)</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_GetExtensions">FtpCommandHandler.GetExtensions()</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_T_System_String_">FtpCommandHandler.T(String)</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_T_System_String_System_Nullable_System_Object____">FtpCommandHandler.T(String, Nullable&lt;Object&gt;[])</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.equals#System_Object_Equals_System_Object_">Object.Equals(Object)</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.equals#System_Object_Equals_System_Object_System_Object_">Object.Equals(Object, Object)</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.gethashcode#System_Object_GetHashCode">Object.GetHashCode()</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.gettype#System_Object_GetType">Object.GetType()</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.memberwiseclone#System_Object_MemberwiseClone">Object.MemberwiseClone()</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.referenceequals#System_Object_ReferenceEquals_System_Object_System_Object_">Object.ReferenceEquals(Object, Object)</a> </div> <div> <a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object.tostring#System_Object_ToString">Object.ToString()</a> </div> </div> <h6><strong>Namespace</strong>: <a class="xref" href="FubarDev.FtpServer.CommandHandlers.html">FubarDev.FtpServer.CommandHandlers</a></h6> <h6><strong>Assembly</strong>: FubarDev.FtpServer.Commands.dll</h6> <h5 id="FubarDev_FtpServer_CommandHandlers_ListCommandHandler_syntax">Syntax</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">[FtpCommandHandler(&quot;LIST&quot;, false, true)] [FtpCommandHandler(&quot;NLST&quot;, false, true)] [FtpCommandHandler(&quot;LS&quot;, false, true)] public class ListCommandHandler : FtpCommandHandler, IFtpCommandHandler, IFtpCommandBase, IFeatureHost</code></pre> </div> <h3 id="constructors">Constructors </h3> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/FubarDevelopment/FtpServer/new/master/docfx_project/apidoc/new?filename=FubarDev_FtpServer_CommandHandlers_ListCommandHandler__ctor_System_Nullable_Microsoft_Extensions_Logging_ILogger_FubarDev_FtpServer_CommandHandlers_ListCommandHandler___.md&amp;value=---%0Auid%3A%20FubarDev.FtpServer.CommandHandlers.ListCommandHandler.%23ctor(System.Nullable%7BMicrosoft.Extensions.Logging.ILogger%7BFubarDev.FtpServer.CommandHandlers.ListCommandHandler%7D%7D)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/FubarDevelopment/FtpServer/blob/master/src/FubarDev.FtpServer.Commands/CommandHandlers/ListCommandHandler.cs/#L43">View Source</a> </span> <a id="FubarDev_FtpServer_CommandHandlers_ListCommandHandler__ctor_" data-uid="FubarDev.FtpServer.CommandHandlers.ListCommandHandler.#ctor*"></a> <h4 id="FubarDev_FtpServer_CommandHandlers_ListCommandHandler__ctor_System_Nullable_Microsoft_Extensions_Logging_ILogger_FubarDev_FtpServer_CommandHandlers_ListCommandHandler___" data-uid="FubarDev.FtpServer.CommandHandlers.ListCommandHandler.#ctor(System.Nullable{Microsoft.Extensions.Logging.ILogger{FubarDev.FtpServer.CommandHandlers.ListCommandHandler}})">ListCommandHandler(Nullable&lt;ILogger&lt;ListCommandHandler&gt;&gt;)</h4> <div class="markdown level1 summary"><p>Initializes a new instance of the <a class="xref" href="FubarDev.FtpServer.CommandHandlers.ListCommandHandler.html">ListCommandHandler</a> class.</p> </div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public ListCommandHandler(ILogger&lt;ListCommandHandler&gt;? logger = default(ILogger&lt;ListCommandHandler&gt;? ))</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.nullable-1">Nullable</a>&lt;<a class="xref" href="https://docs.microsoft.com/dotnet/api/microsoft.extensions.logging.ilogger-1">ILogger</a>&lt;<a class="xref" href="FubarDev.FtpServer.CommandHandlers.ListCommandHandler.html">ListCommandHandler</a>&gt;&gt;</td> <td><span class="parametername">logger</span></td> <td><p>The logger.</p> </td> </tr> </tbody> </table> <h3 id="methods">Methods </h3> <span class="small pull-right mobile-hide"> <span class="divider">|</span> <a href="https://github.com/FubarDevelopment/FtpServer/new/master/docfx_project/apidoc/new?filename=FubarDev_FtpServer_CommandHandlers_ListCommandHandler_Process_FubarDev_FtpServer_FtpCommand_System_Threading_CancellationToken_.md&amp;value=---%0Auid%3A%20FubarDev.FtpServer.CommandHandlers.ListCommandHandler.Process(FubarDev.FtpServer.FtpCommand%2CSystem.Threading.CancellationToken)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a> </span> <span class="small pull-right mobile-hide"> <a href="https://github.com/FubarDevelopment/FtpServer/blob/master/src/FubarDev.FtpServer.Commands/CommandHandlers/ListCommandHandler.cs/#L50">View Source</a> </span> <a id="FubarDev_FtpServer_CommandHandlers_ListCommandHandler_Process_" data-uid="FubarDev.FtpServer.CommandHandlers.ListCommandHandler.Process*"></a> <h4 id="FubarDev_FtpServer_CommandHandlers_ListCommandHandler_Process_FubarDev_FtpServer_FtpCommand_System_Threading_CancellationToken_" data-uid="FubarDev.FtpServer.CommandHandlers.ListCommandHandler.Process(FubarDev.FtpServer.FtpCommand,System.Threading.CancellationToken)">Process(FtpCommand, CancellationToken)</h4> <div class="markdown level1 summary"></div> <div class="markdown level1 conceptual"></div> <h5 class="decalaration">Declaration</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public override Task&lt;IFtpResponse? &gt; Process(FtpCommand command, CancellationToken cancellationToken)</code></pre> </div> <h5 class="parameters">Parameters</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="FubarDev.FtpServer.FtpCommand.html">FtpCommand</a></td> <td><span class="parametername">command</span></td> <td></td> </tr> <tr> <td><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.threading.cancellationtoken">CancellationToken</a></td> <td><span class="parametername">cancellationToken</span></td> <td></td> </tr> </tbody> </table> <h5 class="returns">Returns</h5> <table class="table table-bordered table-striped table-condensed"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.task-1">Task</a>&lt;<a class="xref" href="https://docs.microsoft.com/dotnet/api/system.nullable-1">Nullable</a>&lt;<a class="xref" href="FubarDev.FtpServer.IFtpResponse.html">IFtpResponse</a>&gt;&gt;</td> <td></td> </tr> </tbody> </table> <h5 class="overrides">Overrides</h5> <div><a class="xref" href="FubarDev.FtpServer.CommandHandlers.FtpCommandHandler.html#FubarDev_FtpServer_CommandHandlers_FtpCommandHandler_Process_FubarDev_FtpServer_FtpCommand_System_Threading_CancellationToken_">FtpCommandHandler.Process(FtpCommand, CancellationToken)</a></div> <h3 id="implements">Implements</h3> <div> <a class="xref" href="FubarDev.FtpServer.IFtpCommandHandler.html">IFtpCommandHandler</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.IFtpCommandBase.html">IFtpCommandBase</a> </div> <div> <a class="xref" href="FubarDev.FtpServer.IFeatureHost.html">IFeatureHost</a> </div> </article> </div> <div class="hidden-sm col-md-2" role="complementary"> <div class="sideaffix"> <div class="contribution"> <ul class="nav"> <li> <a href="https://github.com/FubarDevelopment/FtpServer/new/master/docfx_project/apidoc/new?filename=FubarDev_FtpServer_CommandHandlers_ListCommandHandler.md&amp;value=---%0Auid%3A%20FubarDev.FtpServer.CommandHandlers.ListCommandHandler%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A" class="contribution-link">Improve this Doc</a> </li> <li> <a href="https://github.com/FubarDevelopment/FtpServer/blob/master/src/FubarDev.FtpServer.Commands/CommandHandlers/ListCommandHandler.cs/#L32" class="contribution-link">View Source</a> </li> </ul> </div> <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix"> <!-- <p><a class="back-to-top" href="#top">Back to top</a><p> --> </nav> </div> </div> </div> </div> <footer> <div class="grad-bottom"></div> <div class="footer"> <div class="container"> <span class="pull-right"> <a href="#top">Back to top</a> </span> <table border='0'><tr><td><span>Copyright © 2018 Fubar Development Junker<br>Generated by <strong>DocFX</strong></span></td><td><a rel='license' href='http://creativecommons.org/licenses/by-sa/4.0/'><img alt='Creative Commons License' style='border-width:0' src='https://i.creativecommons.org/l/by-sa/4.0/88x31.png'></a><br><span xmlns:dct='http://purl.org/dc/terms/' property='dct:title'>FluentMigrator Documentation</span> by <a xmlns:cc='http://creativecommons.org/ns#' href='https://fluentmigrator.github.io' property='cc:attributionName' rel='cc:attributionURL'>FluentMigrator Project</a> is licensed under a <a rel='license' href='http://creativecommons.org/licenses/by-sa/4.0/'>Creative Commons Attribution-ShareAlike 4.0 International License</a>.</td></tr></table> </div> </div> </footer> </div> <script type="text/javascript" src="../styles/docfx.vendor.js"></script> <script type="text/javascript" src="../styles/docfx.js"></script> <script type="text/javascript" src="../styles/main.js"></script> </body> </html>
{ "content_hash": "770182417ab55604debc0ccac62a92d5", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 785, "avg_line_length": 57.79233226837061, "alnum_prop": 0.6860522969760628, "repo_name": "FubarDevelopment/FtpServer", "id": "ae3c8d562752d70dabb1aca4eadd8e49d1668a52", "size": "18092", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/FubarDev.FtpServer.CommandHandlers.ListCommandHandler.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1108064" } ], "symlink_target": "" }
layout: page title: 01 -- First lecture time: 2.5 hours --- # Preamble This first lecture is divided in 3 parts. First, we will review the motivations of why learning R? Second, we will go through a first session with R to get used to the syntax and learn how to generate a simple plot. Third, we will explore vectors as they are at the heart on how objects are stored in R's memory. ------ # Motivation - Why learn R? ## R is not a GUI, and that's a good thing The learning curve might be steeper than with other software, but with R, you can save all the steps you used to go from the data to the results. So, if you want to redo your analysis because you collected more data, you don't have to remember which button you clicked in which order to obtain your results, you just have to run your script again. Working with scripts makes the steps you used in your analysis clear, and the code you write can be inspected by someone else who can give you feedback and spot mistakes. Working with scripts forces you to have deeper understanding of what you are doing, and facilitates your learning and comprehension of the methods you use. ## R code is great for reproducibility Reproducibility is when someone else (including your future self) can obtain the same results from the same dataset when using the same analysis. R integrates with other tools to generate manuscripts from your code. If you collect more data, or fix a mistake in your dataset, the figures and the statistical tests in your manuscript are updated automatically. An increasing number of journals and funding agencies expect analyses to be reproducible, knowing R will give you an edge with these requirements. ## R is interdisciplinary and extensible With 6,000+ packages that can be installed to extend its capabilities, R provides a framework that allows you to combine analyses across many scientific disciplines to best suit the analyses you want to use on your data. For instance, R has packages for image analysis, GIS, time series, population genetics, and a lot more. ## R works on data of all shapes and size The skills you learn with R scale easily with the size of your dataset. Whether your dataset has hundreds or millions of lines, it won't make much difference to you. R is designed for data analysis. It comes with special data structures and data types that make handling of missing data and statistical factors convenient. R can connect to spreadsheets, databases, and many other data formats, on your computer or on the web. ## R produces high-quality graphics The plotting functionalities in R are endless, and allow you to adjust any aspect of your graph to convey most effectively the message from your data. ## R has a large community Thousands of people use R daily. Many of them are willing to help you through mailing lists and stack overflow. ## Not only R is free, but it is also open-source and cross-platform Anyone can inspect the source code to see how R works. Because of this transparency, there is less chance for mistakes, and if you (or someone else) find some, you can report and fix bugs. ----- # A first R session * Start RStudio * Under the `File` menu, click on `New project`, choose `New directory`, then `Empty project` * Enter a name for this new folder, and choose a convenient location for it. This will be your **working directory** for the rest of the day (e.g., `~/R-class/week1`) * Click on "Create project" * Under the `Files` tab on the right of the screen, click on `New Folder` and create a folder named `data` within your newly created working directory. (e.g., `~/R-class/week1/data`) * Create a new R script (File > New File > R script) and save it in your working directory (e.g. `my-first-script.R`) ## Good practices There are two main ways of interacting with R: using the console or by using script files (plain text files that contain your code). The recommended approach when working on a data analysis project is dubbed "the source code is real". The objects you are creating should be seen as disposable as they are the direct realization of your code. Every object in your analysis can be recreated from your code, and all steps are documented. Therefore, it is best to enter as little commands as possible in the R console. Instead, all code should be written in script files, and evaluated from there. The R console should be used to inspect objects, test a function or get help. With this approach, the `.Rhistory` file automatically created during your session should not be very useful. Similarly, you should separate the original data (raw data) from intermediate datasets that you may create for the need of a particular analysis. For instance, you may want to create a `data/` directory within your working directory that stores the raw data, and have a `data_output/` directory for intermediate datasets and a `figure_output/` directory for the plots you will generate. ## Creating objects Let's start by creating a simple object: ```r x <- 10 x ``` We assigned to `x` the number 10. `<-` is the assignment operator. Assigns values on the right to objects on the left. Mostly similar to `=` but not always. Learn to use `<-` as it is good programming practice. Using `=` in place of `<-` can lead to issues down the line. `=` should only be used to specify the values of arguments in functions for instance `read.csv(file="data/some_data.csv")`. We can now manipulate this value to do things with it. For instance: ```r x * 2 x + 5 x + x ``` or we can create new objects using `x`: ```r y <- x + x + 5 ``` Let's try something different: ```r x <- c(2, 4, 6) x ``` Two things: - we overwrote the content of `x` - `x` now contains 3 elements Using the `[]`, we can access individual elements of this object: ```r x[1] x[2] x[3] ``` --- ### Challenge What is the content of this vector? ```r q <- c(x, x, 5) ``` --- We can also use these objects with functions, for instance to compute the mean and the standard deviation: ```r mean(x) sd(d) ``` This is useful to print the value of the mean or the standard deviation, but we can also save these values in their own variables: ```r mean_x <- mean(x) mean_x ``` The function `ls()` returns the objects that are currently in the memory of your session. The function `data()` allows you to load into memory datasets that are provided as examples with R (or some packages). Let's load the `Nile` dataset that provides the annual flow of the river Nile between 1871 and 1970. ```r data(Nile) ``` Using `ls()` shows you that the function `data()` made the variable `Nile` available to you. Let's make an histogram of the values of the flows: ```r hist(Nile) ``` --- ### Challenge The following: `abline(v=100, col="red")` would draw a vertical line on an existing plot at the value 100 colored in red. How would you add such a line to our histogram to show where the mean falls in this distribution? --- We can now save this plot in its own file: ```r pdf(file="nile_flow.pdf") hist(Nile) abline(v=mean(Nile), col="red") dev.off() ``` ------ # Vectors Vectors are at the heart of how data are stored into R's memory. Almost everything in R is stored as a vector. When we typed `x <- 10` we created a vector of length 1. When we typed `x <- c(2, 4, 6)` we created a vector of length 3. These vectors are of class `numeric`. Vectors can be of 6 different classes (we'll mostly work with 4). ### The different "classes" of vector * `"numeric"` is the general class for vectors that hold numbers (e.g., `c(1, 5, 10)`) * `"integer"` is the class for vectors for integers. To differentiate them from `numeric` we must add an `L` afterwards (e.g., `c(1L, 2L, 5L)`) * `"character"` is the general class for vectors that hold text strings (e.g., `c("blue", "red", "black")`) * `"logical"` for holding `TRUE` and `FALSE` (boolean data type) The other types of vectors are `"complex"` (for complex numbers) and `"raw"` a special internal type that is not of use for the majority of users. ### How to create vectors? The easiest way is to create them directly as we have done before: ```r x <- c(5, 10, 15, 20, 25) class(x) ``` However, there will be cases when we want to create empty vectors that will be later populated with values. ```r x <- numeric(5) x ``` Similarly, we can create empty vectors of class `"character"` using `character(5)`, or of class `"logical"`: `logical(5)`, etc. ### Naming the elements of a vector ```r fav_colors <- c("red", "blue", "green", "yellow") names(fav_colors) names(fav_colors) <- c("John", "Lucy", "Greg", "Sarah") fav_colors names(fav_colors) unname(fav_colors) ``` ### How to access elements of a vector? They can be accessed by their indices: ```r fav_colors[2] fav_colors[2:4] ``` repeatitions are allowed: ```r fav_colors[c(2,3,2,4,1,2)] ``` or if the vector is named, it can be accessed by the names of the elements: ```r fav_colors["John"] ``` --- ### Challenges * How to access the content of the vector for "Lucy", "Sarah" and "John" (in this order)? * How to get the name of the second person? --- ### How to update/replace the value of a vector? ```r x[4] <- 22 ``` ```r fav_colors["Sarah"] <- "turquoise" ``` ### How to add elements to a vector? ```r x <- c(5, 10, 15, 20) x <- c(x, 25) # adding at the end x <- c(0, x) # adding at the beginning x ``` With named vectors: ```r fav_colors c(fav_colors, "purple") fav_colors <- c(fav_colors, "Tracy" = "purple") ``` Notes: * here is the case where using the `=` is OK/needed * pay attention to where the quotes are --- ### Challenge * If we add another element to our vector: ```r fav_color <- c(fav_colors, "black") ``` how to use the function `names()` to assign the name "Ana" to this last element? --- ### How to remove elements from a vector? ```r x[-5] x[-c(1, 3, 5)] ``` but this `fav_colors[-c("Tracy")]` does not work. We need to use the function `match()`: ```r fav_colors[-match("Tracy", names(fav_colors))] ``` The function `match()` looks for the position of the **first exact match** within another vector. ### Sequences `:` is a special function that creates numeric vectors of integer in increasing or decreasing order, test `1:10` and `10:1` for instance. The function `seq()` (for __seq__uence) can be used to create more complex patterns: ```r seq(1, 10, by=2) ``` ``` ## [1] 1 3 5 7 9 ``` ```r seq(5, 10, length.out=3) ``` ``` ## [1] 5.0 7.5 10.0 ``` ```r seq(50, by=5, length.out=10) ``` ``` ## [1] 50 55 60 65 70 75 80 85 90 95 ``` ```r seq(1, 8, by=3) # sequence stops to stay below upper limit ``` ``` ## [1] 1 4 7 ``` ```r seq(1.1, 2, length.out=10) ``` ``` ## [1] 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 ``` ### Repeating ```r x <- rep(8, 4) x rep(1:3, 3) ``` ### Operations on vectors ```r x <- c(5, 10, 15) x + 10 x + c(10, 15, 20) x * 10 x * c(2, 4, 3) ``` Note that operations on vectors are elementwise. ### Recycling R allows you to do operations on vectors of different lengths. The shorter vector will be "recycled" (~ repeated) to match the length of the longer one: ```r x <- c(5, 10, 15) x + c(2, 4, 6, 8, 10, 12) # no warning when it's a multiple x + c(2, 4, 6, 8, 10, 12, 14) # warning ``` ### Boolean operations and Filtering ```r u <- c(1, 4, 2, 5, 6, 3, 7) u < 3 u[u < 3] u[u < 3 | u >= 4] u[u > 5 & u < 1 ] ## nothing matches this condition u[u > 5 & u < 8] ``` With character strings: ```r fav_colors <- c("John" = "red", "Lucy" = "blue", "Greg" = "green", "Sarah" = "yellow", "Tracy" = "purple") fav_colors == "blue" fav_colors[fav_colors == "blue"] which(fav_colors == "blue") names(fav_colors)[which(fav_colors == "blue")] fav_colors == "green" | fav_colors == "blue" | fav_colors == "yellow" fav_colors %in% c("green", "blue", "yellow") fav_colors[fav_colors %in% c("green", "blue", "yellow")] ```
{ "content_hash": "8792e0364c8eead79ca3f5e65e56eb59", "timestamp": "", "source": "github", "line_count": 502, "max_line_length": 81, "avg_line_length": 23.743027888446214, "alnum_prop": 0.6959476466146489, "repo_name": "r-bio/r-bio.github.io", "id": "90f84b3457867f2a2e293d830b46be09774f910a", "size": "11923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "01-intro-R.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22032" }, { "name": "HTML", "bytes": "54496" } ], "symlink_target": "" }
package com.hazelcast.internal.metrics; import com.hazelcast.internal.metrics.collectors.MetricsCollector; import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * The MetricsRegistry is a registry of various Hazelcast/JVM internal * information to help out with debugging, performance or stability issues. * Each HazelcastInstance has one local MetricsRegistry instance. * <p> * A MetricsRegistry can contain many {@link Probe} instances. A probe is * registered under a name, and can be read by creating a {@link Gauge}, see * {@link #newLongGauge(String)}. * <p> * The metrics registry doesn't interpret the name in any way, it is treated as * is. For example, {@code [tag1=foo,tag2=bar]} and {@code [tag2=bar,tag1=foo]} * will be treated as two different metrics even though they have same tags and * values. Clients making use of the metrics can use the tags. For backwards * compatibility, the name does not have to be enclosed in {@code []}. * * <h3>Duplicate Registrations</h3> The MetricsRegistry is lenient regarding * duplicate registrations of probes. So if there is an existing probe for a * given name and a new probe with the same name is registered, the old probe * is overwritten. The reason to be lenient is that the MetricRegistry should * not throw exception. Of course, there will be a log warning. * * <h3>Performance</h3> The MetricRegistry is designed for low overhead probes. * So once a probe is registered, there is no overhead for the provider of the * probe data. The provider could have for example a volatile long field and * increment this using a lazy-set. As long as the MetricRegistry can * frequently read out this field, the MetricRegistry is perfectly happy with * such low overhead probes. So it is up to the provider of the probe how much * overhead is required. * * <h3>Static and dynamic metrics</h3> The MetricRegistry collects metrics * from static and dynamic metrics sources, these metrics are referred to as * static and dynamic metrics. * <p/> * The static metrics are the ones that are registered once and cannot be * removed during the lifetime of the given Hazelcast instance. These are * typically system metrics either Hazelcast or JVM/OS ones. * <p/> * The dynamic metrics are collected dynamically during each collection cycle * via the {@link DynamicMetricsProvider} interface. Typical examples for the * dynamic metrics are the metrics exposed by the distributed data structures * that can be created and destroyed dynamically. * <p/> * The MetricsRegistry doesn't cache the dynamic metrics, therefore the dynamic * metrics don't increase the heap live set. In exchange, they may allocate * during the collection cycle. It is therefore the responsibility of the * dynamic metric sources to keep allocation low. */ public interface MetricsRegistry { /** * Returns the minimum ProbeLevel this MetricsRegistry is recording. */ ProbeLevel minimumLevel(); /** * Creates a {@link LongGauge} for a given metric name. * * If no gauge exists for the name, it will be created but no probe is set. * The reason to do so is that you don't want to depend on the order of * registration. Perhaps you want to read out e.g. operations.count gauge, * but the OperationService has not started yet and the metric is not yet * available. Another cause is that perhaps a probe is not registered, but * the metric is created. For example when experimenting with a new * implementation, e.g. a new OperationService implementation, that doesn't * provide the operation.count probe. * * Multiple calls with the same name return different Gauge instances; so * the Gauge instance is not cached. This is done to prevent memory leaks. * * @param name the name of the metric. * @return the created LongGauge. * @throws NullPointerException if name is null. */ LongGauge newLongGauge(String name); /** * Creates a {@link DoubleGauge} for a given metric name. * * @param name name of the metric * @return the create DoubleGauge * @throws NullPointerException if name is null. * @see #newLongGauge(String) */ DoubleGauge newDoubleGauge(String name); /** * Gets a set of all current probe names. * * The returned set is immutable and is a snapshot of the names. So the * reader gets a stable view on the names. * * @return set of all current names. */ Set<String> getNames(); /** * Scans the source object for any fields/methods that have been annotated * with {@link Probe} annotation, and registers these fields/methods as * static probe instances. * <p> * If a probe is called 'queueSize' and the namePrefix is 'operations', * then the name of the probe instance is 'operations.queueSize'. * <p> * If a probe with the same name already exists, then the probe is replaced. * <p> * If an object has no @Probe annotations, the call is ignored. * * @param source the object to scan. * @param namePrefix the name prefix. * @throws NullPointerException if namePrefix or source is null. * @throws IllegalArgumentException if the source contains a Probe * annotation on a field/method of unsupported type. */ <S> void registerStaticMetrics(S source, String namePrefix); /** * Scans the source object for any fields/methods that have been annotated * with {@link Probe} annotation, and registers these fields/methods as * static probe instances. * <p> * If a probe is called 'queueSize' and the namePrefix is 'operations', * then the name of the probe instance is 'operations.queueSize'. * <p> * If a probe with the same name already exists, then the probe is replaced. * <p> * If an object has no @Probe annotations, the call is ignored. * * @param descriptor the metric descriptor. * @param source the object to scan. * @throws NullPointerException if namePrefix or source is null. * @throws IllegalArgumentException if the source contains a Probe * annotation on a field/method of unsupported type. */ <S> void registerStaticMetrics(MetricDescriptor descriptor, S source); /** * Registers dynamic metrics sources that collect metrics in each metrics * collection cycle. * * @param metricsProvider The object that provides dynamic metrics */ void registerDynamicMetricsProvider(DynamicMetricsProvider metricsProvider); /** * Deregisters the given dynamic metrics provider. The metrics collection * cycles after this call will not call the given metrics provider until * it is registered again. * * @param metricsProvider The metrics provider to deregister */ void deregisterDynamicMetricsProvider(DynamicMetricsProvider metricsProvider); /** * Registers a probe. * * If a probe for the given name exists, it will be overwritten. * * @param source the object that the probe function to be used with * @param name the name of the probe * @param level the ProbeLevel * @param unit the unit * @param function the probe function * @throws NullPointerException if source, name, level or probe is null. */ <S> void registerStaticProbe(S source, MetricDescriptor descriptor, String name, ProbeLevel level, ProbeUnit unit, ProbeFunction function); /** * Registers a probe. * * If a probe for the given name exists, it will be overwritten. * * @param source the object that the probe function to be used with * @param name the name of the probe. * @param level the ProbeLevel * @param function the probe * @throws NullPointerException if source, name, level or probe is null. */ <S> void registerStaticProbe(S source, String name, ProbeLevel level, LongProbeFunction<S> function); /** * Registers a probe. * * If a probe for the given name exists, it will be overwritten. * * @param source the object that the probe function to be used with * @param name the name of the probe. * @param level the ProbeLevel * @param unit the unit * @param probe the probe * @throws NullPointerException if source, name, level or probe is null. */ <S> void registerStaticProbe(S source, String name, ProbeLevel level, ProbeUnit unit, LongProbeFunction<S> probe); /** * Registers a probe. * * If a probe for the given name exists, it will be overwritten. * * @param source the object that the probe function to be used with * @param name the name of the probe. * @param level the ProbeLevel * @param unit the unit * @param probe the probe * @throws NullPointerException if source, name, level or probe is null. */ <S> void registerStaticProbe(S source, MetricDescriptor descriptor, String name, ProbeLevel level, ProbeUnit unit, LongProbeFunction<S> probe); /** * Registers a probe. * * If a probe for the given name exists, it will be overwritten. * * @param source the object that the probe function to be used with * @param name the name of the probe * @param level the ProbeLevel * @param probe the probe * @throws NullPointerException if source, name, level or probe is null. */ <S> void registerStaticProbe(S source, String name, ProbeLevel level, DoubleProbeFunction<S> probe); /** * Registers a probe. * * If a probe for the given name exists, it will be overwritten. * * @param source the object that the probe function to be used with * @param name the name of the probe * @param level the ProbeLevel * @param unit the unit * @param probe the probe * @throws NullPointerException if source, name, level or probe is null. */ <S> void registerStaticProbe(S source, String name, ProbeLevel level, ProbeUnit unit, DoubleProbeFunction<S> probe); /** * Registers a probe. * * If a probe for the given name exists, it will be overwritten. * * @param source the object that the probe function to be used with * @param name the name of the probe * @param level the ProbeLevel * @param unit the unit * @param probe the probe * @throws NullPointerException if source, name, level or probe is null. */ <S> void registerStaticProbe(S source, MetricDescriptor descriptor, String name, ProbeLevel level, ProbeUnit unit, DoubleProbeFunction<S> probe); /** * Schedules a publisher to be executed at a fixed rate. * * Probably this method will be removed in the future, but we need a mechanism * for complex gauges that require some calculation to provide their values. * * @param publisher the published task that needs to be executed * @param period the time between executions * @param timeUnit the time unit for period * @param probeLevel the ProbeLevel publisher it publishing on. This is needed to prevent scheduling * publishers if their probe level isn't sufficient. * @throws NullPointerException if publisher or timeUnit is null. * @return the ScheduledFuture that can be used to cancel the task, or null if nothing got scheduled. */ ScheduledFuture<?> scheduleAtFixedRate(Runnable publisher, long period, TimeUnit timeUnit, ProbeLevel probeLevel); /** * Collects the content of the MetricsRegistry. * * @param collector the collector that consumes the metrics collected * @throws NullPointerException if collector is null. */ void collect(MetricsCollector collector); /** * For each object that implements {@link StaticMetricsProvider} the * {@link StaticMetricsProvider#provideStaticMetrics(MetricsRegistry)} is called. * * @param providers the array of objects to initialize. */ void provideMetrics(Object... providers); /** * Creates a new {@link MetricDescriptor}. */ MetricDescriptor newMetricDescriptor(); }
{ "content_hash": "99ca3a65807f405b99181c4eb17bb154", "timestamp": "", "source": "github", "line_count": 299, "max_line_length": 120, "avg_line_length": 41.80936454849498, "alnum_prop": 0.6851451883849292, "repo_name": "emre-aydin/hazelcast", "id": "89d14558f2062a2bfcf17a10666f70300c7f3415", "size": "13126", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/internal/metrics/MetricsRegistry.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1261" }, { "name": "C", "bytes": "353" }, { "name": "Java", "bytes": "39634758" }, { "name": "Shell", "bytes": "29479" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Overview The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using a simple programming model. Hadoop is designed to scale from a few servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, Hadoop can detect and handle failures at the application layer. This provides a highly-available service on top of a cluster of machines, each of which may be prone to failure. Apache Spark is a fast and general engine for large-scale data processing. Learn more at [spark.apache.org][]. This bundle provides a complete deployment of Hadoop and Spark components from [Apache Bigtop][] that performs distributed data processing at scale. Ganglia and rsyslog applications are also provided to monitor cluster health and syslog activity. [spark.apache.org]: http://spark.apache.org/ [Apache Bigtop]: http://bigtop.apache.org/ ## Bundle Composition The applications that comprise this bundle are spread across 5 units as follows: * NameNode v2.7.3 * ResourceManager v2.7.3 * Colocated on the NameNode unit * Slave (DataNode and NodeManager) v2.7.3 * 3 separate units * Spark (Driver in yarn-client mode) v2.1.0 * Client (Hadoop endpoint) * Colocated on the Spark unit * Plugin (Facilitates communication with the Hadoop cluster) * Colocated on the Spark/Client unit * Ganglia (Web interface for monitoring cluster metrics) * Colocated on the Spark/Client unit * Rsyslog (Aggregate cluster syslog events in a single location) * Colocated on the Spark/Client unit Deploying this bundle results in a fully configured Apache Bigtop cluster on any supported cloud, which can be scaled to meet workload demands. # Deploying This charm requires Juju 2.0 or greater. If Juju is not yet set up, please follow the [getting-started][] instructions prior to deploying this bundle. > **Note**: This bundle requires hardware resources that may exceed limits of Free-tier or Trial accounts on some clouds. To deploy to these environments, modify a local copy of [bundle.yaml][] to set `services: 'X': num_units: 1` and `machines: 'X': constraints: mem=3G` as needed to satisfy account limits. Deploy this bundle from the Juju charm store with the `juju deploy` command: juju deploy hadoop-spark Alternatively, deploy a locally modified `bundle.yaml` with: juju deploy /path/to/bundle.yaml The charms in this bundle can also be built from their source layers in the [Bigtop charm repository][]. See the [Bigtop charm README][] for instructions on building and deploying these charms locally. ## Network-Restricted Environments Charms can be deployed in environments with limited network access. To deploy in this environment, configure a Juju model with appropriate proxy and/or mirror options. See [Configuring Models][] for more information. [getting-started]: https://jujucharms.com/docs/stable/getting-started [bundle.yaml]: https://github.com/apache/bigtop/blob/master/bigtop-deploy/juju/hadoop-spark/bundle.yaml [Bigtop charm repository]: https://github.com/apache/bigtop/tree/master/bigtop-packages/src/charm [Bigtop charm README]: https://github.com/apache/bigtop/blob/master/bigtop-packages/src/charm/README.md [Configuring Models]: https://jujucharms.com/docs/stable/models-config # Verifying ## Status The applications that make up this bundle provide status messages to indicate when they are ready: juju status This is particularly useful when combined with `watch` to track the on-going progress of the deployment: watch -n 2 juju status The message for each unit will provide information about that unit's state. Once they all indicate that they are ready, perform application smoke tests to verify that the bundle is working as expected. ## Smoke Test The charms for each core component (namenode, resourcemanager, slave, and spark) provide a `smoke-test` action that can be used to verify the application is functioning as expected. Note that the 'slave' component runs extensive tests provided by Apache Bigtop and may take up to 30 minutes to complete. Run the smoke-test actions as follows: juju run-action namenode/0 smoke-test juju run-action resourcemanager/0 smoke-test juju run-action slave/0 smoke-test juju run-action spark/0 smoke-test Watch the progress of the smoke test actions with: watch -n 2 juju show-action-status Eventually, all of the actions should settle to `status: completed`. If any report `status: failed`, that application is not working as expected. Get more information about a specific smoke test with: juju show-action-output <action-id> ## Utilities Applications in this bundle include command line and web utilities that can be used to verify information about the cluster. From the command line, show the HDFS dfsadmin report and view the current list of YARN NodeManager units with the following: juju run --application namenode "su hdfs -c 'hdfs dfsadmin -report'" juju run --application resourcemanager "su yarn -c 'yarn node -list'" To access the HDFS web console, find the `Public address` of the namenode application and expose it: juju status namenode juju expose namenode The web interface will be available at the following URL: http://NAMENODE_PUBLIC_IP:50070 Similarly, to access the Resource Manager web consoles, find the `Public address` of the resourcemanager application and expose it: juju status resourcemanager juju expose resourcemanager The YARN and Job History web interfaces will be available at the following URLs: http://RESOURCEMANAGER_PUBLIC_IP:8088 http://RESOURCEMANAGER_PUBLIC_IP:19888 Finally, to access the Spark web console, find the `Public address` of the spark application and expose it: juju status spark juju expose spark The web interface will be available at the following URL: http://SPARK_PUBLIC_IP:8080 # Monitoring This bundle includes Ganglia for system-level monitoring of the namenode, resourcemanager, and slave units. Metrics are sent to a centralized ganglia unit for easy viewing in a browser. To view the ganglia web interface, find the `Public address` of the Ganglia application and expose it: juju status ganglia juju expose ganglia The web interface will be available at: http://GANGLIA_PUBLIC_IP/ganglia # Logging This bundle includes rsyslog to collect syslog data from the namenode, resourcemanager, slave, and spark units. These logs are sent to a centralized rsyslog unit for easy syslog analysis. One method of viewing this log data is to simply cat syslog from the rsyslog unit: juju run --unit rsyslog/0 'sudo cat /var/log/syslog' Logs may also be forwarded to an external rsyslog processing service. See the *Forwarding logs to a system outside of the Juju environment* section of the [rsyslog README](https://jujucharms.com/rsyslog/) for more information. # Benchmarking The `resourcemanager` charm in this bundle provide several benchmarks to gauge the performance of the Hadoop cluster. Each benchmark is an action that can be run with `juju run-action`: $ juju actions resourcemanager ACTION DESCRIPTION mrbench Mapreduce benchmark for small jobs nnbench Load test the NameNode hardware and configuration smoke-test Run an Apache Bigtop smoke test. teragen Generate data with teragen terasort Runs teragen to generate sample data, and then runs terasort to sort that data testdfsio DFS IO Testing $ juju run-action resourcemanager/0 nnbench Action queued with id: 55887b40-116c-4020-8b35-1e28a54cc622 $ juju show-action-output 55887b40-116c-4020-8b35-1e28a54cc622 results: meta: composite: direction: asc units: secs value: "128" start: 2016-02-04T14:55:39Z stop: 2016-02-04T14:57:47Z results: raw: '{"BAD_ID": "0", "FILE: Number of read operations": "0", "Reduce input groups": "8", "Reduce input records": "95", "Map output bytes": "1823", "Map input records": "12", "Combine input records": "0", "HDFS: Number of bytes read": "18635", "FILE: Number of bytes written": "32999982", "HDFS: Number of write operations": "330", "Combine output records": "0", "Total committed heap usage (bytes)": "3144749056", "Bytes Written": "164", "WRONG_LENGTH": "0", "Failed Shuffles": "0", "FILE: Number of bytes read": "27879457", "WRONG_MAP": "0", "Spilled Records": "190", "Merged Map outputs": "72", "HDFS: Number of large read operations": "0", "Reduce shuffle bytes": "2445", "FILE: Number of large read operations": "0", "Map output materialized bytes": "2445", "IO_ERROR": "0", "CONNECTION": "0", "HDFS: Number of read operations": "567", "Map output records": "95", "Reduce output records": "8", "WRONG_REDUCE": "0", "HDFS: Number of bytes written": "27412", "GC time elapsed (ms)": "603", "Input split bytes": "1610", "Shuffled Maps ": "72", "FILE: Number of write operations": "0", "Bytes Read": "1490"}' status: completed timing: completed: 2016-02-04 14:57:48 +0000 UTC enqueued: 2016-02-04 14:55:14 +0000 UTC started: 2016-02-04 14:55:27 +0000 UTC The `spark` charm in this bundle provides benchmarks to gauge the performance of the Spark/YARN cluster. Each benchmark is an action that can be run with `juju run-action`: $ juju actions spark ... pagerank Calculate PageRank for a sample data set sparkpi Calculate Pi ... $ juju run-action spark/0 pagerank Action queued with id: 339cec1f-e903-4ee7-85ca-876fb0c3d28e $ juju show-action-output 339cec1f-e903-4ee7-85ca-876fb0c3d28e results: meta: composite: direction: asc units: secs value: "83" start: 2017-04-12T23:22:38Z stop: 2017-04-12T23:24:01Z output: '{''status'': ''completed''}' status: completed timing: completed: 2017-04-12 23:24:02 +0000 UTC enqueued: 2017-04-12 23:22:36 +0000 UTC started: 2017-04-12 23:22:37 +0000 UTC # Scaling By default, three Hadoop slave units are deployed. Scaling these is as simple as adding more units. To add one unit: juju add-unit slave Multiple units may be added at once. For example, add four more slave units: juju add-unit -n4 slave # Issues Apache Bigtop tracks issues using JIRA (Apache account required). File an issue for this bundle at: https://issues.apache.org/jira/secure/CreateIssue!default.jspa Ensure `Bigtop` is selected as the project. Typically, bundle issues are filed in the `deployment` component with the latest stable release selected as the affected version. Any uncertain fields may be left blank. # Contact Information - <bigdata@lists.ubuntu.com> # Resources - [Apache Bigtop home page](http://bigtop.apache.org/) - [Apache Bigtop issue tracking](http://bigtop.apache.org/issue-tracking.html) - [Apache Bigtop mailing lists](http://bigtop.apache.org/mail-lists.html) - [Juju Big Data](https://jujucharms.com/big-data) - [Juju Bigtop charms](https://jujucharms.com/q/bigtop) - [Juju mailing list](https://lists.ubuntu.com/mailman/listinfo/juju)
{ "content_hash": "4d30bb8292236f5b2ae5e6bd5482c2b1", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 103, "avg_line_length": 37.78086419753087, "alnum_prop": 0.7331100400294094, "repo_name": "arenadata/bigtop", "id": "7849c098c98e75a588c94f7e47eb185c2ec10c01", "size": "12241", "binary": false, "copies": "1", "ref": "refs/heads/branch-adh-2.0", "path": "bigtop-deploy/juju/hadoop-spark/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4822" }, { "name": "Dockerfile", "bytes": "22697" }, { "name": "Groovy", "bytes": "599668" }, { "name": "HiveQL", "bytes": "1658" }, { "name": "Java", "bytes": "760573" }, { "name": "Makefile", "bytes": "66241" }, { "name": "PigLatin", "bytes": "15615" }, { "name": "Puppet", "bytes": "180353" }, { "name": "Python", "bytes": "283812" }, { "name": "Roff", "bytes": "49282" }, { "name": "Ruby", "bytes": "19823" }, { "name": "Scala", "bytes": "85334" }, { "name": "Shell", "bytes": "689333" }, { "name": "TSQL", "bytes": "13064" }, { "name": "XSLT", "bytes": "1323" } ], "symlink_target": "" }
cd api MAVEN_ARGS="-DskipTests -Djavac.src.version=15 -Djavac.target.version=15" $MVN package org.apache.maven.plugins:maven-shade-plugin:3.2.4:shade $MAVEN_ARGS CURRENT_VERSION=$($MVN org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate \ -Dexpression=project.version -q -DforceStdout) cp "target/jakarta.mail-api-$CURRENT_VERSION.jar" $OUT/jakarta-mail-api.jar ALL_JARS="jakarta-mail-api.jar" # The classpath at build-time includes the project jars in $OUT as well as the # Jazzer API. BUILD_CLASSPATH=$(echo $ALL_JARS | xargs printf -- "$OUT/%s:"):$JAZZER_API_PATH # All .jar and .class files lie in the same directory as the fuzzer at runtime. RUNTIME_CLASSPATH=$(echo $ALL_JARS | xargs printf -- "\$this_dir/%s:"):\$this_dir for fuzzer in $(find $SRC -name '*Fuzzer.java'); do fuzzer_basename=$(basename -s .java $fuzzer) javac -cp $BUILD_CLASSPATH $fuzzer cp $SRC/$fuzzer_basename.class $OUT/ # Create an execution wrapper that executes Jazzer with the correct arguments. echo "#!/bin/bash # LLVMFuzzerTestOneInput for fuzzer detection. this_dir=\$(dirname \"\$0\") if [[ \"\$@\" =~ (^| )-runs=[0-9]+($| ) ]]; then mem_settings='-Xmx1900m:-Xss900k' else mem_settings='-Xmx2048m:-Xss1024k' fi LD_LIBRARY_PATH=\"$JVM_LD_LIBRARY_PATH\":\$this_dir \ \$this_dir/jazzer_driver --agent_path=\$this_dir/jazzer_agent_deploy.jar \ --cp=$RUNTIME_CLASSPATH \ --target_class=$fuzzer_basename \ --jvm_args=\"\$mem_settings\" \ \$@" > $OUT/$fuzzer_basename chmod u+x $OUT/$fuzzer_basename done
{ "content_hash": "2b5563241e0a328055377920502775e3", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 82, "avg_line_length": 38.794871794871796, "alnum_prop": 0.7058823529411765, "repo_name": "google/oss-fuzz", "id": "ffc879a5ffffccafe3e5e41f846b67b70efecced", "size": "2188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/jakarta-mail-api/build.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "559317" }, { "name": "C++", "bytes": "420884" }, { "name": "CMake", "bytes": "1635" }, { "name": "Dockerfile", "bytes": "899156" }, { "name": "Go", "bytes": "78124" }, { "name": "HTML", "bytes": "13787" }, { "name": "Java", "bytes": "607666" }, { "name": "JavaScript", "bytes": "2508" }, { "name": "Makefile", "bytes": "15308" }, { "name": "Python", "bytes": "1002953" }, { "name": "Ruby", "bytes": "1827" }, { "name": "Rust", "bytes": "9192" }, { "name": "Shell", "bytes": "1433213" }, { "name": "Starlark", "bytes": "5471" }, { "name": "Swift", "bytes": "1363" } ], "symlink_target": "" }
layout: category section-type: category title: C --- ## Category
{ "content_hash": "a01335f81b4d8a570b3e451946771eba", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 22, "avg_line_length": 12.8, "alnum_prop": 0.734375, "repo_name": "TyeolRik/TyeolRik.github.io", "id": "8930742df4d0060e61ad6b4a88dad566c67a500b", "size": "68", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "categories/c.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "63449" }, { "name": "JavaScript", "bytes": "54977" }, { "name": "Ruby", "bytes": "8150" }, { "name": "SCSS", "bytes": "15559" }, { "name": "Shell", "bytes": "462" } ], "symlink_target": "" }
package com.g10.ssm.service.testdatabase; import java.util.List; import com.g10.ssm.po.testdatabase.Strategy; public interface StrategyService { public List<Strategy> queryStrategy() throws Exception; public int updateStrategy(Strategy strategy) throws Exception; public int saveStrategy(Strategy strategy) throws Exception; public int deleteStrategyByPrimaryKey(int strategyId) throws Exception; public int deleteStrategy(Integer[] strategyId) throws Exception; public Strategy queryStrategyById(Integer strategyId) throws Exception; public int selectStrategyId() throws Exception; public List<Strategy> queryStrategyByName(String strategyName) throws Exception; public List<Strategy> queryStrategyByNameAndStatus(String strategyName, int status) throws Exception; public String selectStrategyNameById(Integer strategyId) throws Exception; }
{ "content_hash": "043a860281c6016f6c808e4cfb129228", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 102, "avg_line_length": 30.964285714285715, "alnum_prop": 0.8269896193771626, "repo_name": "scaug10/NETESP", "id": "3492504eab942a16eec3e467de01c16c51669148", "size": "867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/g10/ssm/service/testdatabase/StrategyService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "428303" }, { "name": "HTML", "bytes": "223728" }, { "name": "Java", "bytes": "1377461" }, { "name": "JavaScript", "bytes": "1717412" } ], "symlink_target": "" }
exports.run = function(){ process.stdout.write(">>>>>>"); process.stdin.resume(); process.stdin.setEncoding('utf-8'); process.stdin.on('data',(chunk)=>{ //http://cnodejs.org/topic/57de52197e77820e3acfdfd2 process.stdout.write(chunk); }); }
{ "content_hash": "46d31c56daeaffb40c3e9c15166f12db", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 59, "avg_line_length": 25.181818181818183, "alnum_prop": 0.6137184115523465, "repo_name": "aceunlonely/gcli", "id": "dbd1f1414fe9adc8b56aec7bd27a37bba6ca6f65", "size": "283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/shell/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "15412" } ], "symlink_target": "" }
/* * Created on 24 Oct 2015 ( Time 23:20:29 ) * Generated by Telosys Tools Generator ( version 2.1.1 ) */ package com.kumasi.journal.business.service.mapping; import org.modelmapper.ModelMapper; import org.modelmapper.convention.MatchingStrategies; import org.springframework.stereotype.Component; import com.kumasi.journal.domain.Entry; import com.kumasi.journal.domain.jpa.EntryEntity; import com.kumasi.journal.domain.jpa.EntrytypeEntity; /** * Mapping between entity beans and display beans. */ @Component public class EntryServiceMapper extends AbstractServiceMapper { /** * ModelMapper : bean to bean mapping library. */ private ModelMapper modelMapper; /** * Constructor. */ public EntryServiceMapper() { modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); } /** * Mapping from 'EntryEntity' to 'Entry' * @param entryEntity */ public Entry mapEntryEntityToEntry(EntryEntity entryEntity) { if(entryEntity == null) { return null; } //--- Generic mapping Entry entry = map(entryEntity, Entry.class); //--- Link mapping ( link to Entrytype ) if(entryEntity.getEntrytype() != null) { entry.setEntrytypeId(entryEntity.getEntrytype().getId()); } return entry; } /** * Mapping from 'Entry' to 'EntryEntity' * @param entry * @param entryEntity */ public void mapEntryToEntryEntity(Entry entry, EntryEntity entryEntity) { if(entry == null) { return; } //--- Generic mapping map(entry, entryEntity); //--- Link mapping ( link : entry ) if( hasLinkToEntrytype(entry) ) { EntrytypeEntity entrytype1 = new EntrytypeEntity(); entrytype1.setId( entry.getEntrytypeId() ); entryEntity.setEntrytype( entrytype1 ); } else { entryEntity.setEntrytype( null ); } } /** * Verify that Entrytype id is valid. * @param Entrytype Entrytype * @return boolean */ private boolean hasLinkToEntrytype(Entry entry) { if(entry.getEntrytypeId() != null) { return true; } return false; } /** * {@inheritDoc} */ @Override protected ModelMapper getModelMapper() { return modelMapper; } protected void setModelMapper(ModelMapper modelMapper) { this.modelMapper = modelMapper; } }
{ "content_hash": "766eae0c1a057eaad8232ae58f67c584", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 80, "avg_line_length": 22.55, "alnum_prop": 0.7073170731707317, "repo_name": "obasola/master", "id": "94f258221a7252f2dc1a568ecd7d752e82bf4645", "size": "2255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/kumasi/journal/business/service/mapping/EntryServiceMapper.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "68378" }, { "name": "HTML", "bytes": "4500" }, { "name": "Java", "bytes": "486534" }, { "name": "JavaScript", "bytes": "460476" } ], "symlink_target": "" }
package org.apache.cassandra.cql3.statements; import java.util.List; import com.google.common.collect.ImmutableList; import org.apache.cassandra.auth.*; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.schema.SchemaConstants; import org.apache.cassandra.cql3.ColumnIdentifier; import org.apache.cassandra.cql3.ColumnSpecification; import org.apache.cassandra.cql3.ResultSet; import org.apache.cassandra.db.marshal.BooleanType; import org.apache.cassandra.db.marshal.UTF8Type; import org.apache.cassandra.transport.messages.ResultMessage; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class ListUsersStatement extends ListRolesStatement { // pseudo-virtual cf as the actual datasource is dependent on the IRoleManager impl private static final String KS = SchemaConstants.AUTH_KEYSPACE_NAME; private static final String CF = "users"; private static final List<ColumnSpecification> metadata = ImmutableList.of(new ColumnSpecification(KS, CF, new ColumnIdentifier("name", true), UTF8Type.instance), new ColumnSpecification(KS, CF, new ColumnIdentifier("super", true), BooleanType.instance)); @Override protected ResultMessage formatResults(List<RoleResource> sortedRoles) { ResultSet.ResultMetadata resultMetadata = new ResultSet.ResultMetadata(metadata); ResultSet result = new ResultSet(resultMetadata); IRoleManager roleManager = DatabaseDescriptor.getRoleManager(); for (RoleResource role : sortedRoles) { if (!roleManager.canLogin(role)) continue; result.addColumnValue(UTF8Type.instance.decompose(role.getRoleName())); result.addColumnValue(BooleanType.instance.decompose(Roles.hasSuperuserStatus(role))); } return new ResultMessage.Rows(result); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
{ "content_hash": "3b5615ed07cebc9bca0e4d27f9a8b614", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 117, "avg_line_length": 39.509433962264154, "alnum_prop": 0.7473734479465138, "repo_name": "aureagle/cassandra", "id": "23a4d56dfc014f75a0c8c12b5edc5484161db58a", "size": "2899", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "src/java/org/apache/cassandra/cql3/statements/ListUsersStatement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "801" }, { "name": "Batchfile", "bytes": "23702" }, { "name": "GAP", "bytes": "84363" }, { "name": "Java", "bytes": "17105919" }, { "name": "Lex", "bytes": "10151" }, { "name": "PowerShell", "bytes": "38997" }, { "name": "Python", "bytes": "513134" }, { "name": "Shell", "bytes": "54395" } ], "symlink_target": "" }
var Subgame = require('../Subgame.js'); var backend = require('../../backend.js'); var GLOBAL = require('../../global.js'); var LANG = require('../../language.js'); var util = require('../../utils.js'); var Bee = require('../../characters/Bee.js'); var Bird = require('../../characters/Bird.js'); var Lizard = require('../../characters/Lizard.js'); var WoodLouse = require('../../characters/WoodLouse.js'); var Hedgehog = require('../../characters/agents/Hedgehog.js'); var Mouse = require('../../characters/agents/Mouse.js'); var Panda = require('../../characters/agents/Panda.js'); var Troll = require('../../characters/Troll.js'); module.exports = PartyGame; /** * Superclass for party games. * NOTE: This inherits subgame, see that class for more info. * NOTE: Avoid creating new agents, use the birthday agent and helpers. * * SETUP THESE IN THE SUBCLASS: * guestScales: If you set this before calling PartyGame's create function, guests will be created in the corresponding scales (see createGuests). * hasBirthday: If you set this before calling PartyGame's create function, the birthday agent created (see createAgents). * * VARIABLES THE SUBCLASS CAN USE: * difficulty: The difficulty supplied to the game. * birthdayType: The class of the birthday agent. * helper1Type: The class of the first helper. * helper2Type: The class of the second helper. * birthday: The birthday agent object (see hasBirthday above). * helper1: The first helper object. * helper2: The second helper object. * troll: The troll (will be in troll state at start). * gladeIntro: The group that has the introductory glade, begin you game with this one. * guests: All the guests (see guestScales above). * sfx: Audio sheet with some sound effects. * * FUNCTIONS THE SUBCLASS CAN USE: * switchAgents: Use this to switch helpers. Call this before PartyGame.create! * afterGarlands: Add garlands to glade. * afterBalloons: Add balloons to glade. * afterGifts: Add gifts to glade. */ PartyGame.prototype = Object.create(Subgame.prototype); PartyGame.prototype.constructor = PartyGame; function PartyGame () { Subgame.call(this); // Call parent constructor. } PartyGame.prototype.init = function(options) { options = options || {}; options.mode = [ GLOBAL.MODE.intro, GLOBAL.MODE.playerDo, GLOBAL.MODE.outro ]; options.roundsPerMode = options.roundsPerMode || 5; Subgame.prototype.init.call(this, options); this.difficulty = options.difficulty || 0; // What agents to use. The agents are set up like this (do not change them): // Panda: Mouse, Hedgehog. // Hedgehog: Panda, Mouse. // Mouse: Hedgehog, Panda. this.birthdayType = options.birthday !== undefined ? GLOBAL.AGENT[options.birthday] : this.game.player.agent; if (this.birthdayType === Panda) { this.helper1Type = Mouse; this.helper2Type = Hedgehog; } else if (this.birthdayType === Hedgehog) { this.helper1Type = Panda; this.helper2Type = Mouse; } else { // Mouse this.helper1Type = Hedgehog; this.helper2Type = Panda; } }; PartyGame.prototype.switchAgents = function () { var temp = this.helper1Type; this.helper1Type = this.helper2Type; this.helper2Type = temp; }; PartyGame.prototype.preload = function () { Hedgehog.load.call(this, true); Panda.load.call(this, true); Mouse.load.call(this, true); this.load.audio('party' + Panda.prototype.id, LANG.SPEECH.party.panda.speech); this.load.audio('party' + Hedgehog.prototype.id, LANG.SPEECH.party.hedgehog.speech); this.load.audio('party' + Mouse.prototype.id, LANG.SPEECH.party.mouse.speech); Troll.load.call(this); if (this.guestScales) { Bee.load.call(this); Bird.load.call(this); Lizard.load.call(this); WoodLouse.load.call(this); } this.load.atlasJSONHash('glade', 'img/partygames/glade/atlas.png', 'img/partygames/glade/atlas.json'); this.load.audio('balloonSfx', ['audio/subgames/balloongame/sfx.m4a', 'audio/subgames/balloongame/sfx.ogg', 'audio/subgames/balloongame/sfx.mp3']); }; PartyGame.prototype.create = function () { this.sfx = util.createAudioSheet('balloonSfx', { chestUnlock: [1.9, 1.0], pop: [3.1, 0.3] }); this.gladeIntro = this.add.group(this.gameGroup); // Create general background. this.gladeIntro.create(0, 0, 'glade', 'background'); this.gladeIntro.create(680, 520, 'glade', 'treestump'); this.gladeIntro.create(0, 0, 'glade', 'trees'); if (this.guestScales) { this.createGuests(); } this.createAgents(); // Create banner for the birthday agent. // This might seem a bit complex, it is to adapt for different languages. var banner = this.gladeIntro.create(580, 130, 'glade', 'banner'); banner.anchor.set(0.5); var bannerText = this.add.text(banner.x - 10, banner.y + 15, LANG.TEXT.congratulations, { font: '25pt ' + GLOBAL.FONT }); bannerText.angle = 3; bannerText.anchor.set(1, 0.5); this.gladeIntro.add(bannerText); bannerText = this.add.text(banner.x + 10, banner.y + 15, LANG.TEXT[this.birthdayType.prototype.id + 'Name'] + '!', { font: '25pt ' + GLOBAL.FONT }); bannerText.angle = -3; bannerText.anchor.set(0, 0.5); this.gladeIntro.add(bannerText); this.gladeIntro.create(banner.x, banner.y, 'glade', 'branches').anchor.set(0.5); }; PartyGame.prototype.createAgents = function () { this.helper1 = new (this.helper1Type)(this.game); this.helper1.x = this.pos.helper1 ? this.pos.helper1.x : 0; this.helper1.y = this.pos.helper1 ? this.pos.helper1.y : 0; this.helper1.scale.set(0.15); this.helper1.speech = util.createAudioSheet('party' + this.helper1.id, LANG.SPEECH.party[this.helper1.id].markers); this.gladeIntro.add(this.helper1); this.helper2 = new (this.helper2Type)(this.game); this.helper2.x = this.pos.helper2 ? this.pos.helper2.x : 0; this.helper2.y = this.pos.helper2 ? this.pos.helper2.y : 0; this.helper2.scale.set(0.15); this.helper2.speech = util.createAudioSheet('party' + this.helper2.id, LANG.SPEECH.party[this.helper2.id].markers); this.gladeIntro.add(this.helper2); if (this.hasBirthday) { // Use the current agent if that is who we are celebrating. if (this.agent instanceof this.birthdayType) { this.birthday = this.agent; } else { this.birthday = new (this.birthdayType)(this.game); } this.birthday.x = this.pos.birthday ? this.pos.birthday.x : 0; this.birthday.y = this.pos.birthday ? this.pos.birthday.y : 0; this.birthday.scale.set(0.17); this.gladeIntro.add(this.birthday); this.birthday.speech = util.createAudioSheet('party' + this.birthday.id, LANG.SPEECH.party[this.birthday.id].markers); } this.troll = new Troll (this.game); this.troll.x = this.pos.troll ? this.pos.troll.x : 0; this.troll.y = this.pos.troll ? this.pos.troll.y : 0; this.troll.scale.set(0.12); this.troll.visible = false; this.gladeIntro.add(this.troll); }; PartyGame.prototype.createGuests = function () { var guests = [Bee, Lizard, WoodLouse, Bird, Bird]; var scales = this.guestScales; var tints = [0xff8888, 0x77ee77, 0x8888ff, 0xfaced0, 0xfedcba, 0x11abba, 0xabcdef, 0x333333, 0xed88ba]; this.rnd.shuffle(tints); this.guests = []; for (var i = 0; i < 5; i++) { var index = this.rnd.integerInRange(0, guests.length - 1); var guest = new (guests.splice(index, 1)[0])(this.game, 0, 0); guest.scale.set(scales.splice(index, 1)[0]); guest.visible = false; if (guest instanceof Bird) { guest.tint = tints.splice(0, 1)[0]; } this.guests.push(guest); this.gladeIntro.add(guest); } }; PartyGame.prototype.afterGarlands = function () { this.gladeIntro.create(430, 270, 'glade', 'garland'); }; PartyGame.prototype.afterBalloons = function () { this.gladeIntro.create(200, 249, 'glade', 'balloons'); }; PartyGame.prototype.afterGifts = function () { this.gladeIntro.create(160, 650, 'glade', 'gift1'); this.gladeIntro.create(240, 650, 'glade', 'gift3'); this.gladeIntro.create(200, 660, 'glade', 'gift2'); this.gladeIntro.create(260, 670, 'glade', 'gift5'); this.gladeIntro.create(220, 670, 'glade', 'gift4'); for (var i = 0; i < this.guests.length; i++) { this.guests[i].setHappy(); } }; PartyGame.prototype.nextRound = function () { if (this.currentMode === GLOBAL.MODE.playerDo) { this._counter.value++; } Subgame.prototype.nextRound.call(this); }; /** End the game. */ PartyGame.prototype.endGame = function () { backend.putParty({ done: true }); // TODO: This should not be necessary with better logging. this.game.time.events.add(Phaser.Timer.SECOND * 1, Subgame.prototype.endGame, this); };
{ "content_hash": "38015cad5867676ee9f41768800596e1", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 149, "avg_line_length": 36.19230769230769, "alnum_prop": 0.7018538198134372, "repo_name": "AnderbergE/mWorld", "id": "0a5ee6d1d325817748f3b80a760b02ede48662b3", "size": "8469", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/script/states/partygames/PartyGame.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1011" }, { "name": "HTML", "bytes": "798" }, { "name": "JavaScript", "bytes": "3280957" } ], "symlink_target": "" }
@class BaseRequest, NSString, SKBuiltinBuffer_t, VoipCmdList; @interface VoipSyncReq : WXPBGeneratedMessage { } + (void)initialize; // Remaining properties @property(retain, nonatomic) BaseRequest *baseRequest; // @dynamic baseRequest; @property(retain, nonatomic) NSString *fromUsername; // @dynamic fromUsername; @property(retain, nonatomic) SKBuiltinBuffer_t *keyBuf; // @dynamic keyBuf; @property(retain, nonatomic) VoipCmdList *opLog; // @dynamic opLog; @property(nonatomic) int roomId; // @dynamic roomId; @property(nonatomic) long long roomKey; // @dynamic roomKey; @property(nonatomic) int selector; // @dynamic selector; @property(nonatomic) unsigned long long timestamp64; // @dynamic timestamp64; @end
{ "content_hash": "80326eaf02804bef2ab6ee7ac07b6685", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 79, "avg_line_length": 35.9, "alnum_prop": 0.7674094707520891, "repo_name": "walkdianzi/DashengHook", "id": "59388525a24def90523a69f5c61ea6a2489db532", "size": "891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WeChat-Headers/VoipSyncReq.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "986" }, { "name": "Objective-C", "bytes": "10153542" }, { "name": "Objective-C++", "bytes": "18332" }, { "name": "Shell", "bytes": "1459" } ], "symlink_target": "" }
School project in C - sobel operator ![lena sobel](images/lena_kernelsobel.bmp)
{ "content_hash": "1987105663a81ce4a1274bfe0bf572b0", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 42, "avg_line_length": 27, "alnum_prop": 0.7654320987654321, "repo_name": "Hyrasso/Filtrage", "id": "94f8cb4487f8c287bdf32e3183a3e07331b7fde0", "size": "92", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "24" }, { "name": "C", "bytes": "21756" }, { "name": "Python", "bytes": "284" } ], "symlink_target": "" }
"""Internal module for Python 2 backwards compatibility.""" # flake8: noqa import errno import socket import sys def sendall(sock, *args, **kwargs): return sock.sendall(*args, **kwargs) def shutdown(sock, *args, **kwargs): return sock.shutdown(*args, **kwargs) def ssl_wrap_socket(context, sock, *args, **kwargs): return context.wrap_socket(sock, *args, **kwargs) # For Python older than 3.5, retry EINTR. if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 5): # Adapted from https://bugs.python.org/review/23863/patch/14532/54418 import time # Wrapper for handling interruptable system calls. def _retryable_call(s, func, *args, **kwargs): # Some modules (SSL) use the _fileobject wrapper directly and # implement a smaller portion of the socket interface, thus we # need to let them continue to do so. timeout, deadline = None, 0.0 attempted = False try: timeout = s.gettimeout() except AttributeError: pass if timeout: deadline = time.time() + timeout try: while True: if attempted and timeout: now = time.time() if now >= deadline: raise socket.error(errno.EWOULDBLOCK, "timed out") else: # Overwrite the timeout on the socket object # to take into account elapsed time. s.settimeout(deadline - now) try: attempted = True return func(*args, **kwargs) except socket.error as e: if e.args[0] == errno.EINTR: continue raise finally: # Set the existing timeout back for future # calls. if timeout: s.settimeout(timeout) def recv(sock, *args, **kwargs): return _retryable_call(sock, sock.recv, *args, **kwargs) def recv_into(sock, *args, **kwargs): return _retryable_call(sock, sock.recv_into, *args, **kwargs) else: # Python 3.5 and above automatically retry EINTR def recv(sock, *args, **kwargs): return sock.recv(*args, **kwargs) def recv_into(sock, *args, **kwargs): return sock.recv_into(*args, **kwargs) if sys.version_info[0] < 3: # In Python 3, the ssl module raises socket.timeout whereas it raises # SSLError in Python 2. For compatibility between versions, ensure # socket.timeout is raised for both. import functools try: from ssl import SSLError as _SSLError except ImportError: class _SSLError(Exception): """A replacement in case ssl.SSLError is not available.""" pass _EXPECTED_SSL_TIMEOUT_MESSAGES = ( "The handshake operation timed out", "The read operation timed out", "The write operation timed out", ) def _handle_ssl_timeout(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except _SSLError as e: message = len(e.args) == 1 and unicode(e.args[0]) or '' if any(x in message for x in _EXPECTED_SSL_TIMEOUT_MESSAGES): # Raise socket.timeout for compatibility with Python 3. raise socket.timeout(*e.args) raise return wrapper recv = _handle_ssl_timeout(recv) recv_into = _handle_ssl_timeout(recv_into) sendall = _handle_ssl_timeout(sendall) shutdown = _handle_ssl_timeout(shutdown) ssl_wrap_socket = _handle_ssl_timeout(ssl_wrap_socket) if sys.version_info[0] < 3: from urllib import unquote from urlparse import parse_qs, urlparse from itertools import imap, izip from string import letters as ascii_letters from Queue import Queue # special unicode handling for python2 to avoid UnicodeDecodeError def safe_unicode(obj, *args): """ return the unicode representation of obj """ try: return unicode(obj, *args) except UnicodeDecodeError: # obj is byte string ascii_text = str(obj).encode('string_escape') return unicode(ascii_text) def iteritems(x): return x.iteritems() def iterkeys(x): return x.iterkeys() def itervalues(x): return x.itervalues() def nativestr(x): return x if isinstance(x, str) else x.encode('utf-8', 'replace') def next(x): return x.next() unichr = unichr xrange = xrange basestring = basestring unicode = unicode long = long BlockingIOError = socket.error else: from urllib.parse import parse_qs, unquote, urlparse from string import ascii_letters from queue import Queue def iteritems(x): return iter(x.items()) def iterkeys(x): return iter(x.keys()) def itervalues(x): return iter(x.values()) def nativestr(x): return x if isinstance(x, str) else x.decode('utf-8', 'replace') def safe_unicode(value): if isinstance(value, bytes): value = value.decode('utf-8', 'replace') return str(value) next = next unichr = chr imap = map izip = zip xrange = range basestring = str unicode = str long = int BlockingIOError = BlockingIOError try: # Python 3 from queue import LifoQueue, Empty, Full except ImportError: # Python 2 from Queue import LifoQueue, Empty, Full
{ "content_hash": "bfc300abe57e0d54643d0c8e682b7c38", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 77, "avg_line_length": 30.30851063829787, "alnum_prop": 0.5854685854685855, "repo_name": "5977862/redis-py", "id": "a0036de31ede0a57f6227cc532e1d46721f5c60a", "size": "5698", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "redis/_compat.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "316161" }, { "name": "Ruby", "bytes": "1095" }, { "name": "Shell", "bytes": "7822" } ], "symlink_target": "" }
/** * @author b00295750 * */ package org.onosproject.pcep.pcepio.types; import java.util.Objects; import org.jboss.netty.buffer.ChannelBuffer; import org.onosproject.pcep.pcepio.protocol.PcepVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.MoreObjects; /** * Provides IPv4 Sub Object. */ public class IPv4SubObject implements PcepValueType { /*Reference : RFC 4874:3.1.1 * 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |L| Type | Length | IPv4 address (4 bytes) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | IPv4 address (continued) | Prefix Length | Resvd | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ protected static final Logger log = LoggerFactory.getLogger(IPv4SubObject.class); public static final byte TYPE = 0x01; public static final byte LENGTH = 8; public static final byte VALUE_LENGTH = 6; public static final byte OBJ_LENGTH = 8; public static final byte LBIT = 0; public static final int SHIFT_LBIT_POSITION = 7; private int ipAddress; private byte prefixLen; private byte resvd; /** * Constructor to initialize ipv4 address. * * @param ipAddr ipv4 address */ public IPv4SubObject(int ipAddr) { this.ipAddress = ipAddr; } /** * constructor to initialize ipAddress, prefixLen and resvd. * * @param ipAddress ipv4 address * @param prefixLen prefix length * @param resvd reserved flags value */ public IPv4SubObject(int ipAddress, byte prefixLen, byte resvd) { this.ipAddress = ipAddress; this.prefixLen = prefixLen; this.resvd = resvd; } /** * Returns a new instance of IPv4SubObject. * * @param ipAddress ipv4 address * @param prefixLen prefix length * @param resvd reserved flags value * @return object of IPv4SubObject */ public static IPv4SubObject of(int ipAddress, byte prefixLen, byte resvd) { return new IPv4SubObject(ipAddress, prefixLen, resvd); } /** * Returns prefixLen of IPv4 IP address. * * @return byte value of rawValue */ public byte getPrefixLen() { return prefixLen; } /** * Returns value of IPv4 IP address. * * @return int value of ipv4 address */ public int getIpAddress() { return ipAddress; } @Override public PcepVersion getVersion() { return PcepVersion.PCEP_1; } @Override public short getType() { return TYPE; } @Override public short getLength() { return LENGTH; } @Override public int hashCode() { return Objects.hash(ipAddress, prefixLen, resvd); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof IPv4SubObject) { IPv4SubObject other = (IPv4SubObject) obj; return Objects.equals(this.ipAddress, other.ipAddress) && Objects.equals(this.prefixLen, other.prefixLen) && Objects.equals(this.resvd, other.resvd); } return false; } /** * Reads the channel buffer and returns object of IPv4SubObject. * * @param c type of channel buffer * @return object of IPv4SubObject */ public static PcepValueType read(ChannelBuffer c) { int ipAddess = c.readInt(); byte prefixLen = c.readByte(); byte resvd = c.readByte(); return new IPv4SubObject(ipAddess, prefixLen, resvd); } @Override public int write(ChannelBuffer c) { int iLenStartIndex = c.writerIndex(); byte bValue = LBIT; bValue = (byte) (bValue << SHIFT_LBIT_POSITION); bValue = (byte) (bValue | TYPE); c.writeByte(bValue); c.writeByte(OBJ_LENGTH); c.writeInt(ipAddress); c.writeByte(prefixLen); c.writeByte(resvd); return c.writerIndex() - iLenStartIndex; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("Type", TYPE) .add("Length", LENGTH) .add("IPv4Address", ipAddress) .add("PrefixLength", prefixLen) .toString(); } }
{ "content_hash": "9934c8b5c7961e93beb925a62b9a1c58", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 117, "avg_line_length": 27.566265060240966, "alnum_prop": 0.5688374125874126, "repo_name": "maheshraju-Huawei/actn", "id": "e8ce5a9dd1e30f06836246faa256eb5b0b62ebdf", "size": "5193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/pcep-api/src/main/java/org/onosproject/pcep/pcepio/types/IPv4SubObject.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "72456" }, { "name": "CSS", "bytes": "181720" }, { "name": "Groff", "bytes": "1090" }, { "name": "HTML", "bytes": "504491" }, { "name": "Java", "bytes": "26121936" }, { "name": "JavaScript", "bytes": "3094308" }, { "name": "Protocol Buffer", "bytes": "7499" }, { "name": "Python", "bytes": "118029" }, { "name": "Shell", "bytes": "2697" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8' ?> <!-- was: <?xml version="1.0" encoding="UTF-8"?> --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/> <mvc:resources mapping="/js/*" location="/js/"/> <mvc:resources mapping="/css/*" location="/css/"/> <mvc:resources mapping="/imagenes/*" location="/imagenes/"/> <mvc:resources mapping="/webjars/*" location="classpath:/META-INF/resources/webjars/"/> <!-- Se añade para poder utilizar la etiqueta @Autowiring dentro del paquete Controlador--> <context:annotation-config/> <context:component-scan base-package="Controlador"/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/jsp/" p:suffix=".jsp" /> </beans>
{ "content_hash": "1b421b91e4734a42b67157f667127c09", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 95, "avg_line_length": 50.22857142857143, "alnum_prop": 0.6319681456200228, "repo_name": "rafaelg5/Ingenieria-de-Software", "id": "7b9069db6cd3ddbcd5e0ea85fb10e66959b1a3c6", "size": "1759", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Práctica1-2/WebPage/src/main/webapp/WEB-INF/dispatcher-servlet.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "42547" } ], "symlink_target": "" }
package org.lahab.clucene.server; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DebugServlet extends HttpServlet { private static final Logger LOGGER = Logger.getLogger(DebugServlet.class.getName()); private static final long serialVersionUID = 1L; public static final String PATH = "/_debug"; protected Worker _worker; public DebugServlet(Worker worker) { _worker = worker; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOGGER.info("useless ftm"); } }
{ "content_hash": "96eaab96c7f11fdff00e949afe797c12", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 118, "avg_line_length": 25.896551724137932, "alnum_prop": 0.7909454061251664, "repo_name": "lahabana/clucene", "id": "63a3809cf1c2ac52995073de52cb6c4de18b4e19", "size": "1378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/main/java/org/lahab/clucene/server/DebugServlet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "114634" }, { "name": "Perl", "bytes": "5476" }, { "name": "Shell", "bytes": "9842" } ], "symlink_target": "" }
package org.onetwo.common.web.utils; import java.io.InputStream; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import javax.servlet.RequestDispatcher; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.onetwo.apache.io.IOUtils; import org.onetwo.common.exception.ServiceException; import org.onetwo.common.jackson.JsonMapper; import org.onetwo.common.log.JFishLoggerFactory; import org.onetwo.common.utils.LangUtils; import org.onetwo.common.utils.StringUtils; import org.slf4j.Logger; import org.springframework.http.MediaType; import org.springframework.util.Assert; abstract public class ResponseUtils { private static final Logger logger = JFishLoggerFactory.getLogger(ResponseUtils.class); public static final String ERROR_RESPONSE_HEADER = "X-RESPONSE-JFISH-ERROR"; public static final String TEXT_TYPE = "text/plain; charset=UTF-8"; public static final String JSON_TYPE = "application/json; charset=UTF-8"; public static final String XML_TYPE = "text/xml; charset=UTF-8"; public static final String HTML_TYPE = "text/html; charset=UTF-8"; public static final String JS_TYPE = "text/javascript"; // public static final String COOKIE_PATH; // public static final String COOKIE_DOMAIN; // public static final String COOKIE_DOMAIN = // "";//BaseSiteConfig.getInstance().getCookieDomain(); public static final DateFormat COOKIE_DATA_FORMAT; private static final JsonMapper JSON_MAPPER = JsonMapper.IGNORE_NULL; static { DateFormat df = new SimpleDateFormat("d MMM yyyy HH:mm:ss z", Locale.US); df.setTimeZone(TimeZone.getTimeZone("GMT")); COOKIE_DATA_FORMAT = df; /*String domain = ""; String path = ""; try { domain = BaseSiteConfig.getInstance().getCookieDomain(); path = BaseSiteConfig.getInstance().getCookiePath(); path = StringUtils.appendEndWith(path, "/"); } catch (Exception e) { logger.error("use default domain, because read domain path error : "+e.getMessage()); } COOKIE_DOMAIN = domain; COOKIE_PATH = path;*/ } /**** * 重定向 * * @param response * @param path */ public static void redirect(HttpServletResponse response, String path) { try { response.sendRedirect(path); } catch (Exception e) { throw new ServiceException(e); } } public static void forward(HttpServletRequest request, HttpServletResponse response, String path) { RequestDispatcher rd = request.getRequestDispatcher(path); try { rd.forward(request, response); } catch (Exception e) { throw new ServiceException(e); } } /** * 设置HttpOnly Cookie * * @param response * @param name * @param value * @param path * @param maxage * 分钟 * @param domain */ public static void setHttpOnlyCookie(HttpServletResponse response, String name, String value, String path, int maxage, String domain) { Assert.hasLength(name, "cookies name must has text"); if (StringUtils.isBlank(value)) value = ""; StringBuffer cookie = new StringBuffer(); cookie.append(name); cookie.append("="); cookie.append(Escape.escape(value)); // if (StringUtils.isBlank(path)) { if (path==null) { path = "/"; } cookie.append("; path=").append(path); if (maxage > 0) { Date expires = new Date((new Date()).getTime() + TimeUnit.MINUTES.toMillis(maxage)); cookie.append("; expires="); cookie.append(COOKIE_DATA_FORMAT.format(expires)); } else if (maxage == 0) { Date expires = new Date((new Date()).getTime() - TimeUnit.MINUTES.toMillis(60)); cookie.append("; expires="); cookie.append(COOKIE_DATA_FORMAT.format(expires)); } //本地时,不需要设置,设置了有些浏览器会读不到cookies if (StringUtils.isNotBlank(domain)) { cookie.append("; domain=").append(domain); } cookie.append("; HttpOnly"); response.addHeader("Set-Cookie", cookie.toString()); } /** * 获取cookie的值 * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName) { return RequestUtils.getCookieValue(request, cookieName); } public static String getUnescapeCookieValue(HttpServletRequest request, String cookieName) { return RequestUtils.getUnescapeCookieValue(request, cookieName); } /* *//** * 删除cookie * * @param response * @param name * @param path */ /* * public static void removeCookie(HttpServletRequest request, * HttpServletResponse response, String name) { Cookie[] cookies = * request.getCookies(); if(cookies==null) return ; for(Cookie ck : * cookies){ if(name.equals(ck.getName())){ ck.setMaxAge(0); * response.addCookie(ck); } } } */ public static void removeCookie(HttpServletResponse response, String name, String path, String domain) { Cookie ck = new Cookie(name, ""); ck.setMaxAge(0); if (StringUtils.isNotBlank(path)) { ck.setPath(path); } if (StringUtils.isNotBlank(domain)) { ck.setDomain(domain); } response.addCookie(ck); } public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) { Cookie[] cookies = request.getCookies(); if(cookies==null) { return ; } for(Cookie ck : cookies) { if(name.equals(ck.getName())) { ck.setMaxAge(0); response.addCookie(ck); } } } public static void renderScript(PrintWriter out, String content) { renderScript(true, out, content); } public static void renderScript(boolean flush, PrintWriter out, String content) { if (StringUtils.isBlank(content)) return; out.println("<script>"); out.println(content); out.println("</script>"); if (flush) out.flush(); } public static void renderJsonp(HttpServletResponse response, final String callbackName, final Object params) { String jsonParam = JsonMapper.DEFAULT_MAPPER.toJson(params); renderJsonp(response, callbackName, jsonParam); } public static void renderJsonp(HttpServletResponse response, HttpServletRequest request, final String callbackParam) { String callback = request.getParameter(callbackParam); callback = StringUtils.isBlank(callback)?"callback":callback; StringBuilder result = new StringBuilder().append(callback).append("();"); render(response, result.toString(), JS_TYPE, true); } public static void renderJsonp(HttpServletResponse response, final String callbackName, final String jsonParam) { StringBuilder result = new StringBuilder().append(callbackName).append("(").append(jsonParam).append(");"); render(response, result.toString(), JS_TYPE, true); } public static void renderText(HttpServletResponse response, String text){ render(response, text, null, false); } public static void renderJs(HttpServletResponse response, String text){ render(response, text, JS_TYPE, true); } public static void renderJson(HttpServletResponse response, String text){ render(response, text, JSON_TYPE, true); } public static void renderJsonByAgent(HttpServletRequest request, HttpServletResponse response, String text){ String contextType = RequestUtils.getJsonContextTypeByUserAgent(request); render(response, text, contextType, true); } public static void renderObjectAsJson(HttpServletResponse response, Object data){ String text = JSON_MAPPER.toJson(data); render(response, text, JSON_TYPE, true); } public static void renderHtml(HttpServletResponse response, String html){ render(response, html, HTML_TYPE, true); } public static void render(HttpServletResponse response, String text, String contentType, boolean noCache){ try { if(!StringUtils.isBlank(contentType)) response.setContentType(contentType); else response.setContentType(TEXT_TYPE); if (noCache) { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setDateHeader("Expires", 0); } PrintWriter pr = response.getWriter(); pr.write(text); pr.flush(); } catch (Exception e) { logger.error("render error: " + e.getMessage(), e); } } public static void addP3PHeader(HttpServletResponse response){ response.addHeader("P3P", "CP=\"NON DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM CNT PRE LOC\""); // response.addHeader("P3P", "CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\""); // response.addHeader("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""); } /*** * 设置下载的header * @author weishao zeng * @param response * @param filename */ public static void configDownloadHeaders(HttpServletResponse response, String filename) { response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); String name = LangUtils.encodeUrl(filename); response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + name); } public static void download(HttpServletResponse response, InputStream input, String filename) { try { response.setContentLength(input.available()); // response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); // String name = new String(filename.getBytes("GBK"), "ISO8859-1"); // response.setHeader("Content-Disposition", "attachment;filename=" + name); ResponseUtils.configDownloadHeaders(response, filename); IOUtils.copy(input, response.getOutputStream()); } catch (Exception e) { String msg = "download file error:"; logger.error(msg + e.getMessage(), e); } } }
{ "content_hash": "bbf7868a231d5806c152061e2b5fdaac", "timestamp": "", "source": "github", "line_count": 300, "max_line_length": 155, "avg_line_length": 33.096666666666664, "alnum_prop": 0.7016819417866854, "repo_name": "wayshall/onetwo", "id": "feb05a60728aaeb5b33f5ed331e27f623b5c441c", "size": "10011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/modules/web/src/main/java/org/onetwo/common/web/utils/ResponseUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "758" }, { "name": "FreeMarker", "bytes": "81409" }, { "name": "HTML", "bytes": "44447" }, { "name": "Java", "bytes": "4171699" }, { "name": "JavaScript", "bytes": "1820" }, { "name": "Shell", "bytes": "573" }, { "name": "Smarty", "bytes": "3018" } ], "symlink_target": "" }
namespace ui { namespace { class MockColorProviderSource : public ColorProviderSource { public: MOCK_METHOD(ColorProviderManager::Key, GetColorProviderKey, (), (const, override)); MOCK_METHOD(const ColorProvider*, GetColorProvider, (), (const, override)); }; class MockColorProviderSourceObserver : public ColorProviderSourceObserver { public: void ObserveForTesting(ColorProviderSource* source) { Observe(source); } MOCK_METHOD(void, OnColorProviderChanged, (), ()); }; } // namespace using ColorProviderSourceObserverTest = testing::Test; // Verify the observation is reset when source is destroyed. TEST_F(ColorProviderSourceObserverTest, DestroyingSourceClearsItFromObservers) { auto source = std::make_unique<MockColorProviderSource>(); MockColorProviderSourceObserver observer_1; MockColorProviderSourceObserver observer_2; // OnColorProviderChanged() should be called twice. Once when the observer is // first added to the source and again when the source is destroyed. EXPECT_CALL(observer_1, OnColorProviderChanged()).Times(2); EXPECT_CALL(observer_2, OnColorProviderChanged()).Times(2); auto set_observation = [&](MockColorProviderSourceObserver* observer) { observer->ObserveForTesting(source.get()); EXPECT_EQ(source.get(), observer->GetColorProviderSourceForTesting()); EXPECT_TRUE(source->observers_for_testing().HasObserver(observer)); }; set_observation(&observer_1); set_observation(&observer_2); // When the source is destroyed the observer's source() method should return // nullptr. source.reset(); EXPECT_EQ(nullptr, observer_1.GetColorProviderSourceForTesting()); EXPECT_EQ(nullptr, observer_2.GetColorProviderSourceForTesting()); } // Verify the observer is removed from the source's observer list when the // observer is destroyed. TEST_F(ColorProviderSourceObserverTest, DestroyingObserverClearsItFromSource) { MockColorProviderSource source; auto observer_1 = std::make_unique<MockColorProviderSourceObserver>(); auto observer_2 = std::make_unique<MockColorProviderSourceObserver>(); // OnColorProviderChanged() should be called once when the observer is first // added to the source. EXPECT_CALL(*observer_1, OnColorProviderChanged()).Times(1); EXPECT_CALL(*observer_2, OnColorProviderChanged()).Times(1); auto set_observation = [&](MockColorProviderSourceObserver* observer) { observer->ObserveForTesting(&source); EXPECT_EQ(&source, observer->GetColorProviderSourceForTesting()); EXPECT_TRUE(source.observers_for_testing().HasObserver(observer)); }; set_observation(observer_1.get()); set_observation(observer_2.get()); // When the observer is destroyed it should be removed from the source's list // of observers. Other observers should remain. observer_1.reset(); EXPECT_FALSE(source.observers_for_testing().empty()); EXPECT_TRUE(source.observers_for_testing().HasObserver(observer_2.get())); observer_2.reset(); EXPECT_TRUE(source.observers_for_testing().empty()); // Further calls to NotifyColorProviderChanged() should succeed and not // result in any more calls to OnColorProviderChanged(). source.NotifyColorProviderChanged(); } // Verify OnColorProviderChanged() is called by the source as expected. TEST_F(ColorProviderSourceObserverTest, ObserverCorrectlySetsObservationOfSource) { MockColorProviderSource source; MockColorProviderSourceObserver observer_1; MockColorProviderSourceObserver observer_2; // observer_2 should receive notifications up to and including when its // observation is reset below. EXPECT_CALL(observer_1, OnColorProviderChanged()).Times(4); EXPECT_CALL(observer_2, OnColorProviderChanged()).Times(3); auto set_observation_and_notify = [&](MockColorProviderSourceObserver* observer) { observer->ObserveForTesting(&source); EXPECT_EQ(&source, observer->GetColorProviderSourceForTesting()); EXPECT_TRUE(source.observers_for_testing().HasObserver(observer)); source.NotifyColorProviderChanged(); }; set_observation_and_notify(&observer_1); set_observation_and_notify(&observer_2); observer_2.ObserveForTesting(nullptr); // After removing the observation for observer_2 we should still get // notifications for observer_1. EXPECT_EQ(&source, observer_1.GetColorProviderSourceForTesting()); EXPECT_EQ(nullptr, observer_2.GetColorProviderSourceForTesting()); EXPECT_TRUE(source.observers_for_testing().HasObserver(&observer_1)); EXPECT_FALSE(source.observers_for_testing().HasObserver(&observer_2)); source.NotifyColorProviderChanged(); } } // namespace ui
{ "content_hash": "3d540f0b12cebfaa92faf2be074141e9", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 80, "avg_line_length": 39.94017094017094, "alnum_prop": 0.7554033811256152, "repo_name": "chromium/chromium", "id": "717d3f3877972bab0fd6c578bb7096e817bd3460", "size": "5074", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "ui/color/color_provider_source_observer_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using System; namespace NMultiTool.Library.Infrastructure { public class SingletonAttribute : Attribute { } }
{ "content_hash": "eb10138ba96a8f5ae7ba7c5be1f31048", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 47, "avg_line_length": 15.375, "alnum_prop": 0.7235772357723578, "repo_name": "trondr/NMultiTool", "id": "d281591060a3b6516c9412c144f12abc1612f2ef", "size": "125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/NMultiTool.Library/Infrastructure/SingletonAttribute.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "2408" }, { "name": "C#", "bytes": "239351" }, { "name": "HTML", "bytes": "6020" }, { "name": "PowerShell", "bytes": "9659" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Cortex\Auth\Transformers\Adminarea; use Cortex\Auth\Models\Manager; use Rinvex\Support\Traits\Escaper; use League\Fractal\TransformerAbstract; class ManagerTransformer extends TransformerAbstract { use Escaper; /** * @return array */ public function transform(Manager $manager): array { $country = $manager->country_code ? country($manager->country_code) : null; $language = $manager->language_code ? language($manager->language_code) : null; return $this->escape([ 'id' => (string) $manager->getRouteKey(), 'DT_RowId' => 'row_'.$manager->getRouteKey(), 'is_active' => (bool) $manager->is_active, 'given_name' => (string) $manager->given_name, 'family_name' => (string) $manager->family_name, 'username' => (string) $manager->username, 'email' => (string) $manager->email, 'email_verified_at' => (string) $manager->email_verified_at, 'phone' => (string) $manager->phone, 'phone_verified_at' => (string) $manager->phone_verified_at, 'country_code' => (string) optional($country)->getName(), 'country_emoji' => (string) optional($country)->getEmoji(), 'language_code' => (string) optional($language)->getName(), 'title' => (string) $manager->title, 'organization' => (string) $manager->organization, 'birthday' => (string) $manager->birthday, 'gender' => (string) $manager->gender, 'social' => (array) $manager->social, 'last_activity' => (string) $manager->last_activity, 'created_at' => (string) $manager->created_at, 'updated_at' => (string) $manager->updated_at, ]); } }
{ "content_hash": "6e86f1fc31cbdbffec267c20ea0ca35f", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 87, "avg_line_length": 39.02127659574468, "alnum_prop": 0.5757906215921483, "repo_name": "rinvex/cortex-fort", "id": "71d40017934ba467e00e1b683a12c329a8f18f94", "size": "1834", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Transformers/Adminarea/ManagerTransformer.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "139966" }, { "name": "PHP", "bytes": "78724" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>MatcherProducers - ScalaTest 2.1.7 - org.scalatest.matchers.MatcherProducers</title> <meta name="description" content="MatcherProducers - ScalaTest 2.1.7 - org.scalatest.matchers.MatcherProducers" /> <meta name="keywords" content="MatcherProducers ScalaTest 2.1.7 org.scalatest.matchers.MatcherProducers" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'org.scalatest.matchers.MatcherProducers$'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> <!-- gtag [javascript] --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-71294502-1"></script> <script defer> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-71294502-1'); </script> </head> <body class="value"> <!-- Top of doc.scalatest.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204546 = window.pid204546 || rnd; var plc204546 = window.plc204546 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <a href="MatcherProducers.html" title="Go to companion"><img src="../../../lib/object_to_trait_big.png" /></a> <p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.matchers">matchers</a></p> <h1><a href="MatcherProducers.html" title="Go to companion">MatcherProducers</a></h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">MatcherProducers</span><span class="result"> extends <a href="MatcherProducers.html" class="extype" name="org.scalatest.matchers.MatcherProducers">MatcherProducers</a></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Companion object that facilitates the importing of <code>MatcherProducers</code> members as an alternative to mixing it in. One use case is to import <code>MatcherProducers</code>'s members so you can use <code>MatcherProducers</code> in the Scala interpreter. </p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-2.1.7-for-scala-2.10/src/main/scala/org/scalatest/matchers/MatcherProducers.scala" target="_blank">MatcherProducers.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a href="MatcherProducers.html" class="extype" name="org.scalatest.matchers.MatcherProducers">MatcherProducers</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalatest.matchers.MatcherProducers"><span>MatcherProducers</span></li><li class="in" name="org.scalatest.matchers.MatcherProducers"><span>MatcherProducers</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="types" class="types members"> <h3>Type Members</h3> <ol><li name="org.scalatest.matchers.MatcherProducers.Composifier" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="Composifier[T]extendsAnyRef"></a> <a id="Composifier[T]:Composifier[T]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <a href="MatcherProducers$Composifier.html"><span class="name">Composifier</span></a><span class="tparams">[<span name="T">T</span>]</span><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <p class="comment cmt">Class used via an implicit conversion that adds <code>composeTwice</code>, <code>mapResult</code>, and <code>mapArgs</code> methods to functions that produce a <code>Matcher</code>.</p> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:AnyRef):Boolean"></a> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:AnyRef):Boolean"></a> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="org.scalatest.matchers.MatcherProducers#convertToComposifier" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="convertToComposifier[T](f:T=&gt;org.scalatest.matchers.Matcher[T]):MatcherProducers.this.Composifier[T]"></a> <a id="convertToComposifier[T]((T)⇒Matcher[T]):Composifier[T]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">implicit </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">convertToComposifier</span><span class="tparams">[<span name="T">T</span>]</span><span class="params">(<span name="f">f: (<span class="extype" name="org.scalatest.matchers.MatcherProducers.convertToComposifier.T">T</span>) ⇒ <a href="Matcher.html" class="extype" name="org.scalatest.matchers.Matcher">Matcher</a>[<span class="extype" name="org.scalatest.matchers.MatcherProducers.convertToComposifier.T">T</span>]</span>)</span><span class="result">: <a href="#Composifier[T]extendsAnyRef" class="extmbr" name="org.scalatest.matchers.MatcherProducers.Composifier">Composifier</a>[<span class="extype" name="org.scalatest.matchers.MatcherProducers.convertToComposifier.T">T</span>]</span> </span> </h4> <p class="shortcomment cmt">Implicit conversion that converts a function of <code>T =&gt; Matcher[T]</code> to an object that has <code>composeTwice</code>, <code>mapResult</code> and <code>mapArgs</code> methods.</p><div class="fullcomment"><div class="comment cmt"><p>Implicit conversion that converts a function of <code>T =&gt; Matcher[T]</code> to an object that has <code>composeTwice</code>, <code>mapResult</code> and <code>mapArgs</code> methods.</p><p>The following shows how this trait is used to compose twice and modify error messages:</p><p><pre class="stHighlighted"> <span class="stReserved">import</span> org.scalatest._ <span class="stReserved">import</span> matchers._ <span class="stReserved">import</span> MatcherProducers._ <br /><span class="stReserved">val</span> f = be &gt; (_: <span class="stType">Int</span>) <span class="stReserved">val</span> g = (_: <span class="stType">String</span>).toInt <br /><span class="stLineComment">// f composeTwice g means: (f compose g) andThen (_ compose g)</span> <span class="stReserved">val</span> beAsIntsGreaterThan = f composeTwice g mapResult { mr =&gt; mr.copy( failureMessageArgs = mr.failureMessageArgs.map((<span class="stType">LazyArg</span>(_) { <span class="stQuotedString">&quot;\&quot;&quot;</span> + _.toString + <span class="stQuotedString">&quot;\&quot;.toInt&quot;</span>})), negatedFailureMessageArgs = mr.negatedFailureMessageArgs.map((<span class="stType">LazyArg</span>(_) { <span class="stQuotedString">&quot;\&quot;&quot;</span> + _.toString + <span class="stQuotedString">&quot;\&quot;.toInt&quot;</span>})), midSentenceFailureMessageArgs = mr.midSentenceFailureMessageArgs.map((<span class="stType">LazyArg</span>(_) { <span class="stQuotedString">&quot;\&quot;&quot;</span> + _.toString + <span class="stQuotedString">&quot;\&quot;.toInt&quot;</span>})), midSentenceNegatedFailureMessageArgs = mr.midSentenceNegatedFailureMessageArgs.map((<span class="stType">LazyArg</span>(_) { <span class="stQuotedString">&quot;\&quot;&quot;</span> + _.toString + <span class="stQuotedString">&quot;\&quot;.toInt&quot;</span>})) ) } <br /><span class="stQuotedString">&quot;7&quot;</span> should beAsIntsGreaterThan (<span class="stQuotedString">&quot;8&quot;</span>) </pre></p><p>The last assertion will fail with message like this:</p><p><pre class="stHighlighted"> <span class="stQuotedString">&quot;7&quot;</span>.toInt was not greater than <span class="stQuotedString">&quot;8&quot;</span>.toInt </pre> </p></div><dl class="paramcmts block"><dt class="tparam">T</dt><dd class="cmt"><p>the type used by function <code>f</code></p></dd><dt class="param">f</dt><dd class="cmt"><p>a function that takes a <code>T</code> and return a <code>Matcher[T]</code></p></dd><dt>returns</dt><dd class="cmt"><p>an object that has <code>composeTwice</code>, <code>mapResult</code> and <code>mapArgs</code> methods. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="MatcherProducers.html" class="extype" name="org.scalatest.matchers.MatcherProducers">MatcherProducers</a></dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="org.scalatest.matchers.MatcherProducers"> <h3>Inherited from <a href="MatcherProducers.html" class="extype" name="org.scalatest.matchers.MatcherProducers">MatcherProducers</a></h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
{ "content_hash": "60f5ea8fe8130e933a8563d0904c47bf", "timestamp": "", "source": "github", "line_count": 510, "max_line_length": 714, "avg_line_length": 56.30392156862745, "alnum_prop": 0.6089848511231064, "repo_name": "scalatest/scalatest-website", "id": "cbd03904c927d7e2be8c4cfe983e75c1764ab2c7", "size": "28733", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/scaladoc/2.1.7/org/scalatest/matchers/MatcherProducers$.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8401192" }, { "name": "HTML", "bytes": "4508833233" }, { "name": "JavaScript", "bytes": "12256885" }, { "name": "Procfile", "bytes": "62" }, { "name": "Scala", "bytes": "136544" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import os.path import shutil import tensorflow as tf from tensorboard.backend.event_processing import plugin_event_accumulator as event_accumulator # pylint: disable=line-too-long from tensorboard.backend.event_processing import plugin_event_multiplexer as event_multiplexer # pylint: disable=line-too-long def _AddEvents(path): if not tf.gfile.IsDirectory(path): tf.gfile.MakeDirs(path) fpath = os.path.join(path, 'hypothetical.tfevents.out') with tf.gfile.GFile(fpath, 'w') as f: f.write('') return fpath def _CreateCleanDirectory(path): if tf.gfile.IsDirectory(path): tf.gfile.DeleteRecursively(path) tf.gfile.MkDir(path) class _FakeAccumulator(object): def __init__(self, path): """Constructs a fake accumulator with some fake events. Args: path: The path for the run that this accumulator is for. """ self._path = path self.reload_called = False self._plugin_to_tag_to_content = { 'baz_plugin': { 'foo': 'foo_content', 'bar': 'bar_content', } } def Tags(self): return {} def FirstEventTimestamp(self): return 0 def _TagHelper(self, tag_name, enum): if tag_name not in self.Tags()[enum]: raise KeyError return ['%s/%s' % (self._path, tag_name)] def Tensors(self, tag_name): return self._TagHelper(tag_name, event_accumulator.TENSORS) def PluginTagToContent(self, plugin_name): # We pre-pend the runs with the path and '_' so that we can verify that the # tags are associated with the correct runs. return { self._path + '_' + run: content_mapping for (run, content_mapping ) in self._plugin_to_tag_to_content[plugin_name].items() } def Reload(self): self.reload_called = True def _GetFakeAccumulator(path, size_guidance=None, tensor_size_guidance=None, purge_orphaned_data=None): del size_guidance, tensor_size_guidance, purge_orphaned_data # Unused. return _FakeAccumulator(path) class EventMultiplexerTest(tf.test.TestCase): def setUp(self): super(EventMultiplexerTest, self).setUp() self.stubs = tf.test.StubOutForTesting() self.stubs.Set(event_accumulator, 'EventAccumulator', _GetFakeAccumulator) def tearDown(self): self.stubs.CleanUp() def testEmptyLoader(self): """Tests empty EventMultiplexer creation.""" x = event_multiplexer.EventMultiplexer() self.assertEqual(x.Runs(), {}) def testRunNamesRespected(self): """Tests two EventAccumulators inserted/accessed in EventMultiplexer.""" x = event_multiplexer.EventMultiplexer({'run1': 'path1', 'run2': 'path2'}) self.assertItemsEqual(sorted(x.Runs().keys()), ['run1', 'run2']) self.assertEqual(x.GetAccumulator('run1')._path, 'path1') self.assertEqual(x.GetAccumulator('run2')._path, 'path2') def testReload(self): """EventAccumulators should Reload after EventMultiplexer call it.""" x = event_multiplexer.EventMultiplexer({'run1': 'path1', 'run2': 'path2'}) self.assertFalse(x.GetAccumulator('run1').reload_called) self.assertFalse(x.GetAccumulator('run2').reload_called) x.Reload() self.assertTrue(x.GetAccumulator('run1').reload_called) self.assertTrue(x.GetAccumulator('run2').reload_called) def testPluginRunToTagToContent(self): """Tests the method that produces the run to tag to content mapping.""" x = event_multiplexer.EventMultiplexer({'run1': 'path1', 'run2': 'path2'}) self.assertDictEqual({ 'run1': { 'path1_foo': 'foo_content', 'path1_bar': 'bar_content', }, 'run2': { 'path2_foo': 'foo_content', 'path2_bar': 'bar_content', } }, x.PluginRunToTagToContent('baz_plugin')) def testExceptions(self): """KeyError should be raised when accessing non-existing keys.""" x = event_multiplexer.EventMultiplexer({'run1': 'path1', 'run2': 'path2'}) with self.assertRaises(KeyError): x.Tensors('sv1', 'xxx') def testInitialization(self): """Tests EventMultiplexer is created properly with its params.""" x = event_multiplexer.EventMultiplexer() self.assertEqual(x.Runs(), {}) x = event_multiplexer.EventMultiplexer({'run1': 'path1', 'run2': 'path2'}) self.assertItemsEqual(x.Runs(), ['run1', 'run2']) self.assertEqual(x.GetAccumulator('run1')._path, 'path1') self.assertEqual(x.GetAccumulator('run2')._path, 'path2') def testAddRunsFromDirectory(self): """Tests AddRunsFromDirectory function. Tests the following scenarios: - When the directory does not exist. - When the directory is empty. - When the directory has empty subdirectory. - Contains proper EventAccumulators after adding events. """ x = event_multiplexer.EventMultiplexer() tmpdir = self.get_temp_dir() join = os.path.join fakedir = join(tmpdir, 'fake_accumulator_directory') realdir = join(tmpdir, 'real_accumulator_directory') self.assertEqual(x.Runs(), {}) x.AddRunsFromDirectory(fakedir) self.assertEqual(x.Runs(), {}, 'loading fakedir had no effect') _CreateCleanDirectory(realdir) x.AddRunsFromDirectory(realdir) self.assertEqual(x.Runs(), {}, 'loading empty directory had no effect') path1 = join(realdir, 'path1') tf.gfile.MkDir(path1) x.AddRunsFromDirectory(realdir) self.assertEqual(x.Runs(), {}, 'creating empty subdirectory had no effect') _AddEvents(path1) x.AddRunsFromDirectory(realdir) self.assertItemsEqual(x.Runs(), ['path1'], 'loaded run: path1') loader1 = x.GetAccumulator('path1') self.assertEqual(loader1._path, path1, 'has the correct path') path2 = join(realdir, 'path2') _AddEvents(path2) x.AddRunsFromDirectory(realdir) self.assertItemsEqual(x.Runs(), ['path1', 'path2']) self.assertEqual( x.GetAccumulator('path1'), loader1, 'loader1 not regenerated') path2_2 = join(path2, 'path2') _AddEvents(path2_2) x.AddRunsFromDirectory(realdir) self.assertItemsEqual(x.Runs(), ['path1', 'path2', 'path2/path2']) self.assertEqual( x.GetAccumulator('path2/path2')._path, path2_2, 'loader2 path correct') def testAddRunsFromDirectoryThatContainsEvents(self): x = event_multiplexer.EventMultiplexer() tmpdir = self.get_temp_dir() join = os.path.join realdir = join(tmpdir, 'event_containing_directory') _CreateCleanDirectory(realdir) self.assertEqual(x.Runs(), {}) _AddEvents(realdir) x.AddRunsFromDirectory(realdir) self.assertItemsEqual(x.Runs(), ['.']) subdir = join(realdir, 'subdir') _AddEvents(subdir) x.AddRunsFromDirectory(realdir) self.assertItemsEqual(x.Runs(), ['.', 'subdir']) def testAddRunsFromDirectoryWithRunNames(self): x = event_multiplexer.EventMultiplexer() tmpdir = self.get_temp_dir() join = os.path.join realdir = join(tmpdir, 'event_containing_directory') _CreateCleanDirectory(realdir) self.assertEqual(x.Runs(), {}) _AddEvents(realdir) x.AddRunsFromDirectory(realdir, 'foo') self.assertItemsEqual(x.Runs(), ['foo/.']) subdir = join(realdir, 'subdir') _AddEvents(subdir) x.AddRunsFromDirectory(realdir, 'foo') self.assertItemsEqual(x.Runs(), ['foo/.', 'foo/subdir']) def testAddRunsFromDirectoryWalksTree(self): x = event_multiplexer.EventMultiplexer() tmpdir = self.get_temp_dir() join = os.path.join realdir = join(tmpdir, 'event_containing_directory') _CreateCleanDirectory(realdir) _AddEvents(realdir) sub = join(realdir, 'subdirectory') sub1 = join(sub, '1') sub2 = join(sub, '2') sub1_1 = join(sub1, '1') _AddEvents(sub1) _AddEvents(sub2) _AddEvents(sub1_1) x.AddRunsFromDirectory(realdir) self.assertItemsEqual(x.Runs(), ['.', 'subdirectory/1', 'subdirectory/2', 'subdirectory/1/1']) def testAddRunsFromDirectoryThrowsException(self): x = event_multiplexer.EventMultiplexer() tmpdir = self.get_temp_dir() filepath = _AddEvents(tmpdir) with self.assertRaises(ValueError): x.AddRunsFromDirectory(filepath) def testAddRun(self): x = event_multiplexer.EventMultiplexer() x.AddRun('run1_path', 'run1') run1 = x.GetAccumulator('run1') self.assertEqual(sorted(x.Runs().keys()), ['run1']) self.assertEqual(run1._path, 'run1_path') x.AddRun('run1_path', 'run1') self.assertEqual(run1, x.GetAccumulator('run1'), 'loader not recreated') x.AddRun('run2_path', 'run1') new_run1 = x.GetAccumulator('run1') self.assertEqual(new_run1._path, 'run2_path') self.assertNotEqual(run1, new_run1) x.AddRun('runName3') self.assertItemsEqual(sorted(x.Runs().keys()), ['run1', 'runName3']) self.assertEqual(x.GetAccumulator('runName3')._path, 'runName3') def testAddRunMaintainsLoading(self): x = event_multiplexer.EventMultiplexer() x.Reload() x.AddRun('run1') x.AddRun('run2') self.assertTrue(x.GetAccumulator('run1').reload_called) self.assertTrue(x.GetAccumulator('run2').reload_called) def testAddReloadWithMultipleThreads(self): x = event_multiplexer.EventMultiplexer(max_reload_threads=2) x.Reload() x.AddRun('run1') x.AddRun('run2') x.AddRun('run3') self.assertTrue(x.GetAccumulator('run1').reload_called) self.assertTrue(x.GetAccumulator('run2').reload_called) self.assertTrue(x.GetAccumulator('run3').reload_called) def testReloadWithMoreRunsThanThreads(self): patcher = tf.test.mock.patch('threading.Thread.start', autospec=True) start_mock = patcher.start() self.addCleanup(patcher.stop) patcher = tf.test.mock.patch( 'six.moves.queue.Queue.join', autospec=True) join_mock = patcher.start() self.addCleanup(patcher.stop) x = event_multiplexer.EventMultiplexer(max_reload_threads=2) x.AddRun('run1') x.AddRun('run2') x.AddRun('run3') x.Reload() # 2 threads should have been started despite how there are 3 runs. self.assertEqual(2, start_mock.call_count) self.assertEqual(1, join_mock.call_count) def testReloadWithMoreThreadsThanRuns(self): patcher = tf.test.mock.patch('threading.Thread.start', autospec=True) start_mock = patcher.start() self.addCleanup(patcher.stop) patcher = tf.test.mock.patch( 'six.moves.queue.Queue.join', autospec=True) join_mock = patcher.start() self.addCleanup(patcher.stop) x = event_multiplexer.EventMultiplexer(max_reload_threads=42) x.AddRun('run1') x.AddRun('run2') x.AddRun('run3') x.Reload() # 3 threads should have been started despite how the multiplexer # could have started up to 42 threads. self.assertEqual(3, start_mock.call_count) self.assertEqual(1, join_mock.call_count) def testReloadWith1Thread(self): patcher = tf.test.mock.patch('threading.Thread.start', autospec=True) start_mock = patcher.start() self.addCleanup(patcher.stop) patcher = tf.test.mock.patch( 'six.moves.queue.Queue.join', autospec=True) join_mock = patcher.start() self.addCleanup(patcher.stop) x = event_multiplexer.EventMultiplexer(max_reload_threads=1) x.AddRun('run1') x.AddRun('run2') x.AddRun('run3') x.Reload() # The multiplexer should have started no new threads. self.assertEqual(0, start_mock.call_count) self.assertEqual(0, join_mock.call_count) class EventMultiplexerWithRealAccumulatorTest(tf.test.TestCase): def testDeletingDirectoryRemovesRun(self): x = event_multiplexer.EventMultiplexer() tmpdir = self.get_temp_dir() self.add3RunsToMultiplexer(tmpdir, x) x.Reload() # Delete the directory, then reload. shutil.rmtree(os.path.join(tmpdir, 'run2')) x.Reload() self.assertNotIn('run2', x.Runs().keys()) def add3RunsToMultiplexer(self, logdir, multiplexer): """Creates and adds 3 runs to the multiplexer.""" run1_dir = os.path.join(logdir, 'run1') run2_dir = os.path.join(logdir, 'run2') run3_dir = os.path.join(logdir, 'run3') for dirname in [run1_dir, run2_dir, run3_dir]: _AddEvents(dirname) multiplexer.AddRun(run1_dir, 'run1') multiplexer.AddRun(run2_dir, 'run2') multiplexer.AddRun(run3_dir, 'run3') if __name__ == '__main__': tf.test.main()
{ "content_hash": "208677138d0b4f1c0f126c1ec81ac2bb", "timestamp": "", "source": "github", "line_count": 380, "max_line_length": 127, "avg_line_length": 32.96578947368421, "alnum_prop": 0.6737447114233256, "repo_name": "qiuminxu/tensorboard", "id": "fd2328b3bc00024aed7fb358cf90bd24a6814c4b", "size": "13217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorboard/backend/event_processing/plugin_event_multiplexer_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1083692" }, { "name": "Java", "bytes": "28751" }, { "name": "JavaScript", "bytes": "1576" }, { "name": "Python", "bytes": "1576041" }, { "name": "Shell", "bytes": "9420" }, { "name": "TypeScript", "bytes": "1020404" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; using Cats.Data.UnitWork; using Cats.Data.Hub; using Cats.Models; namespace Cats.Services.Transaction { public class TransactionService : ITransactionService { private readonly Cats.Data.UnitWork.IUnitOfWork _unitOfWork; public TransactionService(Cats.Data.UnitWork.IUnitOfWork unitOfWork) { this._unitOfWork = unitOfWork; } #region generic methods public bool AddTransaction(Models.Transaction item) { _unitOfWork.TransactionRepository.Add(item); _unitOfWork.Save(); return true; } public bool UpdateTransaction(Models.Transaction item) { if (item == null) return false; _unitOfWork.TransactionRepository.Edit(item); _unitOfWork.Save(); return true; } public bool DeleteTransaction(Models.Transaction item) { if (item == null) return false; _unitOfWork.TransactionRepository.Delete(item); _unitOfWork.Save(); return true; } public bool DeleteById(Guid id) { var item = _unitOfWork.TransactionRepository.FindById(id); return DeleteTransaction(item); } public Models.Transaction FindById(Guid id) { return _unitOfWork.TransactionRepository.FindById(id); } public List<Models.Transaction> GetAllTransaction() { return _unitOfWork.TransactionRepository.GetAll(); } public List<Models.Transaction> FindBy(Expression<Func<Models.Transaction, bool>> predicate) { return _unitOfWork.TransactionRepository.FindBy(predicate); } #endregion public IEnumerable<Models.Transaction> PostTransaction(IEnumerable<Models.Transaction> entries) { Guid transactionGroupID = Guid.NewGuid(); DateTime TransactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup {PartitionID = 0, TransactionGroupID = transactionGroupID}); foreach (Models.Transaction entry in entries) { entry.TransactionDate = TransactionDate; entry.TransactionGroupID = transactionGroupID; entry.TransactionID = Guid.NewGuid(); _unitOfWork.TransactionRepository.Add(entry); } _unitOfWork.Save(); return entries; } #region HRD / PSNP Post public List<Models.Transaction> PostHRDPlan(HRD hrd, Ration ration) { List<Models.Transaction> entries = new List<Models.Transaction>(); List<int> regionalBenCount = new List<int>(); ration = hrd.Ration; int RegionID=0; for (int r = 0; r < 12; r++) { regionalBenCount.Add(0); } foreach (HRDDetail fdp in hrd.HRDDetails) { for (int r = 0; r < fdp.DurationOfAssistance; r++) { regionalBenCount[r] += (int)fdp.NumberOfBeneficiaries; RegionID = fdp.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID; } } for (int r = 0; r < 12; r++) { int noben = regionalBenCount[r]; if (noben > 0) { Guid transactionGroupID = Guid.NewGuid(); DateTime transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroupID }); foreach (RationDetail rd in ration.RationDetails) { decimal amount = (rd.Amount/1000)*noben; var entry2 = new Models.Transaction { RegionID = RegionID, CommodityID = rd.CommodityID, ParentCommodityID = rd.Commodity.ParentID, Round = r + 1, ProgramID = TransactionConstants.Constants.HRD_PROGRAM_ID, QuantityInUnit = amount, UnitID = 1, QuantityInMT = amount, LedgerID = Cats.Models.Ledger.Constants.REQUIRMENT_DOCUMENT_PLAN, // previously 200 TransactionDate = transactionDate, TransactionGroupID = transactionGroupID, PlanId = hrd.PlanID, TransactionID = Guid.NewGuid(), }; var entry1 = new Models.Transaction { RegionID = RegionID, CommodityID = rd.CommodityID, ParentCommodityID = rd.Commodity.ParentID, Round = r + 1, ProgramID = TransactionConstants.Constants.HRD_PROGRAM_ID, QuantityInUnit = -amount, UnitID = 1, QuantityInMT = -amount, LedgerID = Cats.Models.Ledger.Constants.REQUIRMENT_DOCUMENT, //previously 100 TransactionDate = transactionDate, TransactionGroupID = transactionGroupID, PlanId = hrd.PlanID, TransactionID = Guid.NewGuid(), }; _unitOfWork.TransactionRepository.Add(entry1); _unitOfWork.TransactionRepository.Add(entry2); entries.Add(entry1); entries.Add(entry2); //hrd.TransactionGroupID = transactionGroupID; //_unitOfWork.HRDRepository.Edit(hrd); _unitOfWork.Save(); } } } return entries; } //TODO: Check if this method is being called, //Where in PSNP workflow did this get posted. public List<Models.Transaction> PostPSNPPlan(RegionalPSNPPlan plan, Ration ration) { List<Models.Transaction> entries = new List<Models.Transaction>(); List<int> regionalBenCount = new List<int>(); for (int r = 0; r < plan.Duration; r++) { regionalBenCount.Add(0); } foreach (RegionalPSNPPlanDetail fdp in plan.RegionalPSNPPlanDetails) { for (int r = 0; r < fdp.FoodRatio; r++) { regionalBenCount[r] += (int)fdp.BeneficiaryCount; } } for (int r = 0; r < plan.Duration; r++) { int noben = regionalBenCount[r]; if (noben > 0) { Guid transactionGroupID = Guid.NewGuid(); DateTime transactionDate = DateTime.Now; foreach (RationDetail rd in ration.RationDetails) { decimal amount = rd.Amount * noben; Models.Transaction entry2 = new Models.Transaction { CommodityID = rd.CommodityID, Round = r + 1, ProgramID = TransactionConstants.Constants.PSNP_PROGRAM_ID, QuantityInUnit = amount, UnitID=1, QuantityInMT = amount, LedgerID = Cats.Models.Ledger.Constants.REQUIRMENT_DOCUMENT_PLAN, // previously 200 TransactionDate = transactionDate, TransactionGroupID = transactionGroupID, PlanId = plan.PlanId, TransactionID = Guid.NewGuid(), }; Models.Transaction entry1 = new Models.Transaction { CommodityID = rd.CommodityID, Round = r + 1, ProgramID = TransactionConstants.Constants.PSNP_PROGRAM_ID, QuantityInUnit = -amount, UnitID = 1, QuantityInMT = -amount, LedgerID = Cats.Models.Ledger.Constants.REQUIRMENT_DOCUMENT, //previously 100 TransactionDate = transactionDate, TransactionGroupID = transactionGroupID, PlanId = plan.PlanId, TransactionID = Guid.NewGuid(), }; _unitOfWork.TransactionRepository.Add(entry1); _unitOfWork.TransactionRepository.Add(entry2); _unitOfWork.Save(); entries.Add(entry1); entries.Add(entry2); } plan.TransactionGroupID = transactionGroupID; _unitOfWork.RegionalPSNPPlanRepository.Edit(plan); } } return entries; } #endregion #region Post RRD //TODO: check if this is called for PSNP. It must be called for both programs public bool PostRequestAllocation(int requestId)//RRD { var result = new List<Models.Transaction>(); var allocationDetails = _unitOfWork.ReliefRequisitionDetailRepository.FindBy(r => r.ReliefRequisition.RequisitionID == requestId); if (allocationDetails == null) return false; var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroup }); foreach (var detail in allocationDetails) { var transaction = new Models.Transaction(); transaction.TransactionID = Guid.NewGuid(); transaction.TransactionGroupID = transactionGroup; transaction.TransactionDate = transactionDate; transaction.UnitID = 1; transaction.QuantityInMT = - detail.Amount; transaction.QuantityInUnit = - detail.Amount; transaction.LedgerID = Models.Ledger.Constants.PLEDGED_TO_FDP; transaction.CommodityID = detail.CommodityID; if (detail.Commodity.ParentID!=null) transaction.ParentCommodityID = detail.Commodity.ParentID; transaction.FDPID = detail.FDPID; transaction.ProgramID = detail.ReliefRequisition.ProgramID; transaction.RegionID = detail.ReliefRequisition.RegionID; transaction.PlanId = detail.ReliefRequisition.RegionalRequest.PlanID; transaction.Round = detail.ReliefRequisition.RegionalRequest.Round; transaction.Month = detail.ReliefRequisition.RegionalRequest.Month; _unitOfWork.TransactionRepository.Add(transaction); //for Register Doc transaction = new Models.Transaction(); transaction.TransactionID = Guid.NewGuid(); transaction.TransactionGroupID = transactionGroup; transaction.TransactionDate = transactionDate; transaction.UnitID = 1; transaction.QuantityInMT = detail.Amount; transaction.QuantityInUnit = detail.Amount; transaction.LedgerID = Models.Ledger.Constants.REQUIRMENT_DOCUMENT; transaction.CommodityID = detail.CommodityID; if (detail.Commodity.ParentID != null) transaction.ParentCommodityID = detail.Commodity.ParentID; transaction.FDPID = detail.FDPID; transaction.ProgramID = detail.ReliefRequisition.ProgramID; transaction.RegionID = detail.ReliefRequisition.RegionID; transaction.PlanId = detail.ReliefRequisition.RegionalRequest.PlanID; transaction.Round = detail.ReliefRequisition.RegionalRequest.Round; transaction.Month = detail.ReliefRequisition.RegionalRequest.Month; _unitOfWork.TransactionRepository.Add(transaction); } _unitOfWork.Save(); return true; } #endregion #region Post Dispatch Plan public bool PostSIAllocation(int requisitionID) { var allocationDetails = _unitOfWork.SIPCAllocationRepository.Get(t => t.ReliefRequisitionDetail.RequisitionID == requisitionID); if (allocationDetails == null) return false; var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup { PartitionID = 0, TransactionGroupID = transactionGroup }); //ProjectCodeID ShippingInstructionID ProgramID QuantityInMT QuantityInUnit UnitID TransactionDate RegionID Month Round DonorID CommoditySourceID GiftTypeID FDP foreach (var allocationDetail in allocationDetails) { var transaction = new Models.Transaction { TransactionID = Guid.NewGuid(), TransactionGroupID = transactionGroup, TransactionDate = transactionDate, UnitID = 1 }; var allocation = allocationDetail; transaction.QuantityInMT = -allocationDetail.AllocatedAmount; transaction.QuantityInUnit = -allocationDetail.AllocatedAmount; transaction.LedgerID = Ledger.Constants.COMMITED_TO_FDP; transaction.CommodityID = allocationDetail.ReliefRequisitionDetail.CommodityID; transaction.ParentCommodityID = allocationDetail.ReliefRequisitionDetail.Commodity.ParentID; transaction.FDPID = allocationDetail.ReliefRequisitionDetail.FDPID; transaction.ProgramID = (int)allocationDetail.ReliefRequisitionDetail.ReliefRequisition.ProgramID; transaction.RegionID = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionID; transaction.PlanId = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionalRequest.PlanID; transaction.Round = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.Round; int hubID1=0 ; if (allocationDetail.AllocationType == TransactionConstants.Constants.SHIPPNG_INSTRUCTION) { transaction.ShippingInstructionID = allocationDetail.Code; hubID1= (int) _unitOfWork.TransactionRepository.FindBy(m=>m.ShippingInstructionID==allocationDetail.Code && m.LedgerID==Ledger.Constants.GOODS_ON_HAND).Select(m=>m.HubID).FirstOrDefault(); } else { transaction.ProjectCodeID = allocationDetail.Code; hubID1 = (int)_unitOfWork.TransactionRepository.FindBy(m => m.ProjectCodeID == allocationDetail.Code && m.LedgerID == Ledger.Constants.GOODS_ON_HAND).Select(m => m.HubID).FirstOrDefault(); } // I see some logical error here // what happens when hub x was selected and the allocation was made from hub y? //TOFIX: // Hub is required for this transaction // Try catch is danger!! Either throw the exception or use conditional statement. if (hubID1!=0) { transaction.HubID = hubID1; } else { transaction.HubID = _unitOfWork.HubAllocationRepository.FindBy(r => r.RequisitionID == allocation.ReliefRequisitionDetail.RequisitionID).Select( h => h.HubID).FirstOrDefault(); } _unitOfWork.TransactionRepository.Add(transaction); // result.Add(transaction); /*post Debit-Pledged To FDP*/ var transaction2 = new Models.Transaction { TransactionID = Guid.NewGuid(), TransactionGroupID = transactionGroup, TransactionDate = transactionDate, UnitID = 1 }; transaction2.QuantityInMT = allocationDetail.AllocatedAmount; transaction2.QuantityInUnit = allocationDetail.AllocatedAmount; transaction2.LedgerID = Ledger.Constants.PLEDGED_TO_FDP; transaction2.CommodityID = allocationDetail.ReliefRequisitionDetail.CommodityID; transaction2.ParentCommodityID = allocationDetail.ReliefRequisitionDetail.Commodity.ParentID; transaction2.FDPID = allocationDetail.ReliefRequisitionDetail.FDPID; transaction2.ProgramID = (int)allocationDetail.ReliefRequisitionDetail.ReliefRequisition.ProgramID; transaction2.RegionID = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionID; transaction2.PlanId = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionalRequest.PlanID; transaction2.Round = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.Round; int hubID2 = 0; if (allocationDetail.AllocationType == TransactionConstants.Constants.SHIPPNG_INSTRUCTION) { var siCode = allocationDetail.Code.ToString(); var shippingInstruction = _unitOfWork.ShippingInstructionRepository.Get(t => t.Value == siCode). FirstOrDefault(); if (shippingInstruction != null) transaction.ShippingInstructionID = shippingInstruction.ShippingInstructionID; hubID2=(int) _unitOfWork.TransactionRepository.FindBy(m => m.ShippingInstructionID == allocationDetail.Code && m.LedgerID == Ledger.Constants.GOODS_ON_HAND).Select(m => m.HubID).FirstOrDefault(); } else { var detail = allocationDetail; var code = detail.Code.ToString(); var projectCode = _unitOfWork.ProjectCodeRepository.Get(t => t.Value == code). FirstOrDefault(); if (projectCode != null) transaction.ProjectCodeID = projectCode.ProjectCodeID; hubID2 = (int)_unitOfWork.TransactionRepository.FindBy(m => m.ProjectCodeID == allocationDetail.Code && m.LedgerID == Ledger.Constants.GOODS_ON_HAND).Select(m => m.HubID).FirstOrDefault(); } if (hubID2!=0) { transaction2.HubID = hubID2; } else { transaction2.HubID = _unitOfWork.HubAllocationRepository.FindBy(r => r.RequisitionID == allocation.ReliefRequisitionDetail.RequisitionID).Select( h => h.HubID).FirstOrDefault(); } _unitOfWork.TransactionRepository.Add(transaction2); allocationDetail.TransactionGroupID = transactionGroup; _unitOfWork.SIPCAllocationRepository.Edit(allocationDetail); //result.Add(transaction); } var requisition = _unitOfWork.ReliefRequisitionRepository.FindById(requisitionID); requisition.Status = 4; _unitOfWork.ReliefRequisitionRepository.Edit(requisition); _unitOfWork.Save(); //return result; return true; } public bool PostSIAllocationUncommit(int requisitionID) { var allocationDetails = _unitOfWork.SIPCAllocationRepository.Get(t => t.ReliefRequisitionDetail.RequisitionID == requisitionID); if (allocationDetails == null) return false; var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup { PartitionID = 0, TransactionGroupID = transactionGroup }); //ProjectCodeID ShippingInstructionID ProgramID QuantityInMT QuantityInUnit UnitID TransactionDate RegionID Month Round DonorID CommoditySourceID GiftTypeID FDP foreach (var allocationDetail in allocationDetails) { var transaction = new Models.Transaction { TransactionID = Guid.NewGuid(), TransactionGroupID = transactionGroup, TransactionDate = transactionDate, UnitID = 1 }; var allocation = allocationDetail; // I see some logical error here // what happens when hub x was selected and the allocation was made from hub y? //TOFIX: // Hub is required for this transaction // Try catch is danger!! Either throw the exception or use conditional statement. int hubID = 0; if (allocationDetail.AllocationType == TransactionConstants.Constants.SHIPPNG_INSTRUCTION) { var siCode = allocationDetail.Code.ToString(); var shippingInstruction = _unitOfWork.ShippingInstructionRepository.Get(t => t.Value == siCode). FirstOrDefault(); if (shippingInstruction != null) transaction.ShippingInstructionID = shippingInstruction.ShippingInstructionID; hubID = (int)_unitOfWork.TransactionRepository.FindBy(m => m.ShippingInstructionID == allocationDetail.Code && m.LedgerID == Ledger.Constants.GOODS_ON_HAND).Select(m => m.HubID).FirstOrDefault(); } else { var detail = allocationDetail; var code = detail.Code.ToString(); var projectCode = _unitOfWork.ProjectCodeRepository.Get(t => t.Value == code). FirstOrDefault(); if (projectCode != null) transaction.ProjectCodeID = projectCode.ProjectCodeID; hubID = (int)_unitOfWork.TransactionRepository.FindBy(m => m.ProjectCodeID == allocationDetail.Code && m.LedgerID == Ledger.Constants.GOODS_ON_HAND).Select(m => m.HubID).FirstOrDefault(); } if (hubID != 0) { transaction.HubID = hubID; } else { transaction.HubID = _unitOfWork.HubAllocationRepository.FindBy(r => r.RequisitionID == allocation.ReliefRequisitionDetail.RequisitionID).Select( h => h.HubID).FirstOrDefault(); } transaction.QuantityInMT = allocationDetail.AllocatedAmount; transaction.QuantityInUnit = allocationDetail.AllocatedAmount; transaction.LedgerID = Ledger.Constants.COMMITED_TO_FDP; transaction.CommodityID = allocationDetail.ReliefRequisitionDetail.CommodityID; transaction.FDPID = allocationDetail.ReliefRequisitionDetail.FDPID; transaction.ProgramID = (int)allocationDetail.ReliefRequisitionDetail.ReliefRequisition.ProgramID; transaction.RegionID = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionID; if (allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionalRequest!=null) { transaction.PlanId = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionalRequest.PlanID; } transaction.Round = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.Round; if (allocationDetail.AllocationType == TransactionConstants.Constants.SHIPPNG_INSTRUCTION) { transaction.ShippingInstructionID = allocationDetail.Code; } else { transaction.ProjectCodeID = allocationDetail.Code; } _unitOfWork.TransactionRepository.Add(transaction); // result.Add(transaction); /*post Debit-Pledged To FDP*/ var transaction2 = new Models.Transaction { TransactionID = Guid.NewGuid(), TransactionGroupID = transactionGroup, TransactionDate = transactionDate, UnitID = 1 }; //TOFIX: do not use try catch int hubID2 = 0; if (allocationDetail.AllocationType == TransactionConstants.Constants.SHIPPNG_INSTRUCTION) { var siCode = allocationDetail.Code.ToString(); var shippingInstruction = _unitOfWork.ShippingInstructionRepository.Get(t => t.Value == siCode). FirstOrDefault(); if (shippingInstruction != null) transaction.ShippingInstructionID = shippingInstruction.ShippingInstructionID; hubID2 = (int)_unitOfWork.TransactionRepository.FindBy(m => m.ShippingInstructionID == allocationDetail.Code && m.LedgerID == Ledger.Constants.GOODS_ON_HAND).Select(m => m.HubID).FirstOrDefault(); } else { var detail = allocationDetail; var code = detail.Code.ToString(); var projectCode = _unitOfWork.ProjectCodeRepository.Get(t => t.Value == code). FirstOrDefault(); if (projectCode != null) transaction.ProjectCodeID = projectCode.ProjectCodeID; hubID2 = (int)_unitOfWork.TransactionRepository.FindBy(m => m.ProjectCodeID == allocationDetail.Code && m.LedgerID == Ledger.Constants.GOODS_ON_HAND).Select(m => m.HubID).FirstOrDefault(); } if (hubID2 != 0) { transaction2.HubID = hubID2; } else { transaction2.HubID = _unitOfWork.HubAllocationRepository.FindBy(r => r.RequisitionID == allocation.ReliefRequisitionDetail.RequisitionID).Select( h => h.HubID).FirstOrDefault(); } transaction2.QuantityInMT = -allocationDetail.AllocatedAmount; transaction2.QuantityInUnit = -allocationDetail.AllocatedAmount; transaction2.LedgerID = Ledger.Constants.PLEDGED_TO_FDP; transaction2.CommodityID = allocationDetail.ReliefRequisitionDetail.CommodityID; transaction2.FDPID = allocationDetail.ReliefRequisitionDetail.FDPID; transaction2.ProgramID = (int)allocationDetail.ReliefRequisitionDetail.ReliefRequisition.ProgramID; transaction2.RegionID = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionID; if (allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionalRequest != null) { transaction2.PlanId = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.RegionalRequest.PlanID; } transaction2.Round = allocationDetail.ReliefRequisitionDetail.ReliefRequisition.Round; if (allocationDetail.AllocationType == TransactionConstants.Constants.SHIPPNG_INSTRUCTION) { var siCode = allocationDetail.Code.ToString(); var shippingInstruction = _unitOfWork.ShippingInstructionRepository.Get(t => t.Value == siCode). FirstOrDefault(); if (shippingInstruction != null) transaction.ShippingInstructionID = shippingInstruction.ShippingInstructionID; } else { var detail = allocationDetail; var code = detail.Code.ToString(); var projectCode = _unitOfWork.ProjectCodeRepository.Get(t => t.Value == code). FirstOrDefault(); if (projectCode != null) transaction.ProjectCodeID = projectCode.ProjectCodeID; } _unitOfWork.TransactionRepository.Add(transaction2); _unitOfWork.SIPCAllocationRepository.Delete(allocationDetail); //result.Add(transaction); } var requisition = _unitOfWork.ReliefRequisitionRepository.FindById(requisitionID); requisition.Status = (int) Cats.Models.Constant.ReliefRequisitionStatus.Approved; _unitOfWork.ReliefRequisitionRepository.Edit(requisition); _unitOfWork.Save(); //return result; return true; } #endregion #region Post Donation Plan public bool PostDonationPlan(DonationPlanHeader donationPlanHeader) { var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroup }); foreach (var donationPlanDetail in donationPlanHeader.DonationPlanDetails) { var transaction = new Models.Transaction { TransactionID = Guid.NewGuid(), ProgramID = donationPlanHeader.ProgramID, DonorID = donationPlanHeader.DonorID, CommoditySourceID = 1, QuantityInMT = donationPlanDetail.AllocatedAmount, TransactionGroupID = transactionGroup, TransactionDate = transactionDate, CommodityID = donationPlanHeader.CommodityID, ParentCommodityID = donationPlanHeader.Commodity.ParentID, ShippingInstructionID = donationPlanHeader.ShippingInstructionId, HubID = donationPlanDetail.HubID, LedgerID = Ledger.Constants.GOODS_RECIEVABLE }; _unitOfWork.TransactionRepository.Add(transaction); transaction= new Models.Transaction { TransactionID = Guid.NewGuid(), ProgramID = donationPlanHeader.ProgramID, DonorID = donationPlanHeader.DonorID, CommoditySourceID = 1, QuantityInMT = -donationPlanDetail.AllocatedAmount, TransactionGroupID = transactionGroup, TransactionDate = transactionDate, CommodityID = donationPlanHeader.CommodityID, ParentCommodityID = donationPlanHeader.Commodity.ParentID, ShippingInstructionID = donationPlanHeader.ShippingInstructionId, HubID = donationPlanDetail.HubID, LedgerID = Ledger.Constants.GIFT_CERTIFICATE //good promissed - pledged is not in ledger list // Former LedgerID = 4 }; _unitOfWork.TransactionRepository.Add(transaction); } var donationHeader = _unitOfWork.DonationPlanHeaderRepository.FindById(donationPlanHeader.DonationHeaderPlanID); if (donationHeader!=null) donationPlanHeader.TransactionGroupID = transactionGroup; _unitOfWork.Save(); return true; } #endregion #region Post Local Purchase public bool PostLocalPurchase(List<LocalPurchaseDetail> localPurchaseDetail) { var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroup }); if (localPurchaseDetail != null) foreach (var detail in localPurchaseDetail) { var transaction = new Models.Transaction { TransactionID = Guid.NewGuid(), CommoditySourceID = Models.Constant.CommoditySourceConst.Constants.LOCALPURCHASE, CommodityID = detail.LocalPurchase.CommodityID, ParentCommodityID = detail.LocalPurchase.Commodity.ParentID, DonorID = detail.LocalPurchase.DonorID, HubID = detail.HubID, ProgramID = detail.LocalPurchase.ProgramID, QuantityInMT = detail.AllocatedAmount, QuantityInUnit = detail.AllocatedAmount, ShippingInstructionID = detail.LocalPurchase.ShippingInstructionID, TransactionDate = transactionDate, TransactionGroupID = transactionGroup //LedgerID = Models.Ledger.Constants }; _unitOfWork.TransactionRepository.Add(transaction); transaction = new Models.Transaction { TransactionID = Guid.NewGuid(), CommoditySourceID = Models.Constant.CommoditySourceConst.Constants.LOCALPURCHASE, CommodityID = detail.LocalPurchase.CommodityID, ParentCommodityID = detail.LocalPurchase.Commodity.ParentID, DonorID = detail.LocalPurchase.DonorID, HubID = detail.HubID, ProgramID = detail.LocalPurchase.ProgramID, QuantityInMT = detail.AllocatedAmount, QuantityInUnit = detail.AllocatedAmount, ShippingInstructionID = detail.LocalPurchase.ShippingInstructionID, TransactionDate = transactionDate, TransactionGroupID = transactionGroup //LedgerID = Models.Ledger.Constants }; _unitOfWork.TransactionRepository.Add(transaction); } try { _unitOfWork.Save(); return true; } catch (Exception) { return false; } } #endregion #region Post Loan public bool PostLoan(LoanReciptPlan loanReciptPlan) { var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroup }); foreach (var loan in loanReciptPlan.LoanReciptPlanDetails) { var transaction = new Models.Transaction() { TransactionID = Guid.NewGuid(), CommoditySourceID =Models.Constant.CommoditySourceConst.Constants.LOAN, CommodityID = loan.LoanReciptPlan.CommodityID, ParentCommodityID = loan.LoanReciptPlan.Commodity.ParentID, ShippingInstructionID = loanReciptPlan.ShippingInstruction.ShippingInstructionID, QuantityInMT = loan.RecievedQuantity, HubID = loan.HubID, TransactionDate = transactionDate, TransactionGroupID = transactionGroup // LedgerID = Cats.Models.Ledger.Constants }; _unitOfWork.TransactionRepository.Add(transaction); transaction = new Models.Transaction() { TransactionID = Guid.NewGuid(), CommoditySourceID = Models.Constant.CommoditySourceConst.Constants.LOAN, CommodityID = loan.LoanReciptPlan.CommodityID, ParentCommodityID = loan.LoanReciptPlan.Commodity.ParentID, ShippingInstructionID = loanReciptPlan.ShippingInstruction.ShippingInstructionID, QuantityInMT = loan.RecievedQuantity, HubID = loan.HubID, TransactionDate = transactionDate, TransactionGroupID = transactionGroup // LedgerID = Cats.Models.Ledger.Constants }; _unitOfWork.TransactionRepository.Add(transaction); } try { _unitOfWork.Save(); return true; } catch (Exception) { return false; } return true; } #endregion //commodityParentId not found #region Post Distribution public bool PostDistribution(int distributionId) { var woredaStcokDistribution = _unitOfWork.WoredaStockDistributionRepository.FindById(distributionId); if (woredaStcokDistribution!=null) { var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroup }); foreach (var woredaStockDistributionDetail in woredaStcokDistribution.WoredaStockDistributionDetails) { var transaction = new Models.Transaction { TransactionID = Guid.NewGuid(), ProgramID = woredaStcokDistribution.ProgramID, QuantityInMT = woredaStockDistributionDetail.DistributedAmount, TransactionGroupID = transactionGroup, TransactionDate = transactionDate, FDPID = woredaStockDistributionDetail.FdpId, Month = woredaStcokDistribution.Month, PlanId = woredaStcokDistribution.PlanID, CommodityID = woredaStockDistributionDetail.CommodityID, //add commodity LedgerID = Ledger.Constants.GOODS_UNDER_CARE }; _unitOfWork.TransactionRepository.Add(transaction); transaction = new Models.Transaction { TransactionID = Guid.NewGuid(), ProgramID = woredaStcokDistribution.ProgramID, QuantityInMT = -woredaStockDistributionDetail.DistributedAmount, TransactionGroupID = transactionGroup, TransactionDate = transactionDate, FDPID = woredaStockDistributionDetail.FdpId, Month = woredaStcokDistribution.Month, PlanId = woredaStcokDistribution.PlanID, CommodityID = woredaStockDistributionDetail.CommodityID, //add commodity LedgerID = Ledger.Constants.DELIVERY_RECEIPT }; _unitOfWork.TransactionRepository.Add(transaction); } woredaStcokDistribution.TransactionGroupID = transactionGroup; _unitOfWork.Save(); } return true; } #endregion #region Post GiftCeritifficate public bool PostGiftCertificate(int giftCertificateId) { var giftCertificate = _unitOfWork.GiftCertificateRepository.Get(t => t.GiftCertificateID == giftCertificateId, null,"GiftCertificateDetails").FirstOrDefault(); if(giftCertificate==null) return false; var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroup }); foreach (var giftCertificateDetail in giftCertificate.GiftCertificateDetails) { var transaction = new Models.Transaction(); transaction.TransactionID = Guid.NewGuid(); transaction.ProgramID = giftCertificate.ProgramID; transaction.DonorID = giftCertificate.DonorID; transaction.CommoditySourceID = giftCertificateDetail.DFundSourceID; transaction.GiftTypeID = giftCertificateDetail.DFundSourceID; transaction.QuantityInMT = giftCertificateDetail.WeightInMT; transaction.QuantityInUnit = giftCertificateDetail.WeightInMT; transaction.TransactionGroupID = transactionGroup; transaction.TransactionDate = transactionDate; transaction.UnitID = 1; transaction.LedgerID = Ledger.Constants.GIFT_CERTIFICATE;//Goods Promised - Gift Certificate - Commited not found in ledger list transaction.CommodityID = giftCertificateDetail.CommodityID; transaction.ParentCommodityID = giftCertificateDetail.Commodity.ParentID; // transaction.ShippingInstructionID = giftCertificate.SINumber; _unitOfWork.TransactionRepository.Add(transaction); transaction = new Models.Transaction(); transaction.TransactionID = Guid.NewGuid(); transaction.ProgramID = giftCertificate.ProgramID; transaction.DonorID = giftCertificate.DonorID; transaction.QuantityInMT = -giftCertificateDetail.WeightInMT; transaction.TransactionGroupID = transactionGroup; transaction.TransactionDate = transactionDate; transaction.QuantityInUnit = giftCertificateDetail.WeightInMT; transaction.UnitID = 1; transaction.ParentCommodityID = giftCertificateDetail.Commodity.ParentID; transaction.LedgerID = Ledger.Constants.PLEDGE;//Goods Promised - Pledge not found in ledger list _unitOfWork.TransactionRepository.Add(transaction); } giftCertificate.StatusID = 2; giftCertificate.TransactionGroupID = transactionGroup; _unitOfWork.Save(); return true; } #endregion // commodityId and commodityParentId not found #region Post Delivery Reconcile public bool PostDeliveryReconcileReceipt(int deliveryReconcileID) { var deliveryReconcile = _unitOfWork.DeliveryReconcileRepository.Get(t => t.DeliveryReconcileID == deliveryReconcileID, null, "Dispatch").FirstOrDefault(); if (deliveryReconcile == null) return false; var transactionGroup = Guid.NewGuid(); var transactionDate = DateTime.Now; _unitOfWork.TransactionGroupRepository.Add(new TransactionGroup() { PartitionID = 0, TransactionGroupID = transactionGroup }); var transaction = new Models.Transaction(); transaction.TransactionID = Guid.NewGuid(); var reliefRequisition = _unitOfWork.ReliefRequisitionRepository.Get(t => t.RequisitionNo == deliveryReconcile.RequsitionNo).FirstOrDefault(); if (reliefRequisition != null) transaction.ProgramID = reliefRequisition.ProgramID; var orDefault = _unitOfWork.DispatchRepository.Get(t => t.DispatchID == deliveryReconcile.DispatchID).FirstOrDefault(); if (orDefault !=null) transaction.DonorID = orDefault.DispatchAllocation.DonorID; transaction.TransactionGroupID = transactionGroup; transaction.TransactionDate = transactionDate; var dispatch = _unitOfWork.DispatchRepository.Get(t => t.DispatchID == deliveryReconcile.DispatchID).FirstOrDefault(); if (dispatch !=null) transaction.ShippingInstructionID = dispatch.DispatchAllocation.ShippingInstructionID; if (reliefRequisition != null) transaction.PlanId = reliefRequisition.RegionalRequest.PlanID; if (reliefRequisition != null) transaction.Round = reliefRequisition.RegionalRequest.Round; //transaction.LedgerID = Ledger.Constants.DELIVERY_RECEIPT; //transaction.FDPID = delivery.FDPID; //var firstOrDefault = delivery.DeliveryDetails.FirstOrDefault(); transaction.LedgerID = Models.Ledger.Constants.DELIVERY_RECEIPT; transaction.FDPID = deliveryReconcile.FDPID; var firstOrDefault = deliveryReconcile.Dispatch.DispatchAllocation; if (firstOrDefault != null) { transaction.CommodityID = firstOrDefault.CommodityID; } transaction.QuantityInMT = deliveryReconcile.ReceivedAmount / 10; transaction.QuantityInUnit = deliveryReconcile.ReceivedAmount; var @default = _unitOfWork.UnitRepository.Get(t => t.Name == "Quintal").FirstOrDefault(); transaction.UnitID = @default != null ? @default.UnitID : 1; _unitOfWork.TransactionRepository.Add(transaction); transaction = new Models.Transaction(); transaction.TransactionID = Guid.NewGuid(); if (reliefRequisition != null) transaction.ProgramID = reliefRequisition.ProgramID; if (orDefault != null) transaction.DonorID = orDefault.DispatchAllocation.DonorID; transaction.TransactionGroupID = transactionGroup; transaction.TransactionDate = transactionDate; if (dispatch != null) transaction.ShippingInstructionID = dispatch.DispatchAllocation.ShippingInstructionID; if (reliefRequisition != null) transaction.PlanId = reliefRequisition.RegionalRequest.PlanID; if (reliefRequisition != null) transaction.Round = reliefRequisition.RegionalRequest.Round; transaction.LedgerID = Models.Ledger.Constants.GOODS_IN_TRANSIT; transaction.HubID = deliveryReconcile.HubID; transaction.FDPID = deliveryReconcile.FDPID; if (firstOrDefault != null) { transaction.CommodityID = firstOrDefault.CommodityID; } transaction.QuantityInMT = -deliveryReconcile.ReceivedAmount / 10; transaction.QuantityInUnit = -deliveryReconcile.ReceivedAmount; transaction.UnitID = @default != null ? @default.UnitID : 1; _unitOfWork.TransactionRepository.Add(transaction); deliveryReconcile.TransactionGroupID = transactionGroup; _unitOfWork.Save(); return true; } #endregion public List<ReceiptAllocation> ReceiptAllocationFindBy(Expression<Func<ReceiptAllocation, bool>> predicate) { return _unitOfWork.ReceiptAllocationReository.FindBy(predicate); } public void Dispose() { _unitOfWork.Dispose(); } } }
{ "content_hash": "431695a3a22f9f22d6f829592a3fc465", "timestamp": "", "source": "github", "line_count": 1081, "max_line_length": 208, "avg_line_length": 48.27382053654024, "alnum_prop": 0.5345124942511115, "repo_name": "ndrmc/cats", "id": "1d1acdd0df74629ad9aeec26d8f48c1a663d04aa", "size": "52186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Services/Cats.Services.Transaction/TransactionService.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "23179" }, { "name": "Batchfile", "bytes": "220" }, { "name": "C#", "bytes": "17077194" }, { "name": "CSS", "bytes": "1272649" }, { "name": "HTML", "bytes": "1205906" }, { "name": "JavaScript", "bytes": "4300261" }, { "name": "PLpgSQL", "bytes": "10605" }, { "name": "SQLPL", "bytes": "11550" }, { "name": "Smalltalk", "bytes": "10" } ], "symlink_target": "" }
"""A simple demonstration of LKD to display IDT and KINTERRUPT associated""" import sys import ctypes import os if os.getcwd().endswith("example"): sys.path.append(os.path.realpath("..")) else: sys.path.append(os.path.realpath(".")) import windows from windows.generated_def.winstructs import * from dbginterface import LocalKernelDebugger # lkd> dt nt!_KIDTENTRY # +0x000 Offset : Uint2B # +0x002 Selector : Uint2B # +0x004 Access : Uint2B # +0x006 ExtendedOffset : Uint2B # Struct _IDT32 definitions class _IDT32(ctypes.Structure): _fields_ = [ ("Offset", WORD), ("Selector", WORD), ("Access", WORD), ("ExtendedOffset", WORD) ] PIDT32 = POINTER(_IDT32) IDT32 = _IDT32 # lkd> dt nt!_KIDTENTRY64 # +0x000 OffsetLow : Uint2B # +0x002 Selector : Uint2B # +0x004 IstIndex : Pos 0, 3 Bits # +0x004 Reserved0 : Pos 3, 5 Bits # +0x004 Type : Pos 8, 5 Bits # +0x004 Dpl : Pos 13, 2 Bits # +0x004 Present : Pos 15, 1 Bit # +0x006 OffsetMiddle : Uint2B # +0x008 OffsetHigh : Uint4B # +0x00c Reserved1 : Uint4B # +0x000 Alignment : Uint8B # Struct _IDT64 definitions class _IDT64(ctypes.Structure): _fields_ = [ ("OffsetLow", WORD), ("Selector", WORD), ("IstIndex", WORD), ("OffsetMiddle", WORD), ("OffsetHigh", DWORD), ("Reserved1", DWORD) ] PIDT64 = POINTER(_IDT64) IDT64 = _IDT64 # lkd> dt nt!_KINTERRUPT Type DispatchCode # +0x000 Type : Int2B # +0x090 DispatchCode : [4] Uint4B def get_kinterrupt_64(kdbg, addr_entry): # You can get the type ID of any name from module to which the type belongs # IDebugSymbols::GetTypeId # https://msdn.microsoft.com/en-us/library/windows/hardware/ff549376%28v=vs.85%29.aspx KINTERRUPT = kdbg.get_type_id("nt", "_KINTERRUPT") # You can get the offset of a symbol identified by its name # IDebugSymbols::GetOffsetByName # https://msdn.microsoft.com/en-us/library/windows/hardware/ff548035(v=vs.85).aspx dispatch_code_offset = kdbg.get_field_offset("nt", KINTERRUPT, "DispatchCode") type_offset = kdbg.get_field_offset("nt", KINTERRUPT, "Type") addr_kinterrupt = addr_entry - dispatch_code_offset # Read a byte from virtual memory # IDebugDataSpaces::ReadVirtual # https://msdn.microsoft.com/en-us/library/windows/hardware/ff554359(v=vs.85).aspx type = kdbg.read_byte(addr_kinterrupt + type_offset) if type == 0x16: return addr_kinterrupt else: return None # lkd> dt nt!_KPCR IdtBase # +0x038 IdtBase : Ptr64 _KIDTENTRY64 # ... # lkd> dt nt!_UNEXPECTED_INTERRUPT # +0x000 PushImm : UChar # +0x001 Vector : UChar # +0x002 PushRbp : UChar # +0x003 JmpOp : UChar # +0x004 JmpOffset : Int4B def get_idt_64(kdbg, num_proc=0): l_idt = [] DEBUG_DATA_KPCR_OFFSET = 0 KPCR = kdbg.get_type_id("nt", "_KPCR") # You can get the number of bytes of memory an instance of the specified type requires # IDebugSymbols::GetTypeSize # https://msdn.microsoft.com/en-us/library/windows/hardware/ff549457(v=vs.85).aspx size_unexpected_interrupt = kdbg.get_type_size("nt", "_UNEXPECTED_INTERRUPT") idt_base_offset = kdbg.get_field_offset("nt", KPCR, "IdtBase") # You can get the location (VA) of a symbol identified by its name # IDebugSymbols::GetOffsetByName # https://msdn.microsoft.com/en-us/library/windows/hardware/ff548035(v=vs.85).aspx addr_nt_KxUnexpectedInterrupt0 = kdbg.get_symbol_offset("nt!KxUnexpectedInterrupt0") # You can data by their type about the specified processor # IDebugDataSpaces::ReadProcessorSystemData # https://msdn.microsoft.com/en-us/library/windows/hardware/ff554326(v=vs.85).aspx kpcr_addr = kdbg.read_processor_system_data(num_proc, DEBUG_DATA_KPCR_OFFSET) # You can read a pointer-size value, it doesn't depend of the target computer's architecture processor idt_base = kdbg.read_ptr(kpcr_addr + idt_base_offset) for i in xrange(0, 0xFF): idt64 = IDT64() # You can read data from virtual address into a ctype structure kdbg.read_virtual_memory_into(idt_base + i * sizeof(IDT64), idt64) addr = (idt64.OffsetHigh << 32) | (idt64.OffsetMiddle << 16) | idt64.OffsetLow if addr < addr_nt_KxUnexpectedInterrupt0 or addr > (addr_nt_KxUnexpectedInterrupt0 + 0xFF * size_unexpected_interrupt): l_idt.append((addr, get_kinterrupt_64(kdbg, addr))) else: l_idt.append((None, None)) return l_idt # lkd> dt nt!_KPCR PrcbData.VectorToInterruptObject # +0x120 PrcbData : # +0x41a0 VectorToInterruptObject : [208] Ptr32 _KINTERRUPT # ... # lkd> dt nt!_KINTERRUPT Type # +0x000 Type : Int2B def get_kinterrupt_32(kdbg, kpcr_addr, index): KPCR = kdbg.get_type_id("nt", "_KPCR") KINTERRUPT = kdbg.get_type_id("nt", "_KINTERRUPT") pcrbdata_offset = kdbg.get_field_offset("nt", KPCR, "PrcbData.VectorToInterruptObject") type_offset = kdbg.get_field_offset("nt", KINTERRUPT, "Type") if index < 0x30: return None addr_kinterrupt = kdbg.read_ptr(kpcr_addr + pcrbdata_offset + (4 * index - 0xC0)) if addr_kinterrupt == 0: return None type = kdbg.read_byte(addr_kinterrupt + type_offset) if type == 0x16: return addr_kinterrupt return None # lkd> dt nt!_KPCR IDT # +0x038 IDT : Ptr32 _KIDTENTRY # +0x120 PrcbData : # +0x41a0 VectorToInterruptObject : [208] Ptr32 _KINTERRUPT def get_idt_32(kdbg, num_proc=0): l_idt = [] DEBUG_DATA_KPCR_OFFSET = 0 KPCR = kdbg.get_type_id("nt", "_KPCR") idt_base_offset = kdbg.get_field_offset("nt", KPCR, "IDT") try: pcrbdata_offset = kdbg.get_field_offset("nt", KPCR, "PrcbData.VectorToInterruptObject") except WindowsError: pcrbdata_offset = 0 addr_nt_KiStartUnexpectedRange = kdbg.get_symbol_offset("nt!KiStartUnexpectedRange") addr_nt_KiEndUnexpectedRange = kdbg.get_symbol_offset("nt!KiEndUnexpectedRange") if pcrbdata_offset == 0: get_kinterrupt = lambda kdbg, addr, kpcr, i: get_kinterrupt_64(kdbg, addr) else: get_kinterrupt = lambda kdbg, addr, kpcr, i: get_kinterrupt_32(kdbg, kpcr, i) kpcr_addr = kdbg.read_processor_system_data(num_proc, DEBUG_DATA_KPCR_OFFSET) idt_base = kdbg.read_ptr(kpcr_addr + idt_base_offset) for i in xrange(0, 0xFF): idt32 = IDT32() kdbg.read_virtual_memory_into(idt_base + i * sizeof(IDT32), idt32) if (idt32.ExtendedOffset == 0 or idt32.Offset == 0): l_idt.append((None, None)) continue addr = (idt32.ExtendedOffset << 16) | idt32.Offset if (addr < addr_nt_KiStartUnexpectedRange or addr > addr_nt_KiEndUnexpectedRange): l_idt.append((addr, get_kinterrupt(kdbg, addr, kpcr_addr, i))) else: addr_kinterrupt = get_kinterrupt(kdbg, addr, kpcr_addr, i) if addr_kinterrupt is None: addr = None l_idt.append((addr, addr_kinterrupt)) return l_idt if __name__ == '__main__': kdbg = LocalKernelDebugger() if windows.current_process.bitness == 32: l_idt = get_idt_32(kdbg) else: l_idt = get_idt_64(kdbg) for i in range(len(l_idt)): if l_idt[i][0] is not None: if l_idt[i][1] is not None: print("0x{0:02X} {1} {2} (KINTERRUPT {3})".format(i, hex(l_idt[i][0]), kdbg.get_symbol(l_idt[i][0])[0], hex(l_idt[i][1]))) else: print("0x{0:02X} {1} {2}".format(i, hex(l_idt[i][0]), kdbg.get_symbol(l_idt[i][0])[0]))
{ "content_hash": "70f6048166dfa8d87e3f038c2a159f7f", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 138, "avg_line_length": 39.18905472636816, "alnum_prop": 0.6252380347848165, "repo_name": "sogeti-esec-lab/LKD", "id": "cccae3f31f6d425075c0fee20d94cec4cbe2f2ec", "size": "7877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/idt.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "763807" } ], "symlink_target": "" }
<?php namespace Magento\Framework\Search\Request\Query; use Magento\Framework\Search\Request\QueryInterface; /** * Match Query */ class Match implements QueryInterface { /** * Name * * @var string */ protected $name; /** * Value * * @var string */ protected $value; /** * Boost * * @var int|null */ protected $boost; /** * Match query array * Possible structure: * array( * ['field' => 'some_field', 'boost' => 'some_boost'], * ['field' => 'some_field', 'boost' => 'some_boost'], * ) * * @var array */ protected $matches = []; /** * @param string $name * @param string $value * @param int|null $boost * @param array $matches * @codeCoverageIgnore */ public function __construct($name, $value, $boost, array $matches) { $this->name = $name; $this->value = $value; $this->boost = $boost; $this->matches = $matches; } /** * @return string */ public function getValue() { return $this->value; } /** * {@inheritdoc} * @codeCoverageIgnore */ public function getType() { return QueryInterface::TYPE_MATCH; } /** * {@inheritdoc} * @codeCoverageIgnore */ public function getName() { return $this->name; } /** * {@inheritdoc} * @codeCoverageIgnore */ public function getBoost() { return $this->boost; } /** * Get Matches * * @return array * @codeCoverageIgnore */ public function getMatches() { return $this->matches; } }
{ "content_hash": "4ef92b2cc2d7b991777ec5f4521ae068", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 70, "avg_line_length": 16.65714285714286, "alnum_prop": 0.4922813036020583, "repo_name": "tarikgwa/test", "id": "7dcdd260af4f9b595cb0b9f07c42834c572f7f31", "size": "1847", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "html/lib/internal/Magento/Framework/Search/Request/Query/Match.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "26588" }, { "name": "CSS", "bytes": "4874492" }, { "name": "HTML", "bytes": "8635167" }, { "name": "JavaScript", "bytes": "6810903" }, { "name": "PHP", "bytes": "55645559" }, { "name": "Perl", "bytes": "7938" }, { "name": "Shell", "bytes": "4505" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
package com.thoughtworks.go.server.service; import com.thoughtworks.go.config.*; import com.thoughtworks.go.config.elastic.ClusterProfile; import com.thoughtworks.go.config.elastic.ElasticProfile; import com.thoughtworks.go.config.materials.PackageMaterial; import com.thoughtworks.go.config.materials.PluggableSCMMaterial; import com.thoughtworks.go.config.materials.ScmMaterial; import com.thoughtworks.go.config.materials.dependency.DependencyMaterial; import com.thoughtworks.go.config.materials.git.GitMaterial; import com.thoughtworks.go.domain.*; import com.thoughtworks.go.domain.buildcause.BuildCause; import com.thoughtworks.go.domain.builder.Builder; import com.thoughtworks.go.domain.builder.CommandBuilder; import com.thoughtworks.go.domain.builder.NullBuilder; import com.thoughtworks.go.domain.config.Configuration; import com.thoughtworks.go.domain.config.ConfigurationProperty; import com.thoughtworks.go.domain.config.ConfigurationValue; import com.thoughtworks.go.domain.config.PluginConfiguration; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.domain.packagerepository.ConfigurationPropertyMother; import com.thoughtworks.go.domain.packagerepository.PackageDefinition; import com.thoughtworks.go.domain.packagerepository.PackageRepository; import com.thoughtworks.go.domain.scm.SCM; import com.thoughtworks.go.helper.GoConfigMother; import com.thoughtworks.go.helper.MaterialsMother; import com.thoughtworks.go.plugin.access.secrets.SecretsExtension; import com.thoughtworks.go.plugin.domain.secrets.Secret; import com.thoughtworks.go.remote.work.BuildAssignment; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.util.command.EnvironmentVariableContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import static com.thoughtworks.go.helper.MaterialsMother.*; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class SecretParamResolverTest { @Mock private SecretsExtension secretsExtension; @Mock private GoConfigService goConfigService; @Mock private RulesService rulesService; private SecretParamResolver secretParamResolver; @BeforeEach void setUp() { secretParamResolver = new SecretParamResolver(secretsExtension, goConfigService, rulesService); } @Nested class ResolveSecretsForScmMaterials { @Test void shouldResolveSecretParams_IfAMaterialCanReferToASecretConfig() { GitMaterial gitMaterial = new GitMaterial("http://example.com"); gitMaterial.setPassword("{{SECRET:[secret_config_id][password]}}"); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()) .thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))) .thenReturn(singletonList(new Secret("password", "some-password"))); secretParamResolver.resolve(gitMaterial); verify(rulesService).validateSecretConfigReferences(gitMaterial); assertThat(gitMaterial.passwordForCommandLine()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfMaterialsDoNotHavePermissionToReferToASecretConfig() { GitMaterial gitMaterial = new GitMaterial("http://example.com"); gitMaterial.setPassword("{{SECRET:[secret_config_id][password]}}"); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(gitMaterial); assertThatCode(() -> secretParamResolver.resolve(gitMaterial)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Nested class ResolveSecretsForPluggableScmMaterials { @Test void shouldResolveSecretParams_IfAMaterialCanReferToASecretConfig() { PluggableSCMMaterial material = pluggableSCMMaterial(); material.getScmConfig().getConfiguration().get(1).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][password]}}")); material.getScmConfig().getConfiguration().get(1).handleSecureValueConfiguration(true); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()) .thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))) .thenReturn(singletonList(new Secret("password", "some-password"))); assertThat(material.getSecretParams().get(0).isUnresolved()).isTrue(); secretParamResolver.resolve(material); verify(rulesService).validateSecretConfigReferences(material); assertThat(material.getSecretParams().get(0).isUnresolved()).isFalse(); assertThat(material.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfMaterialsDoNotHavePermissionToReferToASecretConfig() { PluggableSCMMaterial material = pluggableSCMMaterial(); material.getScmConfig().getConfiguration().get(1).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][password]}}")); material.getScmConfig().getConfiguration().get(1).handleSecureValueConfiguration(true); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(material); assertThatCode(() -> secretParamResolver.resolve(material)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Nested class ResolveSecretsForPluggableScmConfig { @Test void shouldResolveSecretParams_IfConfigCanReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][password]}}"); SCM scm = new SCM("scm-id", "scm-name"); scm.getConfiguration().addAll(asList(k1, k2)); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))) .thenReturn(singletonList(new Secret("password", "some-password"))); assertThat(scm.getSecretParams().get(0).isUnresolved()).isTrue(); secretParamResolver.resolve(scm); verify(rulesService).validateSecretConfigReferences(scm); assertThat(scm.getSecretParams().get(0).isUnresolved()).isFalse(); assertThat(scm.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfConfigDoesNotHavePermissionToReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "{{SECRET:[secret_config_id][lookup_username]}}"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "v2"); SCM scm = new SCM("scm-id", "scm-name"); scm.getConfiguration().addAll(asList(k1, k2)); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(scm); assertThatCode(() -> secretParamResolver.resolve(scm)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Nested class ResolveSecretsForBuildAssignment { @Test void shouldResolveSecretParams_IfBuildAssignmentCanReferSecretConfig() { EnvironmentVariables jobEnvironmentVariables = new EnvironmentVariables(); jobEnvironmentVariables.add("Token", "{{SECRET:[secret_config_id][password]}}"); BuildAssignment buildAssigment = createAssignment(null, jobEnvironmentVariables); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()) .thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))) .thenReturn(singletonList(new Secret("password", "some-password"))); secretParamResolver.resolve(buildAssigment); verify(rulesService).validateSecretConfigReferences(buildAssigment); assertThat(buildAssigment.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfBuildAssignmentDoNotHavePermissionToReferToASecretConfig() { EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext(); environmentVariableContext.setProperty("Token", "{{SECRET:[secret_config_id][password]}}", false); BuildAssignment buildAssigment = createAssignment(environmentVariableContext); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(buildAssigment); assertThatCode(() -> secretParamResolver.resolve(buildAssigment)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } private BuildAssignment createAssignment(EnvironmentVariableContext environmentVariableContext) { return createAssignment(environmentVariableContext, new EnvironmentVariables()); } private BuildAssignment createAssignment(EnvironmentVariableContext environmentVariableContext, EnvironmentVariables jobEnvironmentVariables) { ScmMaterial gitMaterial = gitMaterial("https://example.org"); MaterialRevision gitRevision = new MaterialRevision(gitMaterial, new Modification()); BuildCause buildCause = BuildCause.createManualForced(new MaterialRevisions(gitRevision), Username.ANONYMOUS); JobPlan plan = defaultJobPlan(jobEnvironmentVariables, new EnvironmentVariables()); List<Builder> builders = new ArrayList<>(); builders.add(new CommandBuilder("ls", "", null, new RunIfConfigs(), new NullBuilder(), "")); return BuildAssignment.create(plan, buildCause, builders, null, environmentVariableContext, new ArtifactStores()); } } @Nested class ResolveEnvironmentConfig { @Test void shouldResolveSecretParams_IfJobPlanCanReferSecretConfig() { BasicEnvironmentConfig environmentConfig = new BasicEnvironmentConfig(new CaseInsensitiveString("dev")); environmentConfig.addEnvironmentVariable("key", "{{SECRET:[secret_config_id][password]}}"); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()) .thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))) .thenReturn(singletonList(new Secret("password", "some-password"))); secretParamResolver.resolve(environmentConfig); verify(rulesService).validateSecretConfigReferences(environmentConfig); assertThat(environmentConfig.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfJobPlanDoNotHavePermissionToReferToASecretConfig() { BasicEnvironmentConfig environmentConfig = new BasicEnvironmentConfig(new CaseInsensitiveString("dev")); environmentConfig.addEnvironmentVariable("key", "{{SECRET:[secret_config_id][password]}}"); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(environmentConfig); assertThatCode(() -> secretParamResolver.resolve(environmentConfig)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Test void shouldResolveSecretParamsOfVariousSecretConfig() { final SecretParams allSecretParams = new SecretParams( new SecretParam("secret_config_id_1", "username"), new SecretParam("secret_config_id_1", "password"), new SecretParam("secret_config_id_2", "access_key"), new SecretParam("secret_config_id_2", "secret_key") ); final SecretConfig fileBasedSecretConfig = new SecretConfig("secret_config_id_1", "cd.go.file"); final SecretConfig awsBasedSecretConfig = new SecretConfig("secret_config_id_2", "cd.go.aws"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(fileBasedSecretConfig, awsBasedSecretConfig)); when(secretsExtension.lookupSecrets(fileBasedSecretConfig.getPluginId(), fileBasedSecretConfig, new HashSet<>(asList("username", "password")))) .thenReturn(asList(new Secret("username", "some-username"), new Secret("password", "some-password"))); when(secretsExtension.lookupSecrets(awsBasedSecretConfig.getPluginId(), awsBasedSecretConfig, new HashSet<>(asList("access_key", "secret_key")))) .thenReturn(asList(new Secret("access_key", "ABCDEFGHIJ1D"), new Secret("secret_key", "xyzdfjsdlwdoasd;q"))); assertThat(allSecretParams).hasSize(4); assertThat(allSecretParams.get(0).getValue()).isNull(); assertThat(allSecretParams.get(1).getValue()).isNull(); assertThat(allSecretParams.get(2).getValue()).isNull(); assertThat(allSecretParams.get(3).getValue()).isNull(); secretParamResolver.resolve(allSecretParams); assertThat(allSecretParams).hasSize(4); assertThat(allSecretParams.get(0).getValue()).isEqualTo("some-username"); assertThat(allSecretParams.get(1).getValue()).isEqualTo("some-password"); assertThat(allSecretParams.get(2).getValue()).isEqualTo("ABCDEFGHIJ1D"); assertThat(allSecretParams.get(3).getValue()).isEqualTo("xyzdfjsdlwdoasd;q"); } @Test void shouldResolveValueInAllParamsEvenIfListContainsDuplicatedSecretParams() { final SecretParams allSecretParams = new SecretParams( new SecretParam("secret_config_id_1", "username"), new SecretParam("secret_config_id_1", "username") ); final SecretConfig fileBasedSecretConfig = new SecretConfig("secret_config_id_1", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(fileBasedSecretConfig)); when(secretsExtension.lookupSecrets(fileBasedSecretConfig.getPluginId(), fileBasedSecretConfig, singleton("username"))) .thenReturn(singletonList(new Secret("username", "some-username"))); secretParamResolver.resolve(allSecretParams); assertThat(allSecretParams).hasSize(2); assertThat(allSecretParams.get(0).getValue()).isEqualTo("some-username"); assertThat(allSecretParams.get(1).getValue()).isEqualTo("some-username"); } @Nested class ResolveForList { @Test void shouldResolveListOfMaterials() { GitMaterial gitMaterial = new GitMaterial("http://example.com"); gitMaterial.setPassword("{{SECRET:[secret_config_id][password]}}"); PluggableSCMMaterial pluggableSCMMaterial = pluggableSCMMaterial(); pluggableSCMMaterial.getScmConfig().getConfiguration().get(1).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][token]}}")); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))).thenReturn(singletonList(new Secret("password", "some-password"))); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("token")))).thenReturn(singletonList(new Secret("token", "some-token"))); secretParamResolver.resolve(asList(gitMaterial, pluggableSCMMaterial)); verify(rulesService).validateSecretConfigReferences(gitMaterial); verify(rulesService).validateSecretConfigReferences(pluggableSCMMaterial); assertThat(gitMaterial.passwordForCommandLine()).isEqualTo("some-password"); assertThat(pluggableSCMMaterial.getSecretParams().get(0).getValue()).isEqualTo("some-token"); } @Test void shouldOnlyResolveScmAndPluggableScmAndPackageMaterials() { GitMaterial gitMaterial = new GitMaterial("http://example.com"); gitMaterial.setPassword("{{SECRET:[secret_config_id][password]}}"); DependencyMaterial dependencyMaterial = dependencyMaterial("{{SECRET:[secret_id][pipeline]}}", "defaultStage"); PackageMaterial packageMaterial = packageMaterial(); packageMaterial.getPackageDefinition().getConfiguration().get(0).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][package_token]}}")); PluggableSCMMaterial pluggableSCMMaterial = pluggableSCMMaterial(); pluggableSCMMaterial.getScmConfig().getConfiguration().get(0).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][token]}}")); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))).thenReturn(singletonList(new Secret("password", "some-password"))); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("token")))).thenReturn(singletonList(new Secret("token", "some-token"))); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("package_token")))).thenReturn(singletonList(new Secret("package_token", "some-package-token"))); secretParamResolver.resolve(asList(gitMaterial, dependencyMaterial, packageMaterial, pluggableSCMMaterial)); verify(rulesService).validateSecretConfigReferences(gitMaterial); verify(rulesService).validateSecretConfigReferences(pluggableSCMMaterial); verify(rulesService).validateSecretConfigReferences(packageMaterial); verifyNoMoreInteractions(rulesService); } } @Nested class ResolveSecretsForPackageMaterials { @Test void shouldResolveSecretParams_IfAMaterialCanReferToASecretConfig() { PackageMaterial material = MaterialsMother.packageMaterial(); material.getPackageDefinition().getConfiguration().get(0).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][password]}}")); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))).thenReturn(singletonList(new Secret("password", "some-password"))); assertThat(material.getSecretParams().get(0).isUnresolved()).isTrue(); secretParamResolver.resolve(material); verify(rulesService).validateSecretConfigReferences(material); assertThat(material.getSecretParams().get(0).isUnresolved()).isFalse(); assertThat(material.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfMaterialsDoNotHavePermissionToReferToASecretConfig() { PackageMaterial material = MaterialsMother.packageMaterial(); material.getPackageDefinition().getConfiguration().get(0).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][password]}}")); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(material); assertThatCode(() -> secretParamResolver.resolve(material)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Nested class ResolveSecretsForPackageRepository { @Test void shouldResolveSecretParams_IfConfigCanReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][password]}}"); PackageRepository repository = new PackageRepository("repo-id", "repo-name", new PluginConfiguration(), new Configuration(k1, k2)); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))).thenReturn(singletonList(new Secret("password", "some-password"))); assertThat(repository.getSecretParams().get(0).isUnresolved()).isTrue(); secretParamResolver.resolve(repository); verify(rulesService).validateSecretConfigReferences(repository); assertThat(repository.getSecretParams().get(0).isUnresolved()).isFalse(); assertThat(repository.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfConfigDoesNotHavePermissionToReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][lookup_password]}}"); PackageRepository repository = new PackageRepository("repo-id", "repo-name", new PluginConfiguration(), new Configuration(k1, k2)); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(repository); assertThatCode(() -> secretParamResolver.resolve(repository)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Nested class ResolveSecretsForPackageDefinition { @Test void shouldResolveSecretParams_IfConfigCanReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][password]}}"); PackageRepository repository = new PackageRepository("repo-id", "repo-name", new PluginConfiguration(), new Configuration(k1)); PackageDefinition packageDefinition = new PackageDefinition("pkg-id", "pkg-name", new Configuration(k2)); packageDefinition.setRepository(repository); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))).thenReturn(singletonList(new Secret("password", "some-password"))); assertThat(packageDefinition.getSecretParams().get(0).isUnresolved()).isTrue(); secretParamResolver.resolve(packageDefinition); verify(rulesService).validateSecretConfigReferences(packageDefinition); assertThat(packageDefinition.getSecretParams().get(0).isUnresolved()).isFalse(); assertThat(packageDefinition.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfConfigDoesNotHavePermissionToReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][lookup_password]}}"); PackageRepository repository = new PackageRepository("repo-id", "repo-name", new PluginConfiguration(), new Configuration(k1)); PackageDefinition packageDefinition = new PackageDefinition("pkg-id", "pkg-name", new Configuration(k2)); packageDefinition.setRepository(repository); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(packageDefinition); assertThatCode(() -> secretParamResolver.resolve(packageDefinition)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Nested class ResolveSecretsForClusterProfile { @Test void shouldResolveSecretParams_IfConfigCanReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][password]}}"); ClusterProfile clusterProfile = new ClusterProfile("cluster-id", "plugin-id", k1, k2); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))).thenReturn(singletonList(new Secret("password", "some-password"))); assertThat(clusterProfile.getSecretParams().get(0).isUnresolved()).isTrue(); secretParamResolver.resolve(clusterProfile); verify(rulesService).validateSecretConfigReferences(clusterProfile); assertThat(clusterProfile.getSecretParams().get(0).isUnresolved()).isFalse(); assertThat(clusterProfile.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfConfigDoesNotHavePermissionToReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][lookup_password]}}"); ClusterProfile clusterProfile = new ClusterProfile("cluster-id", "plugin-id", k1, k2); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(clusterProfile); assertThatCode(() -> secretParamResolver.resolve(clusterProfile)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } @Nested class ResolveSecretsForElasticProfile { @Test void shouldResolveSecretParams_IfConfigCanReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][password]}}"); ElasticProfile elasticProfile = new ElasticProfile("elastic-id", "cluster-profile-id", k1, k2); SecretConfig secretConfig = new SecretConfig("secret_config_id", "cd.go.file"); when(goConfigService.cruiseConfig()).thenReturn(GoConfigMother.configWithSecretConfig(secretConfig)); when(secretsExtension.lookupSecrets("cd.go.file", secretConfig, new HashSet<>(singletonList("password")))).thenReturn(singletonList(new Secret("password", "some-password"))); assertThat(elasticProfile.getSecretParams().get(0).isUnresolved()).isTrue(); secretParamResolver.resolve(elasticProfile); verify(rulesService).validateSecretConfigReferences(elasticProfile); assertThat(elasticProfile.getSecretParams().get(0).isUnresolved()).isFalse(); assertThat(elasticProfile.getSecretParams().get(0).getValue()).isEqualTo("some-password"); } @Test void shouldErrorOut_IfConfigDoesNotHavePermissionToReferToASecretConfig() { ConfigurationProperty k1 = ConfigurationPropertyMother.create("k1", false, "v1"); ConfigurationProperty k2 = ConfigurationPropertyMother.create("k2", false, "{{SECRET:[secret_config_id][lookup_password]}}"); ElasticProfile elasticProfile = new ElasticProfile("elastic-id", "cluster-profile-id", k1, k2); doThrow(new RuntimeException()).when(rulesService).validateSecretConfigReferences(elasticProfile); assertThatCode(() -> secretParamResolver.resolve(elasticProfile)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(goConfigService); verifyNoInteractions(secretsExtension); } } private JobPlan defaultJobPlan(EnvironmentVariables variables, EnvironmentVariables triggerVariables) { JobIdentifier identifier = new JobIdentifier("Up42", 1, "1", "test", "1", "unit_test", 123L); return new DefaultJobPlan(new Resources(), new ArrayList<>(), -1, identifier, null, variables, triggerVariables, null, null); } }
{ "content_hash": "bbd27999bd0b6bd1cd63bfb682f57a51", "timestamp": "", "source": "github", "line_count": 560, "max_line_length": 201, "avg_line_length": 55.605357142857144, "alnum_prop": 0.7085005941102798, "repo_name": "GaneshSPatil/gocd", "id": "2584b3d6673e60e4fd7e0c5a0814f5a94a095263", "size": "31740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/test-fast/java/com/thoughtworks/go/server/service/SecretParamResolverTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "466" }, { "name": "CSS", "bytes": "1578" }, { "name": "EJS", "bytes": "1626" }, { "name": "FreeMarker", "bytes": "10183" }, { "name": "Groovy", "bytes": "2467987" }, { "name": "HTML", "bytes": "330937" }, { "name": "Java", "bytes": "21404638" }, { "name": "JavaScript", "bytes": "2331039" }, { "name": "NSIS", "bytes": "23525" }, { "name": "PowerShell", "bytes": "664" }, { "name": "Ruby", "bytes": "623850" }, { "name": "SCSS", "bytes": "820788" }, { "name": "Sass", "bytes": "21277" }, { "name": "Shell", "bytes": "169730" }, { "name": "TypeScript", "bytes": "4428865" }, { "name": "XSLT", "bytes": "207072" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>gem5: mem/ruby/network/garnet/fixed-pipeline/NetworkLink_d.cc File Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="classes.html"><span>Classes</span></a></li> <li id="current"><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul></div> <h1>mem/ruby/network/garnet/fixed-pipeline/NetworkLink_d.cc File Reference</h1><code>#include &quot;<a class="el" href="CreditLink__d_8hh-source.html">mem/ruby/network/garnet/fixed-pipeline/CreditLink_d.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="NetworkLink__d_8hh-source.html">mem/ruby/network/garnet/fixed-pipeline/NetworkLink_d.hh</a>&quot;</code><br> <p> <a href="NetworkLink__d_8cc-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> </table> <hr size="1"><address style="align: right;"><small> Generated on Fri Apr 17 12:39:16 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address> </body> </html>
{ "content_hash": "c2b02f77a15c5fd2b80b1d386da6288a", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 226, "avg_line_length": 48.906976744186046, "alnum_prop": 0.6357584403233476, "repo_name": "wnoc-drexel/gem5-stable", "id": "996678ca306c391ac8e5f9d898e0bacb1e1c68b4", "size": "2103", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/doxygen/html/NetworkLink__d_8cc.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "239800" }, { "name": "C", "bytes": "957228" }, { "name": "C++", "bytes": "13915041" }, { "name": "CSS", "bytes": "9813" }, { "name": "Emacs Lisp", "bytes": "1969" }, { "name": "Groff", "bytes": "11130043" }, { "name": "HTML", "bytes": "132838214" }, { "name": "Java", "bytes": "3096" }, { "name": "Makefile", "bytes": "20709" }, { "name": "PHP", "bytes": "10107" }, { "name": "Perl", "bytes": "36183" }, { "name": "Protocol Buffer", "bytes": "3246" }, { "name": "Python", "bytes": "3739380" }, { "name": "Shell", "bytes": "49333" }, { "name": "Visual Basic", "bytes": "2884" } ], "symlink_target": "" }