code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
2
1.05M
#ifndef SM_PYTHON_ID_HPP #define SM_PYTHON_ID_HPP #include <numpy_eigen/boost_python_headers.hpp> #include <boost/python/to_python_converter.hpp> #include <Python.h> #include <boost/cstdint.hpp> namespace sm { namespace python { // to use: sm::python::Id_python_converter<FrameId>::register_converter(); // adapted from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/ template<typename ID_T> struct Id_python_converter { typedef ID_T id_t; // The "Convert from C to Python" API static PyObject * convert(id_t const & id){ PyObject * i = PyInt_FromLong(id.getId()); // It seems that the call to "incref(.)" caused a memory leak! // I will check this in hoping it doesn't cause any instability. return i;//boost::python::incref(i); } // The "Convert from Python to C" API // Two functions: convertible() and construct() static void * convertible(PyObject* obj_ptr) { if (!(PyInt_Check(obj_ptr) || PyLong_Check(obj_ptr))) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { // Get the value. boost::uint64_t value; if ( PyInt_Check(obj_ptr) ) { value = PyInt_AsUnsignedLongLongMask(obj_ptr); } else { value = PyLong_AsUnsignedLongLong(obj_ptr); } void* storage = ((boost::python::converter::rvalue_from_python_storage<id_t>*) data)->storage.bytes; new (storage) id_t(value); // Stash the memory chunk pointer for later use by boost.python data->convertible = storage; } // The registration function. static void register_converter() { // This code checks if the type has already been registered. // http://stackoverflow.com/questions/9888289/checking-whether-a-converter-has-already-been-registered boost::python::type_info info = boost::python::type_id<id_t>(); const boost::python::converter::registration* reg = boost::python::converter::registry::query(info); if (reg == NULL || reg->m_to_python == NULL) { // This is the code to register the type. boost::python::to_python_converter<id_t,Id_python_converter>(); boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<id_t>()); } } }; }} #endif /* SM_PYTHON_ID_HPP */
ethz-asl/Schweizer-Messer
sm_python/include/sm/python/Id.hpp
C++
bsd-3-clause
2,754
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/paint/paint_invalidator.h" #include "base/trace_event/trace_event.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/renderer/core/accessibility/ax_object_cache.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/layout/layout_block_flow.h" #include "third_party/blink/renderer/core/layout/layout_shift_tracker.h" #include "third_party/blink/renderer/core/layout/layout_table.h" #include "third_party/blink/renderer/core/layout/layout_table_section.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h" #include "third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" #include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h" #include "third_party/blink/renderer/core/page/link_highlight.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/paint/clip_path_clipper.h" #include "third_party/blink/renderer/core/paint/object_paint_properties.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h" #include "third_party/blink/renderer/core/paint/pre_paint_tree_walk.h" #include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h" namespace blink { void PaintInvalidator::UpdatePaintingLayer(const LayoutObject& object, PaintInvalidatorContext& context) { if (object.HasLayer() && To<LayoutBoxModelObject>(object).HasSelfPaintingLayer()) { context.painting_layer = To<LayoutBoxModelObject>(object).Layer(); } else if (object.IsColumnSpanAll() || object.IsFloatingWithNonContainingBlockParent()) { // See |LayoutObject::PaintingLayer| for the special-cases of floating under // inline and multicolumn. // Post LayoutNG the |LayoutObject::IsFloatingWithNonContainingBlockParent| // check can be removed as floats will be painted by the correct layer. context.painting_layer = object.PaintingLayer(); } auto* layout_block_flow = DynamicTo<LayoutBlockFlow>(object); if (layout_block_flow && !object.IsLayoutNGBlockFlow() && layout_block_flow->ContainsFloats()) context.painting_layer->SetNeedsPaintPhaseFloat(); if (object.IsFloating() && (object.IsInLayoutNGInlineFormattingContext() || IsLayoutNGContainingBlock(object.ContainingBlock()))) context.painting_layer->SetNeedsPaintPhaseFloat(); if (!context.painting_layer->NeedsPaintPhaseDescendantOutlines() && ((object != context.painting_layer->GetLayoutObject() && object.StyleRef().HasOutline()) || // If this is a block-in-inline, it may need to paint outline. // See |StyleForContinuationOutline|. (layout_block_flow && layout_block_flow->StyleForContinuationOutline()))) context.painting_layer->SetNeedsPaintPhaseDescendantOutlines(); } void PaintInvalidator::UpdateFromTreeBuilderContext( const PaintPropertyTreeBuilderFragmentContext& tree_builder_context, PaintInvalidatorContext& context) { DCHECK_EQ(tree_builder_context.current.paint_offset, context.fragment_data->PaintOffset()); // For performance, we ignore subpixel movement of composited layers for paint // invalidation. This will result in imperfect pixel-snapped painting. // See crbug.com/833083 for details. if (!RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() && tree_builder_context.current .directly_composited_container_paint_offset_subpixel_delta == tree_builder_context.current.paint_offset - tree_builder_context.old_paint_offset) { context.old_paint_offset = tree_builder_context.current.paint_offset; } else { context.old_paint_offset = tree_builder_context.old_paint_offset; } context.transform_ = tree_builder_context.current.transform; } void PaintInvalidator::UpdateLayoutShiftTracking( const LayoutObject& object, const PaintPropertyTreeBuilderFragmentContext& tree_builder_context, PaintInvalidatorContext& context) { if (!object.ShouldCheckGeometryForPaintInvalidation()) return; if (tree_builder_context.this_or_ancestor_opacity_is_zero || context.inside_opaque_layout_shift_root) { object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true); return; } auto& layout_shift_tracker = object.GetFrameView()->GetLayoutShiftTracker(); if (!layout_shift_tracker.NeedsToTrack(object)) { object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true); return; } PropertyTreeStateOrAlias property_tree_state( *tree_builder_context.current.transform, *tree_builder_context.current.clip, *tree_builder_context.current_effect); // Adjust old_paint_offset so that LayoutShiftTracker will see the change of // offset caused by change of paint offset translations and scroll offset // below the layout shift root. For more details, see // renderer/core/layout/layout-shift-tracker-old-paint-offset.md. PhysicalOffset adjusted_old_paint_offset = context.old_paint_offset - tree_builder_context.current .additional_offset_to_layout_shift_root_delta - PhysicalOffset::FromVector2dFRound( tree_builder_context.translation_2d_to_layout_shift_root_delta + tree_builder_context.current .scroll_offset_to_layout_shift_root_delta); PhysicalOffset new_paint_offset = tree_builder_context.current.paint_offset; if (object.IsText()) { const auto& text = To<LayoutText>(object); LogicalOffset new_starting_point; LayoutUnit logical_height; text.LogicalStartingPointAndHeight(new_starting_point, logical_height); LogicalOffset old_starting_point = text.PreviousLogicalStartingPoint(); if (new_starting_point == old_starting_point) return; text.SetPreviousLogicalStartingPoint(new_starting_point); if (old_starting_point == LayoutText::UninitializedLogicalStartingPoint()) return; // If the layout shift root has changed, LayoutShiftTracker can't use the // current paint property tree to map the old rect. if (tree_builder_context.current.layout_shift_root_changed) return; layout_shift_tracker.NotifyTextPrePaint( text, property_tree_state, old_starting_point, new_starting_point, adjusted_old_paint_offset, tree_builder_context.translation_2d_to_layout_shift_root_delta, tree_builder_context.current.scroll_offset_to_layout_shift_root_delta, tree_builder_context.current.pending_scroll_anchor_adjustment, new_paint_offset, logical_height); return; } DCHECK(object.IsBox()); const auto& box = To<LayoutBox>(object); PhysicalRect new_rect = box.PhysicalVisualOverflowRectAllowingUnset(); new_rect.Move(new_paint_offset); PhysicalRect old_rect = box.PreviousPhysicalVisualOverflowRect(); old_rect.Move(adjusted_old_paint_offset); // TODO(crbug.com/1178618): We may want to do better than this. For now, just // don't report anything inside multicol containers. const auto* block_flow = DynamicTo<LayoutBlockFlow>(&box); if (block_flow && block_flow->IsFragmentationContextRoot() && block_flow->IsLayoutNGObject()) context.inside_opaque_layout_shift_root = true; bool should_create_containing_block_scope = // TODO(crbug.com/1178618): Support multiple-fragments when switching to // LayoutNGFragmentTraversal. context.fragment_data == &box.FirstFragment() && block_flow && block_flow->ChildrenInline() && block_flow->FirstChild(); if (should_create_containing_block_scope) { // For layout shift tracking of contained LayoutTexts. context.containing_block_scope_.emplace( PhysicalSizeToBeNoop(box.PreviousSize()), PhysicalSizeToBeNoop(box.Size()), old_rect, new_rect); } bool should_report_layout_shift = [&]() -> bool { if (box.ShouldSkipNextLayoutShiftTracking()) { box.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(false); return false; } // If the layout shift root has changed, LayoutShiftTracker can't use the // current paint property tree to map the old rect. if (tree_builder_context.current.layout_shift_root_changed) return false; if (new_rect.IsEmpty() || old_rect.IsEmpty()) return false; // Track self-painting layers separately because their ancestors' // PhysicalVisualOverflowRect may not cover them. if (object.HasLayer() && To<LayoutBoxModelObject>(object).HasSelfPaintingLayer()) return true; // Always track if the parent doesn't need to track (e.g. it has visibility: // hidden), while this object needs (e.g. it has visibility: visible). // This also includes non-anonymous child with an anonymous parent. if (object.Parent()->ShouldSkipNextLayoutShiftTracking()) return true; // Report if the parent is in a different transform space. const auto* parent_context = context.ParentContext(); if (!parent_context || !parent_context->transform_ || parent_context->transform_ != tree_builder_context.current.transform) return true; // Report if this object has local movement (i.e. delta of paint offset is // different from that of the parent). return parent_context->fragment_data->PaintOffset() - parent_context->old_paint_offset != new_paint_offset - context.old_paint_offset; }(); if (should_report_layout_shift) { layout_shift_tracker.NotifyBoxPrePaint( box, property_tree_state, old_rect, new_rect, adjusted_old_paint_offset, tree_builder_context.translation_2d_to_layout_shift_root_delta, tree_builder_context.current.scroll_offset_to_layout_shift_root_delta, tree_builder_context.current.pending_scroll_anchor_adjustment, new_paint_offset); } } bool PaintInvalidator::InvalidatePaint( const LayoutObject& object, const NGPrePaintInfo* pre_paint_info, const PaintPropertyTreeBuilderContext* tree_builder_context, PaintInvalidatorContext& context) { TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"), "PaintInvalidator::InvalidatePaint()", "object", object.DebugName().Ascii()); if (object.IsSVGHiddenContainer() || object.IsLayoutTableCol()) context.subtree_flags |= PaintInvalidatorContext::kSubtreeNoInvalidation; if (context.subtree_flags & PaintInvalidatorContext::kSubtreeNoInvalidation) return false; object.GetMutableForPainting().EnsureIsReadyForPaintInvalidation(); UpdatePaintingLayer(object, context); // Assert that the container state in the invalidation context is consistent // with what the LayoutObject tree says. We cannot do this if we're fragment- // traversing an "orphaned" object (an object that has a fragment inside a // fragmentainer, even though not all its ancestor objects have it; this may // happen to OOFs, and also to floats, if they are inside a non-atomic // inline). In such cases we'll just have to live with the inconsitency, which // means that we'll lose any paint effects from such "missing" ancestors. DCHECK_EQ(context.painting_layer, object.PaintingLayer()) << object; if (AXObjectCache* cache = object.GetDocument().ExistingAXObjectCache()) cache->InvalidateBoundingBox(&object); if (!object.ShouldCheckForPaintInvalidation() && !context.NeedsSubtreeWalk()) return false; if (object.SubtreeShouldDoFullPaintInvalidation()) { context.subtree_flags |= PaintInvalidatorContext::kSubtreeFullInvalidation | PaintInvalidatorContext::kSubtreeFullInvalidationForStackedContents; } if (object.SubtreeShouldCheckForPaintInvalidation()) { context.subtree_flags |= PaintInvalidatorContext::kSubtreeInvalidationChecking; } if (UNLIKELY(object.ContainsInlineWithOutlineAndContinuation()) && // Need this only if the subtree needs to check geometry change. PrePaintTreeWalk::ObjectRequiresTreeBuilderContext(object)) { // Force subtree invalidation checking to ensure invalidation of focus rings // when continuation's geometry changes. context.subtree_flags |= PaintInvalidatorContext::kSubtreeInvalidationChecking; } if (pre_paint_info) { FragmentData& fragment_data = *pre_paint_info->fragment_data; context.fragment_data = &fragment_data; if (tree_builder_context) { DCHECK_EQ(tree_builder_context->fragments.size(), 1u); const auto& fragment_tree_builder_context = tree_builder_context->fragments[0]; UpdateFromTreeBuilderContext(fragment_tree_builder_context, context); UpdateLayoutShiftTracking(object, fragment_tree_builder_context, context); } else { context.old_paint_offset = fragment_data.PaintOffset(); } object.InvalidatePaint(context); } else { unsigned tree_builder_index = 0; for (auto* fragment_data = &object.GetMutableForPainting().FirstFragment(); fragment_data; fragment_data = fragment_data->NextFragment(), tree_builder_index++) { context.fragment_data = fragment_data; DCHECK(!tree_builder_context || tree_builder_index < tree_builder_context->fragments.size()); if (tree_builder_context) { const auto& fragment_tree_builder_context = tree_builder_context->fragments[tree_builder_index]; UpdateFromTreeBuilderContext(fragment_tree_builder_context, context); UpdateLayoutShiftTracking(object, fragment_tree_builder_context, context); } else { context.old_paint_offset = fragment_data->PaintOffset(); } object.InvalidatePaint(context); } } auto reason = static_cast<const DisplayItemClient&>(object) .GetPaintInvalidationReason(); if (object.ShouldDelayFullPaintInvalidation() && (!IsFullPaintInvalidationReason(reason) || // Delay invalidation if the client has never been painted. reason == PaintInvalidationReason::kJustCreated)) pending_delayed_paint_invalidations_.push_back(&object); if (auto* local_frame = DynamicTo<LocalFrame>(object.GetFrame()->Top())) { if (auto* mf_checker = local_frame->View()->GetMobileFriendlinessChecker()) { if (tree_builder_context && (!pre_paint_info || pre_paint_info->is_last_for_node)) mf_checker->NotifyInvalidatePaint(object); } } return reason != PaintInvalidationReason::kNone; } void PaintInvalidator::ProcessPendingDelayedPaintInvalidations() { for (const auto& target : pending_delayed_paint_invalidations_) target->GetMutableForPainting().SetShouldDelayFullPaintInvalidation(); } } // namespace blink
chromium/chromium
third_party/blink/renderer/core/paint/paint_invalidator.cc
C++
bsd-3-clause
15,422
#include <walle/sys/wallesys.h> using namespace std; /// Web Application Library namaspace namespace walle { namespace sys { bool Filesystem::fileExist( const string &file ) { if ( ::access(file.c_str(),F_OK) == 0 ) return true; else return false; } bool Filesystem::isLink( const string &file ) { struct stat statbuf; if( ::lstat(file.c_str(),&statbuf) == 0 ) { if ( S_ISLNK(statbuf.st_mode) != 0 ) return true; } return false; } bool Filesystem::isDir( const string &file ) { struct stat statbuf; if( ::stat(file.c_str(),&statbuf) == 0 ) { if ( S_ISDIR(statbuf.st_mode) != 0 ) return true; } return false; } bool Filesystem::mkLink( const string &srcfile, const string &destfile ) { if ( ::symlink(srcfile.c_str(),destfile.c_str()) == 0 ) return true; else return false; } bool Filesystem::link(const string &srcfile, const string &destfile) { if ( ::link(srcfile.c_str(),destfile.c_str()) == 0 ) return true; else return false; } size_t Filesystem::fileSize( const string &file ) { struct stat statbuf; if( stat(file.c_str(),&statbuf)==0 ) return statbuf.st_size; else return -1; } time_t Filesystem::fileTime( const string &file ) { struct stat statbuf; if( stat(file.c_str(),&statbuf)==0 ) return statbuf.st_mtime; else return -1; } string Filesystem::filePath( const string &file ) { size_t p; if ( (p=file.rfind("/")) != file.npos ) return file.substr( 0, p ); return string( "" ); } string Filesystem::fileName( const string &file ) { size_t p; if ( (p=file.rfind("/")) != file.npos ) return file.substr( p+1 ); return file; } bool Filesystem::renameFile( const string &oldname, const string &newname ) { if ( ::rename(oldname.c_str(),newname.c_str()) != -1 ) return true; else return false; } bool Filesystem::copyFile( const string &srcfile, const string &destfile ) { FILE *src=NULL, *dest=NULL; if ( (src=fopen(srcfile.c_str(),"rb")) == NULL ) { return false; } if ( (dest=fopen(destfile.c_str(),"wb+")) == NULL ) { fclose( src ); return false; } const int bufsize = 8192; char buf[bufsize]; size_t n; while ( (n=fread(buf,1,bufsize,src)) >= 1 ) { if ( fwrite(buf,1,n,dest) != n ) { fclose( src ); fclose( dest ); return false; } } fclose( src ); fclose( dest ); //chmod to 0666 mode_t mask = umask( 0 ); chmod( destfile.c_str(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH ); umask( mask ); return true; } bool Filesystem::deleteFile( const string &file ) { if ( ::remove(file.c_str()) == 0 ) return true; else return false; } bool Filesystem::moveFile( const string &srcfile, const string &destfile ) { if ( renameFile(srcfile,destfile) ) return true; // rename fail, copy and delete file if ( copyFile(srcfile,destfile) ) { if ( deleteFile(srcfile) ) return true; } return false; } vector<string> Filesystem::dirFiles( const string &dir ) { vector<string> files; string file; DIR *pdir = NULL; dirent *pdirent = NULL; if ( (pdir = ::opendir(dir.c_str())) != NULL ) { while ( (pdirent=readdir(pdir)) != NULL ) { file = pdirent->d_name; if ( file!="." && file!=".." ) { if ( isDir(dir+"/"+file) ) file = "/"+file; files.push_back( file ); } } ::closedir( pdir ); } return files; } bool Filesystem::makeDir( const string &dir, const mode_t mode ) { // check size_t len = dir.length(); if ( len <= 0 ) return false; string tomake; char curchr; for( size_t i=0; i<len; ++i ) { // append curchr = dir[i]; tomake += curchr; if ( curchr=='/' || i==(len-1) ) { // need to mkdir if ( !fileExist(tomake) && !isDir(tomake) ) { // able to mkdir mode_t mask = umask( 0 ); if ( mkdir(tomake.c_str(),mode) == -1 ) { umask( mask ); return false; } umask( mask ); } } } return true; } bool Filesystem::copyDir( const string &srcdir, const string &destdir ) { vector<string> files = dirFiles( srcdir ); string from; string to; if ( !fileExist(destdir) ) makeDir( destdir ); for ( size_t i=0; i<files.size(); ++i ) { from = srcdir + "/" + files[i]; to = destdir + "/" + files[i]; if ( files[i][0] == '/' ) { if ( !copyDir(from,to) ) return false; } else if ( !copyFile(from,to) ) return false; } return true; } bool Filesystem::deleteDir( const string &dir ) { vector<string> files = dirFiles( dir ); string todel; // ɾ³ýÎļþ for ( size_t i=0; i<files.size(); ++i ) { todel = dir + "/" + files[i]; // ×ÓĿ¼,µÝ¹éµ÷Óà if ( files[i][0] == '/' ) { if ( !deleteDir(todel) ) return false; } // Îļþ else if ( !deleteFile(todel) ) return false; } // ɾ³ýĿ¼ if ( rmdir(dir.c_str()) == 0 ) return true; return false; } bool Filesystem::moveDir( const string &srcdir, const string &destdir ) { if ( renameFile(srcdir,destdir) ) return true; // rename fail, copy and delete dir if ( copyDir(srcdir,destdir) ) { if (deleteDir(srcdir) ) return true; } return false; } } } // namespace
lilothar/walle-c11
walle/sys/Filesystem.cpp
C++
bsd-3-clause
5,052
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utilities to process compresssed files.""" import contextlib import logging import os import pathlib import re import shutil import struct import tempfile import zipfile class _ApkFileManager: def __init__(self, temp_dir): self._temp_dir = pathlib.Path(temp_dir) self._subdir_by_apks_path = {} self._infolist_by_path = {} def _MapPath(self, path): # Use numbered subdirectories for uniqueness. # Suffix with basename(path) for readability. default = '-'.join( [str(len(self._subdir_by_apks_path)), os.path.basename(path)]) return self._temp_dir / self._subdir_by_apks_path.setdefault(path, default) def InfoList(self, path): """Returns zipfile.ZipFile(path).infolist().""" ret = self._infolist_by_path.get(path) if ret is None: with zipfile.ZipFile(path) as z: ret = z.infolist() self._infolist_by_path[path] = ret return ret def SplitPath(self, minimal_apks_path, split_name): """Returns the path to the apk split extracted by ExtractSplits. Args: minimal_apks_path: The .apks file that was passed to ExtractSplits(). split_name: Then name of the split. Returns: Path to the extracted .apk file. """ subdir = self._subdir_by_apks_path[minimal_apks_path] return self._temp_dir / subdir / 'splits' / f'{split_name}-master.apk' def ExtractSplits(self, minimal_apks_path): """Extracts the master splits in the given .apks file. Returns: List of split names, with "base" always appearing first. """ dest = self._MapPath(minimal_apks_path) split_names = [] logging.debug('Extracting %s', minimal_apks_path) with zipfile.ZipFile(minimal_apks_path) as z: for filename in z.namelist(): # E.g.: # splits/base-master.apk # splits/base-en.apk # splits/vr-master.apk # splits/vr-en.apk m = re.match(r'splits/(.*)-master\.apk', filename) if m: split_names.append(m.group(1)) z.extract(filename, dest) logging.debug('Extracting %s (done)', minimal_apks_path) # Make "base" comes first since that's the main chunk of work. # Also so that --abi-filter detection looks at it first. return sorted(split_names, key=lambda x: (x != 'base', x)) @contextlib.contextmanager def ApkFileManager(): """Context manager that extracts apk splits to a temp dir.""" # Cannot use tempfile.TemporaryDirectory() here because our use of # multiprocessing results in __del__ methods being called in forked processes. temp_dir = tempfile.mkdtemp(suffix='-supersize') zip_files = _ApkFileManager(temp_dir) yield zip_files shutil.rmtree(temp_dir) @contextlib.contextmanager def UnzipToTemp(zip_path, inner_path): """Extract a |inner_path| from a |zip_path| file to an auto-deleted temp file. Args: zip_path: Path to the zip file. inner_path: Path to the file within |zip_path| to extract. Yields: The path of the temp created (and auto-deleted when context exits). """ try: logging.debug('Extracting %s', inner_path) _, suffix = os.path.splitext(inner_path) # Can't use NamedTemporaryFile() because it deletes via __del__, which will # trigger in both this and the fork()'ed processes. fd, temp_file = tempfile.mkstemp(suffix=suffix) with zipfile.ZipFile(zip_path) as z: os.write(fd, z.read(inner_path)) os.close(fd) logging.debug('Extracting %s (done)', inner_path) yield temp_file finally: os.unlink(temp_file) def ReadZipInfoExtraFieldLength(zip_file, zip_info): """Reads the value of |extraLength| from |zip_info|'s local file header. |zip_info| has an |extra| field, but it's read from the central directory. Android's zipalign tool sets the extra field only in local file headers. """ # Refer to https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers zip_file.fp.seek(zip_info.header_offset + 28) return struct.unpack('<H', zip_file.fp.read(2))[0] def MeasureApkSignatureBlock(zip_file): """Measures the size of the v2 / v3 signing block. Refer to: https://source.android.com/security/apksigning/v2 """ # Seek to "end of central directory" struct. eocd_offset_from_end = -22 - len(zip_file.comment) zip_file.fp.seek(eocd_offset_from_end, os.SEEK_END) assert zip_file.fp.read(4) == b'PK\005\006', ( 'failed to find end-of-central-directory') # Read out the "start of central directory" offset. zip_file.fp.seek(eocd_offset_from_end + 16, os.SEEK_END) start_of_central_directory = struct.unpack('<I', zip_file.fp.read(4))[0] # Compute the offset after the last zip entry. last_info = max(zip_file.infolist(), key=lambda i: i.header_offset) last_header_size = (30 + len(last_info.filename) + ReadZipInfoExtraFieldLength(zip_file, last_info)) end_of_last_file = (last_info.header_offset + last_header_size + last_info.compress_size) return start_of_central_directory - end_of_last_file
chromium/chromium
tools/binary_size/libsupersize/zip_util.py
Python
bsd-3-clause
5,188
class AddSomeIndices < ActiveRecord::Migration def change add_index :updates, :created_at add_index :observations, :created_at add_index :observations, :observed_on add_index :identifications, :created_at end end
lucas-ez/inaturalist
db/migrate/20150319205049_add_some_indices.rb
Ruby
mit
233
require File.expand_path('../../test_helper.rb', __FILE__) require File.expand_path('../freeradius_stats.rb', __FILE__) class FreeradiusStatsTest < Test::Unit::TestCase def setup @options = parse_defaults("freeradius_stats") end def teardown end def test_clean_run # Stub the plugin instance where necessary and run # @plugin=PluginName.new(last_run, memory, options) # date hash hash @plugin=FreeradiusStats.new(nil,{},@options) @plugin.returns(FIXTURES[:stats]).once res = @plugin.run() # assertions assert res[:alerts].empty? assert res[:errors].empty? end def test_alert @plugin=FreeradiusStats.new(nil,{},@options) @plugin.returns(FIXTURES[:stats_alert]).once res = @plugin.run() # assertions assert_equal 1, res[:alerts].size assert res[:errors].empty? end FIXTURES=YAML.load(<<-EOS) :stats: | Received response ID 230, code 2, length = 140 FreeRADIUS-Total-Access-Requests = 21287 FreeRADIUS-Total-Access-Accepts = 20677 FreeRADIUS-Total-Access-Rejects = 677 FreeRADIUS-Total-Access-Challenges = 0 FreeRADIUS-Total-Auth-Responses = 21354 FreeRADIUS-Total-Auth-Duplicate-Requests = 0 FreeRADIUS-Total-Auth-Malformed-Requests = 0 FreeRADIUS-Total-Auth-Invalid-Requests = 0 FreeRADIUS-Total-Auth-Dropped-Requests = 0 FreeRADIUS-Total-Auth-Unknown-Types = 0 :stats_alert: | radclient: no response from server for ID 15 socket 3 EOS end
pingdomserver/scout-plugins
freeradius_stats/test.rb
Ruby
mit
1,566
require File.dirname(__FILE__) + '/../spec_helper' describe CodeFormatter do def format(text) CodeFormatter.new(text).to_html end it "determines language based on file path" do formatter = CodeFormatter.new("") formatter.language("unknown").should eq("unknown") formatter.language("hello.rb").should eq("ruby") formatter.language("hello.js").should eq("java_script") formatter.language("hello.css").should eq("css") formatter.language("hello.html.erb").should eq("rhtml") formatter.language("hello.yml").should eq("yaml") formatter.language("Gemfile").should eq("ruby") formatter.language("app.rake").should eq("ruby") formatter.language("foo.gemspec").should eq("ruby") formatter.language("rails console").should eq("ruby") formatter.language("hello.js.rjs").should eq("rjs") formatter.language("hello.scss").should eq("css") formatter.language("rails").should eq("ruby") formatter.language("foo.bar ").should eq("bar") formatter.language("foo ").should eq("foo") formatter.language("").should eq("text") formatter.language(nil).should eq("text") formatter.language("0```").should eq("text") end it "converts to markdown" do format("hello **world**").strip.should eq("<p>hello <strong>world</strong></p>") end it "hard wraps return statements" do format("hello\nworld").strip.should eq("<p>hello<br>\nworld</p>") end it "autolinks a url" do format("http://www.example.com/").strip.should eq('<p><a href="http://www.example.com/">http://www.example.com/</a></p>') end it "formats code block" do # This could use some more extensive tests format("```\nfoo\n```").strip.should include("<div class=\"code_block\">") end it "handle back-slashes in code block" do # This could use some more extensive tests format("```\nf\\'oo\n```").strip.should include("f\\'oo") end it "does not allow html" do format("<img>").strip.should eq("") end end
nischay13144/railscasts
spec/lib/code_formatter_spec.rb
Ruby
mit
1,988
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {runServer} from '../../src/protractor/utils'; describe('Bazel protractor utils', () => { it('should be able to start devserver', async() => { // Test will automatically time out if the server couldn't be launched as expected. await runServer('angular', 'packages/bazel/test/protractor-utils/fake-devserver', '--port', []); }); });
petebacondarwin/angular
packages/bazel/test/protractor-utils/index_test.ts
TypeScript
mit
557
require 'mws/feeds/client'
jack0331/peddler
lib/mws/feeds.rb
Ruby
mit
27
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); tslib_1.__exportStar(require("./2.9/type"), exports); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInR5cGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEscURBQTJCIn0=
AxelSparkster/axelsparkster.github.io
node_modules/tsutils/typeguard/type.js
JavaScript
mit
357
class Role < ActiveRecord::Base has_and_belongs_to_many :users before_validation :camelize_title validates_uniqueness_of :title def camelize_title(role_title = self.title) self.title = role_title.to_s.camelize end def self.[](title) find_or_create_by_title(title.to_s.camelize) end end
clanplaid/wow.clanplaid.net
vendor/plugins/authentication/app/models/role.rb
Ruby
mit
313
var assert = require('assert'); var jsv = require('jsverify'); var R = require('..'); var eq = require('./shared/eq'); describe('compose', function() { it('is a variadic function', function() { eq(typeof R.compose, 'function'); eq(R.compose.length, 0); }); it('performs right-to-left function composition', function() { // f :: (String, Number?) -> ([Number] -> [Number]) var f = R.compose(R.map, R.multiply, parseInt); eq(f.length, 2); eq(f('10')([1, 2, 3]), [10, 20, 30]); eq(f('10', 2)([1, 2, 3]), [2, 4, 6]); }); it('passes context to functions', function() { function x(val) { return this.x * val; } function y(val) { return this.y * val; } function z(val) { return this.z * val; } var context = { a: R.compose(x, y, z), x: 4, y: 2, z: 1 }; eq(context.a(5), 40); }); it('throws if given no arguments', function() { assert.throws( function() { R.compose(); }, function(err) { return err.constructor === Error && err.message === 'compose requires at least one argument'; } ); }); it('can be applied to one argument', function() { var f = function(a, b, c) { return [a, b, c]; }; var g = R.compose(f); eq(g.length, 3); eq(g(1, 2, 3), [1, 2, 3]); }); }); describe('compose properties', function() { jsv.property('composes two functions', jsv.fn(), jsv.fn(), jsv.nat, function(f, g, x) { return R.equals(R.compose(f, g)(x), f(g(x))); }); jsv.property('associative', jsv.fn(), jsv.fn(), jsv.fn(), jsv.nat, function(f, g, h, x) { var result = f(g(h(x))); return R.all(R.equals(result), [ R.compose(f, g, h)(x), R.compose(f, R.compose(g, h))(x), R.compose(R.compose(f, g), h)(x) ]); }); });
angeloocana/ramda
test/compose.js
JavaScript
mit
1,837
#include <utilities.h> #include <fstream> namespace Utilities { namespace Math { double degreesToRadians(double angle) { return (angle * PI) / 180; } double radiansToDegrees(double angle) { return angle * (180/PI); } } namespace File { bool getFileContents(std::vector<uint8_t> &fileBuffer, const std::string &filePath) { std::ifstream inFileStream(filePath, std::ios::binary); if (!inFileStream) { return false; } inFileStream.seekg(0, std::ios::end); auto fileLength = inFileStream.tellg(); inFileStream.seekg(0, std::ios::beg); fileBuffer.resize(fileLength); inFileStream.read(reinterpret_cast<char *>(fileBuffer.data()), fileLength); return true; } } }
velocic/opengl-tutorial-solutions
22-loading-3d-models/src/utilities.cpp
C++
mit
909
<?php $HOME = realpath(dirname(__FILE__)) . "/../../../.."; require_once($HOME . "/tests/class/Common_TestCase.php"); /* * This file is part of EC-CUBE * * Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * SC_Utils::getRealURL()のテストクラス. * * * @author Hiroko Tamagawa * @version $Id: SC_Utils_getRealURLTest.php 22144 2012-12-17 05:25:58Z h_yoshimoto $ */ class SC_Utils_getRealURLTest extends Common_TestCase { protected function setUp() { parent::setUp(); } protected function tearDown() { parent::tearDown(); } ///////////////////////////////////////// // TODO ポート番号のためのコロンが必ず入ってしまうのはOK? public function testGetRealURL_親ディレクトリへの参照を含む場合_正しくパースできる() { $input = 'http://www.example.jp/aaa/../index.php'; $this->expected = 'http://www.example.jp:/index.php'; $this->actual = SC_Utils::getRealURL($input); $this->verify(); } public function testGetRealURL_親ディレクトリへの参照を複数回含む場合_正しくパースできる() { $input = 'http://www.example.jp/aaa/bbb/../../ccc/ddd/../index.php'; $this->expected = 'http://www.example.jp:/ccc/index.php'; $this->actual = SC_Utils::getRealURL($input); $this->verify(); } public function testGetRealURL_カレントディレクトリへの参照を含む場合_正しくパースできる() { $input = 'http://www.example.jp/aaa/./index.php'; $this->expected = 'http://www.example.jp:/aaa/index.php'; $this->actual = SC_Utils::getRealURL($input); $this->verify(); } public function testGetRealURL_httpsの場合_正しくパースできる() { $input = 'https://www.example.jp/aaa/./index.php'; $this->expected = 'https://www.example.jp:/aaa/index.php'; $this->actual = SC_Utils::getRealURL($input); $this->verify(); } ////////////////////////////////////////// }
mnmn111/ec-cube-global
tests/class/util/SC_Utils/SC_Utils_getRealURLTest.php
PHP
gpl-2.0
2,732
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "ags/engine/ac/dynobj/cc_gui.h" #include "ags/engine/ac/dynobj/script_gui.h" #include "ags/globals.h" namespace AGS3 { // return the type name of the object const char *CCGUI::GetType() { return "GUI"; } // serialize the object into BUFFER (which is BUFSIZE bytes) // return number of bytes used int CCGUI::Serialize(const char *address, char *buffer, int bufsize) { const ScriptGUI *shh = (const ScriptGUI *)address; StartSerialize(buffer); SerializeInt(shh->id); return EndSerialize(); } void CCGUI::Unserialize(int index, const char *serializedData, int dataSize) { StartUnserialize(serializedData, dataSize); int num = UnserializeInt(); ccRegisterUnserializedObject(index, &_G(scrGui)[num], this); } } // namespace AGS3
vanfanel/scummvm
engines/ags/engine/ac/dynobj/cc_gui.cpp
C++
gpl-2.0
1,695
<?php namespace app\models; use Yii; /** * This is the model class for table "rel_job". * * @property integer $rj_id * @property string $positiontype * @property string $rj_name * @property string $rj_dep * @property string $work_type * @property string $max_salary * @property string $work_city * @property string $work_year * @property string $education * @property string $work_tempt * @property string $work_desc * @property string $work_address * @property integer $company_id * @property integer $rj_status * @property integer $addtime * @property integer $m_id * @property string $email * @property integer $is_hot * @property string $min_salary * @property integer $is_ok * @property string $lng * @property string $lat */ class RelJob extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'rel_job'; } /** * @inheritdoc */ public function rules() { return [ [['rj_name'], 'required'], [['max_salary'], 'number'], [['work_desc'], 'string'], [['company_id', 'rj_status', 'addtime', 'm_id', 'is_hot', 'is_ok'], 'integer'], [['positiontype', 'rj_dep', 'work_type'], 'string', 'max' => 30], [['rj_name', 'lng', 'lat'], 'string', 'max' => 20], [['work_city', 'work_year', 'education'], 'string', 'max' => 10], [['work_tempt'], 'string', 'max' => 25], [['work_address'], 'string', 'max' => 255], [['email'], 'string', 'max' => 50], [['min_salary'], 'string', 'max' => 220] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'rj_id' => 'Rj ID', 'positiontype' => 'Positiontype', 'rj_name' => 'Rj Name', 'rj_dep' => 'Rj Dep', 'work_type' => 'Work Type', 'max_salary' => 'Max Salary', 'work_city' => 'Work City', 'work_year' => 'Work Year', 'education' => 'Education', 'work_tempt' => 'Work Tempt', 'work_desc' => 'Work Desc', 'work_address' => 'Work Address', 'company_id' => 'Company ID', 'rj_status' => 'Rj Status', 'addtime' => 'Addtime', 'm_id' => 'M ID', 'email' => 'Email', 'is_hot' => 'Is Hot', 'min_salary' => 'Min Salary', 'is_ok' => 'Is Ok', 'lng' => 'Lng', 'lat' => 'Lat', ]; } }
zyweb/group5
models/RelJob.php
PHP
gpl-2.0
2,597
/* * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * Provides user interface objects built according to the Basic look and feel. * The Basic look and feel provides default behavior used by many look and feel * packages. It contains components, layout managers, events, event listeners, * and adapters. You can subclass the classes in this package to create your own * customized look and feel. * <p> * These classes are designed to be used while the corresponding * {@code LookAndFeel} class has been installed * (<code>UIManager.setLookAndFeel(new <i>XXX</i>LookAndFeel())</code>). * Using them while a different {@code LookAndFeel} is installed may produce * unexpected results, including exceptions. Additionally, changing the * {@code LookAndFeel} maintained by the {@code UIManager} without updating the * corresponding {@code ComponentUI} of any {@code JComponent}s may also produce * unexpected results, such as the wrong colors showing up, and is generally not * encouraged. * <p> * <strong>Note:</strong> * Most of the Swing API is <em>not</em> thread safe. For details, see * <a * href="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html" * target="_top">Concurrency in Swing</a>, * a section in * <em><a href="https://docs.oracle.com/javase/tutorial/" * target="_top">The Java Tutorial</a></em>. * * @since 1.2 * @serial exclude */ package javax.swing.plaf.basic;
md-5/jdk10
src/java.desktop/share/classes/javax/swing/plaf/basic/package-info.java
Java
gpl-2.0
2,590
/******************************************************************************* ** ** Photivo ** ** Copyright (C) 2008 Jos De Laender <jos.de_laender@telenet.be> ** Copyright (C) 2012-2013 Michael Munzert <mail@mm-log.com> ** ** This file is part of Photivo. ** ** Photivo is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License version 3 ** as published by the Free Software Foundation. ** ** Photivo is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Photivo. If not, see <http://www.gnu.org/licenses/>. ** *******************************************************************************/ #include "ptError.h" #include "ptCalloc.h" #include "ptImage8.h" #include "ptImage.h" #include "ptResizeFilters.h" #include <cstdio> #include <cstdlib> #include <cassert> //============================================================================== ptImage8::ptImage8(): m_Width(0), m_Height(0), m_Colors(0), m_ColorSpace(ptSpace_sRGB_D65), m_SizeBytes(0) {} //============================================================================== ptImage8::ptImage8(uint16_t AWidth, uint16_t AHeight, short ANrColors) { m_Image.clear(); m_ColorSpace = ptSpace_sRGB_D65; setSize(AWidth, AHeight, ANrColors); } //============================================================================== void ptImage8::setSize(uint16_t AWidth, uint16_t AHeight, int AColorCount) { m_Width = AWidth; m_Height = AHeight; m_Colors = AColorCount; m_SizeBytes = m_Width * m_Height * m_Colors; m_Image.resize(m_Width * m_Height); } //============================================================================== void ptImage8::fillColor(uint8_t ARed, uint8_t AGreen, uint8_t ABlue, uint8_t AAlpha) { std::array<uint8_t, 4> hTemp = {{ARed, AGreen, ABlue, AAlpha}}; std::fill(std::begin(m_Image), std::end(m_Image), hTemp); } //============================================================================== ptImage8::~ptImage8() { // nothing to do } //============================================================================== ptImage8* ptImage8::Set(const ptImage *Origin) { assert(NULL != Origin); assert(ptSpace_Lab != Origin->m_ColorSpace); setSize(Origin->m_Width, Origin->m_Height, Origin->m_Colors); m_ColorSpace = Origin->m_ColorSpace; for (uint32_t i = 0; i < static_cast<uint32_t>(m_Width)*m_Height; i++) { for (short c = 0; c < 3; c++) { // Mind the R<->B swap ! m_Image[i][2-c] = Origin->m_Image[i][c]>>8; } m_Image[i][3] = 0xff; } return this; } //============================================================================== ptImage8 *ptImage8::Set(const ptImage8 *Origin) { assert(NULL != Origin); setSize(Origin->m_Width, Origin->m_Height, Origin->m_Colors); m_ColorSpace = Origin->m_ColorSpace; m_Image = Origin->m_Image; return this; } //============================================================================== void ptImage8::FromQImage(const QImage AImage) { setSize(AImage.width(), AImage.height(), 4); m_ColorSpace = ptSpace_sRGB_D65; memcpy((uint8_t (*)[4]) m_Image.data(), AImage.bits(), m_SizeBytes); }
tectronics/photivo
Sources/ptImage8.cpp
C++
gpl-3.0
3,515
<?php /* ---------------------------------------------------------------------- * app/controllers/find/BrowseObjectsController.php * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2009-2013 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ require_once(__CA_LIB_DIR__."/ca/BaseBrowseController.php"); require_once(__CA_LIB_DIR__."/ca/Browse/ObjectBrowse.php"); require_once(__CA_LIB_DIR__."/core/GeographicMap.php"); class BrowseObjectsController extends BaseBrowseController { # ------------------------------------------------------- /** * Name of table for which this browse returns items */ protected $ops_tablename = 'ca_objects'; /** * Number of items per results page */ protected $opa_items_per_page = array(8, 16, 24, 32); /** * List of result views supported for this browse * Is associative array: keys are view labels, values are view specifier to be incorporated into view name */ protected $opa_views; /** * List of available result sorting fields * Is associative array: values are display names for fields, keys are full fields names (table.field) to be used as sort */ protected $opa_sorts; /** * Name of "find" used to defined result context for ResultContext object * Must be unique for the table and have a corresponding entry in find_navigation.conf */ protected $ops_find_type = 'basic_browse'; # ------------------------------------------------------- public function __construct(&$po_request, &$po_response, $pa_view_paths=null) { parent::__construct($po_request, $po_response, $pa_view_paths); $this->opo_browse = new ObjectBrowse($this->opo_result_context->getSearchExpression(), 'providence'); $this->opa_views = array( 'thumbnail' => _t('thumbnails'), 'full' => _t('full'), 'list' => _t('list'), 'editable' => _t('editable') ); $this->opa_sorts = array_merge(array( 'ca_object_labels.name' => _t('title'), 'ca_objects.type_id' => _t('type'), 'ca_objects.idno_sort' => _t('idno') ), $this->opa_sorts); } # ------------------------------------------------------- public function Index($pa_options=null) { JavascriptLoadManager::register('imageScroller'); JavascriptLoadManager::register('tabUI'); JavascriptLoadManager::register('panel'); parent::Index($pa_options); } # ------------------------------------------------------- /** * Ajax action that returns info on a mapped location based upon the 'id' request parameter. * 'id' is a list of object_ids to display information before. Each integer id is separated by a semicolon (";") * The "ca_objects_results_map_balloon_html" view in Results/ is used to render the content. */ public function getMapItemInfo() { $pa_object_ids = explode(';', $this->request->getParameter('id', pString)); $va_access_values = caGetUserAccessValues($this->request); $this->view->setVar('ids', $pa_object_ids); $this->view->setVar('access_values', $va_access_values); $this->render("Results/ca_objects_results_map_balloon_html.php"); } # ------------------------------------------------------- /** * Returns string representing the name of the item the browse will return * * If $ps_mode is 'singular' [default] then the singular version of the name is returned, otherwise the plural is returned */ public function browseName($ps_mode='singular') { return ($ps_mode === 'singular') ? _t('object') : _t('objects'); } # ------------------------------------------------------- /** * Returns string representing the name of this controller (minus the "Controller" part) */ public function controllerName() { return 'BrowseObjects'; } # ------------------------------------------------------- } ?>
libis/ca_babtekst
app/controllers/find/BrowseObjectsController.php
PHP
gpl-3.0
4,873
<?php /* Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2016 Frédéric France <frederic.france@free.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file htdocs/compta/paiement_charge.php * \ingroup tax * \brief Page to add payment of a tax */ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("bills"); $chid=GETPOST("id", 'int'); $action=GETPOST('action', 'alpha'); $amounts = array(); // Security check $socid=0; if ($user->societe_id > 0) { $socid = $user->societe_id; } /* * Actions */ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm=='yes')) { $error=0; if ($_POST["cancel"]) { $loc = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$chid; header("Location: ".$loc); exit; } $datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); if (! $_POST["paiementtype"] > 0) { setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode")), null, 'errors'); $error++; $action = 'create'; } if ($datepaye == '') { setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("Date")), null, 'errors'); $error++; $action = 'create'; } if (! empty($conf->banque->enabled) && ! $_POST["accountid"] > 0) { setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("AccountToCredit")), null, 'errors'); $error++; $action = 'create'; } if (! $error) { $paymentid = 0; // Read possible payments foreach ($_POST as $key => $value) { if (substr($key,0,7) == 'amount_') { $other_chid = substr($key,7); $amounts[$other_chid] = price2num($_POST[$key]); } } if (count($amounts) <= 0) { $error++; setEventMessages($langs->trans("ErrorNoPaymentDefined"), null, 'errors'); $action='create'; } if (! $error) { $db->begin(); // Create a line of payments $paiement = new PaymentSocialContribution($db); $paiement->chid = $chid; $paiement->datepaye = $datepaye; $paiement->amounts = $amounts; // Tableau de montant $paiement->paiementtype = $_POST["paiementtype"]; $paiement->num_paiement = $_POST["num_paiement"]; $paiement->note = $_POST["note"]; if (! $error) { $paymentid = $paiement->create($user, (GETPOST('closepaidcontrib')=='on'?1:0)); if ($paymentid < 0) { $error++; setEventMessages($paiement->error, null, 'errors'); $action='create'; } } if (! $error) { $result=$paiement->addPaymentToBank($user,'payment_sc','(SocialContributionPayment)', GETPOST('accountid','int'),'',''); if (! ($result > 0)) { $error++; setEventMessages($paiement->error, null, 'errors'); $action='create'; } } if (! $error) { $db->commit(); $loc = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$chid; header('Location: '.$loc); exit; } else { $db->rollback(); } } } } /* * View */ llxHeader(); $form=new Form($db); // Formulaire de creation d'un paiement de charge if ($action == 'create') { $charge = new ChargeSociales($db); $charge->fetch($chid); $charge->accountid=$charge->fk_account?$charge->fk_account:$charge->accountid; $charge->paiementtype=$charge->mode_reglement_id?$charge->mode_reglement_id:$charge->paiementtype; $total = $charge->amount; if (! empty($conf->use_javascript_ajax)) { print "\n".'<script type="text/javascript" language="javascript">'; //Add js for AutoFill print ' $(document).ready(function () {'; print ' $(".AutoFillAmount").on(\'click touchstart\', function(){ var amount = $(this).data("value"); document.getElementById($(this).data(\'rowid\')).value = amount ; });'; print ' });'."\n"; print ' </script>'."\n"; } print load_fiche_titre($langs->trans("DoPayment")); print "<br>\n"; if ($mesg) { print "<div class=\"error\">$mesg</div>"; } print '<form name="add_payment" action="'.$_SERVER['PHP_SELF'].'" method="post">'; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="id" value="'.$chid.'">'; print '<input type="hidden" name="chid" value="'.$chid.'">'; print '<input type="hidden" name="action" value="add_payment">'; dol_fiche_head('', ''); print '<table class="border" width="100%">'; print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td><td><a href="'.DOL_URL_ROOT.'/compta/sociales/card.php?id='.$chid.'">'.$chid.'</a></td></tr>'; print '<tr><td>'.$langs->trans("Type")."</td><td>".$charge->type_libelle."</td></tr>\n"; print '<tr><td>'.$langs->trans("Period")."</td><td>".dol_print_date($charge->periode,'day')."</td></tr>\n"; print '<tr><td>'.$langs->trans("Label").'</td><td>'.$charge->lib."</td></tr>\n"; /*print '<tr><td>'.$langs->trans("DateDue")."</td><td>".dol_print_date($charge->date_ech,'day')."</td></tr>\n"; print '<tr><td>'.$langs->trans("Amount")."</td><td>".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>';*/ $sql = "SELECT sum(p.amount) as total"; $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; $sql.= " WHERE p.fk_charge = ".$chid; $resql = $db->query($sql); if ($resql) { $obj=$db->fetch_object($resql); $sumpaid = $obj->total; $db->free(); } /*print '<tr><td>'.$langs->trans("AlreadyPaid").'</td><td>'.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>'; print '<tr><td class="tdtop">'.$langs->trans("RemainderToPay").'</td><td>'.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'</td></tr>';*/ print '<tr><td class="fieldrequired">'.$langs->trans("Date").'</td><td>'; $datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); $datepayment=empty($conf->global->MAIN_AUTOFILL_DATE)?(empty($_POST["remonth"])?-1:$datepaye):0; $form->select_date($datepayment,'','','','',"add_payment",1,1); print "</td>"; print '</tr>'; print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td>'; $form->select_types_paiements(isset($_POST["paiementtype"])?$_POST["paiementtype"]:$charge->paiementtype, "paiementtype"); print "</td>\n"; print '</tr>'; print '<tr>'; print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>'; print '<td>'; $form->select_comptes(isset($_POST["accountid"])?$_POST["accountid"]:$charge->accountid, "accountid", 0, '',1); // Show opend bank account list print '</td></tr>'; // Number print '<tr><td>'.$langs->trans('Numero'); print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>'; print '</td>'; print '<td><input name="num_paiement" type="text" value="'.GETPOST('num_paiement').'"></td></tr>'."\n"; print '<tr>'; print '<td class="tdtop">'.$langs->trans("Comments").'</td>'; print '<td class="tdtop"><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>'; print '</tr>'; print '</table>'; dol_fiche_end(); /* * Autres charges impayees */ $num = 1; $i = 0; print '<table class="noborder" width="100%">'; print '<tr class="liste_titre">'; //print '<td>'.$langs->trans("SocialContribution").'</td>'; print '<td align="left">'.$langs->trans("DateDue").'</td>'; print '<td align="right">'.$langs->trans("Amount").'</td>'; print '<td align="right">'.$langs->trans("AlreadyPaid").'</td>'; print '<td align="right">'.$langs->trans("RemainderToPay").'</td>'; print '<td align="center">'.$langs->trans("Amount").'</td>'; print "</tr>\n"; $var=true; $total=0; $totalrecu=0; while ($i < $num) { $objp = $charge; print '<tr class="oddeven">'; if ($objp->date_ech > 0) { print "<td align=\"left\">".dol_print_date($objp->date_ech,'day')."</td>\n"; } else { print "<td align=\"center\"><b>!!!</b></td>\n"; } print '<td align="right">'.price($objp->amount)."</td>"; print '<td align="right">'.price($sumpaid)."</td>"; print '<td align="right">'.price($objp->amount - $sumpaid)."</td>"; print '<td align="center">'; if ($sumpaid < $objp->amount) { $namef = "amount_".$objp->id; $nameRemain = "remain_".$objp->id; if (!empty($conf->use_javascript_ajax)) print img_picto("Auto fill",'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->amount - $sumpaid)."'"); $remaintopay=$objp->amount - $sumpaid; print '<input type=hidden class="sum_remain" name="'.$nameRemain.'" value="'.$remaintopay.'">'; print '<input type="text" size="8" name="'.$namef.'" id="'.$namef.'">'; } else { print '-'; } print "</td>"; print "</tr>\n"; $total+=$objp->total; $total_ttc+=$objp->total_ttc; $totalrecu+=$objp->am; $i++; } if ($i > 1) { // Print total print "<tr ".$bc[!$var].">"; print '<td colspan="2" align="left">'.$langs->trans("Total").':</td>'; print "<td align=\"right\"><b>".price($total_ttc)."</b></td>"; print "<td align=\"right\"><b>".price($totalrecu)."</b></td>"; print "<td align=\"right\"><b>".price($total_ttc - $totalrecu)."</b></td>"; print '<td align="center">&nbsp;</td>'; print "</tr>\n"; } print "</table>"; // Bouton Save payment print '<br><div class="center"><input type="checkbox" checked name="closepaidcontrib"> '.$langs->trans("ClosePaidContributionsAutomatically"); print '<br><input type="submit" class="button" name="save" value="'.$langs->trans('ToMakePayment').'">'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">'; print '</div>'; print "</form>\n"; } llxFooter(); $db->close();
tomours/dolibarr
htdocs/compta/paiement_charge.php
PHP
gpl-3.0
10,955
# # Copyright (C) 1997-2016 JDE Developers Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # Authors : # Aitor Martinez Fernandez <aitor.martinez.fernandez@gmail.com> # import traceback import jderobot import threading import Ice from .threadSensor import ThreadSensor from jderobotTypes import NavdataData class NavData: def __init__(self, jdrc, prefix): self.lock = threading.Lock() try: ic = jdrc.getIc() proxyStr = jdrc.getConfig().getProperty(prefix+".Proxy") base = ic.stringToProxy(proxyStr) self.proxy = jderobot.NavdataPrx.checkedCast(base) self.navData = NavdataData() self.update() if not self.proxy: print ('Interface ' + prefix + ' not configured') except Ice.ConnectionRefusedException: print(prefix + ': connection refused') except: traceback.print_exc() exit(-1) def update(self): if self.hasproxy(): localNavdata = self.proxy.getNavdata() navdataData = NavdataData() navdataData.vehicle = localNavdata.vehicle navdataData.state = localNavdata.state navdataData.batteryPercent = localNavdata.batteryPercent navdataData.magX = localNavdata.magX navdataData.magY = localNavdata.magY navdataData.magZ = localNavdata.magZ navdataData.pressure = localNavdata.pressure navdataData.temp = localNavdata.temp navdataData.windSpeed = localNavdata.windSpeed navdataData.windAngle = localNavdata.windAngle navdataData.windCompAngle = localNavdata.windCompAngle navdataData.rotX = localNavdata.rotX navdataData.rotY = localNavdata.rotY navdataData.rotZ = localNavdata.rotZ navdataData.altd = localNavdata.altd navdataData.vx = localNavdata.vx navdataData.vy = localNavdata.vy navdataData.vz = localNavdata.vz navdataData.ax = localNavdata.ax navdataData.ay = localNavdata.ay navdataData.az = localNavdata.az navdataData.tagsCount = localNavdata.tagsCount navdataData.tagsType = localNavdata.tagsType navdataData.tagsXc = localNavdata.tagsXc navdataData.tagsYc = localNavdata.tagsYc navdataData.tagsWidth = localNavdata.tagsWidth navdataData.tagsHeight = localNavdata.tagsHeight navdataData.tagsOrientation = localNavdata.tagsOrientation navdataData.tagsDistance = localNavdata.tagsDistance navdataData.timeStamp = localNavdata.tm self.lock.acquire() self.navData = navdataData self.lock.release() def hasproxy (self): ''' Returns if proxy has ben created or not. @return if proxy has ben created or not (Boolean) ''' return hasattr(self,"proxy") and self.proxy def getNavdata(self): if self.hasproxy(): self.lock.acquire() navData = self.navData self.lock.release() return navData return None class NavdataIceClient: def __init__(self,ic,prefix, start = False): self.navdata = NavData(ic,prefix) self.kill_event = threading.Event() self.thread = ThreadSensor(self.navdata, self.kill_event) self.thread.daemon = True if start: self.start() def start(self): ''' Starts the client. If client is stopped you can not start again, Threading.Thread raised error ''' self.kill_event.clear() self.thread.start() def stop(self): ''' Stops the client. If client is stopped you can not start again, Threading.Thread raised error ''' self.kill_event.set() def getNavData(self): return self.navdata.getNavdata() def hasproxy (self): ''' Returns if proxy has ben created or not. @return if proxy has ben created or not (Boolean) ''' return self.navdata.hasproxy()
fqez/JdeRobot
src/libs/comm_py/comm/ice/navdataIceClient.py
Python
gpl-3.0
4,847
// -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- // vim: set ts=2 et sw=2 tw=80: // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. #include "secport.h" #include "gtest/gtest.h" #include "prnetdb.h" #include <stdint.h> #include <string.h> #include <string> namespace nss_test { // Structures to represent test cases. These are small enough that // passing by value isn't a problem. struct Ucs4Case { PRUint32 c; const char *utf8; }; struct Ucs2Case { PRUint16 c; const char *utf8; }; struct Utf16Case { PRUint32 c; PRUint16 w[2]; }; struct Utf16BadCase { PRUint16 w[3]; }; // Test classes for parameterized tests: class Ucs4Test : public ::testing::TestWithParam<Ucs4Case> {}; class Ucs2Test : public ::testing::TestWithParam<Ucs2Case> {}; class Utf16Test : public ::testing::TestWithParam<Utf16Case> {}; class BadUtf8Test : public ::testing::TestWithParam<const char *> {}; class BadUtf16Test : public ::testing::TestWithParam<Utf16BadCase> {}; class Iso88591Test : public ::testing::TestWithParam<Ucs2Case> {}; // Tests of sec_port_ucs4_utf8_conversion_function, by itself, on // valid inputs: TEST_P(Ucs4Test, ToUtf8) { const Ucs4Case testCase = GetParam(); PRUint32 nc = PR_htonl(testCase.c); unsigned char utf8[8] = {0}; unsigned int len = 0; PRBool result = sec_port_ucs4_utf8_conversion_function( PR_FALSE, (unsigned char *)&nc, sizeof(nc), utf8, sizeof(utf8), &len); ASSERT_TRUE(result); ASSERT_LT(len, sizeof(utf8)); EXPECT_EQ(std::string(testCase.utf8), std::string((char *)utf8, len)); EXPECT_EQ('\0', utf8[len]); } TEST_P(Ucs4Test, FromUtf8) { const Ucs4Case testCase = GetParam(); PRUint32 nc; unsigned int len = 0; PRBool result = sec_port_ucs4_utf8_conversion_function( PR_TRUE, (unsigned char *)testCase.utf8, strlen(testCase.utf8), (unsigned char *)&nc, sizeof(nc), &len); ASSERT_TRUE(result); ASSERT_EQ(sizeof(nc), len); EXPECT_EQ(testCase.c, PR_ntohl(nc)); } TEST_P(Ucs4Test, DestTooSmall) { const Ucs4Case testCase = GetParam(); PRUint32 nc = PR_htonl(testCase.c); unsigned char utf8[8]; unsigned char *utf8end = utf8 + sizeof(utf8); unsigned int len = strlen(testCase.utf8) - 1; ASSERT_LE(len, sizeof(utf8)); PRBool result = sec_port_ucs4_utf8_conversion_function( PR_FALSE, (unsigned char *)&nc, sizeof(nc), utf8end - len, len, &len); ASSERT_FALSE(result); ASSERT_EQ(strlen(testCase.utf8), len); } // Tests of sec_port_ucs2_utf8_conversion_function, by itself, on // valid inputs: TEST_P(Ucs2Test, ToUtf8) { const Ucs2Case testCase = GetParam(); PRUint16 nc = PR_htons(testCase.c); unsigned char utf8[8] = {0}; unsigned int len = 0; PRBool result = sec_port_ucs2_utf8_conversion_function( PR_FALSE, (unsigned char *)&nc, sizeof(nc), utf8, sizeof(utf8), &len); ASSERT_TRUE(result); ASSERT_LT(len, sizeof(utf8)); EXPECT_EQ(std::string(testCase.utf8), std::string((char *)utf8, len)); EXPECT_EQ('\0', utf8[len]); } TEST_P(Ucs2Test, FromUtf8) { const Ucs2Case testCase = GetParam(); PRUint16 nc; unsigned int len = 0; PRBool result = sec_port_ucs2_utf8_conversion_function( PR_TRUE, (unsigned char *)testCase.utf8, strlen(testCase.utf8), (unsigned char *)&nc, sizeof(nc), &len); ASSERT_EQ(PR_TRUE, result); ASSERT_EQ(sizeof(nc), len); EXPECT_EQ(testCase.c, PR_ntohs(nc)); } TEST_P(Ucs2Test, DestTooSmall) { const Ucs2Case testCase = GetParam(); PRUint16 nc = PR_htons(testCase.c); unsigned char utf8[8]; unsigned char *utf8end = utf8 + sizeof(utf8); unsigned int len = strlen(testCase.utf8) - 1; ASSERT_LE(len, sizeof(utf8)); PRBool result = sec_port_ucs2_utf8_conversion_function( PR_FALSE, (unsigned char *)&nc, sizeof(nc), utf8end - len, len, &len); ASSERT_EQ(result, PR_FALSE); ASSERT_EQ(strlen(testCase.utf8), len); } // Tests using UTF-16 and UCS-4 conversion together: TEST_P(Utf16Test, From16To32) { const Utf16Case testCase = GetParam(); PRUint16 from[2] = {PR_htons(testCase.w[0]), PR_htons(testCase.w[1])}; PRUint32 to; unsigned char utf8[8]; unsigned int len = 0; PRBool result = sec_port_ucs2_utf8_conversion_function( PR_FALSE, (unsigned char *)&from, sizeof(from), utf8, sizeof(utf8), &len); ASSERT_EQ(PR_TRUE, result); result = sec_port_ucs4_utf8_conversion_function( PR_TRUE, utf8, len, (unsigned char *)&to, sizeof(to), &len); ASSERT_EQ(PR_TRUE, result); ASSERT_EQ(sizeof(to), len); EXPECT_EQ(testCase.c, PR_ntohl(to)); } TEST_P(Utf16Test, From32To16) { const Utf16Case testCase = GetParam(); PRUint32 from = PR_htonl(testCase.c); unsigned char utf8[8]; unsigned int len = 0; PRBool result = sec_port_ucs4_utf8_conversion_function( PR_FALSE, (unsigned char *)&from, sizeof(from), utf8, sizeof(utf8), &len); ASSERT_EQ(PR_TRUE, result); const std::string utf8copy((char *)utf8, len); PRUint16 to[2]; result = sec_port_ucs2_utf8_conversion_function( PR_TRUE, utf8, len, (unsigned char *)&to, sizeof(to), &len); ASSERT_EQ(PR_TRUE, result); ASSERT_EQ(sizeof(to), len); EXPECT_EQ(testCase.w[0], PR_ntohs(to[0])); EXPECT_EQ(testCase.w[1], PR_ntohs(to[1])); } TEST_P(Utf16Test, SameUtf8) { const Utf16Case testCase = GetParam(); PRUint32 from32 = PR_htonl(testCase.c); unsigned char utf8from32[8]; unsigned int lenFrom32 = 0; PRBool result = sec_port_ucs4_utf8_conversion_function( PR_FALSE, (unsigned char *)&from32, sizeof(from32), utf8from32, sizeof(utf8from32), &lenFrom32); ASSERT_TRUE(result); ASSERT_LE(lenFrom32, sizeof(utf8from32)); PRUint16 from16[2] = {PR_htons(testCase.w[0]), PR_htons(testCase.w[1])}; unsigned char utf8from16[8]; unsigned int lenFrom16 = 0; result = sec_port_ucs2_utf8_conversion_function( PR_FALSE, (unsigned char *)&from16, sizeof(from16), utf8from16, sizeof(utf8from16), &lenFrom16); ASSERT_TRUE(result); ASSERT_LE(lenFrom16, sizeof(utf8from16)); EXPECT_EQ(std::string((char *)utf8from32, lenFrom32), std::string((char *)utf8from16, lenFrom16)); } // Tests of invalid UTF-8 input: TEST_P(BadUtf8Test, HasNoUcs2) { const char *const utf8 = GetParam(); unsigned char destBuf[30]; unsigned int len = 0; PRBool result = sec_port_ucs2_utf8_conversion_function( PR_TRUE, (unsigned char *)utf8, strlen(utf8), destBuf, sizeof(destBuf), &len); EXPECT_FALSE(result); } TEST_P(BadUtf8Test, HasNoUcs4) { const char *const utf8 = GetParam(); unsigned char destBuf[30]; unsigned int len = 0; PRBool result = sec_port_ucs4_utf8_conversion_function( PR_TRUE, (unsigned char *)utf8, strlen(utf8), destBuf, sizeof(destBuf), &len); EXPECT_FALSE(result); } // Tests of invalid UTF-16 input: TEST_P(BadUtf16Test, HasNoUtf8) { const Utf16BadCase testCase = GetParam(); Utf16BadCase srcBuf; unsigned int len; static const size_t maxLen = PR_ARRAY_SIZE(srcBuf.w); size_t srcLen = 0; while (testCase.w[srcLen] != 0) { srcBuf.w[srcLen] = PR_htons(testCase.w[srcLen]); srcLen++; ASSERT_LT(srcLen, maxLen); } unsigned char destBuf[18]; PRBool result = sec_port_ucs2_utf8_conversion_function( PR_FALSE, (unsigned char *)srcBuf.w, srcLen * sizeof(PRUint16), destBuf, sizeof(destBuf), &len); EXPECT_FALSE(result); } // Tests of sec_port_iso88591_utf8_conversion_function on valid inputs: TEST_P(Iso88591Test, ToUtf8) { const Ucs2Case testCase = GetParam(); unsigned char iso88591 = testCase.c; unsigned char utf8[3] = {0}; unsigned int len = 0; ASSERT_EQ(testCase.c, (PRUint16)iso88591); PRBool result = sec_port_iso88591_utf8_conversion_function( &iso88591, 1, utf8, sizeof(utf8), &len); ASSERT_TRUE(result); ASSERT_LT(len, sizeof(utf8)); EXPECT_EQ(std::string(testCase.utf8), std::string((char *)utf8, len)); EXPECT_EQ(0U, utf8[len]); } // Tests for the various representations of NUL (which the above // NUL-terminated test cases omitted): TEST(Utf8Zeroes, From32To8) { unsigned int len; PRUint32 from = 0; unsigned char to; PRBool result = sec_port_ucs4_utf8_conversion_function( PR_FALSE, (unsigned char *)&from, sizeof(from), &to, sizeof(to), &len); ASSERT_TRUE(result); ASSERT_EQ(sizeof(to), len); EXPECT_EQ(0U, to); } TEST(Utf8Zeroes, From16To8) { unsigned int len; PRUint16 from = 0; unsigned char to; PRBool result = sec_port_ucs2_utf8_conversion_function( PR_FALSE, (unsigned char *)&from, sizeof(from), &to, sizeof(to), &len); ASSERT_TRUE(result); ASSERT_EQ(sizeof(to), len); EXPECT_EQ(0U, to); } TEST(Utf8Zeroes, From8To32) { unsigned int len; unsigned char from = 0; PRUint32 to; PRBool result = sec_port_ucs4_utf8_conversion_function( PR_TRUE, &from, sizeof(from), (unsigned char *)&to, sizeof(to), &len); ASSERT_TRUE(result); ASSERT_EQ(sizeof(to), len); EXPECT_EQ(0U, to); } TEST(Utf8Zeroes, From8To16) { unsigned int len; unsigned char from = 0; PRUint16 to; PRBool result = sec_port_ucs2_utf8_conversion_function( PR_TRUE, &from, sizeof(from), (unsigned char *)&to, sizeof(to), &len); ASSERT_TRUE(result); ASSERT_EQ(sizeof(to), len); EXPECT_EQ(0U, to); } // UCS-4 <-> UTF-8 cases const Ucs4Case kUcs4Cases[] = { {0x00000001, "\x01"}, {0x00000002, "\x02"}, {0x00000003, "\x03"}, {0x00000004, "\x04"}, {0x00000007, "\x07"}, {0x00000008, "\x08"}, {0x0000000F, "\x0F"}, {0x00000010, "\x10"}, {0x0000001F, "\x1F"}, {0x00000020, "\x20"}, {0x0000003F, "\x3F"}, {0x00000040, "\x40"}, {0x0000007F, "\x7F"}, {0x00000080, "\xC2\x80"}, {0x00000081, "\xC2\x81"}, {0x00000082, "\xC2\x82"}, {0x00000084, "\xC2\x84"}, {0x00000088, "\xC2\x88"}, {0x00000090, "\xC2\x90"}, {0x000000A0, "\xC2\xA0"}, {0x000000C0, "\xC3\x80"}, {0x000000FF, "\xC3\xBF"}, {0x00000100, "\xC4\x80"}, {0x00000101, "\xC4\x81"}, {0x00000102, "\xC4\x82"}, {0x00000104, "\xC4\x84"}, {0x00000108, "\xC4\x88"}, {0x00000110, "\xC4\x90"}, {0x00000120, "\xC4\xA0"}, {0x00000140, "\xC5\x80"}, {0x00000180, "\xC6\x80"}, {0x000001FF, "\xC7\xBF"}, {0x00000200, "\xC8\x80"}, {0x00000201, "\xC8\x81"}, {0x00000202, "\xC8\x82"}, {0x00000204, "\xC8\x84"}, {0x00000208, "\xC8\x88"}, {0x00000210, "\xC8\x90"}, {0x00000220, "\xC8\xA0"}, {0x00000240, "\xC9\x80"}, {0x00000280, "\xCA\x80"}, {0x00000300, "\xCC\x80"}, {0x000003FF, "\xCF\xBF"}, {0x00000400, "\xD0\x80"}, {0x00000401, "\xD0\x81"}, {0x00000402, "\xD0\x82"}, {0x00000404, "\xD0\x84"}, {0x00000408, "\xD0\x88"}, {0x00000410, "\xD0\x90"}, {0x00000420, "\xD0\xA0"}, {0x00000440, "\xD1\x80"}, {0x00000480, "\xD2\x80"}, {0x00000500, "\xD4\x80"}, {0x00000600, "\xD8\x80"}, {0x000007FF, "\xDF\xBF"}, {0x00000800, "\xE0\xA0\x80"}, {0x00000801, "\xE0\xA0\x81"}, {0x00000802, "\xE0\xA0\x82"}, {0x00000804, "\xE0\xA0\x84"}, {0x00000808, "\xE0\xA0\x88"}, {0x00000810, "\xE0\xA0\x90"}, {0x00000820, "\xE0\xA0\xA0"}, {0x00000840, "\xE0\xA1\x80"}, {0x00000880, "\xE0\xA2\x80"}, {0x00000900, "\xE0\xA4\x80"}, {0x00000A00, "\xE0\xA8\x80"}, {0x00000C00, "\xE0\xB0\x80"}, {0x00000FFF, "\xE0\xBF\xBF"}, {0x00001000, "\xE1\x80\x80"}, {0x00001001, "\xE1\x80\x81"}, {0x00001002, "\xE1\x80\x82"}, {0x00001004, "\xE1\x80\x84"}, {0x00001008, "\xE1\x80\x88"}, {0x00001010, "\xE1\x80\x90"}, {0x00001020, "\xE1\x80\xA0"}, {0x00001040, "\xE1\x81\x80"}, {0x00001080, "\xE1\x82\x80"}, {0x00001100, "\xE1\x84\x80"}, {0x00001200, "\xE1\x88\x80"}, {0x00001400, "\xE1\x90\x80"}, {0x00001800, "\xE1\xA0\x80"}, {0x00001FFF, "\xE1\xBF\xBF"}, {0x00002000, "\xE2\x80\x80"}, {0x00002001, "\xE2\x80\x81"}, {0x00002002, "\xE2\x80\x82"}, {0x00002004, "\xE2\x80\x84"}, {0x00002008, "\xE2\x80\x88"}, {0x00002010, "\xE2\x80\x90"}, {0x00002020, "\xE2\x80\xA0"}, {0x00002040, "\xE2\x81\x80"}, {0x00002080, "\xE2\x82\x80"}, {0x00002100, "\xE2\x84\x80"}, {0x00002200, "\xE2\x88\x80"}, {0x00002400, "\xE2\x90\x80"}, {0x00002800, "\xE2\xA0\x80"}, {0x00003000, "\xE3\x80\x80"}, {0x00003FFF, "\xE3\xBF\xBF"}, {0x00004000, "\xE4\x80\x80"}, {0x00004001, "\xE4\x80\x81"}, {0x00004002, "\xE4\x80\x82"}, {0x00004004, "\xE4\x80\x84"}, {0x00004008, "\xE4\x80\x88"}, {0x00004010, "\xE4\x80\x90"}, {0x00004020, "\xE4\x80\xA0"}, {0x00004040, "\xE4\x81\x80"}, {0x00004080, "\xE4\x82\x80"}, {0x00004100, "\xE4\x84\x80"}, {0x00004200, "\xE4\x88\x80"}, {0x00004400, "\xE4\x90\x80"}, {0x00004800, "\xE4\xA0\x80"}, {0x00005000, "\xE5\x80\x80"}, {0x00006000, "\xE6\x80\x80"}, {0x00007FFF, "\xE7\xBF\xBF"}, {0x00008000, "\xE8\x80\x80"}, {0x00008001, "\xE8\x80\x81"}, {0x00008002, "\xE8\x80\x82"}, {0x00008004, "\xE8\x80\x84"}, {0x00008008, "\xE8\x80\x88"}, {0x00008010, "\xE8\x80\x90"}, {0x00008020, "\xE8\x80\xA0"}, {0x00008040, "\xE8\x81\x80"}, {0x00008080, "\xE8\x82\x80"}, {0x00008100, "\xE8\x84\x80"}, {0x00008200, "\xE8\x88\x80"}, {0x00008400, "\xE8\x90\x80"}, {0x00008800, "\xE8\xA0\x80"}, {0x00009000, "\xE9\x80\x80"}, {0x0000A000, "\xEA\x80\x80"}, {0x0000C000, "\xEC\x80\x80"}, {0x0000FFFF, "\xEF\xBF\xBF"}, {0x00010000, "\xF0\x90\x80\x80"}, {0x00010001, "\xF0\x90\x80\x81"}, {0x00010002, "\xF0\x90\x80\x82"}, {0x00010004, "\xF0\x90\x80\x84"}, {0x00010008, "\xF0\x90\x80\x88"}, {0x00010010, "\xF0\x90\x80\x90"}, {0x00010020, "\xF0\x90\x80\xA0"}, {0x00010040, "\xF0\x90\x81\x80"}, {0x00010080, "\xF0\x90\x82\x80"}, {0x00010100, "\xF0\x90\x84\x80"}, {0x00010200, "\xF0\x90\x88\x80"}, {0x00010400, "\xF0\x90\x90\x80"}, {0x00010800, "\xF0\x90\xA0\x80"}, {0x00011000, "\xF0\x91\x80\x80"}, {0x00012000, "\xF0\x92\x80\x80"}, {0x00014000, "\xF0\x94\x80\x80"}, {0x00018000, "\xF0\x98\x80\x80"}, {0x0001FFFF, "\xF0\x9F\xBF\xBF"}, {0x00020000, "\xF0\xA0\x80\x80"}, {0x00020001, "\xF0\xA0\x80\x81"}, {0x00020002, "\xF0\xA0\x80\x82"}, {0x00020004, "\xF0\xA0\x80\x84"}, {0x00020008, "\xF0\xA0\x80\x88"}, {0x00020010, "\xF0\xA0\x80\x90"}, {0x00020020, "\xF0\xA0\x80\xA0"}, {0x00020040, "\xF0\xA0\x81\x80"}, {0x00020080, "\xF0\xA0\x82\x80"}, {0x00020100, "\xF0\xA0\x84\x80"}, {0x00020200, "\xF0\xA0\x88\x80"}, {0x00020400, "\xF0\xA0\x90\x80"}, {0x00020800, "\xF0\xA0\xA0\x80"}, {0x00021000, "\xF0\xA1\x80\x80"}, {0x00022000, "\xF0\xA2\x80\x80"}, {0x00024000, "\xF0\xA4\x80\x80"}, {0x00028000, "\xF0\xA8\x80\x80"}, {0x00030000, "\xF0\xB0\x80\x80"}, {0x0003FFFF, "\xF0\xBF\xBF\xBF"}, {0x00040000, "\xF1\x80\x80\x80"}, {0x00040001, "\xF1\x80\x80\x81"}, {0x00040002, "\xF1\x80\x80\x82"}, {0x00040004, "\xF1\x80\x80\x84"}, {0x00040008, "\xF1\x80\x80\x88"}, {0x00040010, "\xF1\x80\x80\x90"}, {0x00040020, "\xF1\x80\x80\xA0"}, {0x00040040, "\xF1\x80\x81\x80"}, {0x00040080, "\xF1\x80\x82\x80"}, {0x00040100, "\xF1\x80\x84\x80"}, {0x00040200, "\xF1\x80\x88\x80"}, {0x00040400, "\xF1\x80\x90\x80"}, {0x00040800, "\xF1\x80\xA0\x80"}, {0x00041000, "\xF1\x81\x80\x80"}, {0x00042000, "\xF1\x82\x80\x80"}, {0x00044000, "\xF1\x84\x80\x80"}, {0x00048000, "\xF1\x88\x80\x80"}, {0x00050000, "\xF1\x90\x80\x80"}, {0x00060000, "\xF1\xA0\x80\x80"}, {0x0007FFFF, "\xF1\xBF\xBF\xBF"}, {0x00080000, "\xF2\x80\x80\x80"}, {0x00080001, "\xF2\x80\x80\x81"}, {0x00080002, "\xF2\x80\x80\x82"}, {0x00080004, "\xF2\x80\x80\x84"}, {0x00080008, "\xF2\x80\x80\x88"}, {0x00080010, "\xF2\x80\x80\x90"}, {0x00080020, "\xF2\x80\x80\xA0"}, {0x00080040, "\xF2\x80\x81\x80"}, {0x00080080, "\xF2\x80\x82\x80"}, {0x00080100, "\xF2\x80\x84\x80"}, {0x00080200, "\xF2\x80\x88\x80"}, {0x00080400, "\xF2\x80\x90\x80"}, {0x00080800, "\xF2\x80\xA0\x80"}, {0x00081000, "\xF2\x81\x80\x80"}, {0x00082000, "\xF2\x82\x80\x80"}, {0x00084000, "\xF2\x84\x80\x80"}, {0x00088000, "\xF2\x88\x80\x80"}, {0x00090000, "\xF2\x90\x80\x80"}, {0x000A0000, "\xF2\xA0\x80\x80"}, {0x000C0000, "\xF3\x80\x80\x80"}, {0x000FFFFF, "\xF3\xBF\xBF\xBF"}, {0x00100000, "\xF4\x80\x80\x80"}, {0x00100001, "\xF4\x80\x80\x81"}, {0x00100002, "\xF4\x80\x80\x82"}, {0x00100004, "\xF4\x80\x80\x84"}, {0x00100008, "\xF4\x80\x80\x88"}, {0x00100010, "\xF4\x80\x80\x90"}, {0x00100020, "\xF4\x80\x80\xA0"}, {0x00100040, "\xF4\x80\x81\x80"}, {0x00100080, "\xF4\x80\x82\x80"}, {0x00100100, "\xF4\x80\x84\x80"}, {0x00100200, "\xF4\x80\x88\x80"}, {0x00100400, "\xF4\x80\x90\x80"}, {0x00100800, "\xF4\x80\xA0\x80"}, {0x00101000, "\xF4\x81\x80\x80"}, {0x00102000, "\xF4\x82\x80\x80"}, {0x00104000, "\xF4\x84\x80\x80"}, {0x00108000, "\xF4\x88\x80\x80"}, {0x0010FFFF, "\xF4\x8F\xBF\xBF"}, }; // UCS-2 <-> UTF-8 cases (divided into ISO-8859-1 vs. not). const Ucs2Case kIso88591Cases[] = { {0x0001, "\x01"}, {0x0002, "\x02"}, {0x0003, "\x03"}, {0x0004, "\x04"}, {0x0007, "\x07"}, {0x0008, "\x08"}, {0x000F, "\x0F"}, {0x0010, "\x10"}, {0x001F, "\x1F"}, {0x0020, "\x20"}, {0x003F, "\x3F"}, {0x0040, "\x40"}, {0x007F, "\x7F"}, {0x0080, "\xC2\x80"}, {0x0081, "\xC2\x81"}, {0x0082, "\xC2\x82"}, {0x0084, "\xC2\x84"}, {0x0088, "\xC2\x88"}, {0x0090, "\xC2\x90"}, {0x00A0, "\xC2\xA0"}, {0x00C0, "\xC3\x80"}, {0x00FF, "\xC3\xBF"}, }; const Ucs2Case kUcs2Cases[] = { {0x0100, "\xC4\x80"}, {0x0101, "\xC4\x81"}, {0x0102, "\xC4\x82"}, {0x0104, "\xC4\x84"}, {0x0108, "\xC4\x88"}, {0x0110, "\xC4\x90"}, {0x0120, "\xC4\xA0"}, {0x0140, "\xC5\x80"}, {0x0180, "\xC6\x80"}, {0x01FF, "\xC7\xBF"}, {0x0200, "\xC8\x80"}, {0x0201, "\xC8\x81"}, {0x0202, "\xC8\x82"}, {0x0204, "\xC8\x84"}, {0x0208, "\xC8\x88"}, {0x0210, "\xC8\x90"}, {0x0220, "\xC8\xA0"}, {0x0240, "\xC9\x80"}, {0x0280, "\xCA\x80"}, {0x0300, "\xCC\x80"}, {0x03FF, "\xCF\xBF"}, {0x0400, "\xD0\x80"}, {0x0401, "\xD0\x81"}, {0x0402, "\xD0\x82"}, {0x0404, "\xD0\x84"}, {0x0408, "\xD0\x88"}, {0x0410, "\xD0\x90"}, {0x0420, "\xD0\xA0"}, {0x0440, "\xD1\x80"}, {0x0480, "\xD2\x80"}, {0x0500, "\xD4\x80"}, {0x0600, "\xD8\x80"}, {0x07FF, "\xDF\xBF"}, {0x0800, "\xE0\xA0\x80"}, {0x0801, "\xE0\xA0\x81"}, {0x0802, "\xE0\xA0\x82"}, {0x0804, "\xE0\xA0\x84"}, {0x0808, "\xE0\xA0\x88"}, {0x0810, "\xE0\xA0\x90"}, {0x0820, "\xE0\xA0\xA0"}, {0x0840, "\xE0\xA1\x80"}, {0x0880, "\xE0\xA2\x80"}, {0x0900, "\xE0\xA4\x80"}, {0x0A00, "\xE0\xA8\x80"}, {0x0C00, "\xE0\xB0\x80"}, {0x0FFF, "\xE0\xBF\xBF"}, {0x1000, "\xE1\x80\x80"}, {0x1001, "\xE1\x80\x81"}, {0x1002, "\xE1\x80\x82"}, {0x1004, "\xE1\x80\x84"}, {0x1008, "\xE1\x80\x88"}, {0x1010, "\xE1\x80\x90"}, {0x1020, "\xE1\x80\xA0"}, {0x1040, "\xE1\x81\x80"}, {0x1080, "\xE1\x82\x80"}, {0x1100, "\xE1\x84\x80"}, {0x1200, "\xE1\x88\x80"}, {0x1400, "\xE1\x90\x80"}, {0x1800, "\xE1\xA0\x80"}, {0x1FFF, "\xE1\xBF\xBF"}, {0x2000, "\xE2\x80\x80"}, {0x2001, "\xE2\x80\x81"}, {0x2002, "\xE2\x80\x82"}, {0x2004, "\xE2\x80\x84"}, {0x2008, "\xE2\x80\x88"}, {0x2010, "\xE2\x80\x90"}, {0x2020, "\xE2\x80\xA0"}, {0x2040, "\xE2\x81\x80"}, {0x2080, "\xE2\x82\x80"}, {0x2100, "\xE2\x84\x80"}, {0x2200, "\xE2\x88\x80"}, {0x2400, "\xE2\x90\x80"}, {0x2800, "\xE2\xA0\x80"}, {0x3000, "\xE3\x80\x80"}, {0x3FFF, "\xE3\xBF\xBF"}, {0x4000, "\xE4\x80\x80"}, {0x4001, "\xE4\x80\x81"}, {0x4002, "\xE4\x80\x82"}, {0x4004, "\xE4\x80\x84"}, {0x4008, "\xE4\x80\x88"}, {0x4010, "\xE4\x80\x90"}, {0x4020, "\xE4\x80\xA0"}, {0x4040, "\xE4\x81\x80"}, {0x4080, "\xE4\x82\x80"}, {0x4100, "\xE4\x84\x80"}, {0x4200, "\xE4\x88\x80"}, {0x4400, "\xE4\x90\x80"}, {0x4800, "\xE4\xA0\x80"}, {0x5000, "\xE5\x80\x80"}, {0x6000, "\xE6\x80\x80"}, {0x7FFF, "\xE7\xBF\xBF"}, {0x8000, "\xE8\x80\x80"}, {0x8001, "\xE8\x80\x81"}, {0x8002, "\xE8\x80\x82"}, {0x8004, "\xE8\x80\x84"}, {0x8008, "\xE8\x80\x88"}, {0x8010, "\xE8\x80\x90"}, {0x8020, "\xE8\x80\xA0"}, {0x8040, "\xE8\x81\x80"}, {0x8080, "\xE8\x82\x80"}, {0x8100, "\xE8\x84\x80"}, {0x8200, "\xE8\x88\x80"}, {0x8400, "\xE8\x90\x80"}, {0x8800, "\xE8\xA0\x80"}, {0x9000, "\xE9\x80\x80"}, {0xA000, "\xEA\x80\x80"}, {0xC000, "\xEC\x80\x80"}, {0xFB01, "\xEF\xAC\x81"}, {0xFFFF, "\xEF\xBF\xBF"}}; // UTF-16 <-> UCS-4 cases const Utf16Case kUtf16Cases[] = {{0x00010000, {0xD800, 0xDC00}}, {0x00010001, {0xD800, 0xDC01}}, {0x00010002, {0xD800, 0xDC02}}, {0x00010003, {0xD800, 0xDC03}}, {0x00010004, {0xD800, 0xDC04}}, {0x00010007, {0xD800, 0xDC07}}, {0x00010008, {0xD800, 0xDC08}}, {0x0001000F, {0xD800, 0xDC0F}}, {0x00010010, {0xD800, 0xDC10}}, {0x0001001F, {0xD800, 0xDC1F}}, {0x00010020, {0xD800, 0xDC20}}, {0x0001003F, {0xD800, 0xDC3F}}, {0x00010040, {0xD800, 0xDC40}}, {0x0001007F, {0xD800, 0xDC7F}}, {0x00010080, {0xD800, 0xDC80}}, {0x00010081, {0xD800, 0xDC81}}, {0x00010082, {0xD800, 0xDC82}}, {0x00010084, {0xD800, 0xDC84}}, {0x00010088, {0xD800, 0xDC88}}, {0x00010090, {0xD800, 0xDC90}}, {0x000100A0, {0xD800, 0xDCA0}}, {0x000100C0, {0xD800, 0xDCC0}}, {0x000100FF, {0xD800, 0xDCFF}}, {0x00010100, {0xD800, 0xDD00}}, {0x00010101, {0xD800, 0xDD01}}, {0x00010102, {0xD800, 0xDD02}}, {0x00010104, {0xD800, 0xDD04}}, {0x00010108, {0xD800, 0xDD08}}, {0x00010110, {0xD800, 0xDD10}}, {0x00010120, {0xD800, 0xDD20}}, {0x00010140, {0xD800, 0xDD40}}, {0x00010180, {0xD800, 0xDD80}}, {0x000101FF, {0xD800, 0xDDFF}}, {0x00010200, {0xD800, 0xDE00}}, {0x00010201, {0xD800, 0xDE01}}, {0x00010202, {0xD800, 0xDE02}}, {0x00010204, {0xD800, 0xDE04}}, {0x00010208, {0xD800, 0xDE08}}, {0x00010210, {0xD800, 0xDE10}}, {0x00010220, {0xD800, 0xDE20}}, {0x00010240, {0xD800, 0xDE40}}, {0x00010280, {0xD800, 0xDE80}}, {0x00010300, {0xD800, 0xDF00}}, {0x000103FF, {0xD800, 0xDFFF}}, {0x00010400, {0xD801, 0xDC00}}, {0x00010401, {0xD801, 0xDC01}}, {0x00010402, {0xD801, 0xDC02}}, {0x00010404, {0xD801, 0xDC04}}, {0x00010408, {0xD801, 0xDC08}}, {0x00010410, {0xD801, 0xDC10}}, {0x00010420, {0xD801, 0xDC20}}, {0x00010440, {0xD801, 0xDC40}}, {0x00010480, {0xD801, 0xDC80}}, {0x00010500, {0xD801, 0xDD00}}, {0x00010600, {0xD801, 0xDE00}}, {0x000107FF, {0xD801, 0xDFFF}}, {0x00010800, {0xD802, 0xDC00}}, {0x00010801, {0xD802, 0xDC01}}, {0x00010802, {0xD802, 0xDC02}}, {0x00010804, {0xD802, 0xDC04}}, {0x00010808, {0xD802, 0xDC08}}, {0x00010810, {0xD802, 0xDC10}}, {0x00010820, {0xD802, 0xDC20}}, {0x00010840, {0xD802, 0xDC40}}, {0x00010880, {0xD802, 0xDC80}}, {0x00010900, {0xD802, 0xDD00}}, {0x00010A00, {0xD802, 0xDE00}}, {0x00010C00, {0xD803, 0xDC00}}, {0x00010FFF, {0xD803, 0xDFFF}}, {0x00011000, {0xD804, 0xDC00}}, {0x00011001, {0xD804, 0xDC01}}, {0x00011002, {0xD804, 0xDC02}}, {0x00011004, {0xD804, 0xDC04}}, {0x00011008, {0xD804, 0xDC08}}, {0x00011010, {0xD804, 0xDC10}}, {0x00011020, {0xD804, 0xDC20}}, {0x00011040, {0xD804, 0xDC40}}, {0x00011080, {0xD804, 0xDC80}}, {0x00011100, {0xD804, 0xDD00}}, {0x00011200, {0xD804, 0xDE00}}, {0x00011400, {0xD805, 0xDC00}}, {0x00011800, {0xD806, 0xDC00}}, {0x00011FFF, {0xD807, 0xDFFF}}, {0x00012000, {0xD808, 0xDC00}}, {0x00012001, {0xD808, 0xDC01}}, {0x00012002, {0xD808, 0xDC02}}, {0x00012004, {0xD808, 0xDC04}}, {0x00012008, {0xD808, 0xDC08}}, {0x00012010, {0xD808, 0xDC10}}, {0x00012020, {0xD808, 0xDC20}}, {0x00012040, {0xD808, 0xDC40}}, {0x00012080, {0xD808, 0xDC80}}, {0x00012100, {0xD808, 0xDD00}}, {0x00012200, {0xD808, 0xDE00}}, {0x00012400, {0xD809, 0xDC00}}, {0x00012800, {0xD80A, 0xDC00}}, {0x00013000, {0xD80C, 0xDC00}}, {0x00013FFF, {0xD80F, 0xDFFF}}, {0x00014000, {0xD810, 0xDC00}}, {0x00014001, {0xD810, 0xDC01}}, {0x00014002, {0xD810, 0xDC02}}, {0x00014004, {0xD810, 0xDC04}}, {0x00014008, {0xD810, 0xDC08}}, {0x00014010, {0xD810, 0xDC10}}, {0x00014020, {0xD810, 0xDC20}}, {0x00014040, {0xD810, 0xDC40}}, {0x00014080, {0xD810, 0xDC80}}, {0x00014100, {0xD810, 0xDD00}}, {0x00014200, {0xD810, 0xDE00}}, {0x00014400, {0xD811, 0xDC00}}, {0x00014800, {0xD812, 0xDC00}}, {0x00015000, {0xD814, 0xDC00}}, {0x00016000, {0xD818, 0xDC00}}, {0x00017FFF, {0xD81F, 0xDFFF}}, {0x00018000, {0xD820, 0xDC00}}, {0x00018001, {0xD820, 0xDC01}}, {0x00018002, {0xD820, 0xDC02}}, {0x00018004, {0xD820, 0xDC04}}, {0x00018008, {0xD820, 0xDC08}}, {0x00018010, {0xD820, 0xDC10}}, {0x00018020, {0xD820, 0xDC20}}, {0x00018040, {0xD820, 0xDC40}}, {0x00018080, {0xD820, 0xDC80}}, {0x00018100, {0xD820, 0xDD00}}, {0x00018200, {0xD820, 0xDE00}}, {0x00018400, {0xD821, 0xDC00}}, {0x00018800, {0xD822, 0xDC00}}, {0x00019000, {0xD824, 0xDC00}}, {0x0001A000, {0xD828, 0xDC00}}, {0x0001C000, {0xD830, 0xDC00}}, {0x0001FFFF, {0xD83F, 0xDFFF}}, {0x00020000, {0xD840, 0xDC00}}, {0x00020001, {0xD840, 0xDC01}}, {0x00020002, {0xD840, 0xDC02}}, {0x00020004, {0xD840, 0xDC04}}, {0x00020008, {0xD840, 0xDC08}}, {0x00020010, {0xD840, 0xDC10}}, {0x00020020, {0xD840, 0xDC20}}, {0x00020040, {0xD840, 0xDC40}}, {0x00020080, {0xD840, 0xDC80}}, {0x00020100, {0xD840, 0xDD00}}, {0x00020200, {0xD840, 0xDE00}}, {0x00020400, {0xD841, 0xDC00}}, {0x00020800, {0xD842, 0xDC00}}, {0x00021000, {0xD844, 0xDC00}}, {0x00022000, {0xD848, 0xDC00}}, {0x00024000, {0xD850, 0xDC00}}, {0x00028000, {0xD860, 0xDC00}}, {0x0002FFFF, {0xD87F, 0xDFFF}}, {0x00030000, {0xD880, 0xDC00}}, {0x00030001, {0xD880, 0xDC01}}, {0x00030002, {0xD880, 0xDC02}}, {0x00030004, {0xD880, 0xDC04}}, {0x00030008, {0xD880, 0xDC08}}, {0x00030010, {0xD880, 0xDC10}}, {0x00030020, {0xD880, 0xDC20}}, {0x00030040, {0xD880, 0xDC40}}, {0x00030080, {0xD880, 0xDC80}}, {0x00030100, {0xD880, 0xDD00}}, {0x00030200, {0xD880, 0xDE00}}, {0x00030400, {0xD881, 0xDC00}}, {0x00030800, {0xD882, 0xDC00}}, {0x00031000, {0xD884, 0xDC00}}, {0x00032000, {0xD888, 0xDC00}}, {0x00034000, {0xD890, 0xDC00}}, {0x00038000, {0xD8A0, 0xDC00}}, {0x0003FFFF, {0xD8BF, 0xDFFF}}, {0x00040000, {0xD8C0, 0xDC00}}, {0x00040001, {0xD8C0, 0xDC01}}, {0x00040002, {0xD8C0, 0xDC02}}, {0x00040004, {0xD8C0, 0xDC04}}, {0x00040008, {0xD8C0, 0xDC08}}, {0x00040010, {0xD8C0, 0xDC10}}, {0x00040020, {0xD8C0, 0xDC20}}, {0x00040040, {0xD8C0, 0xDC40}}, {0x00040080, {0xD8C0, 0xDC80}}, {0x00040100, {0xD8C0, 0xDD00}}, {0x00040200, {0xD8C0, 0xDE00}}, {0x00040400, {0xD8C1, 0xDC00}}, {0x00040800, {0xD8C2, 0xDC00}}, {0x00041000, {0xD8C4, 0xDC00}}, {0x00042000, {0xD8C8, 0xDC00}}, {0x00044000, {0xD8D0, 0xDC00}}, {0x00048000, {0xD8E0, 0xDC00}}, {0x0004FFFF, {0xD8FF, 0xDFFF}}, {0x00050000, {0xD900, 0xDC00}}, {0x00050001, {0xD900, 0xDC01}}, {0x00050002, {0xD900, 0xDC02}}, {0x00050004, {0xD900, 0xDC04}}, {0x00050008, {0xD900, 0xDC08}}, {0x00050010, {0xD900, 0xDC10}}, {0x00050020, {0xD900, 0xDC20}}, {0x00050040, {0xD900, 0xDC40}}, {0x00050080, {0xD900, 0xDC80}}, {0x00050100, {0xD900, 0xDD00}}, {0x00050200, {0xD900, 0xDE00}}, {0x00050400, {0xD901, 0xDC00}}, {0x00050800, {0xD902, 0xDC00}}, {0x00051000, {0xD904, 0xDC00}}, {0x00052000, {0xD908, 0xDC00}}, {0x00054000, {0xD910, 0xDC00}}, {0x00058000, {0xD920, 0xDC00}}, {0x00060000, {0xD940, 0xDC00}}, {0x00070000, {0xD980, 0xDC00}}, {0x0007FFFF, {0xD9BF, 0xDFFF}}, {0x00080000, {0xD9C0, 0xDC00}}, {0x00080001, {0xD9C0, 0xDC01}}, {0x00080002, {0xD9C0, 0xDC02}}, {0x00080004, {0xD9C0, 0xDC04}}, {0x00080008, {0xD9C0, 0xDC08}}, {0x00080010, {0xD9C0, 0xDC10}}, {0x00080020, {0xD9C0, 0xDC20}}, {0x00080040, {0xD9C0, 0xDC40}}, {0x00080080, {0xD9C0, 0xDC80}}, {0x00080100, {0xD9C0, 0xDD00}}, {0x00080200, {0xD9C0, 0xDE00}}, {0x00080400, {0xD9C1, 0xDC00}}, {0x00080800, {0xD9C2, 0xDC00}}, {0x00081000, {0xD9C4, 0xDC00}}, {0x00082000, {0xD9C8, 0xDC00}}, {0x00084000, {0xD9D0, 0xDC00}}, {0x00088000, {0xD9E0, 0xDC00}}, {0x0008FFFF, {0xD9FF, 0xDFFF}}, {0x00090000, {0xDA00, 0xDC00}}, {0x00090001, {0xDA00, 0xDC01}}, {0x00090002, {0xDA00, 0xDC02}}, {0x00090004, {0xDA00, 0xDC04}}, {0x00090008, {0xDA00, 0xDC08}}, {0x00090010, {0xDA00, 0xDC10}}, {0x00090020, {0xDA00, 0xDC20}}, {0x00090040, {0xDA00, 0xDC40}}, {0x00090080, {0xDA00, 0xDC80}}, {0x00090100, {0xDA00, 0xDD00}}, {0x00090200, {0xDA00, 0xDE00}}, {0x00090400, {0xDA01, 0xDC00}}, {0x00090800, {0xDA02, 0xDC00}}, {0x00091000, {0xDA04, 0xDC00}}, {0x00092000, {0xDA08, 0xDC00}}, {0x00094000, {0xDA10, 0xDC00}}, {0x00098000, {0xDA20, 0xDC00}}, {0x000A0000, {0xDA40, 0xDC00}}, {0x000B0000, {0xDA80, 0xDC00}}, {0x000C0000, {0xDAC0, 0xDC00}}, {0x000D0000, {0xDB00, 0xDC00}}, {0x000FFFFF, {0xDBBF, 0xDFFF}}, {0x0010FFFF, {0xDBFF, 0xDFFF}} }; // Invalid UTF-8 sequences const char *const kUtf8BadCases[] = { "\xC0\x80", "\xC1\xBF", "\xE0\x80\x80", "\xE0\x9F\xBF", "\xF0\x80\x80\x80", "\xF0\x8F\xBF\xBF", "\xF4\x90\x80\x80", "\xF7\xBF\xBF\xBF", "\xF8\x80\x80\x80\x80", "\xF8\x88\x80\x80\x80", "\xF8\x92\x80\x80\x80", "\xF8\x9F\xBF\xBF\xBF", "\xF8\xA0\x80\x80\x80", "\xF8\xA8\x80\x80\x80", "\xF8\xB0\x80\x80\x80", "\xF8\xBF\xBF\xBF\xBF", "\xF9\x80\x80\x80\x88", "\xF9\x84\x80\x80\x80", "\xF9\xBF\xBF\xBF\xBF", "\xFA\x80\x80\x80\x80", "\xFA\x90\x80\x80\x80", "\xFB\xBF\xBF\xBF\xBF", "\xFC\x84\x80\x80\x80\x81", "\xFC\x85\x80\x80\x80\x80", "\xFC\x86\x80\x80\x80\x80", "\xFC\x87\xBF\xBF\xBF\xBF", "\xFC\x88\xA0\x80\x80\x80", "\xFC\x89\x80\x80\x80\x80", "\xFC\x8A\x80\x80\x80\x80", "\xFC\x90\x80\x80\x80\x82", "\xFD\x80\x80\x80\x80\x80", "\xFD\xBF\xBF\xBF\xBF\xBF", "\x80", "\xC3", "\xC3\xC3\x80", "\xED\xA0\x80", "\xED\xBF\x80", "\xED\xBF\xBF", "\xED\xA0\x80\xE0\xBF\xBF", }; // Invalid UTF-16 sequences (0-terminated) const Utf16BadCase kUtf16BadCases[] = { // Leading surrogate not followed by trailing surrogate: {{0xD800, 0, 0}}, {{0xD800, 0x41, 0}}, {{0xD800, 0xfe, 0}}, {{0xD800, 0x3bb, 0}}, {{0xD800, 0xD800, 0}}, {{0xD800, 0xFEFF, 0}}, {{0xD800, 0xFFFD, 0}}, // Trailing surrogate, not preceded by a leading one. {{0xDC00, 0, 0}}, {{0xDE6D, 0xD834, 0}}, }; // Parameterized test instantiations: INSTANTIATE_TEST_CASE_P(Ucs4TestCases, Ucs4Test, ::testing::ValuesIn(kUcs4Cases)); INSTANTIATE_TEST_CASE_P(Iso88591TestCases, Ucs2Test, ::testing::ValuesIn(kIso88591Cases)); INSTANTIATE_TEST_CASE_P(Ucs2TestCases, Ucs2Test, ::testing::ValuesIn(kUcs2Cases)); INSTANTIATE_TEST_CASE_P(Utf16TestCases, Utf16Test, ::testing::ValuesIn(kUtf16Cases)); INSTANTIATE_TEST_CASE_P(BadUtf8TestCases, BadUtf8Test, ::testing::ValuesIn(kUtf8BadCases)); INSTANTIATE_TEST_CASE_P(BadUtf16TestCases, BadUtf16Test, ::testing::ValuesIn(kUtf16BadCases)); INSTANTIATE_TEST_CASE_P(Iso88591TestCases, Iso88591Test, ::testing::ValuesIn(kIso88591Cases)); ; } // namespace nss_test
Yukarumya/Yukarum-Redfoxes
security/nss/gtests/util_gtest/util_utf8_unittest.cc
C++
mpl-2.0
39,251
# encoding: utf-8 #-- # Copyright (C) 2012-2013 Gitorious AS # Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #++ class GroupsController < ApplicationController before_filter :login_required, :except => [:index, :show] before_filter :find_group_and_ensure_group_adminship, :only => [:edit, :update, :avatar] before_filter :check_if_only_site_admins_can_create, :only => [:new, :create] renders_in_global_context def index begin groups, total_pages, page = paginated_groups rescue RangeError flash[:error] = "Page #{params[:page] || 1} does not exist" redirect_to(groups_path, :status => 307) and return end render("index", :locals => { :groups => groups, :page => page, :total_pages => total_pages }) end def show group = Team.find_by_name!(params[:id]) events = paginate(:action => "show", :id => params[:id]) do filter_paginated(params[:page], 30) do |page| Team.events(group, page) end end return if params.key?(:page) && events.length == 0 render("show", :locals => { :group => group, :mainlines => filter(group.repositories.mainlines), :clones => filter(group.repositories.clones), :projects => filter(group.projects), :memberships => Team.memberships(group), :events => events }) end def new render("new", :locals => { :group => Team.new_group }) end def edit render("edit", :locals => { :group => @group }) end def update Team.update_group(@group, params) flash[:success] = 'Team was updated' redirect_to(group_path(@group)) rescue ActiveRecord::RecordInvalid render(:action => "edit", :locals => { :group => @group }) end def create group = Team.create_group(params, current_user) group.save! flash[:success] = I18n.t("groups_controller.group_created") redirect_to group_path(group) rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotFound render("new", :locals => { :group => group }) end def destroy begin Team.destroy_group(params[:id], current_user) flash[:success] = "The team was deleted" redirect_to(groups_path) rescue Team::DestroyGroupError => e flash[:error] = e.message redirect_to(group_path(params[:id])) end end # DELETE avatar def avatar Team.delete_avatar(@group) flash[:success] = "The team image was deleted" redirect_to(group_path(@group)) end protected def find_group_and_ensure_group_adminship @group = Team.find_by_name!(params[:id]) unless admin?(current_user, @group) access_denied and return end end def check_if_only_site_admins_can_create if Gitorious.restrict_team_creation_to_site_admins? unless site_admin?(current_user) flash[:error] = "Only site administrators may create teams" redirect_to(:action => "index") return false end end end def paginated_groups page = (params[:page] || 1).to_i groups, pages = JustPaginate.paginate(page, 50, Team.count) do |range| Team.offset(range.first).limit(range.count).order_by_name end [groups, pages, page] end end
SamuelMoraesF/Gitorious
app/controllers/groups_controller.rb
Ruby
agpl-3.0
3,916
default[:hannibal][:hbase_version] = '1.1.3' default[:hannibal][:checksum]["1.1.3"] = '1e4f4030374a34d9f92dc9605505d421615ab12a9e02a10ed690576ab644f705' default[:hannibal][:download_url] = 'https://github.com/amithkanand/hannibal/releases/download/v.0.12.0-apha'
http-418/chef-bach
cookbooks/bach_repository/attributes/hannibal.rb
Ruby
apache-2.0
263
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2018 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.imagelocationscanner; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.ExtensionAdaptor; public class ExtensionImageLocationScanner extends ExtensionAdaptor { @Override public String getName() { return "ExtensionImageLocationScanner"; } @Override public String getUIName() { return Constant.messages.getString("imagelocationscanner.ui.name"); } @Override public String getDescription() { return Constant.messages.getString("imagelocationscanner.addon.desc"); } @Override public boolean canUnload() { return true; } }
kingthorin/zap-extensions
addOns/imagelocationscanner/src/main/java/org/zaproxy/zap/extension/imagelocationscanner/ExtensionImageLocationScanner.java
Java
apache-2.0
1,403
/** * 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. */ package camelinaction; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; /** * An example how to use Routing Slip EIP. * <p/> * This example uses a bean to compute the initial routing slip * which is used directly on the RoutingSlip EIP * * @version $Revision$ */ public class RoutingSlipTest extends CamelTestSupport { @Test public void testRoutingSlip() throws Exception { // setup expectations that only A and C will receive the message getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:b").expectedMessageCount(0); getMockEndpoint("mock:c").expectedMessageCount(1); // send the incoming message template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testRoutingSlipCool() throws Exception { // setup expectations that all will receive the message getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:b").expectedMessageCount(1); getMockEndpoint("mock:c").expectedMessageCount(1); template.sendBody("direct:start", "We are Cool"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") // compute the routing slip at runtime using a bean // use the routing slip EIP .routingSlip().method(ComputeSlip.class); } }; } }
johnnyrich0617/Camel-Tut
chapter8/routingslip/src/test/java/camelinaction/RoutingSlipTest.java
Java
apache-2.0
2,525
package org.apache.hawq.pxf.plugins.hbase; /* * 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. */ import org.apache.hawq.pxf.api.FilterParser; import org.apache.hawq.pxf.api.io.DataType; import org.apache.hawq.pxf.plugins.hbase.utilities.HBaseColumnDescriptor; import org.apache.hawq.pxf.plugins.hbase.utilities.HBaseDoubleComparator; import org.apache.hawq.pxf.plugins.hbase.utilities.HBaseFloatComparator; import org.apache.hawq.pxf.plugins.hbase.utilities.HBaseIntegerComparator; import org.apache.hawq.pxf.plugins.hbase.utilities.HBaseTupleDescription; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.filter.*; import org.apache.hadoop.hbase.util.Bytes; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.hawq.pxf.api.io.DataType.TEXT; /** * This is the implementation of {@code FilterParser.FilterBuilder} for HBase. * <p> * The class uses the filter parser code to build a filter object, * either simple (single {@link Filter} class) or a compound ({@link FilterList}) * for {@link HBaseAccessor} to use for its scan. * <p> * This is done before the scan starts. It is not a scan time operation. * <p> * HBase row key column is a special case. * If the user defined row key column as TEXT and used {@code <,>,<=,>=,=} operators * the startkey ({@code >/>=}) and the endkey ({@code </<=}) are stored in addition to * the created filter. * This is an addition on top of regular filters and does not replace * any logic in HBase filter objects. */ public class HBaseFilterBuilder implements FilterParser.FilterBuilder { private Map<FilterParser.Operation, CompareFilter.CompareOp> operatorsMap; private Map<FilterParser.LogicalOperation, FilterList.Operator> logicalOperatorsMap; private byte[] startKey; private byte[] endKey; private HBaseTupleDescription tupleDescription; private static final String NOT_OP = "l2"; public HBaseFilterBuilder(HBaseTupleDescription tupleDescription) { initOperatorsMap(); initLogicalOperatorsMap(); startKey = HConstants.EMPTY_START_ROW; endKey = HConstants.EMPTY_END_ROW; this.tupleDescription = tupleDescription; } private boolean filterNotOpPresent(String filterString) { if (filterString.contains(NOT_OP)) { String regex = ".*[o\\d|l\\d]l2.*"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(filterString); return m.matches(); } else { return false; } } /** * Translates a filterString into a HBase {@link Filter} object. * * @param filterString filter string * @return filter object * @throws Exception if parsing failed */ public Filter getFilterObject(String filterString) throws Exception { if (filterString == null) return null; // First check for NOT, HBase does not support this if (filterNotOpPresent(filterString)) return null; FilterParser parser = new FilterParser(this); Object result = parser.parse(filterString.getBytes(FilterParser.DEFAULT_CHARSET)); if (!(result instanceof Filter)) { throw new Exception("String " + filterString + " couldn't be resolved to any supported filter"); } return (Filter) result; } /** * Returns the startKey for scanning the HBase table. * If the user specified a {@code > / >=} operation * on a textual row key column, this value will be returned. * Otherwise, the start of table. * * @return start key for scanning HBase table */ public byte[] startKey() { return startKey; } /** * Returns the endKey for scanning the HBase table. * If the user specified a {@code < / <=} operation * on a textual row key column, this value will be returned. * Otherwise, the end of table. * * @return end key for scanning HBase table */ public byte[] endKey() { return endKey; } /** * Builds a filter from the input operands and operation. * Two kinds of operations are handled: * <ol> * <li>Simple operation between {@code FilterParser.Constant} and {@code FilterParser.ColumnIndex}. * Supported operations are {@code <, >, <=, <=, >=, =, !=}. </li> * <li>Compound operations between {@link Filter} objects. * The only supported operation is {@code AND}. </li> * </ol> * <p> * This function is called by {@link FilterParser}, * each time the parser comes across an operator. */ @Override public Object build(FilterParser.Operation opId, Object leftOperand, Object rightOperand) throws Exception { // Assume column is on the left return handleSimpleOperations(opId, (FilterParser.ColumnIndex) leftOperand, (FilterParser.Constant) rightOperand); } @Override public Object build(FilterParser.Operation operation, Object operand) throws Exception { return handleSimpleOperations(operation, (FilterParser.ColumnIndex) operand); } @Override public Object build(FilterParser.LogicalOperation opId, Object leftOperand, Object rightOperand) { return handleCompoundOperations(opId, (Filter) leftOperand, (Filter) rightOperand); } @Override public Object build(FilterParser.LogicalOperation opId, Object leftOperand) { return null; } /** * Initializes the {@link #operatorsMap} with appropriate values. */ private void initOperatorsMap() { operatorsMap = new EnumMap<FilterParser.Operation, CompareFilter.CompareOp>(FilterParser.Operation.class); operatorsMap.put(FilterParser.Operation.HDOP_LT, CompareFilter.CompareOp.LESS); // "<" operatorsMap.put(FilterParser.Operation.HDOP_GT, CompareFilter.CompareOp.GREATER); // ">" operatorsMap.put(FilterParser.Operation.HDOP_LE, CompareFilter.CompareOp.LESS_OR_EQUAL); // "<=" operatorsMap.put(FilterParser.Operation.HDOP_GE, CompareFilter.CompareOp.GREATER_OR_EQUAL); // ">=" operatorsMap.put(FilterParser.Operation.HDOP_EQ, CompareFilter.CompareOp.EQUAL); // "=" operatorsMap.put(FilterParser.Operation.HDOP_NE, CompareFilter.CompareOp.NOT_EQUAL); // "!=" } private void initLogicalOperatorsMap() { logicalOperatorsMap = new EnumMap<>(FilterParser.LogicalOperation.class); logicalOperatorsMap.put(FilterParser.LogicalOperation.HDOP_AND, FilterList.Operator.MUST_PASS_ALL); logicalOperatorsMap.put(FilterParser.LogicalOperation.HDOP_OR, FilterList.Operator.MUST_PASS_ONE); } private Object handleSimpleOperations(FilterParser.Operation opId, FilterParser.ColumnIndex column) throws Exception { HBaseColumnDescriptor hbaseColumn = tupleDescription.getColumn(column.index()); CompareFilter.CompareOp compareOperation; ByteArrayComparable comparator; switch (opId) { case HDOP_IS_NULL: compareOperation = CompareFilter.CompareOp.EQUAL; comparator = new NullComparator(); break; case HDOP_IS_NOT_NULL: compareOperation = CompareFilter.CompareOp.NOT_EQUAL; comparator = new NullComparator(); break; default: throw new Exception("unsupported unary operation for filtering " + opId); } return new SingleColumnValueFilter(hbaseColumn.columnFamilyBytes(), hbaseColumn.qualifierBytes(), compareOperation, comparator); } /** * Handles simple column-operator-constant expressions. * Creates a special filter in the case the column is the row key column. */ private Filter handleSimpleOperations(FilterParser.Operation opId, FilterParser.ColumnIndex column, FilterParser.Constant constant) throws Exception { HBaseColumnDescriptor hbaseColumn = tupleDescription.getColumn(column.index()); ByteArrayComparable comparator = getComparator(hbaseColumn.columnTypeCode(), constant.constant()); if(operatorsMap.get(opId) == null){ //HBase does not support HDOP_LIKE, use 'NOT NULL' comparator return new SingleColumnValueFilter(hbaseColumn.columnFamilyBytes(), hbaseColumn.qualifierBytes(), CompareFilter.CompareOp.NOT_EQUAL, new NullComparator()); } /** * If row key is of type TEXT, allow filter in start/stop row key API in * HBaseAccessor/Scan object. */ if (textualRowKey(hbaseColumn)) { storeStartEndKeys(opId, constant.constant()); } if (hbaseColumn.isKeyColumn()) { return new RowFilter(operatorsMap.get(opId), comparator); } return new SingleColumnValueFilter(hbaseColumn.columnFamilyBytes(), hbaseColumn.qualifierBytes(), operatorsMap.get(opId), comparator); } /** * Resolves the column's type to a comparator class to be used. * Currently, supported types are TEXT and INTEGER types. */ private ByteArrayComparable getComparator(int type, Object data) throws Exception { ByteArrayComparable result; switch (DataType.get(type)) { case TEXT: result = new BinaryComparator(Bytes.toBytes((String) data)); break; case SMALLINT: case INTEGER: result = new HBaseIntegerComparator(((Integer) data).longValue()); break; case BIGINT: if (data instanceof Long) { result = new HBaseIntegerComparator((Long) data); } else if (data instanceof Integer) { result = new HBaseIntegerComparator(((Integer) data).longValue()); } else { result = null; } break; case FLOAT8: result = new HBaseDoubleComparator((double) data); break; case REAL: if (data instanceof Double) { result = new HBaseDoubleComparator((double) data); } else if (data instanceof Float) { result = new HBaseFloatComparator((float) data); } else { result = null; } break; default: throw new Exception("unsupported column type for filtering " + type); } return result; } /** * Handles operation between already calculated expressions. * Currently only {@code AND}, in the future {@code OR} can be added. * <p> * Four cases here: * <ol> * <li>Both are simple filters.</li> * <li>Left is a FilterList and right is a filter.</li> * <li>Left is a filter and right is a FilterList.</li> * <li>Both are FilterLists.</li> * </ol> * <p> * Currently, 1, 2 can occur, since no parenthesis are used. */ private Filter handleCompoundOperations(FilterParser.LogicalOperation opId, Filter left, Filter right) { return new FilterList(logicalOperatorsMap.get(opId), new Filter[] {left, right}); } /** * Returns true if column is of type TEXT and is a row key column. */ private boolean textualRowKey(HBaseColumnDescriptor column) { return column.isKeyColumn() && column.columnTypeCode() == TEXT.getOID(); } /** * Sets startKey/endKey and their inclusiveness * according to the operation op. * <p> * TODO allow only one assignment to start/end key. * Currently, multiple calls to this function might change * previous assignments. */ private void storeStartEndKeys(FilterParser.Operation op, Object data) { String key = (String) data; // Adding a zero byte to endkey, makes it inclusive // Adding a zero byte to startkey, makes it exclusive byte[] zeroByte = new byte[1]; zeroByte[0] = 0; switch (op) { case HDOP_LT: endKey = Bytes.toBytes(key); break; case HDOP_GT: startKey = Bytes.add(Bytes.toBytes(key), zeroByte); break; case HDOP_LE: endKey = Bytes.add(Bytes.toBytes(key), zeroByte); break; case HDOP_GE: startKey = Bytes.toBytes(key); break; case HDOP_EQ: startKey = Bytes.toBytes(key); endKey = Bytes.add(Bytes.toBytes(key), zeroByte); break; } } }
lavjain/incubator-hawq
pxf/pxf-hbase/src/main/java/org/apache/hawq/pxf/plugins/hbase/HBaseFilterBuilder.java
Java
apache-2.0
13,894
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.health; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Factory to create a {@link CompositeReactiveHealthIndicator}. * * @author Stephane Nicoll * @since 2.0.0 */ public class CompositeReactiveHealthIndicatorFactory { private final Function<String, String> healthIndicatorNameFactory; public CompositeReactiveHealthIndicatorFactory( Function<String, String> healthIndicatorNameFactory) { this.healthIndicatorNameFactory = healthIndicatorNameFactory; } public CompositeReactiveHealthIndicatorFactory() { this(new HealthIndicatorNameFactory()); } /** * Create a {@link CompositeReactiveHealthIndicator} based on the specified health * indicators. Each {@link HealthIndicator} are wrapped to a * {@link HealthIndicatorReactiveAdapter}. If two instances share the same name, the * reactive variant takes precedence. * @param healthAggregator the {@link HealthAggregator} * @param reactiveHealthIndicators the {@link ReactiveHealthIndicator} instances * mapped by name * @param healthIndicators the {@link HealthIndicator} instances mapped by name if * any. * @return a {@link ReactiveHealthIndicator} that delegates to the specified * {@code reactiveHealthIndicators}. */ public CompositeReactiveHealthIndicator createReactiveHealthIndicator( HealthAggregator healthAggregator, Map<String, ReactiveHealthIndicator> reactiveHealthIndicators, Map<String, HealthIndicator> healthIndicators) { Assert.notNull(healthAggregator, "HealthAggregator must not be null"); Assert.notNull(reactiveHealthIndicators, "ReactiveHealthIndicators must not be null"); CompositeReactiveHealthIndicator healthIndicator = new CompositeReactiveHealthIndicator( healthAggregator); merge(reactiveHealthIndicators, healthIndicators) .forEach((beanName, indicator) -> { String name = this.healthIndicatorNameFactory.apply(beanName); healthIndicator.addHealthIndicator(name, indicator); }); return healthIndicator; } private Map<String, ReactiveHealthIndicator> merge( Map<String, ReactiveHealthIndicator> reactiveHealthIndicators, Map<String, HealthIndicator> healthIndicators) { if (ObjectUtils.isEmpty(healthIndicators)) { return reactiveHealthIndicators; } Map<String, ReactiveHealthIndicator> allIndicators = new LinkedHashMap<>( reactiveHealthIndicators); healthIndicators.forEach((beanName, indicator) -> { String name = this.healthIndicatorNameFactory.apply(beanName); allIndicators.computeIfAbsent(name, (n) -> new HealthIndicatorReactiveAdapter(indicator)); }); return allIndicators; } }
vakninr/spring-boot
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/CompositeReactiveHealthIndicatorFactory.java
Java
apache-2.0
3,398
/****************************************** * * * dcm4che: A OpenSource DICOM Toolkit * * * * Distributable under LGPL license. * * See terms of license at gnu.org. * * * ******************************************/ package org.dcm4chex.archive.hl7; /** * @author gunter.zeilinger@tiani.com * @version $Revision: 1357 $ $Date: 2004-12-30 08:55:56 +0800 (周四, 30 12月 2004) $ * @since 27.10.2004 * */ public abstract class HL7Exception extends Exception { public HL7Exception(String message) { super(message); } public HL7Exception(String message, Throwable cause) { super(message, cause); } public abstract String getAcknowledgementCode(); public static class AE extends HL7Exception { public AE(String message) { super(message); } public AE(String message, Throwable cause) { super(message, cause); } public String getAcknowledgementCode() { return "AE"; } } public static class AR extends HL7Exception { public AR(String message) { super(message); } public AR(String message, Throwable cause) { super(message, cause); } public String getAcknowledgementCode() { return "AR"; } } }
medicayun/medicayundicom
dcm4jboss-all/tags/DCM4JBOSS_2_4_2/dcm4jboss-hl7/src/java/org/dcm4chex/archive/hl7/HL7Exception.java
Java
apache-2.0
1,468
//// [crashIntypeCheckInvocationExpression.ts] var nake; function doCompile<P0, P1, P2>(fileset: P0, moduleType: P1) { return undefined; } export var compileServer = task<number, number, any>(<P0, P1, P2>() => { var folder = path.join(), fileset = nake.fileSetSync<number, number, any>(folder) return doCompile<number, number, any>(fileset, moduleType); }); //// [crashIntypeCheckInvocationExpression.js] define(["require", "exports"], function (require, exports) { "use strict"; exports.__esModule = true; exports.compileServer = void 0; var nake; function doCompile(fileset, moduleType) { return undefined; } exports.compileServer = task(function () { var folder = path.join(), fileset = nake.fileSetSync(folder); return doCompile(fileset, moduleType); }); });
Microsoft/TypeScript
tests/baselines/reference/crashIntypeCheckInvocationExpression.js
JavaScript
apache-2.0
858
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.xmladapters; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; /** * A listener which expects a URL as a tag of the view it is associated with. It then opens the URL * in the browser application. */ public class UrlIntentListener implements OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final String url = view.getTag().toString(); final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); final Context context = parent.getContext(); context.startActivity(intent); } }
efortuna/AndroidSDKClone
sdk/samples/android-20/legacy/XmlAdapters/src/com/example/android/xmladapters/UrlIntentListener.java
Java
apache-2.0
1,446
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.autoscaling.storage; import org.elasticsearch.cluster.ClusterInfo; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.DiskUsage; import org.elasticsearch.cluster.metadata.DataStream; import org.elasticsearch.cluster.metadata.DataStreamMetadata; import org.elasticsearch.cluster.metadata.IndexAbstraction; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeFilters; import org.elasticsearch.cluster.node.DiscoveryNodeRole; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNodes; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.allocation.DataTier; import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders; import org.elasticsearch.cluster.routing.allocation.decider.Decision; import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider; import org.elasticsearch.cluster.routing.allocation.decider.FilterAllocationDecider; import org.elasticsearch.cluster.routing.allocation.decider.SameShardAllocationDecider; import org.elasticsearch.common.Strings; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.core.Tuple; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.snapshots.SnapshotShardSizeInfo; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingCapacity; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingDeciderContext; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingDeciderResult; import org.elasticsearch.xpack.autoscaling.capacity.AutoscalingDeciderService; import org.elasticsearch.xpack.cluster.routing.allocation.DataTierAllocationDecider; import java.io.IOException; import java.math.BigInteger; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class ReactiveStorageDeciderService implements AutoscalingDeciderService { public static final String NAME = "reactive_storage"; private final DiskThresholdSettings diskThresholdSettings; private final DataTierAllocationDecider dataTierAllocationDecider; private final AllocationDeciders allocationDeciders; public ReactiveStorageDeciderService(Settings settings, ClusterSettings clusterSettings, AllocationDeciders allocationDeciders) { this.diskThresholdSettings = new DiskThresholdSettings(settings, clusterSettings); this.dataTierAllocationDecider = new DataTierAllocationDecider(); this.allocationDeciders = allocationDeciders; } @Override public String name() { return NAME; } @Override public List<Setting<?>> deciderSettings() { return List.of(); } @Override public List<DiscoveryNodeRole> roles() { return List.of( DiscoveryNodeRole.DATA_ROLE, DiscoveryNodeRole.DATA_CONTENT_NODE_ROLE, DiscoveryNodeRole.DATA_HOT_NODE_ROLE, DiscoveryNodeRole.DATA_WARM_NODE_ROLE, DiscoveryNodeRole.DATA_COLD_NODE_ROLE ); } @Override public AutoscalingDeciderResult scale(Settings configuration, AutoscalingDeciderContext context) { AutoscalingCapacity autoscalingCapacity = context.currentCapacity(); if (autoscalingCapacity == null || autoscalingCapacity.total().storage() == null) { return new AutoscalingDeciderResult(null, new ReactiveReason("current capacity not available", -1, -1)); } AllocationState allocationState = new AllocationState( context, diskThresholdSettings, allocationDeciders, dataTierAllocationDecider ); long unassignedBytes = allocationState.storagePreventsAllocation(); long assignedBytes = allocationState.storagePreventsRemainOrMove(); long maxShardSize = allocationState.maxShardSize(); assert assignedBytes >= 0; assert unassignedBytes >= 0; assert maxShardSize >= 0; String message = message(unassignedBytes, assignedBytes); AutoscalingCapacity requiredCapacity = AutoscalingCapacity.builder() .total(autoscalingCapacity.total().storage().getBytes() + unassignedBytes + assignedBytes, null) .node(maxShardSize, null) .build(); return new AutoscalingDeciderResult(requiredCapacity, new ReactiveReason(message, unassignedBytes, assignedBytes)); } static String message(long unassignedBytes, long assignedBytes) { return unassignedBytes > 0 || assignedBytes > 0 ? "not enough storage available, needs " + new ByteSizeValue(unassignedBytes + assignedBytes) : "storage ok"; } static boolean isDiskOnlyNoDecision(Decision decision) { return singleNoDecision(decision, single -> true).map(DiskThresholdDecider.NAME::equals).orElse(false); } static boolean isFilterTierOnlyDecision(Decision decision, IndexMetadata indexMetadata) { // only primary shards are handled here, allowing us to disregard same shard allocation decider. return singleNoDecision(decision, single -> SameShardAllocationDecider.NAME.equals(single.label()) == false).filter( FilterAllocationDecider.NAME::equals ).map(d -> filterLooksLikeTier(indexMetadata)).orElse(false); } static boolean filterLooksLikeTier(IndexMetadata indexMetadata) { return isOnlyAttributeValueFilter(indexMetadata.requireFilters()) && isOnlyAttributeValueFilter(indexMetadata.includeFilters()) && isOnlyAttributeValueFilter(indexMetadata.excludeFilters()); } private static boolean isOnlyAttributeValueFilter(DiscoveryNodeFilters filters) { if (filters == null) { return true; } else { return DiscoveryNodeFilters.trimTier(filters).isOnlyAttributeValueFilter(); } } static Optional<String> singleNoDecision(Decision decision, Predicate<Decision> predicate) { List<Decision> nos = decision.getDecisions() .stream() .filter(single -> single.type() == Decision.Type.NO) .filter(predicate) .collect(Collectors.toList()); if (nos.size() == 1) { return Optional.ofNullable(nos.get(0).label()); } else { return Optional.empty(); } } // todo: move this to top level class. public static class AllocationState { private final ClusterState state; private final AllocationDeciders allocationDeciders; private final DataTierAllocationDecider dataTierAllocationDecider; private final DiskThresholdSettings diskThresholdSettings; private final ClusterInfo info; private final SnapshotShardSizeInfo shardSizeInfo; private final Predicate<DiscoveryNode> nodeTierPredicate; private final Set<DiscoveryNode> nodes; private final Set<String> nodeIds; private final Set<DiscoveryNodeRole> roles; AllocationState( AutoscalingDeciderContext context, DiskThresholdSettings diskThresholdSettings, AllocationDeciders allocationDeciders, DataTierAllocationDecider dataTierAllocationDecider ) { this( context.state(), allocationDeciders, dataTierAllocationDecider, diskThresholdSettings, context.info(), context.snapshotShardSizeInfo(), context.nodes(), context.roles() ); } AllocationState( ClusterState state, AllocationDeciders allocationDeciders, DataTierAllocationDecider dataTierAllocationDecider, DiskThresholdSettings diskThresholdSettings, ClusterInfo info, SnapshotShardSizeInfo shardSizeInfo, Set<DiscoveryNode> nodes, Set<DiscoveryNodeRole> roles ) { this.state = state; this.allocationDeciders = allocationDeciders; this.dataTierAllocationDecider = dataTierAllocationDecider; this.diskThresholdSettings = diskThresholdSettings; this.info = info; this.shardSizeInfo = shardSizeInfo; this.nodes = nodes; this.nodeIds = nodes.stream().map(DiscoveryNode::getId).collect(Collectors.toSet()); this.nodeTierPredicate = nodes::contains; this.roles = roles; } public long storagePreventsAllocation() { RoutingAllocation allocation = new RoutingAllocation( allocationDeciders, state.getRoutingNodes(), state, info, shardSizeInfo, System.nanoTime() ); return StreamSupport.stream(state.getRoutingNodes().unassigned().spliterator(), false) .filter(shard -> canAllocate(shard, allocation) == false) .filter(shard -> cannotAllocateDueToStorage(shard, allocation)) .mapToLong(this::sizeOf) .sum(); } public long storagePreventsRemainOrMove() { RoutingAllocation allocation = new RoutingAllocation( allocationDeciders, state.getRoutingNodes(), state, info, shardSizeInfo, System.nanoTime() ); List<ShardRouting> candidates = new LinkedList<>(); for (RoutingNode routingNode : state.getRoutingNodes()) { for (ShardRouting shard : routingNode) { if (shard.started() && canRemainOnlyHighestTierPreference(shard, allocation) == false && canAllocate(shard, allocation) == false) { candidates.add(shard); } } } // track these to ensure we do not double account if they both cannot remain and allocated due to storage. Set<ShardRouting> unmovableShards = candidates.stream() .filter(s -> allocatedToTier(s, allocation)) .filter(s -> cannotRemainDueToStorage(s, allocation)) .collect(Collectors.toSet()); long unmovableBytes = unmovableShards.stream() .collect(Collectors.groupingBy(ShardRouting::currentNodeId)) .entrySet() .stream() .mapToLong(e -> unmovableSize(e.getKey(), e.getValue())) .sum(); long unallocatableBytes = candidates.stream() .filter(Predicate.not(unmovableShards::contains)) .filter(s1 -> cannotAllocateDueToStorage(s1, allocation)) .mapToLong(this::sizeOf) .sum(); return unallocatableBytes + unmovableBytes; } /** * Check if shard can remain where it is, with the additional check that the DataTierAllocationDecider did not allow it to stay * on a node in a lower preference tier. */ public boolean canRemainOnlyHighestTierPreference(ShardRouting shard, RoutingAllocation allocation) { boolean result = allocationDeciders.canRemain( shard, allocation.routingNodes().node(shard.currentNodeId()), allocation ) != Decision.NO; if (result && nodes.isEmpty() && Strings.hasText(DataTier.TIER_PREFERENCE_SETTING.get(indexMetadata(shard, allocation).getSettings()))) { // The data tier decider allows a shard to remain on a lower preference tier when no nodes exists on higher preference // tiers. // Here we ensure that if our policy governs the highest preference tier, we assume the shard needs to move to that tier // once a node is started for it. // In the case of overlapping policies, this is consistent with double accounting of unassigned. return isAssignedToTier(shard, allocation) == false; } return result; } private boolean allocatedToTier(ShardRouting s, RoutingAllocation allocation) { return nodeTierPredicate.test(allocation.routingNodes().node(s.currentNodeId()).node()); } /** * Check that disk decider is only decider for a node preventing allocation of the shard. * @return true if and only if a node exists in the tier where only disk decider prevents allocation */ private boolean cannotAllocateDueToStorage(ShardRouting shard, RoutingAllocation allocation) { if (nodeIds.isEmpty() && needsThisTier(shard, allocation)) { return true; } assert allocation.debugDecision() == false; // enable debug decisions to see all decisions and preserve the allocation decision label allocation.debugDecision(true); try { return nodesInTier(allocation.routingNodes()).map(node -> allocationDeciders.canAllocate(shard, node, allocation)) .anyMatch(ReactiveStorageDeciderService::isDiskOnlyNoDecision); } finally { allocation.debugDecision(false); } } /** * Check that the disk decider is only decider that says NO to let shard remain on current node. * @return true if and only if disk decider is only decider that says NO to canRemain. */ private boolean cannotRemainDueToStorage(ShardRouting shard, RoutingAllocation allocation) { assert allocation.debugDecision() == false; // enable debug decisions to see all decisions and preserve the allocation decision label allocation.debugDecision(true); try { return isDiskOnlyNoDecision( allocationDeciders.canRemain(shard, allocation.routingNodes().node(shard.currentNodeId()), allocation) ); } finally { allocation.debugDecision(false); } } private boolean canAllocate(ShardRouting shard, RoutingAllocation allocation) { return nodesInTier(allocation.routingNodes()).anyMatch( node -> allocationDeciders.canAllocate(shard, node, allocation) != Decision.NO ); } boolean needsThisTier(ShardRouting shard, RoutingAllocation allocation) { if (isAssignedToTier(shard, allocation) == false) { return false; } IndexMetadata indexMetadata = indexMetadata(shard, allocation); Set<Decision.Type> decisionTypes = StreamSupport.stream(allocation.routingNodes().spliterator(), false) .map( node -> dataTierAllocationDecider.shouldFilter( indexMetadata, node.node().getRoles(), this::highestPreferenceTier, allocation ) ) .map(Decision::type) .collect(Collectors.toSet()); if (decisionTypes.contains(Decision.Type.NO)) { // we know we have some filter and can respond. Only need this tier if ALL responses where NO. return decisionTypes.size() == 1; } // check for using allocation filters for data tiers. For simplicity, only scale up new tier based on primary shard if (shard.primary() == false) { return false; } assert allocation.debugDecision() == false; // enable debug decisions to see all decisions and preserve the allocation decision label allocation.debugDecision(true); try { // check that it does not belong on any existing node, i.e., there must be only a tier like reason it cannot be allocated return StreamSupport.stream(allocation.routingNodes().spliterator(), false) .anyMatch(node -> isFilterTierOnlyDecision(allocationDeciders.canAllocate(shard, node, allocation), indexMetadata)); } finally { allocation.debugDecision(false); } } private boolean isAssignedToTier(ShardRouting shard, RoutingAllocation allocation) { IndexMetadata indexMetadata = indexMetadata(shard, allocation); return dataTierAllocationDecider.shouldFilter(indexMetadata, roles, this::highestPreferenceTier, allocation) != Decision.NO; } private IndexMetadata indexMetadata(ShardRouting shard, RoutingAllocation allocation) { return allocation.metadata().getIndexSafe(shard.index()); } private Optional<String> highestPreferenceTier(List<String> preferredTiers, DiscoveryNodes unused) { assert preferredTiers.isEmpty() == false; return Optional.of(preferredTiers.get(0)); } public long maxShardSize() { return nodesInTier(state.getRoutingNodes()).flatMap(rn -> StreamSupport.stream(rn.spliterator(), false)) .mapToLong(this::sizeOf) .max() .orElse(0L); } long sizeOf(ShardRouting shard) { long expectedShardSize = getExpectedShardSize(shard); if (expectedShardSize == 0L && shard.primary() == false) { ShardRouting primary = state.getRoutingNodes().activePrimary(shard.shardId()); if (primary != null) { expectedShardSize = getExpectedShardSize(primary); } } assert expectedShardSize >= 0; // todo: we should ideally not have the level of uncertainty we have here. return expectedShardSize == 0L ? ByteSizeUnit.KB.toBytes(1) : expectedShardSize; } private long getExpectedShardSize(ShardRouting shard) { return DiskThresholdDecider.getExpectedShardSize(shard, 0L, info, shardSizeInfo, state.metadata(), state.routingTable()); } long unmovableSize(String nodeId, Collection<ShardRouting> shards) { ClusterInfo clusterInfo = this.info; DiskUsage diskUsage = clusterInfo.getNodeMostAvailableDiskUsages().get(nodeId); if (diskUsage == null) { // do not want to scale up then, since this should only happen when node has just joined (clearly edge case). return 0; } long threshold = Math.max( diskThresholdSettings.getFreeBytesThresholdHigh().getBytes(), thresholdFromPercentage(diskThresholdSettings.getFreeDiskThresholdHigh(), diskUsage) ); long missing = threshold - diskUsage.getFreeBytes(); return Math.max(missing, shards.stream().mapToLong(this::sizeOf).min().orElseThrow()); } private long thresholdFromPercentage(Double percentage, DiskUsage diskUsage) { if (percentage == null) { return 0L; } return (long) Math.ceil(diskUsage.getTotalBytes() * percentage / 100); } Stream<RoutingNode> nodesInTier(RoutingNodes routingNodes) { return nodeIds.stream().map(n -> routingNodes.node(n)); } private static class SingleForecast { private final Map<IndexMetadata, Long> additionalIndices; private final DataStream updatedDataStream; private SingleForecast(Map<IndexMetadata, Long> additionalIndices, DataStream updatedDataStream) { this.additionalIndices = additionalIndices; this.updatedDataStream = updatedDataStream; } public void applyRouting(RoutingTable.Builder routing) { additionalIndices.keySet().forEach(routing::addAsNew); } public void applyMetadata(Metadata.Builder metadataBuilder) { additionalIndices.keySet().forEach(imd -> metadataBuilder.put(imd, false)); metadataBuilder.put(updatedDataStream); } public void applySize(ImmutableOpenMap.Builder<String, Long> builder, RoutingTable updatedRoutingTable) { for (Map.Entry<IndexMetadata, Long> entry : additionalIndices.entrySet()) { List<ShardRouting> shardRoutings = updatedRoutingTable.allShards(entry.getKey().getIndex().getName()); long size = entry.getValue() / shardRoutings.size(); shardRoutings.forEach(s -> builder.put(ClusterInfo.shardIdentifierFromRouting(s), size)); } } } public AllocationState forecast(long forecastWindow, long now) { if (forecastWindow == 0) { return this; } // for now we only look at data-streams. We might want to also detect alias based time-based indices. DataStreamMetadata dataStreamMetadata = state.metadata().custom(DataStreamMetadata.TYPE); if (dataStreamMetadata == null) { return this; } List<SingleForecast> singleForecasts = dataStreamMetadata.dataStreams() .keySet() .stream() .map(state.metadata().getIndicesLookup()::get) .map(IndexAbstraction.DataStream.class::cast) .map(ds -> forecast(state.metadata(), ds, forecastWindow, now)) .filter(Objects::nonNull) .collect(Collectors.toList()); if (singleForecasts.isEmpty()) { return this; } Metadata.Builder metadataBuilder = Metadata.builder(state.metadata()); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(state.routingTable()); ImmutableOpenMap.Builder<String, Long> sizeBuilder = ImmutableOpenMap.builder(); singleForecasts.forEach(p -> p.applyMetadata(metadataBuilder)); singleForecasts.forEach(p -> p.applyRouting(routingTableBuilder)); RoutingTable routingTable = routingTableBuilder.build(); singleForecasts.forEach(p -> p.applySize(sizeBuilder, routingTable)); ClusterState forecastClusterState = ClusterState.builder(state).metadata(metadataBuilder).routingTable(routingTable).build(); ClusterInfo forecastInfo = new ExtendedClusterInfo(sizeBuilder.build(), AllocationState.this.info); return new AllocationState( forecastClusterState, allocationDeciders, dataTierAllocationDecider, diskThresholdSettings, forecastInfo, shardSizeInfo, nodes, roles ); } private SingleForecast forecast(Metadata metadata, IndexAbstraction.DataStream stream, long forecastWindow, long now) { List<Index> indices = stream.getIndices(); if (dataStreamAllocatedToNodes(metadata, indices) == false) return null; long minCreationDate = Long.MAX_VALUE; long totalSize = 0; int count = 0; while (count < indices.size()) { ++count; IndexMetadata indexMetadata = metadata.index(indices.get(indices.size() - count)); long creationDate = indexMetadata.getCreationDate(); if (creationDate < 0) { return null; } minCreationDate = Math.min(minCreationDate, creationDate); totalSize += state.getRoutingTable().allShards(indexMetadata.getIndex().getName()).stream().mapToLong(this::sizeOf).sum(); // we terminate loop after collecting data to ensure we consider at least the forecast window (and likely some more). if (creationDate <= now - forecastWindow) { break; } } if (totalSize == 0) { return null; } // round up long avgSizeCeil = (totalSize - 1) / count + 1; long actualWindow = now - minCreationDate; if (actualWindow == 0) { return null; } // rather than simulate rollover, we copy the index meta data and do minimal adjustments. long scaledTotalSize; int numberNewIndices; if (actualWindow > forecastWindow) { scaledTotalSize = BigInteger.valueOf(totalSize) .multiply(BigInteger.valueOf(forecastWindow)) .divide(BigInteger.valueOf(actualWindow)) .longValueExact(); // round up numberNewIndices = (int) Math.min((scaledTotalSize - 1) / avgSizeCeil + 1, indices.size()); if (scaledTotalSize == 0) { return null; } } else { numberNewIndices = count; scaledTotalSize = totalSize; } IndexMetadata writeIndex = metadata.index(stream.getWriteIndex()); Map<IndexMetadata, Long> newIndices = new HashMap<>(); DataStream dataStream = stream.getDataStream(); for (int i = 0; i < numberNewIndices; ++i) { final String uuid = UUIDs.randomBase64UUID(); final Tuple<String, Long> dummyRolledDatastream = dataStream.nextWriteIndexAndGeneration(state.metadata()); dataStream = dataStream.rollover(new Index(dummyRolledDatastream.v1(), uuid), dummyRolledDatastream.v2()); // this unintentionally copies the in-sync allocation ids too. This has the fortunate effect of these indices // not being regarded new by the disk threshold decider, thereby respecting the low watermark threshold even for primaries. // This is highly desirable so fixing this to clear the in-sync allocation ids will require a more elaborate solution, // ensuring at least that when replicas are involved, we still respect the low watermark. This is therefore left as is // for now with the intention to fix in a follow-up. IndexMetadata newIndex = IndexMetadata.builder(writeIndex) .index(dataStream.getWriteIndex().getName()) .settings(Settings.builder().put(writeIndex.getSettings()).put(IndexMetadata.SETTING_INDEX_UUID, uuid)) .build(); long size = Math.min(avgSizeCeil, scaledTotalSize - (avgSizeCeil * i)); assert size > 0; newIndices.put(newIndex, size); } return new SingleForecast(newIndices, dataStream); } /** * Check that at least one shard is on the set of nodes. If they are all unallocated, we do not want to make any prediction to not * hit the wrong policy. * @param indices the indices of the data stream, in original order from data stream meta. * @return true if the first allocated index is allocated only to the set of nodes. */ private boolean dataStreamAllocatedToNodes(Metadata metadata, List<Index> indices) { for (int i = 0; i < indices.size(); ++i) { IndexMetadata indexMetadata = metadata.index(indices.get(indices.size() - i - 1)); Set<Boolean> inNodes = state.getRoutingTable() .allShards(indexMetadata.getIndex().getName()) .stream() .map(ShardRouting::currentNodeId) .filter(Objects::nonNull) .map(nodeIds::contains) .collect(Collectors.toSet()); if (inNodes.contains(false)) { return false; } if (inNodes.contains(true)) { return true; } } return false; } // for tests ClusterState state() { return state; } ClusterInfo info() { return info; } private static class ExtendedClusterInfo extends ClusterInfo { private final ClusterInfo delegate; private ExtendedClusterInfo(ImmutableOpenMap<String, Long> extraShardSizes, ClusterInfo info) { super( info.getNodeLeastAvailableDiskUsages(), info.getNodeMostAvailableDiskUsages(), extraShardSizes, ImmutableOpenMap.of(), null, null ); this.delegate = info; } @Override public Long getShardSize(ShardRouting shardRouting) { Long shardSize = super.getShardSize(shardRouting); if (shardSize != null) { return shardSize; } else { return delegate.getShardSize(shardRouting); } } @Override public long getShardSize(ShardRouting shardRouting, long defaultValue) { Long shardSize = super.getShardSize(shardRouting); if (shardSize != null) { return shardSize; } else { return delegate.getShardSize(shardRouting, defaultValue); } } @Override public Optional<Long> getShardDataSetSize(ShardId shardId) { return delegate.getShardDataSetSize(shardId); } @Override public String getDataPath(ShardRouting shardRouting) { return delegate.getDataPath(shardRouting); } @Override public ReservedSpace getReservedSpace(String nodeId, String dataPath) { return delegate.getReservedSpace(nodeId, dataPath); } @Override public void writeTo(StreamOutput out) throws IOException { throw new UnsupportedOperationException(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { throw new UnsupportedOperationException(); } } } public static class ReactiveReason implements AutoscalingDeciderResult.Reason { private final String reason; private final long unassigned; private final long assigned; public ReactiveReason(String reason, long unassigned, long assigned) { this.reason = reason; this.unassigned = unassigned; this.assigned = assigned; } public ReactiveReason(StreamInput in) throws IOException { this.reason = in.readString(); this.unassigned = in.readLong(); this.assigned = in.readLong(); } @Override public String summary() { return reason; } public long unassigned() { return unassigned; } public long assigned() { return assigned; } @Override public String getWriteableName() { return ReactiveStorageDeciderService.NAME; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(reason); out.writeLong(unassigned); out.writeLong(assigned); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("reason", reason); builder.field("unassigned", unassigned); builder.field("assigned", assigned); builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReactiveReason that = (ReactiveReason) o; return unassigned == that.unassigned && assigned == that.assigned && reason.equals(that.reason); } @Override public int hashCode() { return Objects.hash(reason, unassigned, assigned); } } }
GlenRSmith/elasticsearch
x-pack/plugin/autoscaling/src/main/java/org/elasticsearch/xpack/autoscaling/storage/ReactiveStorageDeciderService.java
Java
apache-2.0
34,193
/** * Copyright 2010-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; /** * @author Eduardo Macarron * */ public class CartItem implements Serializable { private static final long serialVersionUID = 6620528781626504362L; private Item item; private int quantity; private boolean inStock; private BigDecimal total; public boolean isInStock() { return inStock; } public void setInStock(boolean inStock) { this.inStock = inStock; } public BigDecimal getTotal() { return total; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; calculateTotal(); } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; calculateTotal(); } public void incrementQuantity() { quantity++; calculateTotal(); } private void calculateTotal() { if (item != null && item.getListPrice() != null) { total = item.getListPrice().multiply(new BigDecimal(quantity)); } else { total = null; } } }
Derzhevitskiy/spring-petclinic-master
src/main/java/org/mybatis/jpetstore/domain/CartItem.java
Java
apache-2.0
1,767
/* * 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. */ import angular from 'angular'; import igniteDialog from './dialog.directive'; import igniteDialogTitle from './dialog-title.directive'; import igniteDialogContent from './dialog-content.directive'; import IgniteDialog from './dialog.factory'; angular .module('ignite-console.dialog', [ ]) .factory('IgniteDialog', IgniteDialog) .directive('igniteDialog', igniteDialog) .directive('igniteDialogTitle', igniteDialogTitle) .directive('igniteDialogContent', igniteDialogContent);
ilantukh/ignite
modules/web-console/frontend/app/modules/dialog/dialog.module.js
JavaScript
apache-2.0
1,283
package com.jorgecastilloprz.pagedheadlistview.pagetransformers; import android.support.v4.view.ViewPager; import android.view.View; /** * Created by jorge on 10/08/14. */ public class DepthPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.75f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(0); } else if (position <= 0) { // [-1,0] // Use the default slide transition when moving to the left page view.setAlpha(1); view.setTranslationX(0); view.setScaleX(1); view.setScaleY(1); } else if (position <= 1) { // (0,1] // Fade the page out. view.setAlpha(1 - position); // Counteract the default slide transition view.setTranslationX(pageWidth * -position); // Scale the page down (between MIN_SCALE and 1) float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(0); } } }
0359xiaodong/PagedHeadListView
library/src/main/java/com/jorgecastilloprz/pagedheadlistview/pagetransformers/DepthPageTransformer.java
Java
apache-2.0
1,412
import sys import os from doctest import DocTestSuite, ELLIPSIS, NORMALIZE_WHITESPACE SKIP_DIRS = ( # Skip modules which import and initialize stuff that require QApplication 'Orange/widgets', 'Orange/canvas', # Skip because we don't want Orange.datasets as a module (yet) 'Orange/datasets/' ) if sys.platform == "win32": # convert to platform native path component separators SKIP_DIRS = tuple(os.path.normpath(p) for p in SKIP_DIRS) def find_modules(package): """Return a recursive list of submodules for a given package""" from os import path, walk module = path.dirname(getattr(package, '__file__', package)) parent = path.dirname(module) files = (path.join(dir, file)[len(parent) + 1:-3] for dir, dirs, files in walk(module) for file in files if file.endswith('.py')) files = (f for f in files if not f.startswith(SKIP_DIRS)) files = (f.replace(path.sep, '.') for f in files) return files class Context(dict): """ Execution context that retains the changes the tests make. Preferably use one per module to obtain nice "literate" modules that "follow along". In other words, directly the opposite of: https://docs.python.org/3/library/doctest.html#what-s-the-execution-context By popular demand: http://stackoverflow.com/questions/13106118/object-reuse-in-python-doctest/13106793#13106793 http://stackoverflow.com/questions/3286658/embedding-test-code-or-data-within-doctest-strings """ def copy(self): return self def clear(self): pass def suite(package): """Assemble test suite for doctests in path (recursively)""" from importlib import import_module for module in find_modules(package.__file__): try: module = import_module(module) yield DocTestSuite(module, globs=Context(module.__dict__.copy()), optionflags=ELLIPSIS | NORMALIZE_WHITESPACE) except ValueError: pass # No doctests in module except ImportError: import warnings warnings.warn('Unimportable module: {}'.format(module)) def load_tests(loader, tests, ignore): # This follows the load_tests protocol # https://docs.python.org/3/library/unittest.html#load-tests-protocol import Orange tests.addTests(suite(Orange)) return tests
cheral/orange3
Orange/tests/test_doctest.py
Python
bsd-2-clause
2,448
import { TSESTree } from '@typescript-eslint/types'; import { DefinitionType } from './DefinitionType'; import { DefinitionBase } from './DefinitionBase'; declare class VariableDefinition extends DefinitionBase<DefinitionType.Variable, TSESTree.VariableDeclarator, TSESTree.VariableDeclaration, TSESTree.Identifier> { constructor(name: TSESTree.Identifier, node: VariableDefinition['node'], decl: TSESTree.VariableDeclaration); readonly isTypeDefinition = false; readonly isVariableDefinition = true; } export { VariableDefinition }; //# sourceMappingURL=VariableDefinition.d.ts.map
ChromeDevTools/devtools-frontend
node_modules/@typescript-eslint/scope-manager/dist/definition/VariableDefinition.d.ts
TypeScript
bsd-3-clause
594
/*----------------------------------------------------------------------------- Orderable plugin -----------------------------------------------------------------------------*/ jQuery.fn.symphonyOrderable = function(custom_settings) { var objects = this; var settings = { items: 'li', handles: '*', delay_initialize: false }; jQuery.extend(settings, custom_settings); /*------------------------------------------------------------------------- Orderable -------------------------------------------------------------------------*/ objects = objects.map(function() { var object = this; var state = null; var start = function() { state = { item: jQuery(this).parents(settings.items), min: null, max: null, delta: 0 }; jQuery(document).mousemove(change); jQuery(document).mouseup(stop); jQuery(document).mousemove(); return false; }; var change = function(event) { var item = state.item; var target, next, top = event.pageY; var a = item.height(); var b = item.offset().top; var prev = item.prev(); state.min = Math.min(b, a + (prev.size() > 0 ? prev.offset().top : -Infinity)); state.max = Math.max(a + b, b + (item.next().height() || Infinity)); if (!object.is('.ordering')) { object.addClass('ordering'); item.addClass('ordering'); object.trigger('orderstart', [state.item]); } if (top < state.min) { target = item.prev(settings.items); while (true) { state.delta--; next = target.prev(settings.items); if (next.length === 0 || top >= (state.min -= next.height())) { item.insertBefore(target); break; } target = next; } } else if (top > state.max) { target = item.next(settings.items); while (true) { state.delta++; next = target.next(settings.items); if (next.length === 0 || top <= (state.max += next.height())) { item.insertAfter(target); break; } target = next; } } object.trigger('orderchange', [state.item]); return false; }; var stop = function() { jQuery(document).unbind('mousemove', change); jQuery(document).unbind('mouseup', stop); if (state != null) { object.removeClass('ordering'); state.item.removeClass('ordering'); object.trigger('orderstop', [state.item]); state = null; } return false; }; /*-------------------------------------------------------------------*/ if (object instanceof jQuery === false) { object = jQuery(object); } object.orderable = { cancel: function() { jQuery(document).unbind('mousemove', change); jQuery(document).unbind('mouseup', stop); if (state != null) { object.removeClass('ordering'); state.item.removeClass('ordering'); object.trigger('ordercancel', [state.item]); state = null; } }, initialize: function() { object.addClass('orderable'); object.find(settings.items).each(function() { var item = jQuery(this); var handle = item.find(settings.handles); handle.unbind('mousedown', start); handle.bind('mousedown', start); }); } }; if (settings.delay_initialize !== true) { object.orderable.initialize(); } return object; }); return objects; }; /*---------------------------------------------------------------------------*/
bauhouse/sym-intranet
symphony/assets/symphony.orderable.js
JavaScript
mit
3,588
// wrapped by build app define("d3/src/scale/ordinal", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){ import "../arrays/map"; import "../arrays/range"; import "scale"; d3.scale.ordinal = function() { return d3_scale_ordinal([], {t: "range", a: [[]]}); }; function d3_scale_ordinal(domain, ranger) { var index, range, rangeBand; function scale(x) { return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } function steps(start, step) { return d3.range(domain.length).map(function(i) { return start + step * i; }); } scale.domain = function(x) { if (!arguments.length) return domain; domain = []; index = new d3_Map; var i = -1, n = x.length, xi; while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); return scale[ranger.t].apply(scale, ranger.a); }; scale.range = function(x) { if (!arguments.length) return range; range = x; rangeBand = 0; ranger = {t: "range", a: arguments}; return scale; }; scale.rangePoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain.length - 1 + padding); range = steps(start + step * padding / 2, step); rangeBand = 0; ranger = {t: "rangePoints", a: arguments}; return scale; }; scale.rangeRoundPoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain.length - 1 + padding) | 0; // bitwise floor for symmetry range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); rangeBand = 0; ranger = {t: "rangeRoundPoints", a: arguments}; return scale; }; scale.rangeBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); range = steps(start + step * outerPadding, step); if (reverse) range.reverse(); rangeBand = step * (1 - padding); ranger = {t: "rangeBands", a: arguments}; return scale; }; scale.rangeRoundBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); if (reverse) range.reverse(); rangeBand = Math.round(step * (1 - padding)); ranger = {t: "rangeRoundBands", a: arguments}; return scale; }; scale.rangeBand = function() { return rangeBand; }; scale.rangeExtent = function() { return d3_scaleExtent(ranger.a[0]); }; scale.copy = function() { return d3_scale_ordinal(domain, ranger); }; return scale.domain(domain); } });
hyoo/p3_web
public/js/release/d3/src/scale/ordinal.js
JavaScript
mit
3,374
$CELLULOID_TEST = true require "celluloid"
olleolleolle/celluloid
lib/celluloid/test.rb
Ruby
mit
44
// // DiscVolume.cs // // Author: // Timo Dörr <timo@latecrew.de> // // Copyright 2012 Timo Dörr // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using MonoMac.Foundation; using Banshee.Hardware.Osx.LowLevel; namespace Banshee.Hardware.Osx { public class DiscVolume : Volume, IDiscVolume { public DiscVolume (DeviceArguments arguments, IBlockDevice b) : base(arguments, b) { } #region IDiscVolume implementation public bool HasAudio { get { return true; } } public bool HasData { get { return false; } } public bool HasVideo { get { return false; } } public bool IsRewritable { get { return false; } } public bool IsBlank { get { return false; } } public ulong MediaCapacity { get { return 128338384858; } } #endregion } }
GNOME/banshee
src/Backends/Banshee.Osx/Banshee.Hardware.Osx/DiscVolume.cs
C#
mit
2,171
CKEDITOR.plugins.setLang("imagebase","en-au",{captionPlaceholder:"Enter image caption"});
cdnjs/cdnjs
ajax/libs/ckeditor/4.17.2/plugins/imagebase/lang/en-au.min.js
JavaScript
mit
89
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DataSource = (function () { function DataSource() { } return DataSource; }()); exports.DataSource = DataSource;
cdnjs/cdnjs
ajax/libs/deeplearn/0.6.0-alpha6/contrib/data/datasource.js
JavaScript
mit
205
//=set test "Test"
AlexanderDolgan/juliawp
wp-content/themes/node_modules/gulp-rigger/node_modules/rigger/test/input-settings/stringval.js
JavaScript
gpl-2.0
18
// license:BSD-3-Clause // copyright-holders:Vas Crabb #include "emu.h" #include "ti8x.h" #define LOG_GENERAL (1U << 0) #define LOG_BITPROTO (1U << 1) #define LOG_BYTEPROTO (1U << 2) //#define VERBOSE (LOG_GENERAL | LOG_BITPROTO | LOG_BYTEPROTO) #define LOG_OUTPUT_FUNC device().logerror #include "logmacro.h" #define LOGBITPROTO(...) LOGMASKED(LOG_BITPROTO, __VA_ARGS__) #define LOGBYTEPROTO(...) LOGMASKED(LOG_BYTEPROTO, __VA_ARGS__) DEFINE_DEVICE_TYPE(TI8X_LINK_PORT, ti8x_link_port_device, "ti8x_link_port", "TI-8x Link Port") ti8x_link_port_device::ti8x_link_port_device( machine_config const &mconfig, char const *tag, device_t *owner, uint32_t clock) : ti8x_link_port_device(mconfig, TI8X_LINK_PORT, tag, owner, clock) { } ti8x_link_port_device::ti8x_link_port_device( machine_config const &mconfig, device_type type, char const *tag, device_t *owner, uint32_t clock) : device_t(mconfig, type, tag, owner, clock) , device_single_card_slot_interface<device_ti8x_link_port_interface>(mconfig, *this) , m_tip_handler(*this) , m_ring_handler(*this) , m_dev(nullptr) , m_tip_in(true) , m_tip_out(true) , m_ring_in(true) , m_ring_out(true) { } WRITE_LINE_MEMBER(ti8x_link_port_device::tip_w) { if (bool(state) != m_tip_out) { m_tip_out = bool(state); if (m_dev) m_dev->input_tip(m_tip_out ? 1 : 0); } } WRITE_LINE_MEMBER(ti8x_link_port_device::ring_w) { if (bool(state) != m_ring_out) { m_ring_out = bool(state); if (m_dev) m_dev->input_ring(m_ring_out ? 1 : 0); } } void ti8x_link_port_device::device_start() { m_tip_handler.resolve_safe(); m_ring_handler.resolve_safe(); save_item(NAME(m_tip_in)); save_item(NAME(m_tip_out)); save_item(NAME(m_ring_in)); save_item(NAME(m_ring_out)); m_tip_in = m_tip_out = true; m_ring_in = m_ring_out = true; } void ti8x_link_port_device::device_config_complete() { m_dev = get_card_device(); } device_ti8x_link_port_interface::device_ti8x_link_port_interface( machine_config const &mconfig, device_t &device) : device_interface(device, "ti8xlink") , m_port(dynamic_cast<ti8x_link_port_device *>(device.owner())) { } device_ti8x_link_port_bit_interface::device_ti8x_link_port_bit_interface( machine_config const &mconfig, device_t &device) : device_ti8x_link_port_interface(mconfig, device) , m_error_timer(nullptr) , m_bit_phase(IDLE) , m_tx_bit_buffer(EMPTY) , m_tip_in(true) , m_ring_in(true) { } void device_ti8x_link_port_bit_interface::interface_pre_start() { device_ti8x_link_port_interface::interface_pre_start(); if (!m_error_timer) m_error_timer = device().machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(device_ti8x_link_port_bit_interface::bit_timeout), this)); m_bit_phase = IDLE; m_tx_bit_buffer = EMPTY; m_tip_in = m_ring_in = true; } void device_ti8x_link_port_bit_interface::interface_post_start() { device_ti8x_link_port_interface::interface_post_start(); device().save_item(NAME(m_bit_phase)); device().save_item(NAME(m_tx_bit_buffer)); device().save_item(NAME(m_tip_in)); device().save_item(NAME(m_ring_in)); } void device_ti8x_link_port_bit_interface::interface_pre_reset() { device_ti8x_link_port_interface::interface_pre_reset(); m_error_timer->reset(); m_bit_phase = (m_tip_in && m_ring_in) ? IDLE : WAIT_IDLE; m_tx_bit_buffer = EMPTY; output_tip(1); output_ring(1); } void device_ti8x_link_port_bit_interface::send_bit(bool data) { LOGBITPROTO("queue %d bit\n", data ? 1 : 0); if (EMPTY != m_tx_bit_buffer) device().logerror("device_ti8x_link_port_bit_interface: warning: transmit buffer overrun\n"); m_tx_bit_buffer = data ? PENDING_1 : PENDING_0; if (IDLE == m_bit_phase) check_tx_bit_buffer(); else if (WAIT_IDLE == m_bit_phase) m_error_timer->reset(attotime(1, 0)); // TODO: configurable timeout } void device_ti8x_link_port_bit_interface::accept_bit() { switch (m_bit_phase) { // can't accept a bit that isn't being held case IDLE: case WAIT_ACK_0: case WAIT_ACK_1: case WAIT_REL_0: case WAIT_REL_1: case ACK_0: case ACK_1: case WAIT_IDLE: fatalerror("device_ti8x_link_port_bit_interface: attempt to accept bit when not holding"); break; // release the acknowledgement - if the ring doesn't rise we've lost sync case HOLD_0: assert(m_tip_in); output_ring(1); if (m_ring_in) { LOGBITPROTO("accepted 0 bit\n"); check_tx_bit_buffer(); } else { LOGBITPROTO("accepted 0 bit, ring low (collision) - waiting for bus idle\n"); m_error_timer->reset((EMPTY == m_tx_bit_buffer) ? attotime::never : attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_IDLE; bit_collision(); } break; // release the acknowledgement - if the tip doesn't rise we've lost sync case HOLD_1: assert(m_ring_in); output_tip(1); if (m_tip_in) { LOGBITPROTO("accepted 1 bit\n"); check_tx_bit_buffer(); } else { LOGBITPROTO("accepted 1 bit, tip low (collision) - waiting for bus idle\n"); m_error_timer->reset((EMPTY == m_tx_bit_buffer) ? attotime::never : attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_IDLE; bit_collision(); } break; // something very bad happened (heap smash?) default: throw false; } } WRITE_LINE_MEMBER(device_ti8x_link_port_bit_interface::input_tip) { m_tip_in = bool(state); switch (m_bit_phase) { // if tip falls while idle, it's the beginning of an incoming 0 case IDLE: if (!m_tip_in) { LOGBITPROTO("falling edge on tip, acknowledging 0 bit\n"); m_error_timer->reset(attotime(1, 0)); // TODO: configurable timeout m_bit_phase = ACK_0; output_ring(0); } break; // we're driving tip low in this state, ignore it case WAIT_ACK_0: case ACK_1: case HOLD_1: break; // tip must fall to acknowledge outgoing 1 case WAIT_ACK_1: if (!m_tip_in) { LOGBITPROTO("falling edge on tip, 1 bit acknowledged, confirming\n"); m_error_timer->reset(attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_REL_1; output_ring(1); } break; // if tip falls now, we've lost sync case WAIT_REL_0: case HOLD_0: if (!m_tip_in) { LOGBITPROTO("falling edge on tip, lost sync, waiting for bus idle\n"); m_error_timer->reset((EMPTY == m_tx_bit_buffer) ? attotime::never : attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_IDLE; output_ring(1); bit_collision(); } break; // tip must rise to complete outgoing 1 sequence case WAIT_REL_1: if (m_tip_in) { assert(!m_ring_in); LOGBITPROTO("rising edge on tip, 1 bit sent\n"); check_tx_bit_buffer(); bit_sent(); } break; // tip must rise to accept our acknowledgement case ACK_0: if (m_tip_in) { LOGBITPROTO("rising edge on tip, 0 bit acknowledge confirmed, holding\n"); m_error_timer->reset(); m_bit_phase = HOLD_0; bit_received(false); } break; // if the bus is available, check for bit to send case WAIT_IDLE: if (m_tip_in && m_ring_in) { LOGBITPROTO("rising edge on tip, bus idle detected\n"); check_tx_bit_buffer(); } break; // something very bad happened (heap smash?) default: throw false; } } WRITE_LINE_MEMBER(device_ti8x_link_port_bit_interface::input_ring) { m_ring_in = bool(state); switch (m_bit_phase) { // if ring falls while idle, it's the beginning of an incoming 1 case IDLE: if (!m_ring_in) { LOGBITPROTO("falling edge on ring, acknowledging 1 bit\n"); m_error_timer->reset(attotime(1, 0)); // TODO: configurable timeout m_bit_phase = ACK_1; output_tip(0); } break; // ring must fall to acknowledge outgoing 0 case WAIT_ACK_0: if (!m_ring_in) { LOGBITPROTO("falling edge on ring, 0 bit acknowledged, confirming\n"); m_error_timer->reset(attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_REL_0; output_tip(1); } break; // we're driving ring low in this state, ignore it case WAIT_ACK_1: case ACK_0: case HOLD_0: break; // ring must rise to complete outgoing 0 sequence case WAIT_REL_0: if (m_ring_in) { assert(!m_tip_in); LOGBITPROTO("rising edge on ring, 0 bit sent\n"); check_tx_bit_buffer(); bit_sent(); } break; // if ring falls now, we've lost sync case WAIT_REL_1: case HOLD_1: if (!m_ring_in) { LOGBITPROTO("falling edge on ring, lost sync, waiting for bus idle\n"); m_error_timer->reset((EMPTY == m_tx_bit_buffer) ? attotime::never : attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_IDLE; output_tip(1); bit_collision(); } break; // ring must rise to accept our acknowledgement case ACK_1: if (m_ring_in) { LOGBITPROTO("rising edge on ring, 1 bit acknowledge confirmed, holding\n"); m_error_timer->reset(); m_bit_phase = HOLD_1; bit_received(true); } break; // if the bus is available, check for bit to send case WAIT_IDLE: if (m_tip_in && m_ring_in) { LOGBITPROTO("rising edge on tip, bus idle detected\n"); check_tx_bit_buffer(); } break; // something very bad happened (heap smash?) default: throw false; } } TIMER_CALLBACK_MEMBER(device_ti8x_link_port_bit_interface::bit_timeout) { switch (m_bit_phase) { // something very bad happened (heap smash?) case IDLE: case HOLD_0: case HOLD_1: default: throw false; // receive timeout case ACK_0: case ACK_1: LOGBITPROTO("timeout acknowledging %d bit\n", (ACK_0 == m_bit_phase) ? 0 : 1); output_tip(1); output_ring(1); if (m_tip_in && m_ring_in) { check_tx_bit_buffer(); } else { LOGBITPROTO("waiting for bus idle\n"); m_error_timer->reset((EMPTY == m_tx_bit_buffer) ? attotime::never : attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_IDLE; } bit_receive_timeout(); break; // send timeout: case WAIT_IDLE: assert(EMPTY != m_tx_bit_buffer); [[fallthrough]]; case WAIT_ACK_0: case WAIT_ACK_1: case WAIT_REL_0: case WAIT_REL_1: LOGBITPROTO("timeout sending bit\n"); m_error_timer->reset(); m_bit_phase = (m_tip_in && m_ring_in) ? IDLE : WAIT_IDLE; m_tx_bit_buffer = EMPTY; output_tip(1); output_ring(1); bit_send_timeout(); break; } } void device_ti8x_link_port_bit_interface::check_tx_bit_buffer() { assert(m_tip_in); assert(m_ring_in); switch (m_tx_bit_buffer) { // nothing to do case EMPTY: LOGBITPROTO("no pending bit, entering idle state\n"); m_error_timer->reset(); m_bit_phase = IDLE; break; // pull tip low and wait for acknowledgement case PENDING_0: LOGBITPROTO("sending 0 bit, pulling tip low\n"); m_error_timer->reset(attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_ACK_0; m_tx_bit_buffer = EMPTY; output_tip(0); break; // pull ring low and wait for acknowledgement case PENDING_1: LOGBITPROTO("sending 1 bit, pulling ring low\n"); m_error_timer->reset(attotime(1, 0)); // TODO: configurable timeout m_bit_phase = WAIT_ACK_1; m_tx_bit_buffer = EMPTY; output_ring(0); break; // something very bad happened (heap smash?) default: throw false; } } device_ti8x_link_port_byte_interface::device_ti8x_link_port_byte_interface( machine_config const &mconfig, device_t &device) : device_ti8x_link_port_bit_interface(mconfig, device) , m_tx_byte_buffer(0U) , m_rx_byte_buffer(0U) { } void device_ti8x_link_port_byte_interface::interface_pre_start() { device_ti8x_link_port_bit_interface::interface_pre_start(); m_tx_byte_buffer = m_rx_byte_buffer = 0U; } void device_ti8x_link_port_byte_interface::interface_post_start() { device_ti8x_link_port_bit_interface::interface_post_start(); device().save_item(NAME(m_tx_byte_buffer)); device().save_item(NAME(m_rx_byte_buffer)); } void device_ti8x_link_port_byte_interface::interface_pre_reset() { device_ti8x_link_port_bit_interface::interface_pre_reset(); m_tx_byte_buffer = m_rx_byte_buffer = 0U; } void device_ti8x_link_port_byte_interface::send_byte(u8 data) { if (m_tx_byte_buffer) device().logerror("device_ti8x_link_port_byte_interface: warning: transmit buffer overrun\n"); LOGBYTEPROTO("sending byte 0x%02X\n", data); m_tx_byte_buffer = 0x0080 | u16(data >> 1); send_bit(BIT(data, 0)); } void device_ti8x_link_port_byte_interface::accept_byte() { assert(BIT(m_rx_byte_buffer, 8)); LOGBYTEPROTO("accepting final bit of byte\n"); m_rx_byte_buffer = 0U; accept_bit(); } void device_ti8x_link_port_byte_interface::bit_collision() { LOGBYTEPROTO("bit collection, clearing byte buffers\n"); m_tx_byte_buffer = m_rx_byte_buffer = 0U; byte_collision(); } void device_ti8x_link_port_byte_interface::bit_send_timeout() { LOGBYTEPROTO("bit send timeout, clearing send byte buffer\n"); m_tx_byte_buffer = 0U; byte_send_timeout(); } void device_ti8x_link_port_byte_interface::bit_receive_timeout() { LOGBYTEPROTO("bit receive timeout, clearing receive byte buffer\n"); m_rx_byte_buffer = 0U; byte_receive_timeout(); } void device_ti8x_link_port_byte_interface::bit_sent() { assert(m_tx_byte_buffer); bool const data(BIT(m_tx_byte_buffer, 0)); if (m_tx_byte_buffer >>= 1) { LOGBYTEPROTO("bit sent, sending next bit of byte\n"); send_bit(data); } else { assert(data); LOGBYTEPROTO("final bit of byte sent\n"); byte_sent(); } } void device_ti8x_link_port_byte_interface::bit_received(bool data) { assert(!BIT(m_rx_byte_buffer, 8)); m_rx_byte_buffer = (!m_rx_byte_buffer ? 0x8000 : (m_rx_byte_buffer >> 1)) | (data ? 0x0080U : 0x0000U); if (BIT(m_rx_byte_buffer, 8)) { LOGBYTEPROTO("received final bit of byte 0x%02X\n", u8(m_rx_byte_buffer)); byte_received(u8(m_rx_byte_buffer)); } else { LOGBYTEPROTO("bit received, accepting\n"); accept_bit(); } } #include "bitsocket.h" #include "graphlinkhle.h" #include "teeconn.h" #include "tispeaker.h" void default_ti8x_link_devices(device_slot_interface &device) { device.option_add("bitsock", TI8X_BIT_SOCKET); device.option_add("glinkhle", TI8X_GRAPH_LINK_HLE); device.option_add("tee", TI8X_TEE_CONNECTOR); device.option_add("monospkr", TI8X_SPEAKER_MONO); device.option_add("stereospkr", TI8X_SPEAKER_STEREO); }
johnparker007/mame
src/devices/bus/ti8x/ti8x.cpp
C++
gpl-2.0
14,113
@extends('layouts.loggedout') @section('content') @if(Session::has('error')) <div class="clearfix"> <div class="alert alert-danger"> {{ Session::get('error') }} </div> </div> @endif <h1 class="col-sm-12">{{ trans('reminders.password_reset') }}</h1> {{ Form::open(array('route' => array('password.update'))) }} <p>{{ Form::label('email', 'Email') }} {{ Form::text('email','',array('class' => 'form-control', 'required' => true)) }}</p> <p>{{ Form::label('password', 'Password') }} {{ Form::password('password',array('class' => 'form-control', 'required' => true)) }}</p> <p>{{ Form::label('password_confirmation', 'Password confirm') }} {{ Form::password('password_confirmation',array('class' => 'form-control', 'required' => true)) }}</p> {{ Form::hidden('token', $token) }} <p>{{ Form::submit('Submit',array('class' => 'btn btn-primary')) }}</p> {{ Form::close() }} @stop
ubc/learninglocker
app/views/system/password/reset.blade.php
PHP
gpl-3.0
953
<?php /** * Implements safety checks for safe iframes. * * @warning This filter is *critical* for ensuring that %HTML.SafeIframe * works safely. */ class HTMLPurifier_URIFilter_SafeIframe extends HTMLPurifier_URIFilter { /** * @type string */ public $name = 'SafeIframe'; /** * @type bool */ public $always_load = true; /** * @type string */ protected $regexp = null; // XXX: The not so good bit about how this is all set up now is we // can't check HTML.SafeIframe in the 'prepare' step: we have to // defer till the actual filtering. /** * @param HTMLPurifier_Config $config * @return bool */ public function prepare($config) { $this->regexp = $config->get('URI.SafeIframeRegexp'); return true; } /** * @param HTMLPurifier_URI $uri * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool */ public function filter(&$uri, $config, $context) { // check if filter not applicable if (!$config->get('HTML.SafeIframe')) { return true; } // check if the filter should actually trigger if (!$context->get('EmbeddedURI', true)) { return true; } $token = $context->get('CurrentToken', true); if (!($token && $token->name == 'iframe')) { return true; } // check if we actually have some whitelists enabled if ($this->regexp === null) { return false; } // actually check the whitelists if (!preg_match($this->regexp, $uri->toString())) { return false; } // Make sure that if we're an HTTPS site, the iframe is also HTTPS if (is_https() && $uri->scheme == 'http') { // Convert it to a protocol-relative URL $uri->scheme = null; } return $uri; } } // vim: et sw=4 sts=4
TheCrowsJoker/mahara
htdocs/lib/htmlpurifier/HTMLPurifier/URIFilter/SafeIframe.php
PHP
gpl-3.0
1,996
<?php namespace App\Console\Commands; use App\Console\LnmsCommand; use App\Models\Device; use Illuminate\Database\Eloquent\Builder; use LibreNMS\Config; use LibreNMS\Polling\ConnectivityHelper; use Symfony\Component\Console\Input\InputArgument; class DevicePing extends LnmsCommand { protected $name = 'device:ping'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); $this->addArgument('device spec', InputArgument::REQUIRED); } /** * Execute the console command. * * @return int */ public function handle(): int { $spec = $this->argument('device spec'); $devices = Device::query()->when($spec !== 'all', function (Builder $query) use ($spec) { /** @phpstan-var Builder<Device> $query */ return $query->where('device_id', $spec) ->orWhere('hostname', $spec) ->limit(1); })->get(); if ($devices->isEmpty()) { $devices = [new Device(['hostname' => $spec])]; } Config::set('icmp_check', true); // ignore icmp disabled, this is an explicit user action /** @var Device $device */ foreach ($devices as $device) { $helper = new ConnectivityHelper($device); $response = $helper->isPingable(); $this->line($device->displayName() . ' : ' . ($response->wasSkipped() ? 'skipped' : $response)); } return 0; } }
arrmo/librenms
app/Console/Commands/DevicePing.php
PHP
gpl-3.0
1,546
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.mozstumbler.service.stumblerthread.datahandling; import org.json.JSONObject; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.base.SerializedJSONRows; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.base.JSONRowsObjectBuilder; import org.mozilla.mozstumbler.service.utils.Zipper; /* ReportBatchBuilder accepts MLS GeoSubmit JSON blobs and serializes them to string form. */ public class ReportBatchBuilder extends JSONRowsObjectBuilder { public int getCellCount() { int result = 0; for (JSONObject obj: mJSONEntries) { assert(obj instanceof MLSJSONObject); result += ((MLSJSONObject) obj).getCellCount(); } return result; } public int getWifiCount() { int result = 0; for (JSONObject obj : mJSONEntries) { assert(obj instanceof MLSJSONObject); result += ((MLSJSONObject) obj).getWifiCount(); } return result; } @Override public SerializedJSONRows finalizeToJSONRowsObject() { int obs = entriesCount(); int wifis = getWifiCount(); int cells = getCellCount(); boolean preserveDataAfterGenerateJSON = false; byte[] zippedbytes = Zipper.zipData(generateJSON(preserveDataAfterGenerateJSON).getBytes()); return new ReportBatch(zippedbytes, SerializedJSONRows.StorageState.IN_MEMORY, obs, wifis, cells); } }
petercpg/MozStumbler
libraries/stumbler/src/main/java/org/mozilla/mozstumbler/service/stumblerthread/datahandling/ReportBatchBuilder.java
Java
mpl-2.0
1,691
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2013-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.vaadin.nodemaps.internal.gwt.client; import org.discotools.gwt.leaflet.client.jsobject.JSObject; import org.discotools.gwt.leaflet.client.types.LatLng; public class SearchResult extends JSObject { protected SearchResult() {} public static final SearchResult create(final String title, final LatLng latLng) { final SearchResult result = JSObject.createJSObject().cast(); result.setTitle(title); result.setLatLng(latLng); return result; } public final String getTitle() { return getPropertyAsString("title"); } public final SearchResult setTitle(final String title) { setProperty("title", title); return this; } public final LatLng getLatLng() { return new LatLng(getProperty("latLng")); } public final SearchResult setLatLng(final LatLng latLng) { setProperty("latLng", latLng.getJSObject()); return this; } }
rdkgit/opennms
features/vaadin-node-maps/src/main/java/org/opennms/features/vaadin/nodemaps/internal/gwt/client/SearchResult.java
Java
agpl-3.0
2,174
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.extensions.annotation.common; import com.sun.mirror.apt.AnnotationProcessor; /** This annotation processor processes the annotations provided by default * whith JDK 1.5. This is needed in order to suppress the unnecessary warnings that * apt generates for these default annotations. * See also http://forums.sun.com/thread.jspa?threadID=5345947 * @author fabratu * @version %G%, %I% * @since ProActive 4.10 */ public class BogusAnnotationProcessor implements AnnotationProcessor { public BogusAnnotationProcessor() { } public void process() { // nothing! } }
moliva/proactive
src/Extensions/org/objectweb/proactive/extensions/annotation/common/BogusAnnotationProcessor.java
Java
agpl-3.0
2,065
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.vacuumd; /** * <p>AutomationException class.</p> * * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> * @version $Id: $ */ public class AutomationException extends RuntimeException { private static final long serialVersionUID = -8873671974245928627L; /** * <p>Constructor for AutomationException.</p> * * @param arg0 a {@link java.lang.String} object. */ public AutomationException(String arg0) { super(arg0); } /** * <p>Constructor for AutomationException.</p> * * @param arg0 a {@link java.lang.Throwable} object. */ public AutomationException(Throwable arg0) { super(arg0); } /** * <p>Constructor for AutomationException.</p> * * @param arg0 a {@link java.lang.String} object. * @param arg1 a {@link java.lang.Throwable} object. */ public AutomationException(String arg0, Throwable arg1) { super(arg0, arg1); } }
tdefilip/opennms
opennms-services/src/main/java/org/opennms/netmgt/vacuumd/AutomationException.java
Java
agpl-3.0
2,125
'use strict'; /** * @module br/util/Number */ var StringUtility = require('br/util/StringUtility'); /** * @class * @alias module:br/util/Number * * @classdesc * Utility methods for numbers */ function NumberUtil() { } /** * Returns a numeric representation of the sign on the number. * * @param {Number} n The number (or a number as a string) * @return {int} 1 for positive values, -1 for negative values, or the original value for zero and non-numeric values. */ NumberUtil.sgn = function(n) { return n > 0 ? 1 : n < 0 ? -1 : n; }; /** * @param {Object} n * @return {boolean} true for numbers and their string representations and false for other values including non-numeric * strings, null, Infinity, NaN. */ NumberUtil.isNumber = function(n) { if (typeof n === 'string') { n = n.trim(); } return n != null && n !== '' && n - n === 0; }; /** * Formats the number to the specified number of decimal places. * * @param {Number} n The number (or a number as a string). * @param {Number} dp The number of decimal places. * @return {String} The formatted number. */ NumberUtil.toFixed = function(n, dp) { //return this.isNumber(n) && dp != null ? Number(n).toFixed(dp) : n; //Workaround for IE8/7/6 where toFixed returns 0 for (0.5).toFixed(0) and 0.0 for (0.05).toFixed(1) if (this.isNumber(n) && dp != null) { var sgn = NumberUtil.sgn(n); n = sgn * n; var nFixed = (Math.round(Math.pow(10, dp)*n)/Math.pow(10, dp)).toFixed(dp); return (sgn * nFixed).toFixed(dp); } return n; }; /** * Formats the number to the specified number of significant figures. This fixes the bugs in the native Number function * of the same name that are prevalent in various browsers. If the number of significant figures is less than one, * then the function has no effect. * * @param {Number} n The number (or a number as a string). * @param {Number} sf The number of significant figures. * @return {String} The formatted number. */ NumberUtil.toPrecision = function(n, sf) { return this.isNumber(n) && sf > 0 ? Number(n).toPrecision(sf) : n; }; /** * Formats the number to the specified number of decimal places, omitting any trailing zeros. * * @param {Number} n The number (or a number as a string). * @param {Number} rounding The number of decimal places to round. * @return {String} The rounded number. */ NumberUtil.toRounded = function(n, rounding) { //return this.isNumber(n) && rounding != null ? String(Number(Number(n).toFixed(rounding))) : n; //Workaround for IE8/7/6 where toFixed returns 0 for (0.5).toFixed(0) and 0.0 for (0.05).toFixed(1) if (this.isNumber(n) && rounding != null) { var sgn = NumberUtil.sgn(n); n = sgn * n; var nRounded = (Math.round(Math.pow(10, rounding)*n)/Math.pow(10, rounding)).toFixed(rounding); return sgn * nRounded; } return n; }; /** * Logarithm to base 10. * * @param {Number} n The number (or a number as a string). * @return {Number} The logarithm to base 10. */ NumberUtil.log10 = function(n) { return Math.log(n) / Math.LN10; }; /** * Rounds a floating point number * * @param {Number} n The number (or a number as a string). * @return {Number} The formatted number. */ NumberUtil.round = function(n) { var dp = 13 - (n ? Math.ceil(this.log10(Math.abs(n))) : 0); return this.isNumber(n) ? Number(Number(n).toFixed(dp)) : n; }; /** * Pads the integer part of a number with zeros to reach the specified length. * * @param {Number} value The number (or a number as a string). * @param {Number} numLength The required length of the number. * @return {String} The formatted number. */ NumberUtil.pad = function(value, numLength) { if (this.isNumber(value)) { var nAbsolute = Math.abs(value); var sInteger = new String(parseInt(nAbsolute)); var nSize = numLength || 0; var sSgn = value < 0 ? "-" : ""; value = sSgn + StringUtility.repeat("0", nSize - sInteger.length) + nAbsolute; } return value; }; /** * Counts the amount of decimal places within a number. * Also supports scientific notations * * @param {Number} n The number (or a number as a string). * @return {Number} The number of decimal places */ NumberUtil.decimalPlaces = function(n) { var match = (''+n).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); if (!match) { return 0; } return Math.max( 0, // Number of digits right of decimal point. (match[1] ? match[1].length : 0) // Adjust for scientific notation. - (match[2] ? +match[2] : 0)); } module.exports = NumberUtil;
andreoid/testing
brjs-sdk/workspace/sdk/libs/javascript/br-util/src/br/util/Number.js
JavaScript
lgpl-3.0
4,499
/* Copyright 2012 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.hraven.etl; import java.util.concurrent.Callable; import org.apache.hadoop.mapreduce.Job; /** * Can be used to run a single Hadoop job. The {@link #call()} method will block * until the job is complete and will return a non-null return value indicating * the success of the Hadoop job. */ public class JobRunner implements Callable<Boolean> { private volatile boolean isCalled = false; private final Job job; /** * Post processing step that gets called upon successful completion of the * Hadoop job. */ private final Callable<Boolean> postProcessor; /** * Constructor * * @param job * to job to run in the call method. * @param postProcessor * Post processing step that gets called upon successful completion * of the Hadoop job. Can be null, in which case it will be skipped. * Final results will be the return value of this final processing * step. */ public JobRunner(Job job, Callable<Boolean> postProcessor) { this.job = job; this.postProcessor = postProcessor; } /* * (non-Javadoc) * * @see java.util.concurrent.Callable#call() */ @Override public Boolean call() throws Exception { // Guard to make sure we get called only once. if (isCalled) { return false; } else { isCalled = true; } if (job == null) { return false; } boolean success = false; // Schedule the job on the JobTracker and wait for it to complete. try { success = job.waitForCompletion(true); } catch (InterruptedException interuptus) { // We're told to stop, so honor that. // And restore interupt status. Thread.currentThread().interrupt(); // Indicate that we should NOT run the postProcessor. success = false; } if (success && (postProcessor != null)) { success = postProcessor.call(); } return success; } }
ogre0403/hraven
hraven-etl/src/main/java/com/twitter/hraven/etl/JobRunner.java
Java
apache-2.0
2,525
""" Component-level Specification This module is called component to mirror organization of storm package. """ from ..storm.component import Component class Specification(object): def __init__(self, component_cls, name=None, parallelism=1): if not issubclass(component_cls, Component): raise TypeError("Invalid component: {}".format(component_cls)) if not isinstance(parallelism, int) or parallelism < 1: raise ValueError("Parallelism must be a integer greater than 0") self.component_cls = component_cls self.name = name self.parallelism = parallelism def resolve_dependencies(self, specifications): """Allows specification subclasses to resolve an dependencies that they may have on other specifications. :param specifications: all of the specification objects for this topology. :type specifications: dict """ pass
hodgesds/streamparse
streamparse/dsl/component.py
Python
apache-2.0
976
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.dmn.client.editors.included; import java.util.List; import com.google.gwtmockito.GwtMockitoTestRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.dmn.client.editors.included.common.IncludedModelsPageStateProvider; import org.mockito.Mock; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(GwtMockitoTestRunner.class) public class IncludedModelsPageStateTest { @Mock private IncludedModelsPageStateProvider pageProvider; private IncludedModelsPageState state; @Before public void setup() { state = new IncludedModelsPageState(); } @Test public void testGetCurrentDiagramNamespaceWhenPageProviderIsPresent() { final String expectedNamespace = "://namespace"; when(pageProvider.getCurrentDiagramNamespace()).thenReturn(expectedNamespace); state.init(pageProvider); final String actualNamespace = state.getCurrentDiagramNamespace(); assertEquals(expectedNamespace, actualNamespace); } @Test public void testGetCurrentDiagramNamespaceWhenPageProviderIsNotPresent() { final String expectedNamespace = ""; state.init(null); final String actualNamespace = state.getCurrentDiagramNamespace(); assertEquals(expectedNamespace, actualNamespace); } @Test public void testGenerateIncludedModelsWhenPageProviderIsNotPresent() { state.init(null); final List<BaseIncludedModelActiveRecord> actualIncludedModels = state.generateIncludedModels(); final List<BaseIncludedModelActiveRecord> expectedIncludedModels = emptyList(); assertEquals(expectedIncludedModels, actualIncludedModels); } @Test public void testGenerateIncludedModelsWhenPageProviderIsPresent() { final List<BaseIncludedModelActiveRecord> expectedIncludedModels = asList(mock(BaseIncludedModelActiveRecord.class), mock(BaseIncludedModelActiveRecord.class)); when(pageProvider.generateIncludedModels()).thenReturn(expectedIncludedModels); state.init(pageProvider); final List<BaseIncludedModelActiveRecord> actualIncludedModels = state.generateIncludedModels(); assertEquals(actualIncludedModels, expectedIncludedModels); } }
jomarko/kie-wb-common
kie-wb-common-dmn/kie-wb-common-dmn-client/src/test/java/org/kie/workbench/common/dmn/client/editors/included/IncludedModelsPageStateTest.java
Java
apache-2.0
3,116
/* * 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. */ package org.apache.mahout.math.jet.random; import org.apache.mahout.common.RandomUtils; import org.apache.mahout.math.MahoutTestCase; import org.junit.Test; import java.util.Arrays; import java.util.Locale; import java.util.Random; public final class GammaTest extends MahoutTestCase { @Test public void testNextDouble() { double[] z = new double[100000]; Random gen = RandomUtils.getRandom(); for (double alpha : new double[]{1, 2, 10, 0.1, 0.01, 100}) { Gamma g = new Gamma(alpha, 1, gen); for (int i = 0; i < z.length; i++) { z[i] = g.nextDouble(); } Arrays.sort(z); // verify that empirical CDF matches theoretical one pretty closely for (double q : seq(0.01, 1, 0.01)) { double p = z[(int) (q * z.length)]; assertEquals(q, g.cdf(p), 0.01); } } } @Test public void testCdf() { Random gen = RandomUtils.getRandom(); // verify scaling for special case of alpha = 1 for (double beta : new double[]{1, 0.1, 2, 100}) { Gamma g1 = new Gamma(1, beta, gen); Gamma g2 = new Gamma(1, 1, gen); for (double x : seq(0, 0.99, 0.1)) { assertEquals(String.format(Locale.ENGLISH, "Rate invariance: x = %.4f, alpha = 1, beta = %.1f", x, beta), 1 - Math.exp(-x * beta), g1.cdf(x), 1.0e-9); assertEquals(String.format(Locale.ENGLISH, "Rate invariance: x = %.4f, alpha = 1, beta = %.1f", x, beta), g2.cdf(beta * x), g1.cdf(x), 1.0e-9); } } // now test scaling for a selection of values of alpha for (double alpha : new double[]{0.01, 0.1, 1, 2, 10, 100, 1000}) { Gamma g = new Gamma(alpha, 1, gen); for (double beta : new double[]{0.1, 1, 2, 100}) { Gamma g1 = new Gamma(alpha, beta, gen); for (double x : seq(0, 0.9999, 0.001)) { assertEquals( String.format(Locale.ENGLISH, "Rate invariance: x = %.4f, alpha = %.2f, beta = %.1f", x, alpha, beta), g.cdf(x * beta), g1.cdf(x), 0); } } } // now check against known values computed using R for various values of alpha checkGammaCdf(0.01, 1, 0.0000000, 0.9450896, 0.9516444, 0.9554919, 0.9582258, 0.9603474, 0.9620810, 0.9635462, 0.9648148, 0.9659329, 0.9669321); checkGammaCdf(0.1, 1, 0.0000000, 0.7095387, 0.7591012, 0.7891072, 0.8107067, 0.8275518, 0.8413180, 0.8529198, 0.8629131, 0.8716623, 0.8794196); checkGammaCdf(1, 1, 0.0000000, 0.1812692, 0.3296800, 0.4511884, 0.5506710, 0.6321206, 0.6988058, 0.7534030, 0.7981035, 0.8347011, 0.8646647); checkGammaCdf(10, 1, 0.000000e+00, 4.649808e-05, 8.132243e-03, 8.392402e-02, 2.833757e-01, 5.420703e-01, 7.576078e-01, 8.906006e-01, 9.567017e-01, 9.846189e-01, 9.950046e-01); checkGammaCdf(100, 1, 0.000000e+00, 3.488879e-37, 1.206254e-15, 1.481528e-06, 1.710831e-02, 5.132988e-01, 9.721363e-01, 9.998389e-01, 9.999999e-01, 1.000000e+00, 1.000000e+00); // > pgamma(seq(0,0.02,by=0.002),0.01,1) // [1] 0.0000000 0.9450896 0.9516444 0.9554919 0.9582258 0.9603474 0.9620810 0.9635462 0.9648148 0.9659329 0.9669321 // > pgamma(seq(0,0.2,by=0.02),0.1,1) // [1] 0.0000000 0.7095387 0.7591012 0.7891072 0.8107067 0.8275518 0.8413180 0.8529198 0.8629131 0.8716623 0.8794196 // > pgamma(seq(0,2,by=0.2),1,1) // [1] 0.0000000 0.1812692 0.3296800 0.4511884 0.5506710 0.6321206 0.6988058 0.7534030 0.7981035 0.8347011 0.8646647 // > pgamma(seq(0,20,by=2),10,1) // [1] 0.000000e+00 4.649808e-05 8.132243e-03 8.392402e-02 2.833757e-01 5.420703e-01 7.576078e-01 8.906006e-01 9.567017e-01 9.846189e-01 9.950046e-01 // > pgamma(seq(0,200,by=20),100,1) // [1] 0.000000e+00 3.488879e-37 1.206254e-15 1.481528e-06 1.710831e-02 5.132988e-01 9.721363e-01 9.998389e-01 9.999999e-01 1.000000e+00 1.000000e+00 } private static void checkGammaCdf(double alpha, double beta, double... values) { Gamma g = new Gamma(alpha, beta, RandomUtils.getRandom()); int i = 0; for (double x : seq(0, 2 * alpha, 2 * alpha / 10)) { assertEquals(String.format(Locale.ENGLISH, "alpha=%.2f, i=%d, x=%.2f", alpha, i, x), values[i], g.cdf(x), 1.0e-7); i++; } } private static double[] seq(double from, double to, double by) { double[] r = new double[(int) Math.ceil(0.999999 * (to - from) / by)]; int i = 0; for (double x = from; x < to - (to - from) * 1.0e-6; x += by) { r[i++] = x; } return r; } @Test public void testPdf() { Random gen = RandomUtils.getRandom(); for (double alpha : new double[]{0.01, 0.1, 1, 2, 10, 100}) { for (double beta : new double[]{0.1, 1, 2, 100}) { Gamma g1 = new Gamma(alpha, beta, gen); for (double x : seq(0, 0.99, 0.1)) { double p = Math.pow(beta, alpha) * Math.pow(x, alpha - 1) * Math.exp(-beta * x - org.apache.mahout.math.jet.stat.Gamma.logGamma(alpha)); assertEquals(String.format(Locale.ENGLISH, "alpha=%.2f, beta=%.2f, x=%.2f\n", alpha, beta, x), p, g1.pdf(x), 1.0e-9); } } } } }
BigData-Lab-Frankfurt/HiBench-DSE
common/mahout-distribution-0.7-hadoop1/math/src/test/java/org/apache/mahout/math/jet/random/GammaTest.java
Java
apache-2.0
5,887
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CParseHandlerQueryOutput.cpp // // @doc: // Implementation of the SAX parse handler class parsing the list of // output column references in a DXL query. //--------------------------------------------------------------------------- #include "naucrates/dxl/parser/CParseHandlerQueryOutput.h" #include "naucrates/dxl/operators/CDXLOperatorFactory.h" #include "naucrates/dxl/parser/CParseHandlerFactory.h" #include "naucrates/dxl/parser/CParseHandlerScalarIdent.h" using namespace gpdxl; XERCES_CPP_NAMESPACE_USE //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::CParseHandlerQueryOutput // // @doc: // Constructor // //--------------------------------------------------------------------------- CParseHandlerQueryOutput::CParseHandlerQueryOutput( CMemoryPool *mp, CParseHandlerManager *parse_handler_mgr, CParseHandlerBase *parse_handler_root) : CParseHandlerBase(mp, parse_handler_mgr, parse_handler_root), m_dxl_array(nullptr) { } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::~CParseHandlerQueryOutput // // @doc: // Destructor // //--------------------------------------------------------------------------- CParseHandlerQueryOutput::~CParseHandlerQueryOutput() { m_dxl_array->Release(); } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::GetOutputColumnsDXLArray // // @doc: // Return the list of query output columns // //--------------------------------------------------------------------------- CDXLNodeArray * CParseHandlerQueryOutput::GetOutputColumnsDXLArray() { GPOS_ASSERT(nullptr != m_dxl_array); return m_dxl_array; } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::StartElement // // @doc: // Invoked by Xerces to process an opening tag // //--------------------------------------------------------------------------- void CParseHandlerQueryOutput::StartElement(const XMLCh *const element_uri, const XMLCh *const element_local_name, const XMLCh *const element_qname, const Attributes &attrs) { if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), element_local_name)) { // start the query output section in the DXL document GPOS_ASSERT(nullptr == m_dxl_array); m_dxl_array = GPOS_NEW(m_mp) CDXLNodeArray(m_mp); } else if (0 == XMLString::compareString( CDXLTokens::XmlstrToken(EdxltokenScalarIdent), element_local_name)) { // we must have seen a proj list already and initialized the proj list node GPOS_ASSERT(nullptr != m_dxl_array); // start new scalar ident element CParseHandlerBase *child_parse_handler = CParseHandlerFactory::GetParseHandler( m_mp, CDXLTokens::XmlstrToken(EdxltokenScalarIdent), m_parse_handler_mgr, this); m_parse_handler_mgr->ActivateParseHandler(child_parse_handler); // store parse handler this->Append(child_parse_handler); child_parse_handler->startElement(element_uri, element_local_name, element_qname, attrs); } else { CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray( m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer()); } } //--------------------------------------------------------------------------- // @function: // CParseHandlerQueryOutput::EndElement // // @doc: // Invoked by Xerces to process a closing tag // //--------------------------------------------------------------------------- void CParseHandlerQueryOutput::EndElement(const XMLCh *const, // element_uri, const XMLCh *const element_local_name, const XMLCh *const // element_qname ) { if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenQueryOutput), element_local_name)) { CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray( m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name); GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer()); } const ULONG size = this->Length(); for (ULONG ul = 0; ul < size; ul++) { CParseHandlerScalarIdent *child_parse_handler = dynamic_cast<CParseHandlerScalarIdent *>((*this)[ul]); GPOS_ASSERT(nullptr != child_parse_handler); CDXLNode *pdxlnIdent = child_parse_handler->CreateDXLNode(); pdxlnIdent->AddRef(); m_dxl_array->Append(pdxlnIdent); } // deactivate handler m_parse_handler_mgr->DeactivateHandler(); } // EOF
50wu/gpdb
src/backend/gporca/libnaucrates/src/parser/CParseHandlerQueryOutput.cpp
C++
apache-2.0
4,849
/** * Copyright (c) 2005-2007, Paul Tuckey * All rights reserved. * ==================================================================== * Licensed under the BSD License. Text as follows. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * - Neither the name tuckey.org nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ==================================================================== */ package org.tuckey.web.filters.urlrewrite; import org.tuckey.web.filters.urlrewrite.gzip.GzipFilter; import org.tuckey.web.filters.urlrewrite.utils.Log; import org.tuckey.web.filters.urlrewrite.utils.ModRewriteConfLoader; import org.tuckey.web.filters.urlrewrite.utils.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXParseException; import javax.servlet.ServletContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Configuration object for urlrewrite filter. * * @author Paul Tuckey * @version $Revision: 43 $ $Date: 2006-10-31 17:29:59 +1300 (Tue, 31 Oct 2006) $ */ public class Conf { private static Log log = Log.getLog(Conf.class); private final List errors = new ArrayList(); private final List rules = new ArrayList(50); private final List catchElems = new ArrayList(10); private List outboundRules = new ArrayList(50); private boolean ok = false; private Date loadedDate = null; private int ruleIdCounter = 0; private int outboundRuleIdCounter = 0; private String fileName; private String confSystemId; protected boolean useQueryString; protected boolean useContext; private static final String NONE_DECODE_USING = "null"; private static final String HEADER_DECODE_USING = "header"; private static final String DEFAULT_DECODE_USING = "header,utf-8"; protected String decodeUsing = DEFAULT_DECODE_USING; private boolean decodeUsingEncodingHeader; protected String defaultMatchType = null; private ServletContext context; private boolean docProcessed = false; private boolean engineEnabled = true; /** * Empty const for testing etc. */ public Conf() { loadedDate = new Date(); } /** * Constructor for use only when loading XML style configuration. * * @param fileName to display on status screen */ public Conf(ServletContext context, final InputStream inputStream, String fileName, String systemId) { this(context, inputStream, fileName, systemId, false); } /** * Normal constructor. * * @param fileName to display on status screen * @param modRewriteStyleConf true if loading mod_rewrite style conf */ public Conf(ServletContext context, final InputStream inputStream, String fileName, String systemId, boolean modRewriteStyleConf) { // make sure context is setup before calling initialise() this.context = context; this.fileName = fileName; this.confSystemId = systemId; if (modRewriteStyleConf) { loadModRewriteStyle(inputStream); } else { loadDom(inputStream); } if (docProcessed) initialise(); loadedDate = new Date(); } protected void loadModRewriteStyle(InputStream inputStream) { ModRewriteConfLoader loader = new ModRewriteConfLoader(); try { loader.process(inputStream, this); docProcessed = true; // fixed } catch (IOException e) { addError("Exception loading conf " + " " + e.getMessage(), e); } } /** * Constructor when run elements don't need to be initialised correctly, for docuementation etc. */ public Conf(URL confUrl) { // make sure context is setup before calling initialise() this.context = null; this.fileName = confUrl.getFile(); this.confSystemId = confUrl.toString(); try { loadDom(confUrl.openStream()); } catch (IOException e) { addError("Exception loading conf " + " " + e.getMessage(), e); } if (docProcessed) initialise(); loadedDate = new Date(); } /** * Constructor when run elements don't need to be initialised correctly, for docuementation etc. */ public Conf(InputStream inputStream, String conffile) { this(null, inputStream, conffile, conffile); } /** * Load the dom document from the inputstream * <p/> * Note, protected so that is can be extended. * * @param inputStream stream of the conf file to load */ protected synchronized void loadDom(final InputStream inputStream) { if (inputStream == null) { log.error("inputstream is null"); return; } DocumentBuilder parser; /** * the thing that resolves dtd's and other xml entities. */ ConfHandler handler = new ConfHandler(confSystemId); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); log.debug("XML builder factory is: " + factory.getClass().getName()); factory.setValidating(true); factory.setNamespaceAware(true); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); try { parser = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("Unable to setup XML parser for reading conf", e); return; } log.debug("XML Parser: " + parser.getClass().getName()); parser.setErrorHandler(handler); parser.setEntityResolver(handler); try { log.debug("about to parse conf"); Document doc = parser.parse(inputStream, confSystemId); processConfDoc(doc); } catch (SAXParseException e) { addError("Parse error on line " + e.getLineNumber() + " " + e.getMessage(), e); } catch (Exception e) { addError("Exception loading conf " + " " + e.getMessage(), e); } } /** * Process dom document and populate Conf object. * <p/> * Note, protected so that is can be extended. */ protected void processConfDoc(Document doc) { Element rootElement = doc.getDocumentElement(); if ("true".equalsIgnoreCase(getAttrValue(rootElement, "use-query-string"))) setUseQueryString(true); if ("true".equalsIgnoreCase(getAttrValue(rootElement, "use-context"))) { log.debug("use-context set to true"); setUseContext(true); } setDecodeUsing(getAttrValue(rootElement, "decode-using")); setDefaultMatchType(getAttrValue(rootElement, "default-match-type")); NodeList rootElementList = rootElement.getChildNodes(); for (int i = 0; i < rootElementList.getLength(); i++) { Node node = rootElementList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("rule")) { Element ruleElement = (Element) node; // we have a rule node NormalRule rule = new NormalRule(); processRuleBasics(ruleElement, rule); procesConditions(ruleElement, rule); processRuns(ruleElement, rule); Node toNode = ruleElement.getElementsByTagName("to").item(0); rule.setTo(getNodeValue(toNode)); rule.setToType(getAttrValue(toNode, "type")); rule.setToContextStr(getAttrValue(toNode, "context")); rule.setToLast(getAttrValue(toNode, "last")); rule.setQueryStringAppend(getAttrValue(toNode, "qsappend")); if ("true".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(true); processSetAttributes(ruleElement, rule); addRule(rule); } else if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("class-rule")) { Element ruleElement = (Element) node; ClassRule classRule = new ClassRule(); if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "enabled"))) classRule.setEnabled(false); if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "last"))) classRule.setLast(false); classRule.setClassStr(getAttrValue(ruleElement, "class")); classRule.setMethodStr(getAttrValue(ruleElement, "method")); addRule(classRule); } else if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("outbound-rule")) { Element ruleElement = (Element) node; // we have a rule node OutboundRule rule = new OutboundRule(); processRuleBasics(ruleElement, rule); if ("true".equalsIgnoreCase(getAttrValue(ruleElement, "encodefirst"))) rule.setEncodeFirst(true); procesConditions(ruleElement, rule); processRuns(ruleElement, rule); Node toNode = ruleElement.getElementsByTagName("to").item(0); rule.setTo(getNodeValue(toNode)); rule.setToLast(getAttrValue(toNode, "last")); if ("false".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(false); processSetAttributes(ruleElement, rule); addOutboundRule(rule); } else if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getTagName().equals("catch")) { Element catchXMLElement = (Element) node; // we have a rule node CatchElem catchElem = new CatchElem(); catchElem.setClassStr(getAttrValue(catchXMLElement, "class")); processRuns(catchXMLElement, catchElem); catchElems.add(catchElem); } } docProcessed = true; } private void processRuleBasics(Element ruleElement, RuleBase rule) { if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "enabled"))) rule.setEnabled(false); String ruleMatchType = getAttrValue(ruleElement, "match-type"); if (StringUtils.isBlank(ruleMatchType)) ruleMatchType = defaultMatchType; rule.setMatchType(ruleMatchType); Node nameNode = ruleElement.getElementsByTagName("name").item(0); rule.setName(getNodeValue(nameNode)); Node noteNode = ruleElement.getElementsByTagName("note").item(0); rule.setNote(getNodeValue(noteNode)); Node fromNode = ruleElement.getElementsByTagName("from").item(0); rule.setFrom(getNodeValue(fromNode)); if ("true".equalsIgnoreCase(getAttrValue(fromNode, "casesensitive"))) rule.setFromCaseSensitive(true); } private static void processSetAttributes(Element ruleElement, RuleBase rule) { NodeList setNodes = ruleElement.getElementsByTagName("set"); for (int j = 0; j < setNodes.getLength(); j++) { Node setNode = setNodes.item(j); if (setNode == null) continue; SetAttribute setAttribute = new SetAttribute(); setAttribute.setValue(getNodeValue(setNode)); setAttribute.setType(getAttrValue(setNode, "type")); setAttribute.setName(getAttrValue(setNode, "name")); rule.addSetAttribute(setAttribute); } } private static void processRuns(Element ruleElement, Runnable runnable) { NodeList runNodes = ruleElement.getElementsByTagName("run"); for (int j = 0; j < runNodes.getLength(); j++) { Node runNode = runNodes.item(j); if (runNode == null) continue; Run run = new Run(); processInitParams(runNode, run); run.setClassStr(getAttrValue(runNode, "class")); run.setMethodStr(getAttrValue(runNode, "method")); run.setJsonHandler("true".equalsIgnoreCase(getAttrValue(runNode, "jsonhandler"))); run.setNewEachTime("true".equalsIgnoreCase(getAttrValue(runNode, "neweachtime"))); runnable.addRun(run); } // gzip element is just a shortcut to run: org.tuckey.web.filters.urlrewrite.gzip.GzipFilter NodeList gzipNodes = ruleElement.getElementsByTagName("gzip"); for (int j = 0; j < gzipNodes.getLength(); j++) { Node runNode = gzipNodes.item(j); if (runNode == null) continue; Run run = new Run(); run.setClassStr(GzipFilter.class.getName()); run.setMethodStr("doFilter(ServletRequest, ServletResponse, FilterChain)"); processInitParams(runNode, run); runnable.addRun(run); } } private static void processInitParams(Node runNode, Run run) { if (runNode.getNodeType() == Node.ELEMENT_NODE) { Element runElement = (Element) runNode; NodeList initParamsNodeList = runElement.getElementsByTagName("init-param"); for (int k = 0; k < initParamsNodeList.getLength(); k++) { Node initParamNode = initParamsNodeList.item(k); if (initParamNode == null) continue; if (initParamNode.getNodeType() != Node.ELEMENT_NODE) continue; Element initParamElement = (Element) initParamNode; Node paramNameNode = initParamElement.getElementsByTagName("param-name").item(0); Node paramValueNode = initParamElement.getElementsByTagName("param-value").item(0); run.addInitParam(getNodeValue(paramNameNode), getNodeValue(paramValueNode)); } } } private static void procesConditions(Element ruleElement, RuleBase rule) { NodeList conditionNodes = ruleElement.getElementsByTagName("condition"); for (int j = 0; j < conditionNodes.getLength(); j++) { Node conditionNode = conditionNodes.item(j); if (conditionNode == null) continue; Condition condition = new Condition(); condition.setValue(getNodeValue(conditionNode)); condition.setType(getAttrValue(conditionNode, "type")); condition.setName(getAttrValue(conditionNode, "name")); condition.setNext(getAttrValue(conditionNode, "next")); condition.setCaseSensitive("true".equalsIgnoreCase(getAttrValue(conditionNode, "casesensitive"))); condition.setOperator(getAttrValue(conditionNode, "operator")); rule.addCondition(condition); } } private static String getNodeValue(Node node) { if (node == null) return null; NodeList nodeList = node.getChildNodes(); if (nodeList == null) return null; Node child = nodeList.item(0); if (child == null) return null; if ((child.getNodeType() == Node.TEXT_NODE)) { String value = ((Text) child).getData(); return value.trim(); } return null; } private static String getAttrValue(Node n, String attrName) { if (n == null) return null; NamedNodeMap attrs = n.getAttributes(); if (attrs == null) return null; Node attr = attrs.getNamedItem(attrName); if (attr == null) return null; String val = attr.getNodeValue(); if (val == null) return null; return val.trim(); } /** * Initialise the conf file. This will run initialise on each rule and condition in the conf file. */ public void initialise() { if (log.isDebugEnabled()) { log.debug("now initialising conf"); } initDecodeUsing(decodeUsing); boolean rulesOk = true; for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); if (!rule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < outboundRules.size(); i++) { final OutboundRule outboundRule = (OutboundRule) outboundRules.get(i); if (!outboundRule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < catchElems.size(); i++) { final CatchElem catchElem = (CatchElem) catchElems.get(i); if (!catchElem.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } if (rulesOk) { ok = true; } if (log.isDebugEnabled()) { log.debug("conf status " + ok); } } private void initDecodeUsing(String decodeUsingSetting) { decodeUsingSetting = StringUtils.trimToNull(decodeUsingSetting); if (decodeUsingSetting == null) decodeUsingSetting = DEFAULT_DECODE_USING; if ( decodeUsingSetting.equalsIgnoreCase(HEADER_DECODE_USING)) { // is 'header' decodeUsingEncodingHeader = true; decodeUsingSetting = null; } else if ( decodeUsingSetting.startsWith(HEADER_DECODE_USING + ",")) { // is 'header,xxx' decodeUsingEncodingHeader = true; decodeUsingSetting = decodeUsingSetting.substring((HEADER_DECODE_USING + ",").length()); } if (NONE_DECODE_USING.equalsIgnoreCase(decodeUsingSetting)) { decodeUsingSetting = null; } if ( decodeUsingSetting != null ) { try { URLDecoder.decode("testUrl", decodeUsingSetting); this.decodeUsing = decodeUsingSetting; } catch (UnsupportedEncodingException e) { addError("unsupported 'decodeusing' " + decodeUsingSetting + " see Java SDK docs for supported encodings"); } } else { this.decodeUsing = null; } } /** * Destory the conf gracefully. */ public void destroy() { for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); rule.destroy(); } } /** * Will add the rule to the rules list. * * @param rule The Rule to add */ public void addRule(final Rule rule) { rule.setId(ruleIdCounter++); rules.add(rule); } /** * Will add the rule to the rules list. * * @param outboundRule The outbound rule to add */ public void addOutboundRule(final OutboundRule outboundRule) { outboundRule.setId(outboundRuleIdCounter++); outboundRules.add(outboundRule); } /** * Will get the List of errors. * * @return the List of errors */ public List getErrors() { return errors; } /** * Will get the List of rules. * * @return the List of rules */ public List getRules() { return rules; } /** * Will get the List of outbound rules. * * @return the List of outbound rules */ public List getOutboundRules() { return outboundRules; } /** * true if the conf has been loaded ok. * * @return boolean */ public boolean isOk() { return ok; } private void addError(final String errorMsg, final Exception e) { errors.add(errorMsg); log.error(errorMsg, e); } private void addError(final String errorMsg) { errors.add(errorMsg); } public Date getLoadedDate() { return (Date) loadedDate.clone(); } public String getFileName() { return fileName; } public boolean isUseQueryString() { return useQueryString; } public void setUseQueryString(boolean useQueryString) { this.useQueryString = useQueryString; } public boolean isUseContext() { return useContext; } public void setUseContext(boolean useContext) { this.useContext = useContext; } public String getDecodeUsing() { return decodeUsing; } public void setDecodeUsing(String decodeUsing) { this.decodeUsing = decodeUsing; } public void setDefaultMatchType(String defaultMatchType) { if (RuleBase.MATCH_TYPE_WILDCARD.equalsIgnoreCase(defaultMatchType)) { this.defaultMatchType = RuleBase.MATCH_TYPE_WILDCARD; } else { this.defaultMatchType = RuleBase.DEFAULT_MATCH_TYPE; } } public String getDefaultMatchType() { return defaultMatchType; } public List getCatchElems() { return catchElems; } public boolean isDecodeUsingCustomCharsetRequired() { return decodeUsing != null; } public boolean isEngineEnabled() { return engineEnabled; } public void setEngineEnabled(boolean engineEnabled) { this.engineEnabled = engineEnabled; } public boolean isLoadedFromFile() { return fileName != null; } public boolean isDecodeUsingEncodingHeader() { return decodeUsingEncodingHeader; } }
safarijv/urlrewritefilter
src/main/java/org/tuckey/web/filters/urlrewrite/Conf.java
Java
bsd-3-clause
23,779
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # 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. """Utils functions used in Task Python API.""" from tensorflow_lite_support.cc.task.core.proto import base_options_pb2 from tensorflow_lite_support.python.task.core import task_options from tensorflow_lite_support.python.task.core.proto import configuration_pb2 _ProtoBaseOptions = base_options_pb2.BaseOptions def ConvertToProtoBaseOptions( options: task_options.BaseOptions) -> _ProtoBaseOptions: """Convert the Python BaseOptions to Proto BaseOptions. Python BaseOptions is a subset of the Proto BaseOptions that strips off configurations that are useless in Python development. Args: options: the Python BaseOptions object. Returns: The Proto BaseOptions object. """ proto_options = _ProtoBaseOptions() if options.model_file.file_content: proto_options.model_file.file_content = options.model_file.file_content elif options.model_file.file_name: proto_options.model_file.file_name = options.model_file.file_name proto_options.compute_settings.tflite_settings.cpu_settings.num_threads = ( options.num_threads) if options.use_coral: proto_options.compute_settings.tflite_settings.delegate = ( configuration_pb2.Delegate.EDGETPU_CORAL) return proto_options
chromium/chromium
third_party/tflite_support/src/tensorflow_lite_support/python/task/core/task_utils.py
Python
bsd-3-clause
1,839
# frozen_string_literal: true module Spree module Admin class PropertiesController < ResourceController def index respond_with(@collection) end private def collection return @collection if @collection # params[:q] can be blank upon pagination params[:q] = {} if params[:q].blank? @collection = super @search = @collection.ransack(params[:q]) @collection = @search.result. page(params[:page]). per(Spree::Config[:properties_per_page]) @collection end end end end
pervino/solidus
backend/app/controllers/spree/admin/properties_controller.rb
Ruby
bsd-3-clause
601
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Variable = void 0; const variable_1 = __importDefault(require("eslint-scope/lib/variable")); const Variable = variable_1.default; exports.Variable = Variable; //# sourceMappingURL=Variable.js.map
ChromeDevTools/devtools-frontend
node_modules/@typescript-eslint/experimental-utils/dist/ts-eslint-scope/Variable.js
JavaScript
bsd-3-clause
419
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/device/hid/hid_preparsed_data.h" #include <cstddef> #include <cstdint> #include "base/debug/dump_without_crashing.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "components/device_event_log/device_event_log.h" namespace device { namespace { // Windows parses HID report descriptors into opaque _HIDP_PREPARSED_DATA // objects. The internal structure of _HIDP_PREPARSED_DATA is reserved for // internal system use. The structs below are inferred and may be wrong or // incomplete. // https://docs.microsoft.com/en-us/windows-hardware/drivers/hid/preparsed-data // // _HIDP_PREPARSED_DATA begins with a fixed-sized header containing information // about a single top-level HID collection. The header is followed by a // variable-sized array describing the fields that make up each report. // // Input report items appear first in the array, followed by output report items // and feature report items. The number of items of each type is given by // |input_item_count|, |output_item_count| and |feature_item_count|. The sum of // these counts should equal |item_count|. The total size in bytes of all report // items is |size_bytes|. #pragma pack(push, 1) struct PreparsedDataHeader { // Unknown constant value. _HIDP_PREPARSED_DATA identifier? uint64_t magic; // Top-level collection usage information. uint16_t usage; uint16_t usage_page; uint16_t unknown[3]; // Number of report items for input reports. Includes unused items. uint16_t input_item_count; uint16_t unknown2; // Maximum input report size, in bytes. Includes the report ID byte. Zero if // there are no input reports. uint16_t input_report_byte_length; uint16_t unknown3; // Number of report items for output reports. Includes unused items. uint16_t output_item_count; uint16_t unknown4; // Maximum output report size, in bytes. Includes the report ID byte. Zero if // there are no output reports. uint16_t output_report_byte_length; uint16_t unknown5; // Number of report items for feature reports. Includes unused items. uint16_t feature_item_count; // Total number of report items (input, output, and feature). Unused items are // excluded. uint16_t item_count; // Maximum feature report size, in bytes. Includes the report ID byte. Zero if // there are no feature reports. uint16_t feature_report_byte_length; // Total size of all report items, in bytes. uint16_t size_bytes; uint16_t unknown6; }; #pragma pack(pop) static_assert(sizeof(PreparsedDataHeader) == 44, "PreparsedDataHeader has incorrect size"); #pragma pack(push, 1) struct PreparsedDataItem { // Usage page for |usage_minimum| and |usage_maximum|. uint16_t usage_page; // Report ID for the report containing this item. uint8_t report_id; // Bit offset from |byte_index|. uint8_t bit_index; // Bit width of a single field defined by this item. uint16_t bit_size; // The number of fields defined by this item. uint16_t report_count; // Byte offset from the start of the report containing this item, including // the report ID byte. uint16_t byte_index; // The total number of bits for all fields defined by this item. uint16_t bit_count; // The bit field for the corresponding main item in the HID report. This bit // field is defined in the Device Class Definition for HID v1.11 section // 6.2.2.5. // https://www.usb.org/document-library/device-class-definition-hid-111 uint32_t bit_field; uint32_t unknown; // Usage information for the collection containing this item. uint16_t link_usage_page; uint16_t link_usage; uint32_t unknown2[9]; // The usage range for this item. uint16_t usage_minimum; uint16_t usage_maximum; // The string descriptor index range associated with this item. If the item // has no string descriptors, |string_minimum| and |string_maximum| are set to // zero. uint16_t string_minimum; uint16_t string_maximum; // The designator index range associated with this item. If the item has no // designators, |designator_minimum| and |designator_maximum| are set to zero. uint16_t designator_minimum; uint16_t designator_maximum; // The data index range associated with this item. uint16_t data_index_minimum; uint16_t data_index_maximum; uint32_t unknown3; // The range of fields defined by this item in logical units. int32_t logical_minimum; int32_t logical_maximum; // The range of fields defined by this item in units defined by |unit| and // |unit_exponent|. If this item does not use physical units, // |physical_minimum| and |physical_maximum| are set to zero. int32_t physical_minimum; int32_t physical_maximum; // The unit definition for this item. The format for this definition is // described in the Device Class Definition for HID v1.11 section 6.2.2.7. // https://www.usb.org/document-library/device-class-definition-hid-111 uint32_t unit; uint32_t unit_exponent; }; #pragma pack(pop) static_assert(sizeof(PreparsedDataItem) == 104, "PreparsedDataItem has incorrect size"); bool ValidatePreparsedDataHeader(const PreparsedDataHeader& header) { static bool has_dumped_without_crashing = false; // _HIDP_PREPARSED_DATA objects are expected to start with a known constant // value. constexpr uint64_t kHidPreparsedDataMagic = 0x52444B2050646948; // Require a matching magic value. The details of _HIDP_PREPARSED_DATA are // proprietary and the magic constant may change. If DCHECKS are on, trigger // a CHECK failure and crash. Otherwise, generate a non-crash dump. DCHECK_EQ(header.magic, kHidPreparsedDataMagic); if (header.magic != kHidPreparsedDataMagic) { HID_LOG(ERROR) << "Unexpected magic value."; if (has_dumped_without_crashing) { base::debug::DumpWithoutCrashing(); has_dumped_without_crashing = true; } return false; } if (header.input_report_byte_length == 0 && header.input_item_count > 0) return false; if (header.output_report_byte_length == 0 && header.output_item_count > 0) return false; if (header.feature_report_byte_length == 0 && header.feature_item_count > 0) return false; // Calculate the expected total size of report items in the // _HIDP_PREPARSED_DATA object. Use the individual item counts for each report // type instead of the total |item_count|. In some cases additional items are // allocated but are not used for any reports. Unused items are excluded from // |item_count| but are included in the item counts for each report type and // contribute to the total size of the object. See crbug.com/1199890 for more // information. uint16_t total_item_size = (header.input_item_count + header.output_item_count + header.feature_item_count) * sizeof(PreparsedDataItem); if (total_item_size != header.size_bytes) return false; return true; } bool ValidatePreparsedDataItem(const PreparsedDataItem& item) { // Check that the item does not overlap with the report ID byte. if (item.byte_index == 0) return false; // Check that the bit index does not exceed the maximum bit index in one byte. if (item.bit_index >= CHAR_BIT) return false; // Check that the item occupies at least one bit in the report. if (item.report_count == 0 || item.bit_size == 0 || item.bit_count == 0) return false; return true; } HidServiceWin::PreparsedData::ReportItem MakeReportItemFromPreparsedData( const PreparsedDataItem& item) { size_t bit_index = (item.byte_index - 1) * CHAR_BIT + item.bit_index; return {item.report_id, item.bit_field, item.bit_size, item.report_count, item.usage_page, item.usage_minimum, item.usage_maximum, item.designator_minimum, item.designator_maximum, item.string_minimum, item.string_maximum, item.logical_minimum, item.logical_maximum, item.physical_minimum, item.physical_maximum, item.unit, item.unit_exponent, bit_index}; } } // namespace // static std::unique_ptr<HidPreparsedData> HidPreparsedData::Create( HANDLE device_handle) { PHIDP_PREPARSED_DATA preparsed_data; if (!HidD_GetPreparsedData(device_handle, &preparsed_data) || !preparsed_data) { HID_PLOG(EVENT) << "Failed to get device data"; return nullptr; } HIDP_CAPS capabilities; if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) { HID_PLOG(EVENT) << "Failed to get device capabilities"; HidD_FreePreparsedData(preparsed_data); return nullptr; } return base::WrapUnique(new HidPreparsedData(preparsed_data, capabilities)); } HidPreparsedData::HidPreparsedData(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS capabilities) : preparsed_data_(preparsed_data), capabilities_(capabilities) { DCHECK(preparsed_data_); } HidPreparsedData::~HidPreparsedData() { HidD_FreePreparsedData(preparsed_data_); } const HIDP_CAPS& HidPreparsedData::GetCaps() const { return capabilities_; } std::vector<HidServiceWin::PreparsedData::ReportItem> HidPreparsedData::GetReportItems(HIDP_REPORT_TYPE report_type) const { const auto& header = *reinterpret_cast<const PreparsedDataHeader*>(preparsed_data_); if (!ValidatePreparsedDataHeader(header)) return {}; size_t min_index; size_t item_count; switch (report_type) { case HidP_Input: min_index = 0; item_count = header.input_item_count; break; case HidP_Output: min_index = header.input_item_count; item_count = header.output_item_count; break; case HidP_Feature: min_index = header.input_item_count + header.output_item_count; item_count = header.feature_item_count; break; default: return {}; } if (item_count == 0) return {}; const auto* data = reinterpret_cast<const uint8_t*>(preparsed_data_); const auto* items = reinterpret_cast<const PreparsedDataItem*>( data + sizeof(PreparsedDataHeader)); std::vector<ReportItem> report_items; for (size_t i = min_index; i < min_index + item_count; ++i) { if (ValidatePreparsedDataItem(items[i])) report_items.push_back(MakeReportItemFromPreparsedData(items[i])); } return report_items; } } // namespace device
chromium/chromium
services/device/hid/hid_preparsed_data.cc
C++
bsd-3-clause
10,536
using ServiceStack.DataAnnotations; namespace ServiceStack.Common.Tests.Models { public class ModelWithIndexFields { public string Id { get; set; } [Index] public string Name { get; set; } public string AlbumId { get; set; } [Index(true)] public string UniqueName { get; set; } } }
firstsee/ServiceStack
tests/ServiceStack.Common.Tests/Models/ModelWithIndexFields.cs
C#
bsd-3-clause
300
/*jslint sloppy: true, nomen: true */ /*global exports:true */ /* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2013 Joseph Rollinson, jtrollinson@gmail.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Takes in a QtCookieJar and decorates it with useful functions. */ function decorateCookieJar(jar) { /* Allows one to add a cookie to the cookie jar from inside JavaScript */ jar.addCookie = function(cookie) { jar.addCookieFromMap(cookie); }; /* Getting and Setting jar.cookies gets and sets all the cookies in the * cookie jar. */ jar.__defineGetter__('cookies', function() { return this.cookiesToMap(); }); jar.__defineSetter__('cookies', function(cookies) { this.addCookiesFromMap(cookies); }); return jar; } /* Creates and decorates a new cookie jar. * path is the file path where Phantomjs will store the cookie jar persistently. * path is not mandatory. */ exports.create = function (path) { if (arguments.length < 1) { path = ""; } return decorateCookieJar(phantom.createCookieJar(path)); }; /* Exports the decorateCookieJar function */ exports.decorate = decorateCookieJar;
tianzhihen/phantomjs
src/modules/cookiejar.js
JavaScript
bsd-3-clause
2,651
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/passwords/bubble_controllers/move_to_account_store_bubble_controller.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/sync/sync_service_factory.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" #include "chrome/grit/generated_resources.h" #include "components/favicon/core/favicon_util.h" #include "components/password_manager/core/browser/password_feature_manager.h" #include "components/password_manager/core/browser/password_manager_features_util.h" #include "components/password_manager/core/common/password_manager_ui.h" #include "components/signin/public/base/consent_level.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" namespace metrics_util = password_manager::metrics_util; MoveToAccountStoreBubbleController::MoveToAccountStoreBubbleController( base::WeakPtr<PasswordsModelDelegate> delegate) : PasswordBubbleControllerBase( std::move(delegate), password_manager::metrics_util::AUTOMATIC_MOVE_TO_ACCOUNT_STORE) {} MoveToAccountStoreBubbleController::~MoveToAccountStoreBubbleController() { // Make sure the interactions are reported even if Views didn't notify the // controller about the bubble being closed. if (!interaction_reported_) OnBubbleClosing(); } void MoveToAccountStoreBubbleController::RequestFavicon( base::OnceCallback<void(const gfx::Image&)> favicon_ready_callback) { favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(GetProfile(), ServiceAccessType::EXPLICIT_ACCESS); favicon::GetFaviconImageForPageURL( favicon_service, delegate_->GetPendingPassword().url, favicon_base::IconType::kFavicon, base::BindOnce(&MoveToAccountStoreBubbleController::OnFaviconReady, base::Unretained(this), std::move(favicon_ready_callback)), &favicon_tracker_); } void MoveToAccountStoreBubbleController::OnFaviconReady( base::OnceCallback<void(const gfx::Image&)> favicon_ready_callback, const favicon_base::FaviconImageResult& result) { std::move(favicon_ready_callback).Run(result.image); } std::u16string MoveToAccountStoreBubbleController::GetTitle() const { return l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_MOVE_TITLE); } void MoveToAccountStoreBubbleController::AcceptMove() { dismissal_reason_ = metrics_util::CLICKED_ACCEPT; if (delegate_->GetPasswordFeatureManager()->IsOptedInForAccountStorage()) { // User has already opted in to the account store. Move without reauth. return delegate_->MovePasswordToAccountStore(); } // Otherwise, we should invoke the reauth flow before saving. return delegate_->AuthenticateUserForAccountStoreOptInAndMovePassword(); } void MoveToAccountStoreBubbleController::RejectMove() { dismissal_reason_ = metrics_util::CLICKED_NEVER; return delegate_->BlockMovingPasswordToAccountStore(); } gfx::Image MoveToAccountStoreBubbleController::GetProfileIcon(int size) { if (!GetProfile()) return gfx::Image(); signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(GetProfile()); if (!identity_manager) return gfx::Image(); AccountInfo primary_account_info = identity_manager->FindExtendedAccountInfo( identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin)); DCHECK(!primary_account_info.IsEmpty()); gfx::Image account_icon = primary_account_info.account_image; if (account_icon.IsEmpty()) { account_icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed( profiles::GetPlaceholderAvatarIconResourceID()); } return profiles::GetSizedAvatarIcon(account_icon, /*is_rectangle=*/true, /*width=*/size, /*height=*/size, profiles::SHAPE_CIRCLE); } void MoveToAccountStoreBubbleController::ReportInteractions() { Profile* profile = GetProfile(); if (!profile) return; metrics_util::LogMoveUIDismissalReason( dismissal_reason_, password_manager::features_util::ComputePasswordAccountStorageUserState( profile->GetPrefs(), SyncServiceFactory::GetForProfile(profile))); // TODO(crbug.com/1063852): Consider recording UKM here, via: // metrics_recorder_->RecordUIDismissalReason(dismissal_reason_) }
ric2b/Vivaldi-browser
chromium/chrome/browser/ui/passwords/bubble_controllers/move_to_account_store_bubble_controller.cc
C++
bsd-3-clause
4,892
module CatsHelper end
metaminded/cruddler
test/dummy/app/helpers/cats_helper.rb
Ruby
mit
22
function makeData() { "use strict"; return [makeRandomData(10), makeRandomData(10)]; } function run(svg, data, Plottable) { "use strict"; var largeX = function(d, i){ d.x = Math.pow(10, i); }; var bigNumbers = []; deepCopy(data[0], bigNumbers); bigNumbers.forEach(largeX); var dataseries1 = new Plottable.Dataset(bigNumbers); //Axis var xScale = new Plottable.Scales.Linear(); var yScale = new Plottable.Scales.Linear(); var xAxis = new Plottable.Axes.Numeric(xScale, "bottom"); var yAxis = new Plottable.Axes.Numeric(yScale, "left"); var IdTitle = new Plottable.Components.Label("Identity"); var GenTitle = new Plottable.Components.Label("General"); var FixTitle = new Plottable.Components.Label("Fixed"); var CurrTitle = new Plottable.Components.Label("Currency"); var PerTitle = new Plottable.Components.Label("Percentage"); var SITitle = new Plottable.Components.Label("SI"); var SSTitle = new Plottable.Components.Label("Short Scale"); var plot = new Plottable.Plots.Line().addDataset(dataseries1); plot.x(function(d) { return d.x; }, xScale).y(function(d) { return d.y; }, yScale); var basicTable = new Plottable.Components.Table([[yAxis, plot], [null, xAxis]]); var formatChoices = new Plottable.Components.Table([[IdTitle, GenTitle, FixTitle], [CurrTitle, null, PerTitle], [SITitle, null, SSTitle]]); var bigTable = new Plottable.Components.Table([[basicTable], [formatChoices]]); formatChoices.xAlignment("center"); bigTable.renderTo(svg); function useIdentityFormatter() { xAxis.formatter(Plottable.Formatters.identity(2.1)); yAxis.formatter(Plottable.Formatters.identity()); } function useGeneralFormatter() { xAxis.formatter(Plottable.Formatters.general(7)); yAxis.formatter(Plottable.Formatters.general(3)); } function useFixedFormatter() { xAxis.formatter(Plottable.Formatters.fixed(2.00)); yAxis.formatter(Plottable.Formatters.fixed(7.00)); } function useCurrencyFormatter() { xAxis.formatter(Plottable.Formatters.currency(3, "$", true)); yAxis.formatter(Plottable.Formatters.currency(3, "$", true)); } function usePercentageFormatter() { xAxis.formatter(Plottable.Formatters.percentage(12.3 - 11.3)); yAxis.formatter(Plottable.Formatters.percentage(2.5 + 1.5)); } function useSIFormatter() { xAxis.formatter(Plottable.Formatters.siSuffix(7)); yAxis.formatter(Plottable.Formatters.siSuffix(14)); } function useSSFormatter() { xAxis.formatter(Plottable.Formatters.shortScale(0)); yAxis.formatter(Plottable.Formatters.shortScale(0)); } new Plottable.Interactions.Click().onClick(useIdentityFormatter).attachTo(IdTitle); new Plottable.Interactions.Click().onClick(useGeneralFormatter).attachTo(GenTitle); new Plottable.Interactions.Click().onClick(useFixedFormatter).attachTo(FixTitle); new Plottable.Interactions.Click().onClick(useCurrencyFormatter).attachTo(CurrTitle); new Plottable.Interactions.Click().onClick(usePercentageFormatter).attachTo(PerTitle); new Plottable.Interactions.Click().onClick(useSIFormatter).attachTo(SITitle); new Plottable.Interactions.Click().onClick(useSSFormatter).attachTo(SSTitle); }
iobeam/plottable
quicktests/overlaying/tests/functional/formatter.js
JavaScript
mit
3,212
JsonRoutes.add('post', '/' + Meteor.settings.private.stripe.webhookEndpoint, function (req, res) { Letterpress.Services.Buy.handleEvent(req.body); JsonRoutes.sendResult(res, 200); });
FleetingClouds/Letterpress
server/api/webhooks-api.js
JavaScript
mit
187
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. import argparse import zipfile from os import getcwd, listdir, makedirs, mkdir, rename from os.path import isdir, isfile, join from shutil import move, rmtree from sys import exit as sys_exit from sys import path path.append("..") from platformio.util import exec_command, get_home_dir def _unzip_generated_file(mbed_dir, output_dir, mcu): filename = join( mbed_dir, "build", "export", "MBED_A1_emblocks_%s.zip" % mcu) variant_dir = join(output_dir, "variant", mcu) if isfile(filename): with zipfile.ZipFile(filename) as zfile: mkdir(variant_dir) zfile.extractall(variant_dir) for f in listdir(join(variant_dir, "MBED_A1")): if not f.lower().startswith("mbed"): continue move(join(variant_dir, "MBED_A1", f), variant_dir) rename(join(variant_dir, "MBED_A1.eix"), join(variant_dir, "%s.eix" % mcu)) rmtree(join(variant_dir, "MBED_A1")) else: print "Warning! Skipped board: %s" % mcu def buildlib(mbed_dir, mcu, lib="mbed"): build_command = [ "python", join(mbed_dir, "workspace_tools", "build.py"), "--mcu", mcu, "-t", "GCC_ARM" ] if lib is not "mbed": build_command.append(lib) build_result = exec_command(build_command, cwd=getcwd()) if build_result['returncode'] != 0: print "* %s doesn't support %s library!" % (mcu, lib) def copylibs(mbed_dir, output_dir): libs = ["dsp", "fat", "net", "rtos", "usb", "usb_host"] libs_dir = join(output_dir, "libs") makedirs(libs_dir) print "Moving generated libraries to framework dir..." for lib in libs: if lib == "net": move(join(mbed_dir, "build", lib, "eth"), libs_dir) continue move(join(mbed_dir, "build", lib), libs_dir) def main(mbed_dir, output_dir): print "Starting..." path.append(mbed_dir) from workspace_tools.export import gccarm if isdir(output_dir): print "Deleting previous framework dir..." rmtree(output_dir) settings_file = join(mbed_dir, "workspace_tools", "private_settings.py") if not isfile(settings_file): with open(settings_file, "w") as f: f.write("GCC_ARM_PATH = '%s'" % join(get_home_dir(), "packages", "toolchain-gccarmnoneeabi", "bin")) makedirs(join(output_dir, "variant")) mbed_libs = ["--rtos", "--dsp", "--fat", "--eth", "--usb", "--usb_host"] for mcu in set(gccarm.GccArm.TARGETS): print "Processing board: %s" % mcu buildlib(mbed_dir, mcu) for lib in mbed_libs: buildlib(mbed_dir, mcu, lib) result = exec_command( ["python", join(mbed_dir, "workspace_tools", "project.py"), "--mcu", mcu, "-i", "emblocks", "-p", "0", "-b"], cwd=getcwd() ) if result['returncode'] != 0: print "Unable to build the project for %s" % mcu continue _unzip_generated_file(mbed_dir, output_dir, mcu) copylibs(mbed_dir, output_dir) with open(join(output_dir, "boards.txt"), "w") as fp: fp.write("\n".join(sorted(listdir(join(output_dir, "variant"))))) print "Complete!" if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--mbed', help="The path to mbed framework") parser.add_argument('--output', help="The path to output directory") args = vars(parser.parse_args()) sys_exit(main(args["mbed"], args["output"]))
mseroczynski/platformio
scripts/mbed_to_package.py
Python
mit
3,667
<?php namespace Concrete\Core\Attribute; use Concrete\Core\Attribute\Key\SearchIndexer\SearchIndexerInterface; interface AttributeKeyInterface { /** * @return int */ public function getAttributeKeyID(); /** * @return string */ public function getAttributeKeyHandle(); /** * @return \Concrete\Core\Entity\Attribute\Type */ public function getAttributeType(); /** * @return bool */ public function isAttributeKeySearchable(); /** * @return SearchIndexerInterface */ public function getSearchIndexer(); /** * @return Controller */ public function getController(); }
jaromirdalecky/concrete5
concrete/src/Attribute/AttributeKeyInterface.php
PHP
mit
678
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from azure.cli.testsdk import ScenarioTest class CdnEdgeNodecenarioTest(ScenarioTest): def test_edge_node_crud(self): self.cmd('cdn edge-node list', checks=self.check('length(@)', 3))
yugangw-msft/azure-cli
src/azure-cli/azure/cli/command_modules/cdn/tests/latest/test_nodes_scenarios.py
Python
mit
543
<?php class PSU_Student_Finaid_Application_Factory { public function fetch_by_pidm_aidy_seqno( $pidm, $aidy, $seqno ) { $args = array( 'pidm' => $pidm, 'aidy' => $aidy, 'seqno' => $seqno, ); $where = array( 'rcrapp1_pidm = :pidm', 'rcrapp1_aidy_code = :aidy', 'rcrapp1_seq_no = :seqno', ); $rset = $this->query( $args, $where ); return new PSU_Student_Finaid_Application( $rset ); } public function query( $args, $where = array() ) { $where[] = '1=1'; $where_sql = ' AND ' . implode( ' AND ', $where ); $sql = " SELECT rcrapp4_fath_ssn, rcrapp4_fath_last_name, rcrapp4_fath_first_name_ini, rcrapp4_fath_birth_date, rcrapp4_moth_ssn, rcrapp4_moth_last_name, rcrapp4_moth_first_name_ini, rcrapp4_moth_birth_date FROM rcrapp1 LEFT JOIN rcrapp4 ON rcrapp1_aidy_code = rcrapp4_aidy_code AND rcrapp1_pidm = rcrapp4_pidm AND rcrapp1_infc_code = rcrapp4_infc_code AND rcrapp1_seq_no = rcrapp4_seq_no WHERE rcrapp1_infc_code = 'EDE' $where_sql "; $rset = PSU::db('banner')->GetRow( $sql, $args ); return $rset; } }
jbthibeault/plymouth-webapp
lib/PSU/Student/Finaid/Application/Factory.php
PHP
mit
1,109
/* This file is part of the KDE project Copyright (C) 2006-2007 Alfredo Beaumont Sainz <alfredo.beaumont@gmail.com> 2009 Jeremias Epperlein <jeeree@web.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "TokenElement.h" #include "AttributeManager.h" #include "FormulaCursor.h" #include "Dictionary.h" #include "GlyphElement.h" #include <KoXmlWriter.h> #include <KoXmlReader.h> #include <QPainter> #include <kdebug.h> TokenElement::TokenElement( BasicElement* parent ) : BasicElement( parent ) { m_stretchHorizontally = false; m_stretchVertically = false; } const QList<BasicElement*> TokenElement::childElements() const { // only return the mglyph elements QList<BasicElement*> tmpList; foreach( GlyphElement* tmp, m_glyphs ) tmpList << tmp; return tmpList; } void TokenElement::paint( QPainter& painter, AttributeManager* am ) { // set the painter to background color and paint it painter.setPen( am->colorOf( "mathbackground", this ) ); painter.setBrush( QBrush( painter.pen().color() ) ); painter.drawRect( QRectF( 0.0, 0.0, width(), height() ) ); // set the painter to foreground color and paint the text in the content path QColor color = am->colorOf( "mathcolor", this ); if (!color.isValid()) color = am->colorOf( "color", this ); painter.translate( m_xoffset, baseLine() ); if(m_stretchHorizontally || m_stretchVertically) painter.scale(width() / m_originalSize.width(), height() / m_originalSize.height()); painter.setPen( color ); painter.setBrush( QBrush( color ) ); painter.drawPath( m_contentPath ); } int TokenElement::endPosition() const { return m_rawString.length(); } void TokenElement::layout( const AttributeManager* am ) { m_offsets.erase(m_offsets.begin(),m_offsets.end()); m_offsets << 0.0; // Query the font to use m_font = am->font( this ); QFontMetricsF fm(m_font); // save the token in an empty path m_contentPath = QPainterPath(); /* Current bounding box. Note that the left can be negative, for italics etc */ QRectF boundingrect; if(m_glyphs.isEmpty()) {//optimize for the common case boundingrect = renderToPath(m_rawString, m_contentPath); for (int j = 0; j < m_rawString.length(); ++j) { m_offsets.append(fm.width(m_rawString.left(j+1))); } } else { // replace all the object replacement characters with glyphs // We have to keep track of the bounding box at all times QString chunk; int counter = 0; for( int i = 0; i < m_rawString.length(); i++ ) { if( m_rawString[ i ] != QChar::ObjectReplacementCharacter ) chunk.append( m_rawString[ i ] ); else { m_contentPath.moveTo(boundingrect.right(), 0); QRectF newbox = renderToPath( chunk, m_contentPath ); boundingrect.setRight( boundingrect.right() + newbox.right()); boundingrect.setTop( qMax(boundingrect.top(), newbox.top())); boundingrect.setBottom( qMax(boundingrect.bottom(), newbox.bottom())); qreal glyphoffset = m_offsets.last(); for (int j = 0; j < chunk.length(); ++j) { m_offsets << fm.width(chunk.left(j+1)) + glyphoffset; } m_contentPath.moveTo(boundingrect.right(), 0); newbox = m_glyphs[ counter ]->renderToPath( QString(), m_contentPath ); boundingrect.setRight( boundingrect.right() + newbox.right()); boundingrect.setTop( qMax(boundingrect.top(), newbox.top())); boundingrect.setBottom( qMax(boundingrect.bottom(), newbox.bottom())); m_offsets.append(newbox.width() + m_offsets.last()); counter++; chunk.clear(); } } if( !chunk.isEmpty() ) { m_contentPath.moveTo(boundingrect.right(), 0); QRectF newbox = renderToPath( chunk, m_contentPath ); boundingrect.setRight( boundingrect.right() + newbox.right()); boundingrect.setTop( qMax(boundingrect.top(), newbox.top())); boundingrect.setBottom( qMax(boundingrect.bottom(), newbox.bottom())); // qreal glyphoffset = m_offsets.last(); for (int j = 0; j < chunk.length(); ++j) { m_offsets << fm.width(chunk.left(j+1)) + m_offsets.last(); } } } //FIXME: This is only a temporary solution boundingrect=m_contentPath.boundingRect(); m_offsets.removeLast(); m_offsets.append(m_contentPath.boundingRect().right()); //The left side may be negative, because of italised letters etc. we need to adjust for this when painting //The qMax is just incase. The bounding box left should never be >0 m_xoffset = qMax(-boundingrect.left(), (qreal)0.0); // As the text is added to (0,0) the baseline equals the top edge of the // elements bounding rect, while translating it down the text's baseline moves too setBaseLine( -boundingrect.y() ); // set baseline accordingly setWidth( boundingrect.right() + m_xoffset ); setHeight( boundingrect.height() ); m_originalSize = QSizeF(width(), height()); } bool TokenElement::insertChild( int position, BasicElement* child ) { Q_UNUSED( position) Q_UNUSED( child ) //if( child && child->elementType() == Glyph ) { //m_rawString.insert( QChar( QChar::ObjectReplacementCharacter ) ); // m_glyphs.insert(); // return false; //} else { return false; //} } void TokenElement::insertGlyphs ( int position, QList< GlyphElement* > glyphs ) { for (int i=0; i < glyphs.length(); ++i) { m_glyphs.insert(position+i,glyphs[i]); } } bool TokenElement::insertText ( int position, const QString& text ) { m_rawString.insert (position,text); return true; } QList< GlyphElement* > TokenElement::glyphList ( int position, int length ) { QList<GlyphElement*> tmp; //find out, how many glyphs we have int counter=0; for (int i=position; i<position+length; ++i) { if (m_rawString[ position ] == QChar::ObjectReplacementCharacter) { counter++; } } int start=0; //find out where we should start removing glyphs if (counter>0) { for (int i=0; i<position; ++i) { if (m_rawString[position] == QChar::ObjectReplacementCharacter) { start++; } } } for (int i=start; i<start+counter; ++i) { tmp.append(m_glyphs.at(i)); } return tmp; } int TokenElement::removeText ( int position, int length ) { //find out, how many glyphs we have int counter=0; for (int i=position; i<position+length; ++i) { if (m_rawString[ position ] == QChar::ObjectReplacementCharacter) { counter++; } } int start=0; //find out where we should start removing glyphs if (counter>0) { for (int i=0; i<position; ++i) { if (m_rawString[position] == QChar::ObjectReplacementCharacter) { start++; } } } for (int i=start; i<start+counter; ++i) { m_glyphs.removeAt(i); } m_rawString.remove(position,length); return start; } bool TokenElement::setCursorTo(FormulaCursor& cursor, QPointF point) { int i = 0; cursor.setCurrentElement(this); if (cursorOffset(endPosition())<point.x()) { cursor.setPosition(endPosition()); return true; } //Find the letter we clicked on for( i = 1; i < endPosition(); ++i ) { if (point.x() < cursorOffset(i)) { break; } } //Find out, if we should place the cursor before or after the character if ((point.x()-cursorOffset(i-1))<(cursorOffset(i)-point.x())) { --i; } cursor.setPosition(i); return true; } QLineF TokenElement::cursorLine(int position) const { // inside tokens let the token calculate the cursor x offset qreal tmp = cursorOffset( position ); QPointF top = absoluteBoundingRect().topLeft() + QPointF( tmp, 0 ); QPointF bottom = top + QPointF( 0.0,height() ); return QLineF(top,bottom); } bool TokenElement::acceptCursor( const FormulaCursor& cursor ) { Q_UNUSED( cursor ) return true; } bool TokenElement::moveCursor(FormulaCursor& newcursor, FormulaCursor& oldcursor) { Q_UNUSED( oldcursor ) if ((newcursor.direction()==MoveUp) || (newcursor.direction()==MoveDown) || (newcursor.isHome() && newcursor.direction()==MoveLeft) || (newcursor.isEnd() && newcursor.direction()==MoveRight) ) { return false; } switch( newcursor.direction() ) { case MoveLeft: newcursor+=-1; break; case MoveRight: newcursor+=1; break; default: break; } return true; } qreal TokenElement::cursorOffset( const int position) const { return m_offsets[position]+m_xoffset; } QFont TokenElement::font() const { return m_font; } void TokenElement::setText ( const QString& text ) { removeText(0,m_rawString.length()); insertText(0,text); } const QString& TokenElement::text() { return m_rawString; } bool TokenElement::readMathMLContent( const KoXmlElement& element ) { // iterate over all child elements ( possible embedded glyphs ) and put the text // content in the m_rawString and mark glyph positions with // QChar::ObjectReplacementCharacter GlyphElement* tmpGlyph; KoXmlNode node = element.firstChild(); while( !node.isNull() ) { if( node.isElement() && node.toElement().tagName() == "mglyph" ) { tmpGlyph = new GlyphElement( this ); m_rawString.append( QChar( QChar::ObjectReplacementCharacter ) ); tmpGlyph->readMathML( node.toElement() ); m_glyphs.append(tmpGlyph); } else if( node.isElement() ) return false; /* else if (node.isEntityReference()) { Dictionary dict; m_rawString.append( dict.mapEntity( node.nodeName() ) ); } */ else { m_rawString.append( node.toText().data() ); } node = node.nextSibling(); } m_rawString = m_rawString.simplified(); return true; } void TokenElement::writeMathMLContent( KoXmlWriter* writer, const QString& ns ) const { // split the m_rawString into text content chunks that are divided by glyphs // which are represented as ObjectReplacementCharacter and write each chunk QStringList tmp = m_rawString.split( QChar( QChar::ObjectReplacementCharacter ) ); for ( int i = 0; i < tmp.count(); i++ ) { if( m_rawString.startsWith( QChar( QChar::ObjectReplacementCharacter ) ) ) { m_glyphs[ i ]->writeMathML( writer, ns ); if (i + 1 < tmp.count()) { writer->addTextNode( tmp[ i ] ); } } else { writer->addTextNode( tmp[ i ] ); if (i + 1 < tmp.count()) { m_glyphs[ i ]->writeMathML( writer, ns ); } } } } const QString TokenElement::writeElementContent() const { return m_rawString; }
yxl/emscripten-calligra-mobile
plugins/formulashape/elements/TokenElement.cpp
C++
gpl-2.0
12,060
<?php /** * Customer booking notification */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?> <?php do_action( 'woocommerce_email_header', $email_heading ); ?> <?php echo wpautop( wptexturize( $notification_message ) ); ?> <table cellspacing="0" cellpadding="6" style="width: 100%; border: 1px solid #eee;" border="1" bordercolor="#eee"> <tbody> <tr> <th scope="row" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Booked Product', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_product()->get_title(); ?></td> </tr> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking ID', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_id(); ?></td> </tr> <?php if ( $booking->has_resources() && ( $resource = $booking->get_resource() ) ) : ?> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking Type', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $resource->post_title; ?></td> </tr> <?php endif; ?> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking Start Date', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_start_date(); ?></td> </tr> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php _e( 'Booking End Date', 'woocommerce-bookings' ); ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $booking->get_end_date(); ?></td> </tr> <?php if ( $booking->has_persons() ) : ?> <?php foreach ( $booking->get_persons() as $id => $qty ) : if ( 0 === $qty ) { continue; } $person_type = ( 0 < $id ) ? get_the_title( $id ) : __( 'Person(s)', 'woocommerce-bookings' ); ?> <tr> <th style="text-align:left; border: 1px solid #eee;" scope="row"><?php echo $person_type; ?></th> <td style="text-align:left; border: 1px solid #eee;"><?php echo $qty; ?></td> </tr> <?php endforeach; ?> <?php endif; ?> </tbody> </table> <?php do_action( 'woocommerce_email_footer' ); ?>
snappermorgan/radaralley
wp-content/plugins/woocommerce-bookings/templates/emails/customer-booking-notification.php
PHP
gpl-2.0
2,299
#!/usr/bin/python # # Copyright 2010, 2011 wkhtmltopdf authors # # This file is part of wkhtmltopdf. # # wkhtmltopdf is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # wkhtmltopdf is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with wkhtmltopdf. If not, see <http:#www.gnu.org/licenses/>. from sys import argv, exit import re from datetime import date import os import difflib cdate = re.compile(r"Copyright ([0-9 ,]*) wkhtmltopdf authors") ifdef = re.compile(r"^[\n\r \t]*#ifndef __(.*)__[\t ]*\n#define __(\1)__[\t ]*\n") endif = re.compile(r"#endif.*[\r\n \t]*$") ws = re.compile(r"[ \t]*[\r\n]") branchspace = re.compile(r"([ \t\r\n])(for|if|while|switch|foreach)[\t \r\n]*\(") hangelse = re.compile(r"}[\r\n\t ]*(else)") braceup = re.compile(r"(\)|else)[\r\n\t ]*{") include = re.compile(r"(#include (\"[^\"]*\"|<[^>]*>)\n)+") def includesort(x): return "\n".join(sorted(x.group(0)[:-1].split("\n"))+[""]) changes=False progname="wkhtmltopdf" for path in argv[1:]: if path.split("/")[0] == "include": continue try: data = file(path).read() except: continue mo = cdate.search(data) years = set(mo.group(1).split(", ")) if mo else set() years.add(str(date.today().year)) ext = path.rsplit(".",2)[-1] header = "" cc = "//" if ext in ["hh","h","c","cc","cpp","inl", "inc"]: header += """// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*- // vi:set ts=4 sts=4 sw=4 noet : // """ elif ext in ["sh"]: header += "#!/bin/bash\n#\n" cc = "#" elif ext in ["py"]: header += "#!/usr/bin/python\n#\n" cc = "#" elif ext in ["pro","pri"]: cc = "#" else: continue header += """// Copyright %(years)s %(name)s authors // // This file is part of %(name)s. // // %(name)s is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // %(name)s is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with %(name)s. If not, see <http://www.gnu.org/licenses/>. """%{"years": (", ".join(sorted(list(years)))),"name":progname} if ext in ["c", "h", "inc"]: header = "/*" + header[2:-1] + " */\n\n" cc = " *" hexp = re.compile(r"^/\*([^*]*(\*[^/]))*[^*]*\*/[ \t\n]*"); else: #Strip away generated header hexp = re.compile("^(%s[^\\n]*\\n)*"%(cc)) ndata = hexp.sub("", data,1) ndata = ws.sub("\n", ndata)+"\n" if ext in ["hh","h","inl"]: s=0 e=-1 while ndata[s] in ['\r','\n',' ','\t']: s+=1 while ndata[e] in ['\r','\n',' ','\t']: e-=1 #Strip away generated ifdef if ifdef.search(ndata): ndata = endif.sub("",ifdef.sub("",ndata,1),1) s=0 e=-1 while ndata[s] in ['\r','\n',' ','\t']: s+=1 while ndata[e] in ['\r','\n',' ','\t']: e-=1 ndata=ndata[s:e+1].replace(" ",'\t') if ext in ["hh","h","c","cc","cpp","inl"]: ndata = branchspace.sub(r"\1\2 (",ndata) ndata = hangelse.sub("} else",ndata) ndata = braceup.sub(r"\1 {",ndata) ndata = include.sub(includesort, ndata) if ext in ["hh","h","inl"]: n = os.path.split(path)[-1].replace(".","_").replace(" ","_").upper() ndata = """#ifndef __%s__ #define __%s__ %s #endif %s__%s__%s"""%(n,n,ndata, "//" if ext != "h" else "/*", n, "" if ext != "h" else "*/") ndata = header.replace("//",cc)+ndata+"\n" if ndata != data: for x in difflib.unified_diff(data.split("\n"),ndata.split("\n"), "a/"+path, "b/"+path): print x changes=True file(path, "w").write(ndata) if changes: exit(1)
anouschka42/starktheatreprod
sites/all/libraries/wkhtmltopdf-0.12.0/scripts/sourcefix.py
Python
gpl-2.0
4,292
from __future__ import print_function, unicode_literals from praw.internal import _to_reddit_list from .helper import PRAWTest, betamax class InternalTest(PRAWTest): def test__to_reddit_list(self): output = _to_reddit_list('hello') self.assertEqual('hello', output) def test__to_reddit_list_with_list(self): output = _to_reddit_list(['hello']) self.assertEqual('hello', output) def test__to_reddit_list_with_empty_list(self): output = _to_reddit_list([]) self.assertEqual('', output) def test__to_reddit_list_with_big_list(self): output = _to_reddit_list(['hello', 'world']) self.assertEqual('hello,world', output) @betamax() def test__to_reddit_list_with_object(self): output = _to_reddit_list(self.r.get_subreddit(self.sr)) self.assertEqual(self.sr, output) def test__to_reddit_list_with_object_in_list(self): obj = self.r.get_subreddit(self.sr) output = _to_reddit_list([obj]) self.assertEqual(self.sr, output) def test__to_reddit_list_with_mix(self): obj = self.r.get_subreddit(self.sr) output = _to_reddit_list([obj, 'hello']) self.assertEqual("{0},{1}".format(self.sr, 'hello'), output)
dmarx/praw
tests/test_internal.py
Python
gpl-3.0
1,261
<?php /** *@package plugins.inletArmada */ class InletArmadaPlugin extends KalturaPlugin implements IKalturaObjectLoader, IKalturaEnumerator { const PLUGIN_NAME = 'inletArmada'; public static function getPluginName() { return self::PLUGIN_NAME; } /** * @param string $baseClass * @param string $enumValue * @param array $constructorArgs * @return object */ public static function loadObject($baseClass, $enumValue, array $constructorArgs = null) { if($baseClass == 'KOperationEngine' && $enumValue == KalturaConversionEngineType::INLET_ARMADA) { if(!isset($constructorArgs['params']) || !isset($constructorArgs['outFilePath'])) return null; return new KOperationEngineInletArmada("", $constructorArgs['outFilePath']); } if($baseClass == 'KDLOperatorBase' && $enumValue == self::getApiValue(InletArmadaConversionEngineType::INLET_ARMADA)) { return new KDLOperatorInletArmada($enumValue); } return null; } /** * @param string $baseClass * @param string $enumValue * @return string */ public static function getObjectClass($baseClass, $enumValue) { if($baseClass == 'KOperationEngine' && $enumValue == self::getApiValue(InletArmadaConversionEngineType::INLET_ARMADA)) return 'KOperationEngineInletArmada'; if($baseClass == 'KDLOperatorBase' && $enumValue == self::getConversionEngineCoreValue(InletArmadaConversionEngineType::INLET_ARMADA)) return 'KDLOperatorInletArmada'; return null; } /** * @return array<string> list of enum classes names that extend the base enum name */ public static function getEnums($baseEnumName = null) { if(is_null($baseEnumName)) return array('InletArmadaConversionEngineType'); if($baseEnumName == 'conversionEngineType') return array('InletArmadaConversionEngineType'); return array(); } /** * @return int id of dynamic enum in the DB. */ public static function getConversionEngineCoreValue($valueName) { $value = self::getPluginName() . IKalturaEnumerator::PLUGIN_VALUE_DELIMITER . $valueName; return kPluginableEnumsManager::apiToCore('conversionEngineType', $value); } /** * @return string external API value of dynamic enum. */ public static function getApiValue($valueName) { return self::getPluginName() . IKalturaEnumerator::PLUGIN_VALUE_DELIMITER . $valueName; } }
ratliff/server
plugins/transcoding/inlet_armada/InletArmadaPlugin.php
PHP
agpl-3.0
2,348
require 'spec_helper' describe Spree::Admin::OverviewController do include AuthenticationWorkflow context "loading overview" do let(:user) { create_enterprise_user(enterprise_limit: 2) } before do controller.stub spree_current_user: user end context "when user owns only one enterprise" do let!(:enterprise) { create(:distributor_enterprise, owner: user) } context "when the referer is not an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/some_other_path' } context "and the enterprise has sells='unspecified'" do before do enterprise.update_attribute(:sells, "unspecified") end it "redirects to the welcome page for the enterprise" do spree_get :index response.should redirect_to welcome_admin_enterprise_path(enterprise) end end context "and the enterprise does not have sells='unspecified'" do it "renders the single enterprise dashboard" do spree_get :index response.should render_template "single_enterprise_dashboard" end end end context "when the refer is an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/admin' } it "renders the single enterprise dashboard" do spree_get :index response.should render_template "single_enterprise_dashboard" end end end context "when user owns multiple enterprises" do let!(:enterprise1) { create(:distributor_enterprise, owner: user) } let!(:enterprise2) { create(:distributor_enterprise, owner: user) } context "when the referer is not an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/some_other_path' } context "and at least one owned enterprise has sells='unspecified'" do before do enterprise1.update_attribute(:sells, "unspecified") end it "redirects to the enterprises index" do spree_get :index response.should redirect_to admin_enterprises_path end end context "and no owned enterprises have sells='unspecified'" do it "renders the multiple enterprise dashboard" do spree_get :index response.should render_template "multi_enterprise_dashboard" end end end context "when the refer is an admin page" do before { @request.env['HTTP_REFERER'] = 'http://test.com/admin' } it "renders the multiple enterprise dashboard" do spree_get :index response.should render_template "multi_enterprise_dashboard" end end end end end
levent/openfoodnetwork
spec/controllers/spree/admin/overview_controller_spec.rb
Ruby
agpl-3.0
2,772
/* * 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. */ package org.apache.camel.component.seda; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.junit.jupiter.api.Test; public class SedaSizeTest extends ContextTestSupport { @Test public void testSeda() throws Exception { getMockEndpoint("mock:bar").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("seda:bar"); from("seda:bar?size=5").to("mock:bar"); } }; } }
nikhilvibhav/camel
core/camel-core/src/test/java/org/apache/camel/component/seda/SedaSizeTest.java
Java
apache-2.0
1,588
require 'rubygems' require 'minitest/autorun' require 'rdoc/ri' require 'rdoc/markup' require 'tmpdir' require 'fileutils' class TestRDocRIStore < MiniTest::Unit::TestCase def setup RDoc::TopLevel.reset @tmpdir = File.join Dir.tmpdir, "test_rdoc_ri_store_#{$$}" @s = RDoc::RI::Store.new @tmpdir @top_level = RDoc::TopLevel.new 'file.rb' @klass = @top_level.add_class RDoc::NormalClass, 'Object' @klass.comment = 'original' @cmeth = RDoc::AnyMethod.new nil, 'cmethod' @cmeth.singleton = true @meth = RDoc::AnyMethod.new nil, 'method' @meth_bang = RDoc::AnyMethod.new nil, 'method!' @attr = RDoc::Attr.new nil, 'attr', 'RW', '' @klass.add_method @cmeth @klass.add_method @meth @klass.add_method @meth_bang @klass.add_attribute @attr @nest_klass = @klass.add_class RDoc::NormalClass, 'SubClass' @nest_meth = RDoc::AnyMethod.new nil, 'method' @nest_incl = RDoc::Include.new 'Incl', '' @nest_klass.add_method @nest_meth @nest_klass.add_include @nest_incl @RM = RDoc::Markup end def teardown FileUtils.rm_rf @tmpdir end def assert_cache imethods, cmethods, attrs, modules, ancestors = {} expected = { :class_methods => cmethods, :instance_methods => imethods, :attributes => attrs, :modules => modules, :ancestors => ancestors } assert_equal expected, @s.cache end def assert_directory path assert File.directory?(path), "#{path} is not a directory" end def assert_file path assert File.file?(path), "#{path} is not a file" end def test_attributes @s.cache[:attributes]['Object'] = %w[attr] expected = { 'Object' => %w[attr] } assert_equal expected, @s.attributes end def test_class_file assert_equal File.join(@tmpdir, 'Object', 'cdesc-Object.ri'), @s.class_file('Object') assert_equal File.join(@tmpdir, 'Object', 'SubClass', 'cdesc-SubClass.ri'), @s.class_file('Object::SubClass') end def test_class_methods @s.cache[:class_methods]['Object'] = %w[method] expected = { 'Object' => %w[method] } assert_equal expected, @s.class_methods end def test_class_path assert_equal File.join(@tmpdir, 'Object'), @s.class_path('Object') assert_equal File.join(@tmpdir, 'Object', 'SubClass'), @s.class_path('Object::SubClass') end def test_friendly_path @s.path = @tmpdir @s.type = nil assert_equal @s.path, @s.friendly_path @s.type = :extra assert_equal @s.path, @s.friendly_path @s.type = :system assert_equal "ruby core", @s.friendly_path @s.type = :site assert_equal "ruby site", @s.friendly_path @s.type = :home assert_equal "~/.ri", @s.friendly_path @s.type = :gem @s.path = "#{@tmpdir}/gem_repository/doc/gem_name-1.0/ri" assert_equal "gem gem_name-1.0", @s.friendly_path end def test_instance_methods @s.cache[:instance_methods]['Object'] = %w[method] expected = { 'Object' => %w[method] } assert_equal expected, @s.instance_methods end def test_load_cache cache = { :methods => %w[Object#method], :modules => %w[Object], } Dir.mkdir @tmpdir open File.join(@tmpdir, 'cache.ri'), 'wb' do |io| Marshal.dump cache, io end @s.load_cache assert_equal cache, @s.cache end def test_load_cache_no_cache cache = { :ancestors => {}, :attributes => {}, :class_methods => {}, :instance_methods => {}, :modules => [], } @s.load_cache assert_equal cache, @s.cache end def test_load_class @s.save_class @klass assert_equal @klass, @s.load_class('Object') end def test_load_method_bang @s.save_method @klass, @meth_bang meth = @s.load_method('Object', '#method!') assert_equal @meth_bang, meth end def test_method_file assert_equal File.join(@tmpdir, 'Object', 'method-i.ri'), @s.method_file('Object', 'Object#method') assert_equal File.join(@tmpdir, 'Object', 'method%21-i.ri'), @s.method_file('Object', 'Object#method!') assert_equal File.join(@tmpdir, 'Object', 'SubClass', 'method%21-i.ri'), @s.method_file('Object::SubClass', 'Object::SubClass#method!') assert_equal File.join(@tmpdir, 'Object', 'method-c.ri'), @s.method_file('Object', 'Object::method') end def test_save_cache @s.save_class @klass @s.save_method @klass, @meth @s.save_method @klass, @cmeth @s.save_class @nest_klass @s.save_cache assert_file File.join(@tmpdir, 'cache.ri') expected = { :attributes => { 'Object' => ['attr_accessor attr'] }, :class_methods => { 'Object' => %w[cmethod] }, :instance_methods => { 'Object' => %w[method] }, :modules => %w[Object Object::SubClass], :ancestors => { 'Object' => %w[Object], 'Object::SubClass' => %w[Incl Object], }, } open File.join(@tmpdir, 'cache.ri'), 'rb' do |io| cache = Marshal.load io.read assert_equal expected, cache end end def test_save_cache_duplicate_methods @s.save_method @klass, @meth @s.save_method @klass, @meth @s.save_cache assert_cache({ 'Object' => %w[method] }, {}, {}, []) end def test_save_class @s.save_class @klass assert_directory File.join(@tmpdir, 'Object') assert_file File.join(@tmpdir, 'Object', 'cdesc-Object.ri') assert_cache({}, {}, { 'Object' => ['attr_accessor attr'] }, %w[Object], 'Object' => %w[Object]) assert_equal @klass, @s.load_class('Object') end def test_save_class_basic_object @klass.instance_variable_set :@superclass, nil @s.save_class @klass assert_directory File.join(@tmpdir, 'Object') assert_file File.join(@tmpdir, 'Object', 'cdesc-Object.ri') assert_cache({}, {}, { 'Object' => ['attr_accessor attr'] }, %w[Object], 'Object' => %w[]) assert_equal @klass, @s.load_class('Object') end def test_save_class_merge @s.save_class @klass klass = RDoc::NormalClass.new 'Object' klass.comment = 'new class' s = RDoc::RI::Store.new @tmpdir s.save_class klass s = RDoc::RI::Store.new @tmpdir document = @RM::Document.new( @RM::Paragraph.new('original'), @RM::Paragraph.new('new class')) assert_equal document, s.load_class('Object').comment end def test_save_class_methods @s.save_class @klass assert_directory File.join(@tmpdir, 'Object') assert_file File.join(@tmpdir, 'Object', 'cdesc-Object.ri') assert_cache({}, {}, { 'Object' => ['attr_accessor attr'] }, %w[Object], 'Object' => %w[Object]) assert_equal @klass, @s.load_class('Object') end def test_save_class_nested @s.save_class @nest_klass assert_directory File.join(@tmpdir, 'Object', 'SubClass') assert_file File.join(@tmpdir, 'Object', 'SubClass', 'cdesc-SubClass.ri') assert_cache({}, {}, {}, %w[Object::SubClass], 'Object::SubClass' => %w[Incl Object]) end def test_save_method @s.save_method @klass, @meth assert_directory File.join(@tmpdir, 'Object') assert_file File.join(@tmpdir, 'Object', 'method-i.ri') assert_cache({ 'Object' => %w[method] }, {}, {}, []) assert_equal @meth, @s.load_method('Object', '#method') end def test_save_method_nested @s.save_method @nest_klass, @nest_meth assert_directory File.join(@tmpdir, 'Object', 'SubClass') assert_file File.join(@tmpdir, 'Object', 'SubClass', 'method-i.ri') assert_cache({ 'Object::SubClass' => %w[method] }, {}, {}, []) end end
racker/omnibus
source/ruby-1.9.2-p180/test/rdoc/test_rdoc_ri_store.rb
Ruby
apache-2.0
7,781
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.dataflow.core; import org.springframework.cloud.deployer.spi.core.AppDeploymentRequest; import org.springframework.core.style.ToStringCreator; /** * Description of an execution of a task including resource to be executed and how it was configured via Spring Cloud * Data Flow * * @author Mark Pollack * @author Michael Minella * @since 2.3 */ public class TaskManifest { private AppDeploymentRequest taskDeploymentRequest; private String platformName; /** * Name of the platform the related task execution was executed on. * * @return name of the platform */ public String getPlatformName() { return platformName; } /** * Name of the platform the related task execution was executed on. * * @param platformName platform name */ public void setPlatformName(String platformName) { this.platformName = platformName; } /** * {@code AppDeploymentRequest} representing the task being executed * * @return {@code AppDeploymentRequest} */ public AppDeploymentRequest getTaskDeploymentRequest() { return taskDeploymentRequest; } /** * Task deployment * * @param taskDeploymentRequest {@code AppDeploymentRequest} */ public void setTaskDeploymentRequest(AppDeploymentRequest taskDeploymentRequest) { this.taskDeploymentRequest = taskDeploymentRequest; } public String toString() { return (new ToStringCreator(this)).append("taskDeploymentRequest", this.taskDeploymentRequest).append("platformName", this.platformName).toString(); } }
mminella/spring-cloud-data
spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/TaskManifest.java
Java
apache-2.0
2,150
// Copyright 2015 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package utils import ( "os" jww "github.com/spf13/jwalterweatherman" ) func CheckErr(err error, s ...string) { if err != nil { if len(s) == 0 { jww.CRITICAL.Println(err) } else { for _, message := range s { jww.ERROR.Println(message) } jww.ERROR.Println(err) } } } func StopOnErr(err error, s ...string) { if err != nil { if len(s) == 0 { newMessage := err.Error() // Printing an empty string results in a error with // no message, no bueno. if newMessage != "" { jww.CRITICAL.Println(newMessage) } } else { for _, message := range s { if message != "" { jww.CRITICAL.Println(message) } } } os.Exit(-1) } }
coderzh/hugo
utils/utils.go
GO
apache-2.0
1,295
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; namespace Microsoft.CodeAnalysis.Rebuild { public static class Extensions { internal static void SkipNullTerminator(ref this BlobReader blobReader) { var b = blobReader.ReadByte(); if (b != '\0') { throw new InvalidDataException(string.Format(RebuildResources.Encountered_unexpected_byte_0_when_expecting_a_null_terminator, b)); } } public static MetadataReader? GetEmbeddedPdbMetadataReader(this PEReader peReader) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(x => x.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); if (entry.Type == DebugDirectoryEntryType.Unknown) { return null; } var provider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry); return provider.GetMetadataReader(); } } }
physhi/roslyn
src/Compilers/Core/Rebuild/Extensions.cs
C#
apache-2.0
1,272
binomial_fit.coef()
madmax983/h2o-3
h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_model_output_20.py
Python
apache-2.0
19
<?php class Kwc_Trl_DateHelper_DateTime_Component extends Kwc_Abstract { }
kaufmo/koala-framework
tests/Kwc/Trl/DateHelper/DateTime/Component.php
PHP
bsd-2-clause
75
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include "base/test/task_environment.h" #include "media/base/svc_scalability_mode.h" #include "media/base/video_codecs.h" #include "media/video/mock_gpu_video_accelerator_factories.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.h" #include "third_party/webrtc/api/video_codecs/sdp_video_format.h" #include "third_party/webrtc/api/video_codecs/video_encoder_factory.h" using ::testing::Return; namespace blink { namespace { constexpr webrtc::VideoEncoderFactory::CodecSupport kSupportedPowerEfficient = { true, true}; constexpr webrtc::VideoEncoderFactory::CodecSupport kUnsupported = {false, false}; constexpr gfx::Size kMaxResolution = {1920, 1080}; constexpr uint32_t kMaxFramerateNumerator = 30; constexpr uint32_t kMaxFramerateDenominator = 1; const std::vector<media::SVCScalabilityMode> kScalabilityModes = { media::SVCScalabilityMode::kL1T2, media::SVCScalabilityMode::kL1T3}; bool Equals(webrtc::VideoEncoderFactory::CodecSupport a, webrtc::VideoEncoderFactory::CodecSupport b) { return a.is_supported == b.is_supported && a.is_power_efficient == b.is_power_efficient; } class MockGpuVideoEncodeAcceleratorFactories : public media::MockGpuVideoAcceleratorFactories { public: MockGpuVideoEncodeAcceleratorFactories() : MockGpuVideoAcceleratorFactories(nullptr) {} absl::optional<media::VideoEncodeAccelerator::SupportedProfiles> GetVideoEncodeAcceleratorSupportedProfiles() override { media::VideoEncodeAccelerator::SupportedProfiles profiles = { {media::VP8PROFILE_ANY, kMaxResolution, kMaxFramerateNumerator, kMaxFramerateDenominator, kScalabilityModes}, {media::VP9PROFILE_PROFILE0, kMaxResolution, kMaxFramerateNumerator, kMaxFramerateDenominator, kScalabilityModes}}; return profiles; } }; } // anonymous namespace typedef webrtc::SdpVideoFormat Sdp; typedef webrtc::SdpVideoFormat::Parameters Params; class RTCVideoEncoderFactoryTest : public ::testing::Test { public: RTCVideoEncoderFactoryTest() : encoder_factory_(&mock_gpu_factories_) {} protected: base::test::TaskEnvironment task_environment_; MockGpuVideoEncodeAcceleratorFactories mock_gpu_factories_; RTCVideoEncoderFactory encoder_factory_; }; TEST_F(RTCVideoEncoderFactoryTest, QueryCodecSupportNoSvc) { EXPECT_CALL(mock_gpu_factories_, IsEncoderSupportKnown()) .WillRepeatedly(Return(true)); // VP8, H264, and VP9 profile 0 are supported. EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport( Sdp("VP8"), /*scalability_mode=*/absl::nullopt), kSupportedPowerEfficient)); EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport( Sdp("VP9"), /*scalability_mode=*/absl::nullopt), kSupportedPowerEfficient)); // H264, VP9 profile 2 and AV1 are unsupported. EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport( Sdp("H264", Params{{"level-asymmetry-allowed", "1"}, {"packetization-mode", "1"}, {"profile-level-id", "42001f"}}), /*scalability_mode=*/absl::nullopt), kUnsupported)); EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport( Sdp("VP9", Params{{"profile-id", "2"}}), /*scalability_mode=*/absl::nullopt), kUnsupported)); EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport( Sdp("AV1"), /*scalability_mode=*/absl::nullopt), kUnsupported)); } TEST_F(RTCVideoEncoderFactoryTest, QueryCodecSupportSvc) { EXPECT_CALL(mock_gpu_factories_, IsEncoderSupportKnown()) .WillRepeatedly(Return(true)); // Test supported modes. EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport(Sdp("VP8"), "L1T2"), kSupportedPowerEfficient)); EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport(Sdp("VP9"), "L1T3"), kSupportedPowerEfficient)); // Test unsupported modes. EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport(Sdp("AV1"), "L2T1"), kUnsupported)); EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport(Sdp("H264"), "L1T2"), kUnsupported)); EXPECT_TRUE(Equals(encoder_factory_.QueryCodecSupport(Sdp("VP8"), "L3T3"), kUnsupported)); } } // namespace blink
nwjs/chromium.src
third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory_test.cc
C++
bsd-3-clause
4,887
/* Main.java -- a standalone viewer for Java applets Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.classpath.tools.appletviewer; import gnu.classpath.tools.getopt.ClasspathToolParser; import gnu.classpath.tools.getopt.Option; import gnu.classpath.tools.getopt.OptionException; import gnu.classpath.tools.getopt.OptionGroup; import gnu.classpath.tools.getopt.Parser; import java.applet.Applet; import java.awt.Dimension; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ResourceBundle; class Main { /** * The localized strings are kept in a separate file. */ public static final ResourceBundle messages = ResourceBundle.getBundle ("gnu.classpath.tools.appletviewer.MessagesBundle"); private static HashMap classLoaderCache = new HashMap(); private static ClassLoader getClassLoader(URL codebase, ArrayList archives) { // Should load class loader each time. It is possible that there // are more than one applet to be loaded with different archives. AppletClassLoader loader = new AppletClassLoader(codebase, archives); classLoaderCache.put(codebase, loader); return loader; } private static String code = null; private static String codebase = null; private static String archive = null; private static List parameters = new ArrayList(); private static Dimension dimensions = new Dimension(-1, -1); private static String pipeInName = null; private static String pipeOutName = null; private static boolean pluginMode = false; private static Parser parser = null; static Applet createApplet(AppletTag tag) { Applet applet = null; try { ClassLoader loader = getClassLoader(tag.prependCodeBase(""), tag.getArchives()); String code = tag.getCode(); if (code.endsWith(".class")) code = code.substring(0, code.length() - 6).replace('/', '.'); Class c = loader.loadClass(code); applet = (Applet) c.newInstance(); } catch (Exception e) { e.printStackTrace(); } if (applet == null) applet = new ErrorApplet("Error loading applet"); return applet; } protected static boolean verbose; /** * The main method starting the applet viewer. * * @param args the arguments given on the command line. * * @exception IOException if an error occurs. */ public static void main(String[] args) throws IOException { parser = new ClasspathToolParser("appletviewer", true); parser.setHeader("usage: appletviewer [OPTION] -code CODE | URL..."); OptionGroup attributeGroup = new OptionGroup("Applet tag options"); attributeGroup.add(new Option("code", Main.messages.getString ("gcjwebplugin.code_description"), "CODE") { public void parsed(String argument) throws OptionException { code = argument; } }); attributeGroup.add(new Option("codebase", Main.messages.getString ("gcjwebplugin.codebase_description"), "CODEBASE") { public void parsed(String argument) throws OptionException { codebase = argument; } }); attributeGroup.add(new Option("archive", Main.messages.getString ("gcjwebplugin.archive_description"), "ARCHIVE") { public void parsed(String argument) throws OptionException { archive = argument; } }); attributeGroup.add(new Option("width", Main.messages.getString ("gcjwebplugin.width_description"), "WIDTH") { public void parsed(String argument) throws OptionException { dimensions.width = Integer.parseInt(argument); } }); attributeGroup.add(new Option("height", Main.messages.getString ("gcjwebplugin.height_description"), "HEIGHT") { public void parsed(String argument) throws OptionException { dimensions.height = Integer.parseInt(argument); } }); attributeGroup.add(new Option("param", Main.messages.getString ("gcjwebplugin.param_description"), "NAME,VALUE") { public void parsed(String argument) throws OptionException { parameters.add(argument); } }); OptionGroup pluginGroup = new OptionGroup("Plugin option"); pluginGroup.add(new Option("plugin", Main.messages.getString ("gcjwebplugin.plugin_description"), "INPUT,OUTPUT") { public void parsed(String argument) throws OptionException { pluginMode = true; int comma = argument.indexOf(','); pipeInName = argument.substring(0, comma); pipeOutName = argument.substring(comma + 1); } }); OptionGroup debuggingGroup = new OptionGroup("Debugging option"); debuggingGroup.add(new Option("verbose", Main.messages.getString ("gcjwebplugin.verbose_description"), (String) null) { public void parsed(String argument) throws OptionException { verbose = true; } }); OptionGroup compatibilityGroup = new OptionGroup("Compatibility options"); compatibilityGroup.add(new Option("debug", Main.messages.getString ("gcjwebplugin.debug_description"), (String) null) { public void parsed(String argument) throws OptionException { // Currently ignored. } }); compatibilityGroup.add(new Option("encoding", Main.messages.getString ("gcjwebplugin.encoding_description"), "CHARSET") { public void parsed(String argument) throws OptionException { // FIXME: We should probably be using // java.nio.charset.CharsetDecoder to handle the encoding. What // is the status of Classpath's implementation? } }); parser.add(attributeGroup); parser.add(pluginGroup); parser.add(debuggingGroup); parser.add(compatibilityGroup); String[] urls = parser.parse(args); // Print arguments. printArguments(args); args = urls; if (dimensions.height < 0) dimensions.height = 200; if (dimensions.width < 0) dimensions.width = (int) (1.6 * dimensions.height); //System.setSecurityManager(new AppletSecurityManager(pluginMode)); if (pluginMode) { InputStream in; OutputStream out; in = new FileInputStream(pipeInName); out = new FileOutputStream(pipeOutName); PluginAppletViewer.start(in, out); } else { if (code == null) { // The --code option wasn't given and there are no URL // arguments so we have nothing to work with. if (args.length == 0) { System.err.println(Main.messages.getString("gcjwebplugin.no_input_files")); System.exit(1); } // Create a standalone appletviewer from a list of URLs. new StandaloneAppletViewer(args); } else { // Create a standalone appletviewer from the --code // option. new StandaloneAppletViewer(code, codebase, archive, parameters, dimensions); } } } static void printArguments(String[] args) { if (verbose) { System.out.println("raw arguments:"); for (int i = 0; i < args.length; i++) System.out.println(" " + args[i]); } } }
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/libjava/classpath/tools/gnu/classpath/tools/appletviewer/Main.java
Java
bsd-3-clause
9,974
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/audio/scoped_loop_observer.h" #include "base/bind.h" #include "base/synchronization/waitable_event.h" namespace media { ScopedLoopObserver::ScopedLoopObserver( const scoped_refptr<base::MessageLoopProxy>& loop) : loop_(loop) { ObserveLoopDestruction(true, NULL); } ScopedLoopObserver::~ScopedLoopObserver() { ObserveLoopDestruction(false, NULL); } void ScopedLoopObserver::ObserveLoopDestruction(bool enable, base::WaitableEvent* done) { // Note: |done| may be NULL. if (loop_->BelongsToCurrentThread()) { MessageLoop* loop = MessageLoop::current(); if (enable) { loop->AddDestructionObserver(this); } else { loop->RemoveDestructionObserver(this); } } else { base::WaitableEvent event(false, false); if (loop_->PostTask(FROM_HERE, base::Bind(&ScopedLoopObserver::ObserveLoopDestruction, base::Unretained(this), enable, &event))) { event.Wait(); } else { // The message loop's thread has already terminated, so no need to wait. } } if (done) done->Signal(); } } // namespace media.
timopulkkinen/BubbleFish
media/audio/scoped_loop_observer.cc
C++
bsd-3-clause
1,340
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "skia/ext/fontmgr_default.h" #include "third_party/skia/include/core/SkFontMgr.h" namespace { SkDEBUGCODE(bool g_factory_called;) // This is a purposefully leaky pointer that has ownership of the FontMgr. SkFontMgr* g_fontmgr_override = nullptr; } // namespace namespace skia { void OverrideDefaultSkFontMgr(sk_sp<SkFontMgr> fontmgr) { SkASSERT(!g_factory_called); SkSafeUnref(g_fontmgr_override); g_fontmgr_override = fontmgr.release(); } } // namespace skia SK_API sk_sp<SkFontMgr> SkFontMgr::Factory() { SkDEBUGCODE(g_factory_called = true;); return g_fontmgr_override ? sk_ref_sp(g_fontmgr_override) : skia::CreateDefaultSkFontMgr(); }
nwjs/chromium.src
skia/ext/fontmgr_default.cc
C++
bsd-3-clause
873
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.IO; namespace CefSharp { //TODO: Eval naming for this interface, not happy with this name public interface IResourceHandler { /// <summary> /// Processes request asynchronously. /// </summary> /// <param name="request">The request object.</param> /// <param name="callback">The callback used to Continue or Cancel the request (async).</param> /// <returns>true if the request is handled, false otherwise.</returns> bool ProcessRequestAsync(IRequest request, ICallback callback); Stream GetResponse(IResponse response, out long responseLength, out string redirectUrl); } }
joshvera/CefSharp
CefSharp/IResourceHandler.cs
C#
bsd-3-clause
844
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chromecast.shell; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityNodeProvider; import android.widget.FrameLayout; import androidx.annotation.Nullable; import org.chromium.base.Log; import org.chromium.chromecast.base.CastSwitches; /** * View for displaying a WebContents in CastShell. * * <p>Intended to be used with {@link android.app.Presentation}. * * <p> * Typically, this class is controlled by CastContentWindowAndroid through * CastWebContentsSurfaceHelper. If the CastContentWindowAndroid is destroyed, * CastWebContentsView should be removed from the activity holding it. * Similarily, if the view is removed from a activity or the activity holding * it is destroyed, CastContentWindowAndroid should be notified by intent. */ public class CastWebContentsView extends FrameLayout { private static final String TAG = "CastWebContentV"; private CastWebContentsSurfaceHelper mSurfaceHelper; public CastWebContentsView(Context context) { super(context); initView(); } private void initView() { FrameLayout.LayoutParams matchParent = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); addView(LayoutInflater.from(getContext()) .inflate(R.layout.cast_web_contents_activity, null), matchParent); // Adds a transparent view on top to allow a highlight rectangule to be drawn when // accessibility is turned on. addView(new View(getContext()), matchParent); } public void onStart(Bundle startArgumentsBundle) { Log.d(TAG, "onStart"); if (mSurfaceHelper != null) { return; } mSurfaceHelper = new CastWebContentsSurfaceHelper( CastWebContentsScopes.onLayoutView(getContext(), findViewById(R.id.web_contents_container), CastSwitches.getSwitchValueColor( CastSwitches.CAST_APP_BACKGROUND_COLOR, Color.BLACK), this ::getHostWindowToken), (Uri uri) -> sendIntentSync(CastWebContentsIntentUtils.onWebContentStopped(uri))); CastWebContentsSurfaceHelper.StartParams params = CastWebContentsSurfaceHelper.StartParams.fromBundle(startArgumentsBundle); if (params == null) return; mSurfaceHelper.onNewStartParams(params); } public void onResume() { Log.d(TAG, "onResume"); } public void onPause() { Log.d(TAG, "onPause"); } public void onStop() { Log.d(TAG, "onStop"); if (mSurfaceHelper != null) { mSurfaceHelper.onDestroy(); } } @Nullable protected IBinder getHostWindowToken() { return getWindowToken(); } private void sendIntentSync(Intent in) { CastWebContentsIntentUtils.getLocalBroadcastManager().sendBroadcastSync(in); } @Override public void setAccessibilityDelegate(AccessibilityDelegate delegate) { View contentView = getContentView(); if (contentView != null) { contentView.setAccessibilityDelegate(delegate); } else { Log.w(TAG, "Content view is null!"); } } @Override public boolean onHoverEvent(MotionEvent event) { View contentView = getContentView(); if (contentView != null) { return contentView.onHoverEvent(event); } else { Log.w(TAG, "Content view is null!"); return false; } } public AccessibilityNodeProvider getWebContentsAccessibilityNodeProvider() { View contentView = getContentView(); if (contentView != null) { return contentView.getAccessibilityNodeProvider(); } else { Log.w(TAG, "Content view is null! Returns a null AccessibilityNodeProvider."); return null; } } private View getContentView() { return findViewWithTag(CastWebContentsScopes.VIEW_TAG_CONTENT_VIEW); } }
ric2b/Vivaldi-browser
chromium/chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWebContentsView.java
Java
bsd-3-clause
4,548
require 'test/unit' require 'rails/version' # For getting the rails version constants require 'active_support/vendor' # For loading I18n require 'mocha' require 'net/http' require File.dirname(__FILE__) + '/../lib/recaptcha' class RecaptchaVerifyTest < Test::Unit::TestCase def setup ENV['RECAPTCHA_PRIVATE_KEY'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' @controller = TestController.new @controller.request = stub(:remote_ip => "1.1.1.1") @controller.params = {:recaptcha_challenge_field => "challenge", :recaptcha_response_field => "response"} @expected_post_data = {} @expected_post_data["privatekey"] = ENV['RECAPTCHA_PRIVATE_KEY'] @expected_post_data["remoteip"] = @controller.request.remote_ip @expected_post_data["challenge"] = "challenge" @expected_post_data["response"] = "response" @expected_uri = URI.parse("http://#{Recaptcha::RECAPTCHA_VERIFY_SERVER}/verify") end def test_should_raise_exception_without_private_key assert_raise Recaptcha::RecaptchaError do ENV['RECAPTCHA_PRIVATE_KEY'] = nil @controller.verify_recaptcha end end def test_should_return_false_when_key_is_invalid expect_http_post(response_with_body("false\ninvalid-site-private-key")) assert !@controller.verify_recaptcha assert_equal "invalid-site-private-key", @controller.session[:recaptcha_error] end def test_returns_true_on_success @controller.session[:recaptcha_error] = "previous error that should be cleared" expect_http_post(response_with_body("true\n")) assert @controller.verify_recaptcha assert_nil @controller.session[:recaptcha_error] end def test_errors_should_be_added_to_model expect_http_post(response_with_body("false\nbad-news")) errors = mock errors.expects(:add).with(:base, "Captcha response is incorrect, please try again.") model = mock(:valid? => false, :errors => errors) assert !@controller.verify_recaptcha(:model => model) assert_equal "bad-news", @controller.session[:recaptcha_error] end def test_returns_true_on_success_with_optional_key @controller.session[:recaptcha_error] = "previous error that should be cleared" # reset private key @expected_post_data["privatekey"] = 'ADIFFERENTPRIVATEKEYXXXXXXXXXXXXXX' expect_http_post(response_with_body("true\n")) assert @controller.verify_recaptcha(:private_key => 'ADIFFERENTPRIVATEKEYXXXXXXXXXXXXXX') assert_nil @controller.session[:recaptcha_error] end def test_timeout expect_http_post(Timeout::Error, :exception => true) assert !@controller.verify_recaptcha() assert_equal "recaptcha-not-reachable", @controller.session[:recaptcha_error] end private class TestController include Recaptcha::Verify attr_accessor :request, :params, :session def initialize @session = {} end end def expect_http_post(response, options = {}) unless options[:exception] Net::HTTP.expects(:post_form).with(@expected_uri, @expected_post_data).returns(response) else Net::HTTP.expects(:post_form).raises response end end def response_with_body(body) stub(:body => body) end end
augustf/wtgsite
vendor/plugins/recaptcha/test/verify_recaptcha_test.rb
Ruby
mit
3,213
<?php namespace DoctrineBundle\Tests\DependencyInjection\Fixtures\Bundles\XmlBundle\Entity; class Test { }
boutell/SillyCMS
src/vendor/symfony/src/Symfony/Bundle/DoctrineBundle/Tests/DependencyInjection/Fixtures/Bundles/XmlBundle/Entity/Test.php
PHP
mit
108
<?php class CM_Paging_StreamSubscribe_User extends CM_Paging_StreamSubscribe_Abstract { /** * @param CM_Model_User $user */ public function __construct(CM_Model_User $user) { $source = new CM_PagingSource_Sql('`id`', 'cm_stream_subscribe', '`userId` = ' . $user->getId()); parent::__construct($source); } }
alexispeter/CM
library/CM/Paging/StreamSubscribe/User.php
PHP
mit
347
//--------------------------------------------------------------------- // <copyright file="JsonLightUtils.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.Test.OData.TDD.Tests.Common.JsonLight { using System.Collections.Generic; using Microsoft.OData.Core; using Microsoft.OData.Core.JsonLight; public static class JsonLightUtils { /// <summary>The default streaming Json Light media type.</summary> internal static readonly ODataMediaType JsonLightStreamingMediaType = new ODataMediaType( MimeConstants.MimeApplicationType, MimeConstants.MimeJsonSubType, new[]{ new KeyValuePair<string, string>(MimeConstants.MimeMetadataParameterName, MimeConstants.MimeMetadataParameterValueMinimal), new KeyValuePair<string, string>(MimeConstants.MimeStreamingParameterName, MimeConstants.MimeParameterValueTrue), new KeyValuePair<string, string>(MimeConstants.MimeIeee754CompatibleParameterName, MimeConstants.MimeParameterValueFalse) }); /// <summary> /// Gets the name of the property annotation property. /// </summary> /// <param name="propertyName">The name of the property to annotate.</param> /// <param name="annotationName">The name of the annotation.</param> /// <returns>The property name for the annotation property.</returns> public static string GetPropertyAnnotationName(string propertyName, string annotationName) { return propertyName + JsonLightConstants.ODataPropertyAnnotationSeparatorChar + annotationName; } } }
hotchandanisagar/odata.net
test/FunctionalTests/Tests/DataOData/Tests/OData.TDD.Tests/Common/JsonLight/JsonLightUtils.cs
C#
mit
1,894
require "test_helper" class MaintainingRepoSubscriptionsTest < ActionDispatch::IntegrationTest fixtures :repos def triage_the_sandbox login_via_github visit "/" click_link "issue_triage_sandbox" click_button "I Want to Triage: bemurphy/issue_triage_sandbox" end test "subscribing to a repo" do assert_difference 'ActionMailer::Base.deliveries.size', +1 do triage_the_sandbox assert page.has_content?("issue_triage_sandbox") end assert_equal IssueAssignment.last.delivered, true end test "send an issue! button" do triage_the_sandbox assert_difference 'ActionMailer::Base.deliveries.size', +1 do click_link "issue_triage_sandbox" click_link "Send new issue!" assert page.has_content?("You will receive an email with your new issue shortly") end assert_equal IssueAssignment.last.delivered, true end test "listing subscribers" do triage_the_sandbox click_link 'issue_triage_sandbox' click_link 'Subscribers' assert page.has_content?("@mockstar") end test "list only favorite languages" do login_via_github visit "/" assert !page.has_content?("javascript") end end
colinrubbert/codetriage
test/integration/maintaining_repo_subscriptions_test.rb
Ruby
mit
1,192
// Generated by CoffeeScript 1.3.3 (function() { define(["smog/server", "smog/notify", "templates/connect"], function(server, notify, templ) { return { show: function() { $('#content').html(templ()); $('#connect-modal').modal({ backdrop: false }); return $('#connect-button').click(function() { var host; host = $('#host').val(); return server.connect(host, function(err, okay) { if (err != null) { if (typeof err === 'object' && Object.keys(err).length === 0) { err = "Server unavailable"; } return notify.error("Connection error: " + (err.err || err)); } else { $('#connect-modal').modal('hide'); return window.location.hash = '#/home'; } }); }); } }; }); }).call(this);
wearefractal/smog
public/js/routes/index.js
JavaScript
mit
911
//--------------------------------------------------------------------- // <copyright file="StreamReferenceValueReaderJsonLightTests.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.Test.Taupo.OData.Reader.Tests.JsonLight { #region Namespaces using System.Collections.Generic; using System.Linq; using Microsoft.Test.Taupo.Astoria.Contracts.OData; using Microsoft.Test.Taupo.Astoria.OData; using Microsoft.Test.Taupo.Common; using Microsoft.Test.Taupo.Contracts.EntityModel; using Microsoft.Test.Taupo.Execution; using Microsoft.Test.Taupo.OData.Common; using Microsoft.Test.Taupo.OData.Contracts; using Microsoft.Test.Taupo.OData.Contracts.Json; using Microsoft.Test.Taupo.OData.JsonLight; using Microsoft.Test.Taupo.OData.Reader.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.OData.Edm; using Microsoft.OData.Edm.Library; using TestModels = Microsoft.Test.OData.Utils.Metadata.TestModels; #endregion Namespaces /// <summary> /// Tests reading of various complex value JSON Light payloads. /// </summary> [TestClass, TestCase] public class StreamReferenceValueReaderJsonLightTests : ODataReaderTestCase { [InjectDependency] public IPayloadGenerator PayloadGenerator { get; set; } private PayloadReaderTestDescriptor.Settings settings; [InjectDependency] public PayloadReaderTestDescriptor.Settings Settings { get { return this.settings; } set { this.settings = value; this.settings.ExpectedResultSettings.ObjectModelToPayloadElementConverter = new JsonLightObjectModelToPayloadElementConverter(); } } private sealed class StreamPropertyTestCase { public string DebugDescription { get; set; } public string Json { get; set; } public EntityInstance ExpectedEntity { get; set; } public ExpectedException ExpectedException { get; set; } public bool OnlyResponse { get; set; } public IEdmTypeReference OwningEntityType { get; set; } } [TestMethod, TestCategory("Reader.Json"), Variation(Description = "Verifies correct reading of stream properties (stream reference values) with fully specified metadata.")] public void StreamPropertyTest() { IEdmModel model = TestModels.BuildTestModel(); var testCases = new[] { new StreamPropertyTestCase { DebugDescription = "Just edit link", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/streamproperty/editlink", null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"" }, new StreamPropertyTestCase { DebugDescription = "Just read link", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/test/Cities(1)/Skyline", null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\"" }, new StreamPropertyTestCase { DebugDescription = "Just content type", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/test/Cities(1)/Skyline", "streamproperty:contenttype", null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\"" }, new StreamPropertyTestCase { DebugDescription = "Just ETag", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/test/Cities(1)/Skyline", null, "streamproperty:etag"), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\"" }, new StreamPropertyTestCase { DebugDescription = "Everything", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/streamproperty/editlink", "streamproperty:contenttype", "streamproperty:etag"), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\"" }, new StreamPropertyTestCase { DebugDescription = "Just custom annotation - should report empty stream property", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/test/Cities(1)/Skyline", null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", "custom.value") + "\":\"value\"" }, new StreamPropertyTestCase { DebugDescription = "Everything with custom annotation - custom annotations should be ignored", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/streamproperty/editlink", "streamproperty:contenttype", "streamproperty:etag"), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", "custom.value") + "\":\"value\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", "custom.type") + "\":42" }, new StreamPropertyTestCase { DebugDescription = "With odata.type annotation - should fail", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataTypeAnnotationName) + "\":\"Edm.Stream\"", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_UnexpectedStreamPropertyAnnotation", "Skyline", JsonLightConstants.ODataTypeAnnotationName) }, new StreamPropertyTestCase { DebugDescription = "Everything with navigation link URL annotation - should fail", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/streamproperty/editlink", "streamproperty:contenttype", "streamproperty:etag"), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/streamproperty/navlink\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\"," + "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\"", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_UnexpectedStreamPropertyAnnotation", "Skyline", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) }, new StreamPropertyTestCase { DebugDescription = "Invalid edit link - wrong primitive", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":42", ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_CannotReadPropertyValueAsString", "42", JsonLightConstants.ODataMediaEditLinkAnnotationName), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid edit link - null", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":null", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaEditLinkAnnotationName), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid read link - wrong primitive", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":true", ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_CannotReadPropertyValueAsString", "True", JsonLightConstants.ODataMediaReadLinkAnnotationName), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid read link - null", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":null", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaReadLinkAnnotationName), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid ETag - non primitive", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":[]", ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "PrimitiveValue", "StartArray"), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid ETag - null", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":null", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaETagAnnotationName), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid content type - non primitive", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":{}", ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "PrimitiveValue", "StartObject"), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid content type - null", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":null", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaContentTypeAnnotationName), OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Open stream property", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("OpenSkyline", null, "http://odata.org/streamproperty/editlink", null, null), OwningEntityType = model.FindDeclaredType("TestModel.CityOpenType").ToTypeReference(), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("OpenSkyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_OpenPropertyWithoutValue", "OpenSkyline"), OnlyResponse = true }, new StreamPropertyTestCase { DebugDescription = "Undeclared stream property", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("NewSkyline", null, "http://odata.org/streamproperty/editlink", null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("NewSkyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"", ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "NewSkyline", "TestModel.CityType"), OnlyResponse = true }, new StreamPropertyTestCase { DebugDescription = "Stream property declared with non-stream type", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Name", null, "http://odata.org/streamproperty/editlink", null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_PropertyWithoutValueWithWrongType", "Name", "Edm.String"), OnlyResponse = true }, new StreamPropertyTestCase { DebugDescription = "Stream property with value", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, "http://odata.org/streamproperty/editlink", null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," + "\"Skyline\":\"value\"", ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_StreamPropertyWithValue", "Skyline"), OnlyResponse = true }, }; this.RunStreamPropertyTest(model, testCases); } [TestMethod, TestCategory("Reader.Json"), Variation(Description = "Verifies correct reading of stream properties (stream reference values) with fully specified metadata.")] public void StreamPropertyTestWithRelativeLinkUris() { IEdmModel model = TestModels.BuildTestModel(); var testCases = new[] { new StreamPropertyTestCase { DebugDescription = "Invalid edit link - non-URL", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"xxx yyy zzz\"", ExpectedException = null, OnlyResponse = true, }, new StreamPropertyTestCase { DebugDescription = "Invalid read link - non-URL", ExpectedEntity = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null), Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"xxx yyy zzz\"", ExpectedException = null, OnlyResponse = true, }, }; this.RunStreamPropertyTest(model, testCases); } private void RunStreamPropertyTest(IEdmModel model, IEnumerable<StreamPropertyTestCase> testCases) { var cityType = model.FindDeclaredType("TestModel.CityType").ToTypeReference(); var cities = model.EntityContainer.FindEntitySet("Cities"); IEnumerable<PayloadReaderTestDescriptor> testDescriptors = testCases.Select(testCase => { IEdmTypeReference entityType = testCase.OwningEntityType ?? cityType; EntityInstance entity = PayloadBuilder.Entity(entityType.FullName()).PrimitiveProperty("Id", 1) .JsonRepresentation( "{" + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.DefaultContainer.Cities/" + entityType.FullName() + "()/$entity\"," + "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"" + entityType.FullName() + "\"," + "\"Id\": 1," + testCase.Json + "}") .ExpectedEntityType(entityType, cities); foreach (NamedStreamInstance streamProperty in testCase.ExpectedEntity.Properties.OfType<NamedStreamInstance>()) { entity.Add(streamProperty.DeepCopy()); } return new PayloadReaderTestDescriptor(this.Settings) { DebugDescription = testCase.DebugDescription, PayloadEdmModel = model, PayloadElement = entity, ExpectedException = testCase.ExpectedException, SkipTestConfiguration = tc => testCase.OnlyResponse ? tc.IsRequest : false }; }); this.CombinatorialEngineProvider.RunCombinations( testDescriptors, this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations, (testDescriptor, testConfiguration) => { if (testConfiguration.IsRequest) { testDescriptor = new PayloadReaderTestDescriptor(testDescriptor) { ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_StreamPropertyInRequest") }; } // These descriptors are already tailored specifically for Json Light and // do not require normalization. testDescriptor.TestDescriptorNormalizers.Clear(); var testConfigClone = new ReaderTestConfiguration(testConfiguration); testConfigClone.MessageReaderSettings.BaseUri = null; testDescriptor.RunTest(testConfigClone); }); } } }
hotchandanisagar/odata.net
test/FunctionalTests/Tests/DataOData/Tests/OData.Reader.Tests/JsonLight/StreamReferenceValueReaderJsonLightTests.cs
C#
mit
23,505
var expect = require('expect.js'), defaultOpts = require('..').prototype.options, _ = require('lodash'), parse = require('../lib/parse'), render = require('../lib/render'); var html = function(str, options) { options = _.defaults(options || {}, defaultOpts); var dom = parse(str, options); return render(dom); }; var xml = function(str, options) { options = _.defaults(options || {}, defaultOpts); options.xmlMode = true; var dom = parse(str, options); return render(dom, options); }; describe('render', function() { describe('(html)', function() { it('should render <br /> tags correctly', function() { var str = '<br />'; expect(html(str)).to.equal('<br>'); }); it('should handle double quotes within single quoted attributes properly', function() { var str = '<hr class=\'an "edge" case\' />'; expect(html(str)).to.equal('<hr class="an &#x22;edge&#x22; case">'); }); it('should retain encoded HTML content within attributes', function() { var str = '<hr class="cheerio &amp; node = happy parsing" />'; expect(html(str)).to.equal('<hr class="cheerio &#x26; node = happy parsing">'); }); it('should shorten the "checked" attribute when it contains the value "checked"', function() { var str = '<input checked/>'; expect(html(str)).to.equal('<input checked>'); }); it('should not shorten the "name" attribute when it contains the value "name"', function() { var str = '<input name="name"/>'; expect(html(str)).to.equal('<input name="name">'); }); it('should render comments correctly', function() { var str = '<!-- comment -->'; expect(html(str)).to.equal('<!-- comment -->'); }); it('should render whitespace by default', function() { var str = '<a href="./haha.html">hi</a> <a href="./blah.html">blah</a>'; expect(html(str)).to.equal(str); }); it('should normalize whitespace if specified', function() { var str = '<a href="./haha.html">hi</a> <a href="./blah.html">blah </a>'; expect(html(str, { normalizeWhitespace: true })).to.equal('<a href="./haha.html">hi</a> <a href="./blah.html">blah </a>'); }); it('should preserve multiple hyphens in data attributes', function() { var str = '<div data-foo-bar-baz="value"></div>'; expect(html(str)).to.equal('<div data-foo-bar-baz="value"></div>'); }); it('should render CDATA correctly', function() { var str = '<a> <b> <![CDATA[ asdf&asdf ]]> <c/> <![CDATA[ asdf&asdf ]]> </b> </a>'; expect(xml(str)).to.equal(str); }); }); });
JHand93/WebPerformanceTestSuite
webpagetest-charts-api/node_modules/cheerio/test/render.js
JavaScript
mit
2,628