text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
class CreateAliquotSampleFormats < SharedMigration def self.up create_table :aliquot_sample_formats do |t| t.integer :position t.string :key, :null => false t.string :description t.timestamps end add_index :aliquot_sample_formats, :key, :unique => true add_index :aliquot_sample_formats, :description, :unique => true end def self.down drop_table :aliquot_sample_formats end end
{'content_hash': '35f34a1b40ef8907dd3c354ae3df069d', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 66, 'avg_line_length': 25.5, 'alnum_prop': 0.7230392156862745, 'repo_name': 'ccls/ccls_engine', 'id': '4b17ee6430e7910f19acb20928d84291532504bc', 'size': '408', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/migrate/20100218233849_create_aliquot_sample_formats.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3879'}, {'name': 'Ruby', 'bytes': '865318'}, {'name': 'Shell', 'bytes': '271'}]}
<html> <head> <title>Leaflet</title> <link rel="stylesheet" href="/leaflet/leaflet.css" /> <script src="/leaflet/leaflet.js"></script> <script src="../layer/vector/OSM.js"></script> </head> <body> <div style="width:100%; height:100%" id="map"></div> <script type='text/javascript'> var map = new L.Map('map', {center: new L.LatLng(55.7, 37.6), zoom: 9, zoomAnimation: false }); map.addLayer(new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')); var layer = new L.OSM('ulugo.osm') .on("loaded", function(e) { map.fitBounds(e.target.getBounds()); }); map.addLayer(layer); map.addControl(new L.Control.Layers({}, {"OSM":layer})); </script> </body> </html>
{'content_hash': '08c9f78dadaf1cb76375f81d2a2fd06c', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 95, 'avg_line_length': 32.42857142857143, 'alnum_prop': 0.6490455212922174, 'repo_name': 'MAPC/developmentdatabase-python', 'id': 'ed35e55a3322173dbab9634d6d38bafe59003f08', 'size': '681', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'developmentdatabase/static/lib/leaflet/plugins/shramov/examples/osm.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '19926'}, {'name': 'JavaScript', 'bytes': '565239'}, {'name': 'Python', 'bytes': '302858'}]}
<md-content ng-controller="AddCtrl" layout="column" flex layout-padding> <h3>Depositar na sua conta</h3> <md-input-container class="md-block"> <label>Valor</label> <input type="text" ng-model="valor" ui-number-mask="2"> </md-input-container> <div layout="column"> <md-button class="md-raised md-primary" aria-label="confirmar" ng-click="confirmar()" ng-disabled="!valor"> Confirmar </md-button> </div> </md-content>
{'content_hash': '1aab8d8f863eab4d540bd81f7a4517ac', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 109, 'avg_line_length': 36.833333333333336, 'alnum_prop': 0.6787330316742082, 'repo_name': 'everton-ongit/wepay', 'id': '377b57089d3575f186bd82a37a67ff4ffde7704f', 'size': '442', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/app/add/add.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '10372'}, {'name': 'JavaScript', 'bytes': '19489'}]}
namespace syncer { class SyncPrefs; // This class is used by ProfileSyncService to manage all logic and state // pertaining to initialization of the SyncEngine. class StartupController { public: StartupController(const SyncPrefs* sync_prefs, base::Callback<bool()> can_start, base::Closure start_engine); ~StartupController(); // Starts up sync if it is requested by the user and preconditions are met. // Returns true if these preconditions are met, although does not imply // the engine was started. bool TryStart(); // Same as TryStart() above, but bypasses deferred startup and the first setup // complete check. bool TryStartImmediately(); // Called when a datatype (SyncableService) has a need for sync to start // ASAP, presumably because a local change event has occurred but we're // still in deferred start mode, meaning the SyncableService hasn't been // told to MergeDataAndStartSyncing yet. // It is expected that |type| is a currently active datatype. void OnDataTypeRequestsSyncStartup(ModelType type); // Prepares this object for a new attempt to start sync, forgetting // whether or not preconditions were previously met. // NOTE: This resets internal state managed by this class, but does not // touch values that are explicitly set and reset by higher layers to // tell this class whether a setup UI dialog is being shown to the user. // See setup_in_progress_. void Reset(const ModelTypeSet registered_types); // Sets the setup in progress flag and tries to start sync if it's true. void SetSetupInProgress(bool setup_in_progress); bool IsSetupInProgress() const { return setup_in_progress_; } base::Time start_engine_time() const { return start_engine_time_; } std::string GetEngineInitializationStateString() const; void OverrideFallbackTimeoutForTest(const base::TimeDelta& timeout); private: enum StartUpDeferredOption { STARTUP_DEFERRED, STARTUP_IMMEDIATE }; // Returns true if all conditions to start the engine are met. bool StartUp(StartUpDeferredOption deferred_option); void OnFallbackStartupTimerExpired(); // Records time spent in deferred state with UMA histograms. void RecordTimeDeferred(); // If true, will bypass the FirstSetupComplete check when triggering sync // startup. bool bypass_setup_complete_; // True if we should start sync ASAP because either a SyncableService has // requested it, or we're done waiting for a sign and decided to go ahead. bool received_start_request_; // The time that StartUp() is called. This is used to calculate time spent // in the deferred state; that is, after StartUp and before invoking the // start_engine_ callback. base::Time start_up_time_; // If |true|, there is setup UI visible so we should not start downloading // data types. // Note: this is explicitly controlled by higher layers (UI) and is meant to // reflect what the UI claims the setup state to be. Therefore, only set this // due to explicit requests to do so via SetSetupInProgress. bool setup_in_progress_; const SyncPrefs* sync_prefs_; // A function that can be invoked repeatedly to determine whether sync can be // started. |start_engine_| should not be invoked unless this returns true. base::Callback<bool()> can_start_; // The callback we invoke when it's time to call expensive // startup routines for the sync engine. base::Closure start_engine_; // The time at which we invoked the start_engine_ callback. base::Time start_engine_time_; base::TimeDelta fallback_timeout_; // Used to compute preferred_types from SyncPrefs as-needed. ModelTypeSet registered_types_; base::WeakPtrFactory<StartupController> weak_factory_; }; } // namespace syncer #endif // COMPONENTS_SYNC_DRIVER_STARTUP_CONTROLLER_H_
{'content_hash': '0316e5d429db8cc398d38e1ce36bf546', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 80, 'avg_line_length': 38.878787878787875, 'alnum_prop': 0.7381137957911146, 'repo_name': 'google-ar/WebARonARCore', 'id': '63c027854831d6e141463f097afba051b55f7b4e', 'size': '4276', 'binary': False, 'copies': '3', 'ref': 'refs/heads/webarcore_57.0.2987.5', 'path': 'components/sync/driver/startup_controller.h', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
namespace uut { class String : public ValueType { UUT_VALUETYPE(uut, String, ValueType) public: typedef std::string DataType; typedef DataType::iterator Iterator; typedef DataType::const_iterator CIterator; String(); String(const char* str); String(const String& str); String(String&& str); String(const std::string& str); String(std::string&& str); bool EndsWith(const String& ends) const; bool EndsWith(const String& ends, StringComparison comparisonType) const; int IndexOf(char value) const; int IndexOf(char value, StringComparison comparisonType) const; int IndexOf(const String& value) const; int IndexOf(const String& value, StringComparison comparisonType) const; int IndexOf(const String& value, int startIndex, StringComparison comparisonType) const; void Insert(int index, const String& value); int LastIndexOf(char value) const; int LastIndexOf(char value, StringComparison comparisonType) const; int LastIndexOf(const String& value) const; int LastIndexOf(const String& value, StringComparison comparisonType) const; void Remove(int startIndex); void Remove(int startIndex, int length); int Replace(char oldChar, char newChar); int Replace(const String& oldValue, const String& newValue); void TrimStart(); void TrimStart(const List<char>& trimChars); void TrimEnd(); void TrimEnd(const List<char>& trimChars); void Trim(); void Trim(const List<char>& trimChars); int Split(char c, List<String>& out) const; List<String> Split(char c) const; String Substring(int startIndex) const; String Substring(int startIndex, int length) const; bool Equals(const String& str) const; bool Equals(const String& str, StringComparison comparisonType) const; uint Count() const { return _data.size(); } bool IsEmpty() const { return _data.empty(); } void Clear() { _data.clear(); } operator const char*() const { return _data.c_str(); } const char* GetData() const { return _data.c_str(); } bool operator == (const char* str) const { return Equals(str); } bool operator != (const char* str) const { return !Equals(str); } bool operator == (const String& str) const { return Equals(str); } bool operator != (const String& str) const { return !Equals(str); } String& operator = (const char* str); String& operator = (const String& str); String& operator = (String&& str); String& operator += (char c); String& operator += (const char* str); String& operator += (const String& str); String operator + (const char* str) const; String operator + (const String& str) const; static String Join(const List<String>& list, const String& str); static String Format(const char* format, ...); Iterator Begin() { return _data.begin(); } Iterator End() { return _data.begin(); } CIterator Begin() const { return _data.begin(); } CIterator End() const { return _data.begin(); } static const String Empty; static int Compare(const String& a, const String& b, StringComparison comparisonType = StringComparison::Ordinal); protected: std::string _data; }; template<class T> String::Iterator begin(String& str) { return str.Begin(); } template<class T> String::Iterator end(String& str) { return str.End(); } template<class T> String::CIterator begin(const String& str) { return str.Begin(); } template<class T> String::CIterator end(const String& str) { return str.End(); } namespace detail { template<typename T> struct StringConvert { static String ToString(const T& value) { return String(value); } }; //template<typename T, class = std::enable_if_t<std::is_fundamental<T>::value>> struct StringConvert { // static String ToString(const T& value) { return String::Empty; } //}; template<> struct StringConvert<String> { static String ToString(const String& value) { return value; } }; template<> struct StringConvert<const Type*> { static String ToString(const Type* value) { return value->ToString(); } }; } template<typename T> static String ToString(T value) { return detail::StringConvert<T>::ToString(value); } UUT_DEFAULT_VALUE(String, String::Empty) }
{'content_hash': '28a8eb8578bfd89ea9154a6992ee08c5', 'timestamp': '', 'source': 'github', 'line_count': 130, 'max_line_length': 116, 'avg_line_length': 31.892307692307693, 'alnum_prop': 0.7047756874095513, 'repo_name': 'kolyden/uut-engine', 'id': '559c64b285892d38212b58e7cf805cc35ea9c984', 'size': '4271', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'UUT/Core/String.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2263439'}, {'name': 'C++', 'bytes': '2142907'}, {'name': 'Objective-C', 'bytes': '8426'}]}
require 'spec_helper' describe Spree::PageLayout do let (:page_layout) { Spree::PageLayout.first } it "build html css js" do html, css = page_layout.build_content html.present?.should be_true css.present?.should be_true end it "create new page_layout tree" do # objects = Spree::Section.roots # section_hash= objects.inject({}){|h,sp| h[sp.slug] = sp; h} # center area # center_area = Spree::PageLayout.create_layout(section_hash['center_area'], "center_area") # center_area.add_section(section_hash['center_part'],:title=>"center_part") # center_area.add_section(section_hash['left_part'],:title=>"left_part") # center_area.add_section(section_hash['right_part'],:title=>"right_part") # center_area.children.count.should eq(3) # center_area.param_values.count.should eq(0) end it "valid section context" do product_detail = Spree::PageLayout.find_by_section_context( Spree::PageLayout::ContextEnum.detail) product_detail.context_detail?.should be_true product_list = Spree::PageLayout.find_by_section_context( Spree::PageLayout::ContextEnum.list) product_list.context_list?.should be_true end it "could update context" do list_section = Spree::PageLayout.find_by_section_context('list') detail_section = Spree::PageLayout.find_by_section_context('detail') #contexts = [Spree::PageLayout::ContextEnum.account, Spree::PageLayout::ContextEnum.thanks,Spree::PageLayout::ContextEnum.cart, Spree::PageLayout::ContextEnum.checkout] contexts = [Spree::PageLayout::ContextEnum.list, Spree::PageLayout::ContextEnum.detail] page_layout.update_section_context contexts for node in page_layout.self_and_descendants if node.is_or_is_descendant_of? list_section node.current_contexts.should eq(list_section.current_contexts) elsif node.is_or_is_descendant_of? detail_section node.current_contexts.should eq(detail_section.current_contexts) else node.current_contexts.should eq(contexts) end end end it "could verify contexts" do Spree::PageLayout.verify_contexts( Spree::PageLayout::ContextEnum.cart, [:cart, :checkout, :thankyou ] ).should be_true Spree::PageLayout.verify_contexts( [Spree::PageLayout::ContextEnum.cart], [:cart, :checkout, :thankyou ] ).should be_true Spree::PageLayout.verify_contexts( Spree::PageLayout::ContextEnum.either, [:cart, :checkout, :thankyou ] ).should be_false end it "could replace section" do original_page_layout = page_layout.dup root2 = Spree::Section.find('root2') page_layout.replace_with(root2) original_page_layout.param_values.empty?.should be_true page_layout.section.should eq root2 page_layout.param_values.present?.should be_true end end
{'content_hash': '32591e64cce624099a25291ddb631452', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 172, 'avg_line_length': 40.5, 'alnum_prop': 0.7022927689594356, 'repo_name': 'RuanShan/spree_theme', 'id': '47d223ba92f0a8a3dc995906f69b08f79160f327', 'size': '2858', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/models/page_layout_spec.rb', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '9761'}, {'name': 'JavaScript', 'bytes': '253599'}, {'name': 'Ruby', 'bytes': '284748'}]}
base::LazyInstance<base::TestDiscardableMemoryAllocator> g_discardable_memory_allocator = LAZY_INSTANCE_INITIALIZER; int main(int argc, char** argv) { #if defined(OS_WIN) ui::ScopedOleInitializer ole_initializer_; #endif base::CommandLine::Init(argc, argv); base::AtExitManager at_exit; #if defined(USE_X11) // This demo uses InProcessContextFactory which uses X on a separate Gpu // thread. gfx::InitializeThreadedX11(); #endif gl::init::InitializeGLOneOff(); // The ContextFactory must exist before any Compositors are created. bool context_factory_for_test = false; cc::SurfaceManager surface_manager; std::unique_ptr<ui::InProcessContextFactory> context_factory( new ui::InProcessContextFactory(context_factory_for_test, &surface_manager)); context_factory->set_use_test_surface(false); base::MessageLoopForUI message_loop; base::i18n::InitializeICU(); ui::RegisterPathProvider(); base::FilePath ui_test_pak_path; CHECK(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); base::DiscardableMemoryAllocator::SetInstance( g_discardable_memory_allocator.Pointer()); base::PowerMonitor power_monitor( base::WrapUnique(new base::PowerMonitorDeviceSource)); #if defined(OS_WIN) gfx::win::MaybeInitializeDirectWrite(); #endif #if defined(USE_AURA) std::unique_ptr<aura::Env> env = aura::Env::CreateInstance(); aura::Env::GetInstance()->set_context_factory(context_factory.get()); #endif ui::InitializeInputMethodForTesting(); ui::MaterialDesignController::Initialize(); { views::DesktopTestViewsDelegate views_delegate; #if defined(USE_AURA) wm::WMState wm_state; #endif #if !defined(OS_CHROMEOS) && defined(USE_AURA) std::unique_ptr<display::Screen> desktop_screen( views::CreateDesktopScreen()); display::Screen::SetScreenInstance(desktop_screen.get()); #endif views::examples::ShowExamplesWindow(views::examples::QUIT_ON_CLOSE); base::RunLoop().Run(); ui::ResourceBundle::CleanupSharedInstance(); } ui::ShutdownInputMethod(); #if defined(USE_AURA) env.reset(); #endif return 0; }
{'content_hash': '825fab7409c0f86d89e79e091ccbae68', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 74, 'avg_line_length': 27.506172839506174, 'alnum_prop': 0.7172351885098743, 'repo_name': 'google-ar/WebARonARCore', 'id': '26b103fec7a8a7ff231f6fd5adacba57c212dac1', 'size': '3768', 'binary': False, 'copies': '1', 'ref': 'refs/heads/webarcore_57.0.2987.5', 'path': 'ui/views/examples/examples_main.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
My wedding's homepage using [Creative](http://startbootstrap.com/template-overviews/creative/).
{'content_hash': 'c4ed725abc64e77b3aea13858a9da215', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 95, 'avg_line_length': 96.0, 'alnum_prop': 0.8020833333333334, 'repo_name': 'mfuentesm/jamieymauricio', 'id': '4ce948d537c8a919da3f81da2ef834aef0f50d6c', 'size': '96', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '18680'}, {'name': 'HTML', 'bytes': '11725'}, {'name': 'JavaScript', 'bytes': '4910'}]}
local types = require "base.types" local common = types.common -- Forwarding constructor based on type name. function common.__call(parent, ...) local obj = parent.new(...) setmetatable(obj, parent) return obj end -- Getter lookup. function common.__index(table, key) local mt = getmetatable(table) local func = mt.getters[key] if func == nil then error("no member named '" .. key .. "'", 2) end return func(table) end -- Setter lookup. function common.__newindex(table, key, value) local mt = getmetatable(table) local func = mt.setters[key] if func == nil then error("no member named '" .. key .. "'", 2) end func(table, value) end -- Module exports. return nil
{'content_hash': '0cd51bd0141fb9e7a86d82e83a442a43', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 51, 'avg_line_length': 23.0, 'alnum_prop': 0.6345108695652174, 'repo_name': 'bobsomers/flexrender', 'id': '676eefe776a328f174580c307c8f10fc551126fb', 'size': '767', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'frlib/base/common.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '282212'}, {'name': 'Lua', 'bytes': '72520'}, {'name': 'Shell', 'bytes': '9263'}]}
from thrift.Thrift import * import fb303.ttypes import hive_metastore.ttypes import queryplan.ttypes from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class JobTrackerState: INITIALIZING = 1 RUNNING = 2 _VALUES_TO_NAMES = { 1: "INITIALIZING", 2: "RUNNING", } _NAMES_TO_VALUES = { "INITIALIZING": 1, "RUNNING": 2, } class HiveClusterStatus: """ Attributes: - taskTrackers - mapTasks - reduceTasks - maxMapTasks - maxReduceTasks - state """ thrift_spec = ( None, # 0 (1, TType.I32, 'taskTrackers', None, None, ), # 1 (2, TType.I32, 'mapTasks', None, None, ), # 2 (3, TType.I32, 'reduceTasks', None, None, ), # 3 (4, TType.I32, 'maxMapTasks', None, None, ), # 4 (5, TType.I32, 'maxReduceTasks', None, None, ), # 5 (6, TType.I32, 'state', None, None, ), # 6 ) def __init__(self, taskTrackers=None, mapTasks=None, reduceTasks=None, maxMapTasks=None, maxReduceTasks=None, state=None,): self.taskTrackers = taskTrackers self.mapTasks = mapTasks self.reduceTasks = reduceTasks self.maxMapTasks = maxMapTasks self.maxReduceTasks = maxReduceTasks self.state = state def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I32: self.taskTrackers = iprot.readI32(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.I32: self.mapTasks = iprot.readI32(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.I32: self.reduceTasks = iprot.readI32(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.I32: self.maxMapTasks = iprot.readI32(); else: iprot.skip(ftype) elif fid == 5: if ftype == TType.I32: self.maxReduceTasks = iprot.readI32(); else: iprot.skip(ftype) elif fid == 6: if ftype == TType.I32: self.state = iprot.readI32(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('HiveClusterStatus') if self.taskTrackers is not None: oprot.writeFieldBegin('taskTrackers', TType.I32, 1) oprot.writeI32(self.taskTrackers) oprot.writeFieldEnd() if self.mapTasks is not None: oprot.writeFieldBegin('mapTasks', TType.I32, 2) oprot.writeI32(self.mapTasks) oprot.writeFieldEnd() if self.reduceTasks is not None: oprot.writeFieldBegin('reduceTasks', TType.I32, 3) oprot.writeI32(self.reduceTasks) oprot.writeFieldEnd() if self.maxMapTasks is not None: oprot.writeFieldBegin('maxMapTasks', TType.I32, 4) oprot.writeI32(self.maxMapTasks) oprot.writeFieldEnd() if self.maxReduceTasks is not None: oprot.writeFieldBegin('maxReduceTasks', TType.I32, 5) oprot.writeI32(self.maxReduceTasks) oprot.writeFieldEnd() if self.state is not None: oprot.writeFieldBegin('state', TType.I32, 6) oprot.writeI32(self.state) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class HiveServerException(Exception): """ Attributes: - message - errorCode - SQLState """ thrift_spec = ( None, # 0 (1, TType.STRING, 'message', None, None, ), # 1 (2, TType.I32, 'errorCode', None, None, ), # 2 (3, TType.STRING, 'SQLState', None, None, ), # 3 ) def __init__(self, message=None, errorCode=None, SQLState=None,): self.message = message self.errorCode = errorCode self.SQLState = SQLState def read(self, iprot): if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.STRING: self.message = iprot.readString(); else: iprot.skip(ftype) elif fid == 2: if ftype == TType.I32: self.errorCode = iprot.readI32(); else: iprot.skip(ftype) elif fid == 3: if ftype == TType.STRING: self.SQLState = iprot.readString(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStructBegin('HiveServerException') if self.message is not None: oprot.writeFieldBegin('message', TType.STRING, 1) oprot.writeString(self.message) oprot.writeFieldEnd() if self.errorCode is not None: oprot.writeFieldBegin('errorCode', TType.I32, 2) oprot.writeI32(self.errorCode) oprot.writeFieldEnd() if self.SQLState is not None: oprot.writeFieldBegin('SQLState', TType.STRING, 3) oprot.writeString(self.SQLState) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __str__(self): return repr(self) def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other)
{'content_hash': '81dbcc4e85b1ac6673434818effa6e3f', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 188, 'avg_line_length': 29.906382978723403, 'alnum_prop': 0.6246442800227661, 'repo_name': 'genericDataCompany/hsandbox', 'id': 'f10f8c454db1a7ca2d81707c13440765875f6a7d', 'size': '7145', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'common/hive-0.9.0-bin/lib/py/hive_service/ttypes.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '26324'}, {'name': 'C++', 'bytes': '40407'}, {'name': 'Java', 'bytes': '20935825'}, {'name': 'Objective-C', 'bytes': '1894'}, {'name': 'PHP', 'bytes': '898217'}, {'name': 'Perl', 'bytes': '539854'}, {'name': 'Python', 'bytes': '786538'}, {'name': 'Shell', 'bytes': '146660'}, {'name': 'XSLT', 'bytes': '1431'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '872109a5ec47f1d51d365eab0025176e', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': 'e36c4ed50b3ffce2d5c4bc9c4148d06d241811c7', 'size': '169', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Inga/Inga triflora/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<div class="sidebar"> <div id="sidebar-social"> <h4>Social</h4> <li style="white-space:nowrap;"><i class="fa fa-envelope"></i><a href="mailto:[email protected]" title="Email"> [email protected]</a></li> <li><i class="fa fa-twitter"></i><a href="http://twitter.com/EduardSzoecs" title="Twitter"> @EduardSzoecs</a></li> <li><i class="fa fa-skype"></i><a href="skype:profile_name?userinfo"> szocs.eduard</a></li> <li><i class="fa fa-github"></i><a href="https://github.com/EDiLD" title="Github"> EDiLD</a></li> <li><i class="fa fa-stack-overflow"></i><a href="http://stackoverflow.com/users/511399/edi" title="Stackoverflow"> EDi</a></li> <h4>Links</h4> <li><i class="ai ai-researchgate-square"></i><a href="http://www.researchgate.net/profile/Eduard_Szoecs" title="Researchgate"> Researchgate</a></li> <li><i class="ai ai-google-scholar-square"></i><a href="https://scholar.google.de/citations?user=QlQH1zEAAAAJ&hl=en" title="Google scholar"> Google Scholar</a></li> <li><i class="ai ai-orcid"></i><a href="http://orcid.org/0000-0001-5376-1194" title="Orcid"> ORCID</a></li> <li style="white-space:nowrap;"><i class="fa fa-university"></i><a href="https://www.uni-koblenz-landau.de/en/campus-landau/faculty7/environmental-sciences/landscape-ecology/Staff/eduardszoecs" title="Univerity"> University</a></li> <li><i class="fa fa-fw fa-rss"></i><a href="{{ site.url }}/feed.xml" title="Subscribe RSS"> Subscribe</a></li> </div> </div>
{'content_hash': 'a4405acbdf54c9d0ef9700df5bb1491e', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 238, 'avg_line_length': 90.11764705882354, 'alnum_prop': 0.6514360313315927, 'repo_name': 'EDiLD/edild.github.com', 'id': '3fa1147db1725d8e75ffe583c52d2197b40714ef', 'size': '1532', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_includes/sidebar.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '17093'}, {'name': 'HTML', 'bytes': '8889'}, {'name': 'R', 'bytes': '4475'}, {'name': 'Ruby', 'bytes': '50'}]}
#include <stdio.h> #include <stdint.h> #include <sel4/sel4.h> #include <sel4utils/util.h> #include <VchanProxy.h> #include "vmm/vmm.h" #include "vmm/vchan_copy.h" #include "vmm/vchan_sharemem.h" #define DPRINTF(num, ...) printf(__VA_ARGS__); int32_t rpc_in_new_connection(vchan_connect_t con) { // DPRINTF(DBG_SERVER, "Proxy: new connection \n"); return (int32_t)vchan_com_out_new_connection(con); } int32_t rpc_in_rem_connection(vchan_connect_t con) { // DPRINTF(DBG_SERVER, "Proxy: rem connection \n"); return (int32_t)vchan_com_out_rem_connection(con); } int32_t rpc_in_get_buf(vchan_ctrl_t con, int32_t cmd) { // DPRINTF(DBG_SERVER, "Proxy: get buff \n"); return (int32_t)vchan_com_out_get_buf(con, (int)cmd); } int32_t rpc_in_status(vchan_ctrl_t con) { // DPRINTF(DBG_SERVER, "Proxy: in status \n"); return (int32_t)vchan_com_out_status(con); } int32_t rpc_in_alert_status(vchan_ctrl_t con) { // DPRINTF(DBG_SERVER, "Proxy: alert status \n"); return (int32_t)vchan_com_out_alert_status(con); } void rpc_in_ping() { // DPRINTF(DBG_SERVER, "Proxy: ping \n"); vchan_com_out_ping(); } void vevent_out_callback(void *arg) { // DPRINTF(DBG_SERVER, "Proxy: vevent out callback \n"); vevent_in_write_void(); // DPRINTF(DBG_SERVER, "Proxy: vevent out sent with result %d \n", result); vevent_out_reg_callback(vevent_out_callback, arg); } int run(void) { // DPRINTF(DBG_SERVER, "Proxy: started \n"); vevent_out_reg_callback(vevent_out_callback, NULL); return 0; }
{'content_hash': 'c55f36c0f8756667722b98227e37aedc', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 76, 'avg_line_length': 25.508474576271187, 'alnum_prop': 0.6750830564784053, 'repo_name': 'smaccm/smaccm', 'id': 'c5b9ff32ffaa095cabcbaf51f9bb51e99cff878c', 'size': '1756', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'models/Trusted_Build_Test/vChan_demo/components/VchanProxy/src/proxy.c', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ANTLR', 'bytes': '451'}, {'name': 'Batchfile', 'bytes': '683'}, {'name': 'C', 'bytes': '11288334'}, {'name': 'C++', 'bytes': '311661'}, {'name': 'CSS', 'bytes': '8414'}, {'name': 'Common Lisp', 'bytes': '2573'}, {'name': 'GAP', 'bytes': '1308789'}, {'name': 'HTML', 'bytes': '261273'}, {'name': 'Java', 'bytes': '13163755'}, {'name': 'Limbo', 'bytes': '2106'}, {'name': 'Lua', 'bytes': '8914'}, {'name': 'MATLAB', 'bytes': '10198'}, {'name': 'Makefile', 'bytes': '205845'}, {'name': 'Objective-C', 'bytes': '908928'}, {'name': 'Python', 'bytes': '14200'}, {'name': 'Shell', 'bytes': '812'}]}
/** * Authored by AlmogBaku * [email protected] * http://www.almogbaku.com/ * * 9/8/13 9:33 PM */ angular.element(document).ready(function() { angular.bootstrap(document, ['app']); }); /** * DEBUG!!!!!! @TODO remove it! */ function getApp(service) { return angular.element(document).injector().get(service); }
{'content_hash': '36a7a4c186aa8416b0585da2df0f8a58', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 61, 'avg_line_length': 18.842105263157894, 'alnum_prop': 0.5865921787709497, 'repo_name': 'AlmogBaku/actionable-connections', 'id': '02fe790aca46bff3259227a97906df90531cf66d', 'size': '358', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/load.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2844'}, {'name': 'HTML', 'bytes': '6605'}, {'name': 'JavaScript', 'bytes': '21727'}, {'name': 'Ruby', 'bytes': '969'}]}
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>org.apache.sysds.hops.rewrite (Apache SystemDS 2.3.0-SNAPSHOT API)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../../jquery/jquery-3.5.1.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.sysds.hops.rewrite (Apache SystemDS 2.3.0-SNAPSHOT API)"; } } catch(err) { } //--> var pathtoroot = "../../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <main role="main"> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.apache.sysds.hops.rewrite</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <th class="colFirst" scope="row"><a href="HopDagValidator.html" title="class in org.apache.sysds.hops.rewrite">HopDagValidator</a></th> <td class="colLast"> <div class="block">This class allows to check hop dags for validity, e.g., parent-child linking.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="HopRewriteRule.html" title="class in org.apache.sysds.hops.rewrite">HopRewriteRule</a></th> <td class="colLast"> <div class="block">Base class for all hop rewrites in order to enable generic application of all rules.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="HopRewriteUtils.html" title="class in org.apache.sysds.hops.rewrite">HopRewriteUtils</a></th> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="MarkForLineageReuse.html" title="class in org.apache.sysds.hops.rewrite">MarkForLineageReuse</a></th> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="ProgramRewriter.html" title="class in org.apache.sysds.hops.rewrite">ProgramRewriter</a></th> <td class="colLast"> <div class="block">This program rewriter applies a variety of rule-based rewrites on all hop dags of the given program in one pass over the entire program.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="ProgramRewriteStatus.html" title="class in org.apache.sysds.hops.rewrite">ProgramRewriteStatus</a></th> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteAlgebraicSimplificationDynamic.html" title="class in org.apache.sysds.hops.rewrite">RewriteAlgebraicSimplificationDynamic</a></th> <td class="colLast"> <div class="block">Rule: Algebraic Simplifications.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteAlgebraicSimplificationStatic.html" title="class in org.apache.sysds.hops.rewrite">RewriteAlgebraicSimplificationStatic</a></th> <td class="colLast"> <div class="block">Rule: Algebraic Simplifications.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteBlockSizeAndReblock.html" title="class in org.apache.sysds.hops.rewrite">RewriteBlockSizeAndReblock</a></th> <td class="colLast"> <div class="block">Rule: BlockSizeAndReblock.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteCommonSubexpressionElimination.html" title="class in org.apache.sysds.hops.rewrite">RewriteCommonSubexpressionElimination</a></th> <td class="colLast"> <div class="block">Rule: CommonSubexpressionElimination.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteCompressedReblock.html" title="class in org.apache.sysds.hops.rewrite">RewriteCompressedReblock</a></th> <td class="colLast"> <div class="block">Rule: Compressed Re block if config compressed.linalg is enabled, we inject compression directions after read of matrices if number of rows is above 1000 and cols at least 1.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteConstantFolding.html" title="class in org.apache.sysds.hops.rewrite">RewriteConstantFolding</a></th> <td class="colLast"> <div class="block">Rule: Constant Folding.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteElementwiseMultChainOptimization.html" title="class in org.apache.sysds.hops.rewrite">RewriteElementwiseMultChainOptimization</a></th> <td class="colLast"> <div class="block">Prerequisite: RewriteCommonSubexpressionElimination must run before this rule.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteFederatedExecution.html" title="class in org.apache.sysds.hops.rewrite">RewriteFederatedExecution</a></th> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteFederatedExecution.PrivacyConstraintRetriever.html" title="class in org.apache.sysds.hops.rewrite">RewriteFederatedExecution.PrivacyConstraintRetriever</a></th> <td class="colLast"> <div class="block">FederatedUDF for retrieving privacy constraint of data stored in file name.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteForLoopVectorization.html" title="class in org.apache.sysds.hops.rewrite">RewriteForLoopVectorization</a></th> <td class="colLast"> <div class="block">Rule: Simplify program structure by pulling if or else statement body out (removing the if statement block ifself) in order to allow intra-procedure analysis to propagate exact statistics.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteGPUSpecificOps.html" title="class in org.apache.sysds.hops.rewrite">RewriteGPUSpecificOps</a></th> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteHoistLoopInvariantOperations.html" title="class in org.apache.sysds.hops.rewrite">RewriteHoistLoopInvariantOperations</a></th> <td class="colLast"> <div class="block">Rule: Simplify program structure by hoisting loop-invariant operations out of while, for, or parfor loops.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteIndexingVectorization.html" title="class in org.apache.sysds.hops.rewrite">RewriteIndexingVectorization</a></th> <td class="colLast"> <div class="block">Rule: Indexing vectorization.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteInjectSparkLoopCheckpointing.html" title="class in org.apache.sysds.hops.rewrite">RewriteInjectSparkLoopCheckpointing</a></th> <td class="colLast"> <div class="block">Rule: Insert checkpointing operations for caching purposes.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteInjectSparkPReadCheckpointing.html" title="class in org.apache.sysds.hops.rewrite">RewriteInjectSparkPReadCheckpointing</a></th> <td class="colLast"> <div class="block">Rule: BlockSizeAndReblock.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteMarkLoopVariablesUpdateInPlace.html" title="class in org.apache.sysds.hops.rewrite">RewriteMarkLoopVariablesUpdateInPlace</a></th> <td class="colLast"> <div class="block">Rule: Mark loop variables that are only read/updated through cp left indexing for update in-place.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteMatrixMultChainOptimization.html" title="class in org.apache.sysds.hops.rewrite">RewriteMatrixMultChainOptimization</a></th> <td class="colLast"> <div class="block">Rule: Determine the optimal order of execution for a chain of matrix multiplications Solution: Classic Dynamic Programming Approach: Currently, the approach based only on matrix dimensions Goal: To reduce the number of computations in the run-time (map-reduce) layer</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteMatrixMultChainOptimizationSparse.html" title="class in org.apache.sysds.hops.rewrite">RewriteMatrixMultChainOptimizationSparse</a></th> <td class="colLast"> <div class="block">Rule: Determine the optimal order of execution for a chain of matrix multiplications Solution: Classic Dynamic Programming Approach: Currently, the approach based only on matrix dimensions and sparsity estimates using the MNC sketch Goal: To reduce the number of computations in the run-time (map-reduce) layer</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteMergeBlockSequence.html" title="class in org.apache.sysds.hops.rewrite">RewriteMergeBlockSequence</a></th> <td class="colLast"> <div class="block">Rule: Simplify program structure by merging sequences of last-level statement blocks in order to create optimization opportunities.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteRemoveDanglingParentReferences.html" title="class in org.apache.sysds.hops.rewrite">RewriteRemoveDanglingParentReferences</a></th> <td class="colLast"> <div class="block">This rewrite is a general-purpose cleanup pass that removes any dangling parent references in one pass through the hop DAG.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteRemoveEmptyBasicBlocks.html" title="class in org.apache.sysds.hops.rewrite">RewriteRemoveEmptyBasicBlocks</a></th> <td class="colLast"> <div class="block">Rule: Simplify program structure by removing empty last-level blocks, which may originate from the original program or due to a sequence of rewrites (e.g., checkpoint injection and subsequent IPA).</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteRemoveForLoopEmptySequence.html" title="class in org.apache.sysds.hops.rewrite">RewriteRemoveForLoopEmptySequence</a></th> <td class="colLast"> <div class="block">Rule: Simplify program structure by removing (par)for statements iterating over an empty sequence, i.e., (par)for-loops without a single iteration.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteRemovePersistentReadWrite.html" title="class in org.apache.sysds.hops.rewrite">RewriteRemovePersistentReadWrite</a></th> <td class="colLast"> <div class="block">This rewrite is a custom rewrite for JMLC in order to replace all persistent reads and writes with transient reads and writes from the symbol table.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteRemoveReadAfterWrite.html" title="class in org.apache.sysds.hops.rewrite">RewriteRemoveReadAfterWrite</a></th> <td class="colLast"> <div class="block">Rule: RemoveReadAfterWrite.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteRemoveUnnecessaryBranches.html" title="class in org.apache.sysds.hops.rewrite">RewriteRemoveUnnecessaryBranches</a></th> <td class="colLast"> <div class="block">Rule: Simplify program structure by pulling if or else statement body out (removing the if statement block ifself) in order to allow intra-procedure analysis to propagate exact statistics.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteRemoveUnnecessaryCasts.html" title="class in org.apache.sysds.hops.rewrite">RewriteRemoveUnnecessaryCasts</a></th> <td class="colLast"> <div class="block">Rule: RemoveUnnecessaryCasts.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteSplitDagDataDependentOperators.html" title="class in org.apache.sysds.hops.rewrite">RewriteSplitDagDataDependentOperators</a></th> <td class="colLast"> <div class="block">Rule: Split Hop DAG after specific data-dependent operators.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="RewriteSplitDagUnknownCSVRead.html" title="class in org.apache.sysds.hops.rewrite">RewriteSplitDagUnknownCSVRead</a></th> <td class="colLast"> <div class="block">Rule: Split Hop DAG after CSV reads with unknown size.</div> </td> </tr> <tr class="altColor"> <th class="colFirst" scope="row"><a href="RewriteTransientWriteParentHandling.html" title="class in org.apache.sysds.hops.rewrite">RewriteTransientWriteParentHandling</a></th> <td class="colLast"> <div class="block">Rule: Eliminate for Transient Write DataHops to have no parents Solution: Move parent edges of Transient Write Hop to parent of its child Reason: Transient Write not being a root messes up analysis for Lop's to Instruction translation (according to Amol)</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="StatementBlockRewriteRule.html" title="class in org.apache.sysds.hops.rewrite">StatementBlockRewriteRule</a></th> <td class="colLast"> <div class="block">Base class for all hop rewrites in order to enable generic application of all rules.</div> </td> </tr> </tbody> </table> </li> </ul> </div> </main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a id="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small>Copyright &#169; 2021 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </footer> </body> </html>
{'content_hash': 'c6c9c5767385cfd29ac8a1fe3449e7f4', 'timestamp': '', 'source': 'github', 'line_count': 402, 'max_line_length': 209, 'avg_line_length': 42.975124378109456, 'alnum_prop': 0.7137647603611947, 'repo_name': 'apache/incubator-systemml', 'id': '08b06266cc8c1246ca65a3d080656b69af73a718', 'size': '17276', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/api/java/org/apache/sysds/hops/rewrite/package-summary.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '31285'}, {'name': 'Batchfile', 'bytes': '22265'}, {'name': 'C', 'bytes': '8676'}, {'name': 'C++', 'bytes': '30804'}, {'name': 'CMake', 'bytes': '10312'}, {'name': 'Cuda', 'bytes': '30575'}, {'name': 'Java', 'bytes': '12990600'}, {'name': 'Jupyter Notebook', 'bytes': '36387'}, {'name': 'Makefile', 'bytes': '936'}, {'name': 'Protocol Buffer', 'bytes': '66399'}, {'name': 'Python', 'bytes': '195969'}, {'name': 'R', 'bytes': '672462'}, {'name': 'Scala', 'bytes': '185698'}, {'name': 'Shell', 'bytes': '152940'}]}
[![npm version](https://badge.fury.io/js/snowscape.svg)](https://badge.fury.io/js/snowscape) install ``` $ npm i -g snowscape ``` execute ``` $ snowscape ```
{'content_hash': '17e5ca5c68910c31b27389f6617a6a74', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 92, 'avg_line_length': 12.461538461538462, 'alnum_prop': 0.6419753086419753, 'repo_name': 'feb19/snowscape', 'id': 'fd253f8c48c1f196f05b13ebb91ecb592d5474ce', 'size': '174', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3138'}]}
import React from 'react'; class Home extends React.Component { render() { return ( <div className='container'> <div className='page-header'> <h1>Events at Hacker Dojo</h1> </div> </div> ); } } export default Home;
{'content_hash': '50e9be366080b11eb277139a95ec9f20', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 40, 'avg_line_length': 17.733333333333334, 'alnum_prop': 0.5639097744360902, 'repo_name': 'billsaysthis/fhd-events', 'id': '7d3e3ecc7a60b0b24c293e8d1c9dea0468f4c5b2', 'size': '266', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/components/Home.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '188402'}, {'name': 'HTML', 'bytes': '562'}, {'name': 'JavaScript', 'bytes': '1270421'}]}
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textAbout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scrollbars="vertical" android:textAppearance="?android:attr/textAppearanceSmall" android:textSize="10sp" /> </FrameLayout>
{'content_hash': 'b02b9f1012d7337f090934bf27e4989f', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 71, 'avg_line_length': 35.0, 'alnum_prop': 0.6795918367346939, 'repo_name': 'darizotas/metadatastrip', 'id': '9fc8e19b892f2f4f684a114b8cec625c8d228313', 'size': '490', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'res/layout/fragment_about_dialog.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '53237'}]}
require 'spec_helper' require 'whois/parsers/whois.domain-registry.nl.rb' describe Whois::Parsers::WhoisDomainRegistryNl, "property_nameservers_with_ip.expected" do subject do file = fixture("responses", "whois.domain-registry.nl/nl/property_nameservers_with_ip.txt") part = Whois::Record::Part.new(body: File.read(file)) described_class.new(part) end describe "#nameservers" do it do expect(subject.nameservers).to be_a(Array) expect(subject.nameservers.size).to eq(2) expect(subject.nameservers[0]).to be_a(Whois::Parser::Nameserver) expect(subject.nameservers[0].name).to eq("ns1.tntpost.nl") expect(subject.nameservers[0].ipv4).to eq("145.78.21.10") expect(subject.nameservers[1]).to be_a(Whois::Parser::Nameserver) expect(subject.nameservers[1].name).to eq("ns2.tntpost.nl") expect(subject.nameservers[1].ipv4).to eq("80.69.76.10") end end end
{'content_hash': '36a94a975b59b844990eaf6831f65d24', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 95, 'avg_line_length': 38.666666666666664, 'alnum_prop': 0.7036637931034483, 'repo_name': 'weppos/whois-parser', 'id': 'efc7e3d23dffc383757c1a414bd52dd779fca89c', 'size': '1220', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'spec/whois/parsers/responses/whois.domain-registry.nl/nl/property_nameservers_with_ip_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '2354053'}]}
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkInteractorStyleWrap.h" #include "vtkInteractorStyleSwitchBaseWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkRenderWindowInteractorWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkInteractorStyleSwitchBaseWrap::ptpl; VtkInteractorStyleSwitchBaseWrap::VtkInteractorStyleSwitchBaseWrap() { } VtkInteractorStyleSwitchBaseWrap::VtkInteractorStyleSwitchBaseWrap(vtkSmartPointer<vtkInteractorStyleSwitchBase> _native) { native = _native; } VtkInteractorStyleSwitchBaseWrap::~VtkInteractorStyleSwitchBaseWrap() { } void VtkInteractorStyleSwitchBaseWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkInteractorStyleSwitchBase").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("InteractorStyleSwitchBase").ToLocalChecked(), ConstructorGetter); } void VtkInteractorStyleSwitchBaseWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkInteractorStyleSwitchBaseWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkInteractorStyleWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkInteractorStyleWrap::ptpl)); tpl->SetClassName(Nan::New("VtkInteractorStyleSwitchBaseWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetInteractor", GetInteractor); Nan::SetPrototypeMethod(tpl, "getInteractor", GetInteractor); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); #ifdef VTK_NODE_PLUS_VTKINTERACTORSTYLESWITCHBASEWRAP_INITPTPL VTK_NODE_PLUS_VTKINTERACTORSTYLESWITCHBASEWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkInteractorStyleSwitchBaseWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkInteractorStyleSwitchBase> native = vtkSmartPointer<vtkInteractorStyleSwitchBase>::New(); VtkInteractorStyleSwitchBaseWrap* obj = new VtkInteractorStyleSwitchBaseWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkInteractorStyleSwitchBaseWrap::GetInteractor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkInteractorStyleSwitchBaseWrap *wrapper = ObjectWrap::Unwrap<VtkInteractorStyleSwitchBaseWrap>(info.Holder()); vtkInteractorStyleSwitchBase *native = (vtkInteractorStyleSwitchBase *)wrapper->native.GetPointer(); vtkRenderWindowInteractor * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetInteractor(); VtkRenderWindowInteractorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkRenderWindowInteractorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkRenderWindowInteractorWrap *w = new VtkRenderWindowInteractorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkInteractorStyleSwitchBaseWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkInteractorStyleSwitchBaseWrap *wrapper = ObjectWrap::Unwrap<VtkInteractorStyleSwitchBaseWrap>(info.Holder()); vtkInteractorStyleSwitchBase *native = (vtkInteractorStyleSwitchBase *)wrapper->native.GetPointer(); vtkInteractorStyleSwitchBase * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkInteractorStyleSwitchBaseWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkInteractorStyleSwitchBaseWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkInteractorStyleSwitchBaseWrap *w = new VtkInteractorStyleSwitchBaseWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkInteractorStyleSwitchBaseWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkInteractorStyleSwitchBaseWrap *wrapper = ObjectWrap::Unwrap<VtkInteractorStyleSwitchBaseWrap>(info.Holder()); vtkInteractorStyleSwitchBase *native = (vtkInteractorStyleSwitchBase *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkInteractorStyleSwitchBase * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkInteractorStyleSwitchBaseWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkInteractorStyleSwitchBaseWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkInteractorStyleSwitchBaseWrap *w = new VtkInteractorStyleSwitchBaseWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); }
{'content_hash': 'db6ea02455b20b2e030aa0814f3a9bfd', 'timestamp': '', 'source': 'github', 'line_count': 168, 'max_line_length': 121, 'avg_line_length': 34.839285714285715, 'alnum_prop': 0.7602938663933025, 'repo_name': 'axkibe/node-vtk', 'id': 'aaddcc5a42c3ccb35bc437ac72788797d460bd5a', 'size': '5853', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'wrappers/8.1.1/vtkInteractorStyleSwitchBaseWrap.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C++', 'bytes': '75388342'}, {'name': 'CMake', 'bytes': '915'}, {'name': 'JavaScript', 'bytes': '70'}, {'name': 'Roff', 'bytes': '145455'}]}
package org.hisp.dhis.mock.batchhandler; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.amplecode.quick.BatchHandler; import org.amplecode.quick.JdbcConfiguration; /** * @author Lars Helge Overland */ public class MockBatchHandler<T> implements BatchHandler<T> { private List<T> inserts = new ArrayList<>(); private List<T> updates = new ArrayList<>(); private List<T> deletes = new ArrayList<>(); @Override public BatchHandler<T> init() { return this; } @Override public JdbcConfiguration getConfiguration() { return null; } @Override public BatchHandler<T> setTableName( String name ) { return this; } @Override public boolean addObject( T object ) { return inserts.add( object ); } @Override public int insertObject( T object, boolean returnGeneratedIdentifier ) { inserts.add( object ); return 0; } @Override public void updateObject( T object ) { updates.add( object ); } @Override public void deleteObject( T object ) { deletes.add( object ); } @Override public boolean objectExists( T object ) { return false; } @Override public int getObjectIdentifier( Object object ) { return 0; } @Override public Collection<Integer> flush() { return new HashSet<>(); } public List<T> getInserts() { return inserts; } public List<T> getUpdates() { return updates; } public List<T> getDeletes() { return deletes; } }
{'content_hash': '5f3f68d280b8bdeb222ff64bf20fe0c0', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 74, 'avg_line_length': 17.79591836734694, 'alnum_prop': 0.5934633027522935, 'repo_name': 'kakada/dhis2', 'id': '9f17eb995a46e8f5be7ce85c50a09ec839035075', 'size': '3300', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dhis-support/dhis-support-test/src/main/java/org/hisp/dhis/mock/batchhandler/MockBatchHandler.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '396164'}, {'name': 'Game Maker Language', 'bytes': '20893'}, {'name': 'HTML', 'bytes': '340997'}, {'name': 'Java', 'bytes': '18116166'}, {'name': 'JavaScript', 'bytes': '7103857'}, {'name': 'Ruby', 'bytes': '1011'}, {'name': 'Shell', 'bytes': '376'}, {'name': 'XSLT', 'bytes': '24103'}]}
<?xml version="1.0" encoding="UTF-8"?> <sem:triples xmlns:sem="http://marklogic.com/semantics"> <sem:triple> <sem:subject>http://www.lds.org/concept/cpg/faith-in-the-lord-jesus-christ</sem:subject> <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate> <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/concept/cpg/faith-in-the-lord-jesus-christ</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate> <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/curriculum-planning-guide</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/concept/cpg/faith-in-the-lord-jesus-christ</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate> <sem:object xml:lang="eng" datatype="xsd:string">Faith in the Lord Jesus Christ</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/concept/cpg/faith-in-the-lord-jesus-christ</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#narrower</sem:predicate> <sem:object datatype="sem:iri">http://www.lds.org/concept/cpg/principles-ordinances-and-covenants-of-the-gospel</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/concept/cpg/faith-in-the-lord-jesus-christ</sem:subject> <sem:predicate>http://www.lds.org/core#relCount</sem:predicate> <sem:object datatype="xsd:integer">1</sem:object> </sem:triple> </sem:triples>
{'content_hash': '854ece2ef8213be1103c14efb3eb0781', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 128, 'avg_line_length': 57.25, 'alnum_prop': 0.7117903930131004, 'repo_name': 'freshie/ml-taxonomies', 'id': 'b724cc22dd0510d70bcab0e2075d691a0e8162e9', 'size': '1603', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'roxy/data/gospel-topical-explorer-v2/taxonomies/doctrine/cpg/faith-in-the-lord-jesus-christ.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4422'}, {'name': 'CSS', 'bytes': '38665'}, {'name': 'HTML', 'bytes': '356'}, {'name': 'JavaScript', 'bytes': '411651'}, {'name': 'Ruby', 'bytes': '259121'}, {'name': 'Shell', 'bytes': '7329'}, {'name': 'XQuery', 'bytes': '857170'}, {'name': 'XSLT', 'bytes': '13753'}]}
package com.f2prateek.couchpotato.ui.debug; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewDebug; import com.f2prateek.couchpotato.ui.ActivityHierarchyServer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * <p>This class can be used to enable the use of HierarchyViewer inside an * application. HierarchyViewer is an Android SDK tool that can be used * to inspect and debug the user interface of running applications. For * security reasons, HierarchyViewer does not work on production builds * (for instance phones bought in store.) By using this class, you can * make HierarchyViewer work on any device. You must be very careful * however to only enable HierarchyViewer when debugging your * application.</p> * * <p>To use this view server, your application must require the INTERNET * permission.</p> */ public class SocketActivityHierarchyServer implements Runnable, ActivityHierarchyServer { /** * The default port used to start view servers. */ private static final int VIEW_SERVER_DEFAULT_PORT = 4939; private static final int VIEW_SERVER_MAX_CONNECTIONS = 10; private static final String LOG_TAG = "SocketActivityHierarchyServer"; private static final String VALUE_PROTOCOL_VERSION = "4"; private static final String VALUE_SERVER_VERSION = "4"; // Protocol commands // Returns the protocol version private static final String COMMAND_PROTOCOL_VERSION = "PROTOCOL"; // Returns the server version private static final String COMMAND_SERVER_VERSION = "SERVER"; // Lists all of the available windows in the system private static final String COMMAND_WINDOW_MANAGER_LIST = "LIST"; // Keeps a connection open and notifies when the list of windows changes private static final String COMMAND_WINDOW_MANAGER_AUTOLIST = "AUTOLIST"; // Returns the focused window private static final String COMMAND_WINDOW_MANAGER_GET_FOCUS = "GET_FOCUS"; private ServerSocket mServer; private final int mPort; private Thread mThread; private ExecutorService mThreadPool; private final List<WindowListener> mListeners = new CopyOnWriteArrayList<>(); private final HashMap<View, String> mWindows = new HashMap<>(); private final ReentrantReadWriteLock mWindowsLock = new ReentrantReadWriteLock(); private View mFocusedWindow; private final ReentrantReadWriteLock mFocusLock = new ReentrantReadWriteLock(); /** * Creates a new ActivityHierarchyServer associated with the specified window manager on the * default local port. The server is not started by default. * * @see #start() */ public SocketActivityHierarchyServer() { mPort = SocketActivityHierarchyServer.VIEW_SERVER_DEFAULT_PORT; } /** * Starts the server. * * @return True if the server was successfully created, or false if it already exists. * @throws java.io.IOException If the server cannot be created. */ public boolean start() throws IOException { if (mThread != null) { return false; } mThread = new Thread(this, "Local View Server [port=" + mPort + "]"); mThreadPool = Executors.newFixedThreadPool(VIEW_SERVER_MAX_CONNECTIONS); mThread.start(); return true; } @Override public void onActivityCreated(Activity activity, Bundle bundle) { String name = activity.getTitle().toString(); if (TextUtils.isEmpty(name)) { name = activity.getClass().getCanonicalName() // + "/0x" + System.identityHashCode(activity); } else { name += " (" + activity.getClass().getCanonicalName() + ")"; } mWindowsLock.writeLock().lock(); try { mWindows.put(activity.getWindow().getDecorView().getRootView(), name); } finally { mWindowsLock.writeLock().unlock(); } fireWindowsChangedEvent(); } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { View view = activity.getWindow().getDecorView(); mFocusLock.writeLock().lock(); try { mFocusedWindow = view == null ? null : view.getRootView(); } finally { mFocusLock.writeLock().unlock(); } fireFocusChangedEvent(); } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } @Override public void onActivityDestroyed(Activity activity) { mWindowsLock.writeLock().lock(); try { mWindows.remove(activity.getWindow().getDecorView().getRootView()); } finally { mWindowsLock.writeLock().unlock(); } fireWindowsChangedEvent(); } public void run() { try { mServer = new ServerSocket(mPort, VIEW_SERVER_MAX_CONNECTIONS, InetAddress.getLocalHost()); } catch (Exception e) { Log.w(LOG_TAG, "Starting ServerSocket error: ", e); } while (mServer != null && Thread.currentThread() == mThread) { // Any uncaught exception will crash the system process try { Socket client = mServer.accept(); if (mThreadPool != null) { mThreadPool.submit(new ViewServerWorker(client)); } else { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { Log.w(LOG_TAG, "Connection error: ", e); } } } private static boolean writeValue(Socket client, String value) { boolean result; BufferedWriter out = null; try { OutputStream clientStream = client.getOutputStream(); out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024); out.write(value); out.write("\n"); out.flush(); result = true; } catch (Exception e) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; } private void fireWindowsChangedEvent() { for (WindowListener listener : mListeners) { listener.windowsChanged(); } } private void fireFocusChangedEvent() { for (WindowListener listener : mListeners) { listener.focusChanged(); } } private void addWindowListener(WindowListener listener) { if (!mListeners.contains(listener)) { mListeners.add(listener); } } private void removeWindowListener(WindowListener listener) { mListeners.remove(listener); } private interface WindowListener { void windowsChanged(); void focusChanged(); } private static class UncloseableOutputStream extends OutputStream { private final OutputStream mStream; UncloseableOutputStream(OutputStream stream) { mStream = stream; } public void close() throws IOException { // Don't close the stream } public boolean equals(Object o) { return mStream.equals(o); } public void flush() throws IOException { mStream.flush(); } public int hashCode() { return mStream.hashCode(); } public String toString() { return mStream.toString(); } public void write(byte[] buffer, int offset, int count) throws IOException { mStream.write(buffer, offset, count); } public void write(byte[] buffer) throws IOException { mStream.write(buffer); } public void write(int oneByte) throws IOException { mStream.write(oneByte); } } private class ViewServerWorker implements Runnable, WindowListener { private Socket mClient; private boolean mNeedWindowListUpdate; private boolean mNeedFocusedWindowUpdate; private final Object[] mLock = new Object[0]; public ViewServerWorker(Socket client) { mClient = client; mNeedWindowListUpdate = false; mNeedFocusedWindowUpdate = false; } public void run() { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(mClient.getInputStream()), 1024); final String request = in.readLine(); String command; String parameters; int index = request.indexOf(' '); if (index == -1) { command = request; parameters = ""; } else { command = request.substring(0, index); parameters = request.substring(index + 1); } boolean result; if (COMMAND_PROTOCOL_VERSION.equalsIgnoreCase(command)) { result = writeValue(mClient, VALUE_PROTOCOL_VERSION); } else if (COMMAND_SERVER_VERSION.equalsIgnoreCase(command)) { result = writeValue(mClient, VALUE_SERVER_VERSION); } else if (COMMAND_WINDOW_MANAGER_LIST.equalsIgnoreCase(command)) { result = listWindows(mClient); } else if (COMMAND_WINDOW_MANAGER_GET_FOCUS.equalsIgnoreCase(command)) { result = getFocusedWindow(mClient); } else if (COMMAND_WINDOW_MANAGER_AUTOLIST.equalsIgnoreCase(command)) { result = windowManagerAutolistLoop(); } else { result = windowCommand(mClient, command, parameters); } if (!result) { Log.w(LOG_TAG, "An error occurred with the command: " + command); } } catch (IOException e) { Log.w(LOG_TAG, "Connection error: ", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (mClient != null) { try { mClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } private boolean windowCommand(Socket client, String command, String parameters) { boolean success = true; BufferedWriter out = null; try { // Find the hash code of the window int index = parameters.indexOf(' '); if (index == -1) { index = parameters.length(); } final String code = parameters.substring(0, index); int hashCode = (int) Long.parseLong(code, 16); // Extract the command's parameter after the window description if (index < parameters.length()) { parameters = parameters.substring(index + 1); } else { parameters = ""; } final View window = findWindow(hashCode); if (window == null) { return false; } // call stuff final Method dispatch = ViewDebug.class.getDeclaredMethod("dispatchCommand", View.class, String.class, String.class, OutputStream.class); dispatch.setAccessible(true); dispatch.invoke(null, window, command, parameters, new UncloseableOutputStream(client.getOutputStream())); if (!client.isOutputShutdown()) { out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); out.write("DONE\n"); out.flush(); } } catch (Exception e) { Log.w(LOG_TAG, "Could not send command " + command // + " with parameters " + parameters, e); success = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { success = false; } } } return success; } private View findWindow(int hashCode) { if (hashCode == -1) { View window = null; mWindowsLock.readLock().lock(); try { window = mFocusedWindow; } finally { mWindowsLock.readLock().unlock(); } return window; } mWindowsLock.readLock().lock(); try { for (Entry<View, String> entry : mWindows.entrySet()) { if (System.identityHashCode(entry.getKey()) == hashCode) { return entry.getKey(); } } } finally { mWindowsLock.readLock().unlock(); } return null; } private boolean listWindows(Socket client) { boolean result = true; BufferedWriter out = null; try { mWindowsLock.readLock().lock(); OutputStream clientStream = client.getOutputStream(); out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024); for (Entry<View, String> entry : mWindows.entrySet()) { out.write(Integer.toHexString(System.identityHashCode(entry.getKey()))); out.write(' '); out.append(entry.getValue()); out.write('\n'); } out.write("DONE.\n"); out.flush(); } catch (Exception e) { result = false; } finally { mWindowsLock.readLock().unlock(); if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; } private boolean getFocusedWindow(Socket client) { boolean result = true; String focusName = null; BufferedWriter out = null; try { OutputStream clientStream = client.getOutputStream(); out = new BufferedWriter(new OutputStreamWriter(clientStream), 8 * 1024); View focusedWindow = null; mFocusLock.readLock().lock(); try { focusedWindow = mFocusedWindow; } finally { mFocusLock.readLock().unlock(); } if (focusedWindow != null) { mWindowsLock.readLock().lock(); try { focusName = mWindows.get(mFocusedWindow); } finally { mWindowsLock.readLock().unlock(); } out.write(Integer.toHexString(System.identityHashCode(focusedWindow))); out.write(' '); out.append(focusName); } out.write('\n'); out.flush(); } catch (Exception e) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; } public void windowsChanged() { synchronized (mLock) { mNeedWindowListUpdate = true; mLock.notifyAll(); } } public void focusChanged() { synchronized (mLock) { mNeedFocusedWindowUpdate = true; mLock.notifyAll(); } } private boolean windowManagerAutolistLoop() { addWindowListener(this); BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(mClient.getOutputStream())); while (!Thread.interrupted()) { boolean needWindowListUpdate = false; boolean needFocusedWindowUpdate = false; synchronized (mLock) { while (!mNeedWindowListUpdate && !mNeedFocusedWindowUpdate) { mLock.wait(); } if (mNeedWindowListUpdate) { mNeedWindowListUpdate = false; needWindowListUpdate = true; } if (mNeedFocusedWindowUpdate) { mNeedFocusedWindowUpdate = false; needFocusedWindowUpdate = true; } } if (needWindowListUpdate) { out.write("LIST UPDATE\n"); out.flush(); } if (needFocusedWindowUpdate) { out.write("FOCUS UPDATE\n"); out.flush(); } } } catch (Exception e) { Log.w(LOG_TAG, "Connection error: ", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } removeWindowListener(this); } return true; } } }
{'content_hash': '5b00cafe7a2acf228acf86c95a9914a0', 'timestamp': '', 'source': 'github', 'line_count': 570, 'max_line_length': 97, 'avg_line_length': 28.887719298245614, 'alnum_prop': 0.6141746629418195, 'repo_name': 'f2prateek/android-couchpotato', 'id': '9102ff4757bcec5b781573f21ebdbb1d7a2a25f6', 'size': '17066', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'couchpotato/src/debug/java/com/f2prateek/couchpotato/ui/debug/SocketActivityHierarchyServer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '5268'}, {'name': 'Java', 'bytes': '410944'}]}
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Bullseye</title> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyByl4gRpPmSXUOYX3SA8n-t_WvvNcEf79A&libraries=places,geometry"> </script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet"> <link href="style.css" rel="stylesheet"> </head> <body> <div id="app"></div> </body> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script> <script src="bundle.js" defer></script> </html>
{'content_hash': '67845dbc237d11c49701ae52a109b1f3', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 136, 'avg_line_length': 37.04545454545455, 'alnum_prop': 0.7165644171779141, 'repo_name': 'Bullseyed/Bullseye', 'id': 'fe6188aaeb536e17731d55fa310190ced5444117', 'size': '815', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1366'}, {'name': 'HTML', 'bytes': '815'}, {'name': 'JavaScript', 'bytes': '3439188'}]}
use inventory_vector::InventoryVector; use {Encode, VarInt}; #[cfg(test)] mod tests { use super::*; #[test] fn it_implements_types_required_for_protocol() { let m = InvMessage::default(); assert_eq!(m.name(), "inv"); assert_eq!(m.len(), 8); } } #[derive(Debug, Default, Encode, PartialEq)] pub struct InvMessage { #[count] pub inventory: Vec<InventoryVector>, } impl InvMessage { #[inline] pub fn len(&self) -> usize { 8 + (36 * self.inventory.len()) } #[inline] pub fn name(&self) -> &'static str { "inv" } }
{'content_hash': '80e9e3cb1651aaa8d3aa8a6fb8cae947', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 52, 'avg_line_length': 19.451612903225808, 'alnum_prop': 0.5588723051409619, 'repo_name': 'tomasvdw/bitcrust', 'id': '3440feedd275c1f3e4ec4b23a3f3e34ef4ae4df9', 'size': '603', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'net/src/message/inv_message.rs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '10080'}, {'name': 'HTML', 'bytes': '28242'}, {'name': 'JavaScript', 'bytes': '863'}, {'name': 'Python', 'bytes': '3826'}, {'name': 'Rust', 'bytes': '794393'}, {'name': 'Shell', 'bytes': '3988'}]}
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class mil_navy_nrl_norm_NormStream */ #ifndef _Included_mil_navy_nrl_norm_NormStream #define _Included_mil_navy_nrl_norm_NormStream #ifdef __cplusplus extern "C" { #endif /* * Class: mil_navy_nrl_norm_NormStream * Method: close * Signature: (Z)V */ JNIEXPORT void JNICALL Java_mil_navy_nrl_norm_NormStream_close (JNIEnv *, jobject, jboolean); /* * Class: mil_navy_nrl_norm_NormStream * Method: write * Signature: ([BII)I */ JNIEXPORT jint JNICALL Java_mil_navy_nrl_norm_NormStream_write (JNIEnv *, jobject, jbyteArray, jint, jint); /* * Class: mil_navy_nrl_norm_NormStream * Method: flush * Signature: (ZLmil/navy/nrl/norm/enums/NormFlushMode;)V */ JNIEXPORT void JNICALL Java_mil_navy_nrl_norm_NormStream_flush (JNIEnv *, jobject, jboolean, jobject); /* * Class: mil_navy_nrl_norm_NormStream * Method: setAutoFlush * Signature: (Lmil/navy/nrl/norm/enums/NormFlushMode;)V */ JNIEXPORT void JNICALL Java_mil_navy_nrl_norm_NormStream_setAutoFlush (JNIEnv *, jobject, jobject); /* * Class: mil_navy_nrl_norm_NormStream * Method: setPushEnable * Signature: (Z)V */ JNIEXPORT void JNICALL Java_mil_navy_nrl_norm_NormStream_setPushEnable (JNIEnv *, jobject, jboolean); /* * Class: mil_navy_nrl_norm_NormStream * Method: hasVacancy * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_mil_navy_nrl_norm_NormStream_hasVacancy (JNIEnv *, jobject); /* * Class: mil_navy_nrl_norm_NormStream * Method: markEom * Signature: ()V */ JNIEXPORT void JNICALL Java_mil_navy_nrl_norm_NormStream_markEom (JNIEnv *, jobject); /* * Class: mil_navy_nrl_norm_NormStream * Method: read * Signature: ([BII)I */ JNIEXPORT jint JNICALL Java_mil_navy_nrl_norm_NormStream_read (JNIEnv *, jobject, jbyteArray, jint, jint); /* * Class: mil_navy_nrl_norm_NormStream * Method: seekMsgStart * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_mil_navy_nrl_norm_NormStream_seekMsgStart (JNIEnv *, jobject); /* * Class: mil_navy_nrl_norm_NormStream * Method: getReadOffset * Signature: ()J */ JNIEXPORT jlong JNICALL Java_mil_navy_nrl_norm_NormStream_getReadOffset (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
{'content_hash': '1addd502f472cbbc1629ea93dac56bfa', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 73, 'avg_line_length': 24.817204301075268, 'alnum_prop': 0.6941074523396881, 'repo_name': 'aletheia7/norm', 'id': '48696f4aa48fe6229b83dd4a6a9531124691cd7f', 'size': '2308', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'norm/src/java/jni/normStreamJni.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Go', 'bytes': '70061'}]}
<!DOCTYPE html> <!-- | Generated by Apache Maven Doxia at 2016-07-27 | Rendered using Apache Maven Fluido Skin 1.4 --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="Date-Revision-yyyymmdd" content="20160727" /> <meta http-equiv="Content-Language" content="en" /> <title>PMD JavaScript &#x2013; Surefire Report</title> <link rel="stylesheet" href="./css/apache-maven-fluido-1.4.min.css" /> <link rel="stylesheet" href="./css/site.css" /> <link rel="stylesheet" href="./css/print.css" media="print" /> <script type="text/javascript" src="./js/apache-maven-fluido-1.4.min.js"></script> </head> <body class="topBarEnabled"> <a href="https://github.com/pmd/pmd"> <img style="position: absolute; top: 0; right: 0; border: 0; z-index: 10000;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"> </a> <div id="topbar" class="navbar navbar-fixed-top "> <div class="navbar-inner"> <div class="container-fluid"> <a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="index.html" title="PMD"> <img src="images/logo/pmd_logo_tiny.png" alt="PMD" /> </a> <ul class="nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Parent Project <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="../index.html" title="PMD">PMD</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Rule Sets <b class="caret"></b></a> <ul class="dropdown-menu"> <li class="dropdown-submenu"> <a href="rules/index.html" title="ecmascript">ecmascript</a> <ul class="dropdown-menu"> <li> <a href="rules/ecmascript/basic.html" title="Basic Ecmascript">Basic Ecmascript</a> </li> <li> <a href="rules/ecmascript/braces.html" title="Braces">Braces</a> </li> <li> <a href="rules/ecmascript/controversial.html" title="Controversial Ecmascript">Controversial Ecmascript</a> </li> <li> <a href="rules/ecmascript/unnecessary.html" title="Unnecessary">Unnecessary</a> </li> </ul> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Project Documentation <b class="caret"></b></a> <ul class="dropdown-menu"> <li class="dropdown-submenu"> <a href="project-info.html" title="Project Information">Project Information</a> <ul class="dropdown-menu"> <li> <a href="project-summary.html" title="Project Summary">Project Summary</a> </li> <li> <a href="dependencies.html" title="Dependencies">Dependencies</a> </li> <li> <a href="dependency-convergence.html" title="Dependency Convergence">Dependency Convergence</a> </li> <li> <a href="dependency-info.html" title="Dependency Information">Dependency Information</a> </li> <li> <a href="dependency-management.html" title="Dependency Management">Dependency Management</a> </li> <li> <a href="plugin-management.html" title="Plugin Management">Plugin Management</a> </li> <li> <a href="plugins.html" title="Project Plugins">Project Plugins</a> </li> <li> <a href="team-list.html" title="Project Team">Project Team</a> </li> <li> <a href="mail-lists.html" title="Mailing Lists">Mailing Lists</a> </li> <li> <a href="integration.html" title="Continuous Integration">Continuous Integration</a> </li> <li> <a href="issue-tracking.html" title="Issue Tracking">Issue Tracking</a> </li> <li> <a href="license.html" title="Project License">Project License</a> </li> <li> <a href="source-repository.html" title="Source Repository">Source Repository</a> </li> </ul> </li> <li class="dropdown-submenu"> <a href="project-reports.html" title="Project Reports">Project Reports</a> <ul class="dropdown-menu"> <li> <a href="xref/index.html" title="Source Xref">Source Xref</a> </li> <li> <a href="xref-test/index.html" title="Test Source Xref">Test Source Xref</a> </li> <li> <a href="apidocs/index.html" title="JavaDocs">JavaDocs</a> </li> <li> <a href="testapidocs/index.html" title="Test JavaDocs">Test JavaDocs</a> </li> <li> <a href="cpd.html" title="CPD">CPD</a> </li> <li> <a href="checkstyle.html" title="Checkstyle">Checkstyle</a> </li> <li> <a href="surefire-report.html" title="Surefire Report">Surefire Report</a> </li> <li> <a href="jacoco/index.html" title="JaCoCo Test">JaCoCo Test</a> </li> <li> <a href="dependency-updates-report.html" title="Dependency Updates Report">Dependency Updates Report</a> </li> <li> <a href="plugin-updates-report.html" title="Plugin Updates Report">Plugin Updates Report</a> </li> <li> <a href="property-updates-report.html" title="Property Updates Report">Property Updates Report</a> </li> </ul> </li> </ul> </li> </ul> <ul class="nav pull-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">External Links <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="http://sourceforge.net/projects/pmd" title="SourceForge.net Project Page">SourceForge.net Project Page</a> </li> <li> <a href="http://sourceforge.net" title="Hosted by SourceForge">Hosted by SourceForge</a> </li> </ul> </li> </ul> </div> </div> </div> </div> <div class="container-fluid"> <div id="banner"> <div class="pull-left"> <a href="../" id="bannerLeft"> <img src="../images/logo/pmd_logo_small.png" alt="pmd-logo"/> </a> </div> <div class="pull-right"> <a href="http://sourceforge.net/" id="bannerRight"> <img src="../images/sflogo.png" alt="SourceForge"/> </a> </div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 2016-07-27 <span class="divider">|</span> </li> <li id="projectVersion">Version: 5.5.1 <span class="divider">|</span> </li> <li class=""> <a href="http://www.sourceforge.net/" class="externalLink" title="SourceForge"> SourceForge</a> <span class="divider">/</span> </li> <li class=""> <a href="../" title="PMD"> PMD</a> <span class="divider">/</span> </li> <li class=""> <a href="./" title="PMD JavaScript"> PMD JavaScript</a> <span class="divider">/</span> </li> <li class="active ">Surefire Report</li> </ul> </div> <div class="row-fluid"> <div id="leftColumn" class="span2"> <div class="well sidebar-nav"> <ul class="nav nav-list"> <li class="nav-header">Parent Project</li> <li> <a href="../index.html" title="PMD"> <span class="none"></span> PMD</a> </li> <li class="nav-header">Rule Sets</li> <li> <a href="rules/index.html" title="ecmascript"> <span class="icon-chevron-down"></span> ecmascript</a> <ul class="nav nav-list"> <li> <a href="rules/ecmascript/basic.html" title="Basic Ecmascript"> <span class="none"></span> Basic Ecmascript</a> </li> <li> <a href="rules/ecmascript/braces.html" title="Braces"> <span class="none"></span> Braces</a> </li> <li> <a href="rules/ecmascript/controversial.html" title="Controversial Ecmascript"> <span class="none"></span> Controversial Ecmascript</a> </li> <li> <a href="rules/ecmascript/unnecessary.html" title="Unnecessary"> <span class="none"></span> Unnecessary</a> </li> </ul> </li> <li class="nav-header">Project Documentation</li> <li> <a href="project-info.html" title="Project Information"> <span class="icon-chevron-right"></span> Project Information</a> </li> <li> <a href="project-reports.html" title="Project Reports"> <span class="icon-chevron-down"></span> Project Reports</a> <ul class="nav nav-list"> <li> <a href="xref/index.html" title="Source Xref"> <span class="none"></span> Source Xref</a> </li> <li> <a href="xref-test/index.html" title="Test Source Xref"> <span class="none"></span> Test Source Xref</a> </li> <li> <a href="apidocs/index.html" title="JavaDocs"> <span class="none"></span> JavaDocs</a> </li> <li> <a href="testapidocs/index.html" title="Test JavaDocs"> <span class="none"></span> Test JavaDocs</a> </li> <li> <a href="cpd.html" title="CPD"> <span class="none"></span> CPD</a> </li> <li> <a href="checkstyle.html" title="Checkstyle"> <span class="none"></span> Checkstyle</a> </li> <li class="active"> <a href="#"><span class="none"></span>Surefire Report</a> </li> <li> <a href="jacoco/index.html" title="JaCoCo Test"> <span class="none"></span> JaCoCo Test</a> </li> <li> <a href="dependency-updates-report.html" title="Dependency Updates Report"> <span class="none"></span> Dependency Updates Report</a> </li> <li> <a href="plugin-updates-report.html" title="Plugin Updates Report"> <span class="none"></span> Plugin Updates Report</a> </li> <li> <a href="property-updates-report.html" title="Property Updates Report"> <span class="none"></span> Property Updates Report</a> </li> </ul> </li> </ul> <hr /> <div id="poweredBy"> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <div class="clear"></div> <a href="http://maven.apache.org/" title="Maven" class="builtBy"> <img class="builtBy" alt="Built by Maven" src="http://maven.apache.org/images/logos/maven-feather.png" /> </a> <a href="http://sourceforge.net/" title="SourceForge.net" class="builtBy"> <img class="builtBy" alt="SourceForge.net. Fast, secure and Free Open Source software downloads" src="http://sflogo.sourceforge.net/sflogo.php?group_id=56262&type=10" width="80" height="15" /> </a> </div> </div> </div> <div id="bodyColumn" class="span10" > <script type="text/javascript"> //<![CDATA[ function toggleDisplay(elementId) { var elm = document.getElementById(elementId + 'error'); if (elm && typeof elm.style != "undefined") { if (elm.style.display == "none") { elm.style.display = ""; document.getElementById(elementId + 'off').style.display = "none"; document.getElementById(elementId + 'on').style.display = "inline"; } else if (elm.style.display == "") { elm.style.display = "none"; document.getElementById(elementId + 'off').style.display = "inline"; document.getElementById(elementId + 'on').style.display = "none"; } } } //]]> </script> <div class="section"> <h2><a name="Surefire_Report"></a>Surefire Report</h2></div> <div class="section"> <h2><a name="Summary"></a>Summary</h2><a name="Summary"></a> <p>[<a href="#Summary">Summary</a>] [<a href="#Package_List">Package List</a>] [<a href="#Test_Cases">Test Cases</a>]</p><br /> <table border="1" class="table table-striped"> <tr class="a"> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td>135</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>3.283</td></tr></table><br /> <p>Note: failures are anticipated and checked for with assertions while errors are unanticipated.</p><br /></div> <div class="section"> <h2><a name="Package_List"></a>Package List</h2><a name="Package_List"></a> <p>[<a href="#Summary">Summary</a>] [<a href="#Package_List">Package List</a>] [<a href="#Test_Cases">Test Cases</a>]</p><br /> <table border="1" class="table table-striped"> <tr class="a"> <th>Package</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.braces">net.sourceforge.pmd.lang.ecmascript.rule.braces</a></td> <td>21</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.045</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.basic">net.sourceforge.pmd.lang.ecmascript.rule.basic</a></td> <td>54</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.486</td></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.ast">net.sourceforge.pmd.lang.ecmascript.ast</a></td> <td>14</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.076</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmd.ant">net.sourceforge.pmd.ant</a></td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>1.142</td></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.cpd">net.sourceforge.pmd.cpd</a></td> <td>7</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.146</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmd">net.sourceforge.pmd</a></td> <td>8</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>1.035</td></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.unnecessary">net.sourceforge.pmd.lang.ecmascript.rule.unnecessary</a></td> <td>24</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.156</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.controversial">net.sourceforge.pmd.lang.ecmascript.rule.controversial</a></td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.002</td></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript">net.sourceforge.pmd.lang.ecmascript</a></td> <td>4</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.002</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmd.cli">net.sourceforge.pmd.cli</a></td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.193</td></tr></table><br /> <p>Note: package statistics are not computed recursively, they only sum up all of its testsuites numbers.</p> <div class="section"> <h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.braces"></a>net.sourceforge.pmd.lang.ecmascript.rule.braces</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.braces"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.bracesBracesRulesTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.bracesBracesRulesTest">BracesRulesTest</a></td> <td>21</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.045</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.basic"></a>net.sourceforge.pmd.lang.ecmascript.rule.basic</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.basic"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.basicBasicRulesTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.basicBasicRulesTest">BasicRulesTest</a></td> <td>54</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.486</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.lang.ecmascript.ast"></a>net.sourceforge.pmd.lang.ecmascript.ast</h3><a name="net.sourceforge.pmd.lang.ecmascript.ast"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.astEcmascriptParserTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascript.astEcmascriptParserTest">EcmascriptParserTest</a></td> <td>8</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.044</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.astASTFunctionNodeTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascript.astASTFunctionNodeTest">ASTFunctionNodeTest</a></td> <td>2</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.019</td></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.astASTTryStatementTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascript.astASTTryStatementTest">ASTTryStatementTest</a></td> <td>4</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.013</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.ant"></a>net.sourceforge.pmd.ant</h3><a name="net.sourceforge.pmd.ant"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.antPMDTaskTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.antPMDTaskTest">PMDTaskTest</a></td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>1.142</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.cpd"></a>net.sourceforge.pmd.cpd</h3><a name="net.sourceforge.pmd.cpd"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.cpdEcmascriptTokenizerTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.cpdEcmascriptTokenizerTest">EcmascriptTokenizerTest</a></td> <td>5</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.053</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmd.cpdCPDCommandLineInterfaceTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.cpdCPDCommandLineInterfaceTest">CPDCommandLineInterfaceTest</a></td> <td>2</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.093</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd"></a>net.sourceforge.pmd</h3><a name="net.sourceforge.pmd"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmdReportTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmdReportTest">ReportTest</a></td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.418</td></tr> <tr class="a"> <td><a href="#net.sourceforge.pmdLanguageVersionTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmdLanguageVersionTest">LanguageVersionTest</a></td> <td>3</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.012</td></tr> <tr class="b"> <td><a href="#net.sourceforge.pmdRuleSetFactoryTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmdRuleSetFactoryTest">RuleSetFactoryTest</a></td> <td>4</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.605</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.unnecessary"></a>net.sourceforge.pmd.lang.ecmascript.rule.unnecessary</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.unnecessary"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.unnecessaryUnnecessaryRulesTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.unnecessaryUnnecessaryRulesTest">UnnecessaryRulesTest</a></td> <td>24</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.156</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.controversial"></a>net.sourceforge.pmd.lang.ecmascript.rule.controversial</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.controversial"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.controversialControversialRulesTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascript.rule.controversialControversialRulesTest">ControversialRulesTest</a></td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.002</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.lang.ecmascript"></a>net.sourceforge.pmd.lang.ecmascript</h3><a name="net.sourceforge.pmd.lang.ecmascript"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.lang.ecmascriptEcmascriptParserOptionsTest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.lang.ecmascriptEcmascriptParserOptionsTest">EcmascriptParserOptionsTest</a></td> <td>4</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.002</td></tr></table></div> <div class="section"> <h3><a name="net.sourceforge.pmd.cli"></a>net.sourceforge.pmd.cli</h3><a name="net.sourceforge.pmd.cli"></a> <table border="1" class="table table-striped"> <tr class="a"> <th></th> <th>Class</th> <th>Tests</th> <th>Errors </th> <th>Failures</th> <th>Skipped</th> <th>Success Rate</th> <th>Time</th></tr> <tr class="b"> <td><a href="#net.sourceforge.pmd.cliCLITest"><img src="images/icon_success_sml.gif" alt="" /></a></td> <td><a href="#net.sourceforge.pmd.cliCLITest">CLITest</a></td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>100%</td> <td>0.193</td></tr></table></div><br /></div> <div class="section"> <h2><a name="Test_Cases"></a>Test Cases</h2><a name="Test_Cases"></a> <p>[<a href="#Summary">Summary</a>] [<a href="#Package_List">Package List</a>] [<a href="#Test_Cases">Test Cases</a>]</p> <div class="section"> <h3><a name="EcmascriptParserTest"></a>EcmascriptParserTest</h3><a name="net.sourceforge.pmd.lang.ecmascript.astEcmascriptParserTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testCaseAsIdentifier</td> <td>0.001</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testXorAssignment</td> <td>0.024</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testSuppresionComment</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testArrayAccess</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testArrayMethod</td> <td>0.004</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testVoidKeyword</td> <td>0.001</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testLineNumbers</td> <td>0</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testLineNumbersWithinEcmascriptRules</td> <td>0.007</td></tr></table></div> <div class="section"> <h3><a name="ASTFunctionNodeTest"></a>ASTFunctionNodeTest</h3><a name="net.sourceforge.pmd.lang.ecmascript.astASTFunctionNodeTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testGetBodyFunctionClosureExpression</td> <td>0.019</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testGetBody</td> <td>0</td></tr></table></div> <div class="section"> <h3><a name="ReportTest"></a>ReportTest</h3><a name="net.sourceforge.pmdReportTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testExclusionsInReportWithNOPMDEcmascript</td> <td>0.418</td></tr></table></div> <div class="section"> <h3><a name="ASTTryStatementTest"></a>ASTTryStatementTest</h3><a name="net.sourceforge.pmd.lang.ecmascript.astASTTryStatementTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testMultipleCatchAndFinallyBlock</td> <td>0.006</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testFinallyBlockOnly</td> <td>0</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testCatchAndFinallyBlock</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testCatchBlockOnly</td> <td>0.002</td></tr></table></div> <div class="section"> <h3><a name="ControversialRulesTest"></a>ControversialRulesTest</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.controversialControversialRulesTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidWithStatement::0 Basic case</td> <td>0.002</td></tr></table></div> <div class="section"> <h3><a name="PMDTaskTest"></a>PMDTaskTest</h3><a name="net.sourceforge.pmd.antPMDTaskTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testEcmascript</td> <td>1.142</td></tr></table></div> <div class="section"> <h3><a name="CLITest"></a>CLITest</h3><a name="net.sourceforge.pmd.cliCLITest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>useEcmaScript</td> <td>0.193</td></tr></table></div> <div class="section"> <h3><a name="EcmascriptTokenizerTest"></a>EcmascriptTokenizerTest</h3><a name="net.sourceforge.pmd.cpdEcmascriptTokenizerTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testIgnoreMultiLineComments</td> <td>0.047</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testIgnoreSingleLineComments</td> <td>0.001</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>test1</td> <td>0.002</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>test2</td> <td>0.002</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>parseStringNotAsMultiline</td> <td>0.001</td></tr></table></div> <div class="section"> <h3><a name="BracesRulesTest"></a>BracesRulesTest</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.bracesBracesRulesTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ForLoopsMustUseBraces::0 Ok</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ForLoopsMustUseBraces::1 Ok, for in</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ForLoopsMustUseBraces::2 Bad</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ForLoopsMustUseBraces::3 Bad, no increment</td> <td>0.002</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ForLoopsMustUseBraces::4 Bad, no condition/increment</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ForLoopsMustUseBraces::5 Bad, no initializer/condition/increment</td> <td>0.002</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ForLoopsMustUseBraces::6 Bad, for in</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::0 Ok, if/else</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::1 Ok, if/else if/else</td> <td>0</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::2 Ok, if without braces</td> <td>0</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::3 Ok, nest if without braces</td> <td>0</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::4 Bad, if/else with else missing braces</td> <td>0</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::5 Bad, if/else with if and else missing braces</td> <td>0</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::6 Bad, if/else if/else, with else missing braces</td> <td>0.001</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::7 Bad, if/else if/else, with else if and else missing braces</td> <td>0.004</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfElseStmtsMustUseBraces::8 Bad, if/else if/else, with if and else if and else missing braces</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfStmtsMustUseBraces::0 Ok</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfStmtsMustUseBraces::1 Bad</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>IfStmtsMustUseBraces::2 Bad, nested</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>WhileLoopsMustUseBraces::0 Ok, with braces</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>WhileLoopsMustUseBraces::1 no braces</td> <td>0.002</td></tr></table></div> <div class="section"> <h3><a name="LanguageVersionTest"></a>LanguageVersionTest</h3><a name="net.sourceforge.pmdLanguageVersionTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testRegisteredRulesets[0]</td> <td>0.011</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testFindVersionsForLanguageNameAndVersion[0]</td> <td>0.001</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testGetLanguageVersionForTerseName[0]</td> <td>0</td></tr></table></div> <div class="section"> <h3><a name="EcmascriptParserOptionsTest"></a>EcmascriptParserOptionsTest</h3><a name="net.sourceforge.pmd.lang.ecmascriptEcmascriptParserOptionsTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testEqualsHashcode</td> <td>0.002</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testDefaults</td> <td>0</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testSetters</td> <td>0</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testConstructor</td> <td>0</td></tr></table></div> <div class="section"> <h3><a name="UnnecessaryRulesTest"></a>UnnecessaryRulesTest</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.unnecessaryUnnecessaryRulesTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>NoElseReturn::0 Simple violation</td> <td>0.018</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>NoElseReturn::1 Simple fix</td> <td>0.006</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>NoElseReturn::2 No return in if</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::0 Ok, function</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::1 Ok, if</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::2 Ok, for</td> <td>0.009</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::3 Ok, for in</td> <td>0.01</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::4 Ok, while</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::5 Ok, do while</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::6 Ok, switch</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::7 Ok, try</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::8 Bad, global</td> <td>0.002</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::9 Bad, function</td> <td>0.003</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::10 Bad, if</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::11 Bad, for</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::12 Bad, for in</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::13 Bad, while</td> <td>0.008</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::14 Bad, do while</td> <td>0.017</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::15 Bad, switch</td> <td>0.008</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryBlock::16 Bad, try</td> <td>0.01</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryParentheses::0 Ok, simple</td> <td>0.002</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryParentheses::1 Bad, simple</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryParentheses::2 Ok, complex</td> <td>0.002</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnnecessaryParentheses::3 Bad, complex</td> <td>0.022</td></tr></table></div> <div class="section"> <h3><a name="RuleSetFactoryTest"></a>RuleSetFactoryTest</h3><a name="net.sourceforge.pmdRuleSetFactoryTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testDtd</td> <td>0.055</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testXmlSchema</td> <td>0.04</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testReadWriteRoundTrip</td> <td>0.501</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>testAllPMDBuiltInRulesMeetConventions</td> <td>0.009</td></tr></table></div> <div class="section"> <h3><a name="BasicRulesTest"></a>BasicRulesTest</h3><a name="net.sourceforge.pmd.lang.ecmascript.rule.basicBasicRulesTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::0 Ok, all cases</td> <td>0.037</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::1 Bad, assignment, all cases</td> <td>0.016</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::2 Ok, allow assignment, if</td> <td>0.029</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::3 Ok, allow assignment, while</td> <td>0.019</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::4 Ok, allow assignment, do</td> <td>0.032</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::5 Ok, allow assignment, for</td> <td>0</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::6 Ok, allow assignment, ternary</td> <td>0.013</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::7 Ok, allow assignment, ternary results</td> <td>0.03</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::8 Bad, increment/decrement, all cases</td> <td>0</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AssignmentInOperand::9 Ok, allow increment/decrement, all cases</td> <td>0.017</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::0 Ok, object literals</td> <td>0.008</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::1 Bad, object literals</td> <td>0.016</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::2 Bad, object literals, multi-line nested</td> <td>0</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::3 Bad, object literals, compressed nested</td> <td>0.009</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::4 Ok, allow object literals</td> <td>0.006</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::5 Ok, array literals</td> <td>0.007</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::6 Bad, array literals</td> <td>0.006</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::7 Bad, array literals, multi-line nested</td> <td>0.006</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::8 Bad, array literals, compressed nested</td> <td>0.009</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>AvoidTrailingComma::9 Ok, allow array literals</td> <td>0.007</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ConsistentReturn::0 Ok, no return</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ConsistentReturn::1 Ok, 1 return w/ result</td> <td>0.013</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ConsistentReturn::2 Ok, 1 return w/o result</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ConsistentReturn::3 Ok, nested function with different return result</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ConsistentReturn::4 Bad, mixed result</td> <td>0.004</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ConsistentReturn::5 Bad, mixed result with nested function</td> <td>0.005</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>EqualComparison::0 Ok, all cases</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>EqualComparison::1 Bad, all cases</td> <td>0.007</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>GlobalVariable::0 Ok, all cases</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>GlobalVariable::1 Bad, all cases</td> <td>0.005</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>InnaccurateNumericLiteral::0 Ok integer</td> <td>0.007</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>InnaccurateNumericLiteral::1 Bad integer</td> <td>0.005</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>InnaccurateNumericLiteral::2 Ok float</td> <td>0.006</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>InnaccurateNumericLiteral::3 Bad float</td> <td>0.006</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>InnaccurateNumericLiteral::4 Ok float w/ exponent</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>InnaccurateNumericLiteral::5 Bad float w/ exponent</td> <td>0.006</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ScopeForInVariable::0 Ok, global scope</td> <td>0.006</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ScopeForInVariable::1 Ok, function scope</td> <td>0.006</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ScopeForInVariable::2 Ok, nested function</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ScopeForInVariable::3 Bad, global scope</td> <td>0.005</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ScopeForInVariable::4 Bad, function scope</td> <td>0.029</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>ScopeForInVariable::5 Bad, nested function</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::0 Ok, return</td> <td>0.006</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::1 Ok, loop continue</td> <td>0.009</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::2 Ok, loop break;</td> <td>0.004</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::3 Ok, switch break</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::4 Ok, throw</td> <td>0.014</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::5 Bad, return</td> <td>0.008</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::6 Bad, loop continue</td> <td>0.004</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::7 Bad, loop break;</td> <td>0.003</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::8 Bad, switch break</td> <td>0.006</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UnreachableCode::9 Bad, throw</td> <td>0.004</td></tr> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UseBaseWithParseInt::0 KO, missing the base argument</td> <td>0.005</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>UseBaseWithParseInt::1 OK, have the appropriate 'base' parameter</td> <td>0.004</td></tr></table></div> <div class="section"> <h3><a name="CPDCommandLineInterfaceTest"></a>CPDCommandLineInterfaceTest</h3><a name="net.sourceforge.pmd.cpdCPDCommandLineInterfaceTest"></a> <table border="1" class="table table-striped"> <tr class="a"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>shouldFindNoDuplicatesWithDifferentFileExtensions</td> <td>0.057</td></tr> <tr class="b"> <td><img src="images/icon_success_sml.gif" alt="" /></td> <td>shouldFindDuplicatesWithDifferentFileExtensions</td> <td>0.036</td></tr></table></div><br /></div> </div> </div> </div> <hr/> <footer> <div class="container-fluid"> <div class="row-fluid"> <p >Copyright &copy; 2002&#x2013;2016 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved. </p> </div> </div> </footer> </body> </html>
{'content_hash': 'e6cc9c9aa4fbfe613583c966747e6b28', 'timestamp': '', 'source': 'github', 'line_count': 1380, 'max_line_length': 296, 'avg_line_length': 36.86014492753623, 'alnum_prop': 0.5743802465252521, 'repo_name': 'jasonwee/videoOnCloud', 'id': '74e739225405585f215633b97da288d5c1f34f06', 'size': '50867', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pmd/pmd-doc-5.5.1/pmd-javascript/surefire-report.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '116270'}, {'name': 'C', 'bytes': '2209717'}, {'name': 'C++', 'bytes': '375267'}, {'name': 'CSS', 'bytes': '1134648'}, {'name': 'Dockerfile', 'bytes': '1656'}, {'name': 'HTML', 'bytes': '306558398'}, {'name': 'Java', 'bytes': '1465506'}, {'name': 'JavaScript', 'bytes': '9028509'}, {'name': 'Jupyter Notebook', 'bytes': '30907'}, {'name': 'Less', 'bytes': '107003'}, {'name': 'PHP', 'bytes': '856'}, {'name': 'PowerShell', 'bytes': '77807'}, {'name': 'Pug', 'bytes': '2968'}, {'name': 'Python', 'bytes': '1001861'}, {'name': 'R', 'bytes': '7390'}, {'name': 'Roff', 'bytes': '3553'}, {'name': 'Shell', 'bytes': '206191'}, {'name': 'Thrift', 'bytes': '80564'}, {'name': 'XSLT', 'bytes': '4740'}]}
package com.metamolecular.pubcouch.record; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Iterator; /** * * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultRecordStreamer implements RecordStreamer { private BufferedReader reader; private InputStream stream; public DefaultRecordStreamer(InputStream stream) { this.stream = stream; this.reader = new BufferedReader(new InputStreamReader(stream)); } public Iterator<Record> iterator() { return new RecordIterator(); } private class RecordIterator implements Iterator { public boolean hasNext() { try { reader.mark(1); if (reader.read() != -1) { reader.reset(); return true; } } catch (IOException e) { throw new RuntimeException("Error accessing the underlying datastream.", e); } return false; } public Object next() { Record result = null; try { result = new Record(reader); } catch(IOException e) { throw new RuntimeException(e); } return result; } public void remove() { throw new UnsupportedOperationException("Not supported yet."); } } }
{'content_hash': '6a29b634d4448de5b97b9f72f3267f95', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 84, 'avg_line_length': 18.904109589041095, 'alnum_prop': 0.6217391304347826, 'repo_name': 'metamolecular/pubcouch', 'id': 'b0459f0c06a73ad575134a388a3057942eef522e', 'size': '2582', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/metamolecular/pubcouch/record/DefaultRecordStreamer.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '76494'}, {'name': 'JavaScript', 'bytes': '796'}]}
package org.leguan.testproject.language.java; import java.util.Date; public class ClassWithoutConstructor { public void hello () { } }
{'content_hash': 'ac412fa757712f4e57486cde7bbda793', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 45, 'avg_line_length': 9.866666666666667, 'alnum_prop': 0.7162162162162162, 'repo_name': 'moley/leguan', 'id': '72bf4c6a632302ef3e7bf1b990b9b1d8738e9659', 'size': '148', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'leguan-testprojects/testprojectJava/src/main/java/org/leguan/testproject/language/java/ClassWithoutConstructor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '20530'}, {'name': 'HTML', 'bytes': '35444'}, {'name': 'Java', 'bytes': '2096474'}, {'name': 'JavaScript', 'bytes': '1240'}, {'name': 'Shell', 'bytes': '1844'}, {'name': 'TypeScript', 'bytes': '71940'}]}
var os = require('os'), fs = require('fs'), sys = require('util'), exec = require('child_process').exec; function linux(brightness,callback){ // Enumerate the backlight devices... fs.readdir('/sys/class/backlight', function(err, brightnessDevices){ if(err) { console.error('Error while listing brightness devices. Maybe you need superuser privileges to run this script?'); throw err; } var devicePath = '/sys/class/backlight/' + brightnessDevices[0]; //Read the maximum for the first device fs.readFile(devicePath + '/max_brightness', function(err, maxBrightness){ maxBrightness = parseInt(maxBrightness, 10) if(err) { console.error('Error while reading maximum brightness. Maybe you need superuser privileges to run this script?'); throw err; } // Turn percent into the actual value we need var brightnessValue = Math.floor(brightness / 100 * maxBrightness); // Write out new value fs.createWriteStream(devicePath + '/brightness') .on('end', callback) .write(new Buffer(brightnessValue.toString())); }); }) } function windows(brightness,callback){ //These are the identifiers for the current power scheme var GUID; var subgroup; var powerSetting; // powercfg -q gives information about power settings, but can only give accurate brightness info for laptops or other portable windows devices exec('powercfg -q', function(error,stdout,stderr){ if(!error){ var regExp = /([a-z\-0-9]+)\s\D+$/ var splitOutput = stdout.split('\r\n'); GUID = regExp.exec(splitOutput[0])[1]; for(var i = 0;i<splitOutput.length;i++){ if(splitOutput[i].match(/\(Display\)$/)){ //The subgroup is derived from the output named display subgroup = regExp.exec(splitOutput[i])[1]; } else if(splitOutput[i].match(/\(Display\sbrightness\)$/)){ //The powerSetting is derived from the output named Display powerSetting = regExp.exec(splitOutput[i])[1]; } } //console.log(GUID,subgroup,powerSetting); //Set the the brightness for AC power plan settings exec('powercfg -SetAcValueIndex' + ' ' + GUID + ' ' + subgroup + ' ' + powerSetting + ' ' + brightness,function(err,out,stderror){ if(err) throw err; //Set the brightness when on DC power plan settings exec('powercfg -SetDcValueIndex' + ' ' + GUID + ' ' + subgroup + ' ' + powerSetting + ' ' + brightness,function(err,out,stderror){ if(err) throw err; //Set the modified power plan as the current system plan exec('powercfg -S' + ' ' + GUID,function(err,out,stderror){ if(err) throw err; if(callback) callback(); return true; }); }); }); } else{ throw error; } }); } function changeBrightness(brightness,callback){ //Brightness is in percent switch(os.platform()){ case 'win32': windows(brightness,callback); break; case 'linux': linux(brightness, callback); break; default: throw new Error('OS is not recognized or is unsupported'); break; } } module.exports = changeBrightness;
{'content_hash': '1a7f064293008791d70f9a600c96e92f', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 144, 'avg_line_length': 26.69298245614035, 'alnum_prop': 0.6703910614525139, 'repo_name': 'Jabbath/node-brightness', 'id': 'db9ce1469666fe3301c70905ca7af378834a7a9d', 'size': '3043', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'main.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3148'}]}
<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <meta name="google-site-verification" content="IqC9E_aWJtA4gqC0Bv4gL9MV70PJZ0W7mdU8nLkvLoQ" /> <title>Thinking Mind Healing Heart</title> <link rel="shortcut icon" href="../favicon.ico" /> <!-- Bootstrap Core CSS --> <link href="../css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="../css/style-es.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="../css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- Google Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-75979766-2', 'auto', 'MenteCorazon'); ga('MenteCorazon.send', 'pageview'); </script> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <!-- Intro Header --> <header class="intro"> <div class="row"> <br /> <div class="col-lg-8 col-lg-offset-2"> <ul class="list-inline banner-social-buttons"> <li> <a href="https://www.instagram.com/ThinkingHealing/" class="btn btn-default"><i class="fa fa-instagram fa-fw"></i> Instagram</a> </li> <li> <a href="https://www.youtube.com/channel/UCVo8Wr5AaT04hFwTeAaFv5w" class="btn btn-default"><i class="fa fa-youtube-play fa-fw"></i> Youtube</a> </li> <li> <a href="https://twitter.com/ThinkingHealing" class="btn btn-default"><i class="fa fa-twitter fa-fw"></i> Twitter</a> </li> </ul> </div> </div> </header> <!-- jQuery --> <script src="../js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="../js/jquery.easing.min.js"></script> <!-- Custom Theme JavaScript --> <script src="../js/script.js"></script> </body> </html>
{'content_hash': '066a386f33ef3097a72c5209633aa031', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 167, 'avg_line_length': 35.26027397260274, 'alnum_prop': 0.5578865578865578, 'repo_name': 'ThinkingHealing/thinkinghealing.github.io', 'id': '557c391c1fc31528c53162131007b9142deefa27', 'size': '2574', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'es/index.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '19434'}, {'name': 'HTML', 'bytes': '7838'}, {'name': 'JavaScript', 'bytes': '1129'}]}
package gaia3d.controller.view; import gaia3d.domain.terrain.Terrain; import gaia3d.service.TerrainService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import java.util.List; @Slf4j @Controller @RequestMapping("/terrain") public class TerrainController { @Autowired private TerrainService terrainService; /** * Terrain 목록 * @param model * @return */ @GetMapping(value = "/list") public String list(HttpServletRequest request, Model model) { List<Terrain> terrainList = terrainService.getListTerrain(); model.addAttribute("terrainList", terrainList); return "/terrain/list"; } /** * Terrain 등록 화면 * @param model * @return */ @GetMapping(value = "/input") public String input(Model model) { model.addAttribute("terrain", new Terrain()); return "/terrain/input"; } /** * Terrain 수정 화면 * @param reuqet * @param terrainId * @param model * @return */ @GetMapping(value = "/modify") public String modify(HttpServletRequest reuqet, @RequestParam Integer terrainId, Model model) { Terrain terrain = terrainService.getTerrain(terrainId); model.addAttribute(terrain); return "/terrain/modify"; } /** * Terrain 삭제 * @param terrainId * @param model * @return */ @GetMapping(value = "/delete") public String delete(@RequestParam("terrainId") Integer terrainId, Model model) { terrainService.deleteTerrain(terrainId); return "redirect:/terrain/list"; } }
{'content_hash': '0fff028ee1b3cc29b834620f8a5adae7', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 97, 'avg_line_length': 23.363636363636363, 'alnum_prop': 0.7398554752640356, 'repo_name': 'Gaia3D/mago3d', 'id': '4d823fd339c112966a6bd25ef427bb3b2bc44ef5', 'size': '1823', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'mago3d-admin/src/main/java/gaia3d/controller/view/TerrainController.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '853699'}, {'name': 'HTML', 'bytes': '2164643'}, {'name': 'Java', 'bytes': '2158477'}, {'name': 'JavaScript', 'bytes': '22316674'}, {'name': 'Less', 'bytes': '356476'}, {'name': 'SCSS', 'bytes': '391356'}, {'name': 'Shell', 'bytes': '587'}]}
@interface ViewController : UIViewController @end
{'content_hash': 'e2da20b9691e6576f466ab6459e3ce7d', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 44, 'avg_line_length': 10.6, 'alnum_prop': 0.7924528301886793, 'repo_name': 'Xiexingda/XDVideoCamera', 'id': '2afcaf6f64372ba1260f1303a0d488dcd0dd7658', 'size': '307', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Demo/ViewController.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '38513'}, {'name': 'Ruby', 'bytes': '6187'}]}
var angular = require('angular'); var Interstellar = angular.module('Interstellar', []); Interstellar.provider('interstellarSet', function() { var data = []; var focusIndex = 0; var name = ''; return { init: function(argData) { data = argData; }, $get: function($rootScope) { return { getAll: function() { return data; }, get: function(index) { return data[index]; }, add: function(argData) { // 更新焦点 focusIndex = data.length; data.push(argData); $rootScope.$broadcast('$focusChange'); }, // addR 使用 Replace 的方式添加数据 addR: function(index, argData) { focusIndex = index; data.splice(index, 0 , argData); $rootScope.$broadcast('$focusChange'); }, replace: function(index, behavior) { data.splice(index, 1 , behavior); $rootScope.$broadcast('$focusChange'); }, update: function(index, value) { data[index] = value; }, remove: function(index) { focusIndex = index - 1; data[focusIndex].other = !data[focusIndex].other; data.splice(index, 1); $rootScope.$broadcast('$focusChange'); }, getName: function(){ return name; }, setName: function(argName) { name = argName; $rootScope.$broadcast('$nameChange'); }, getFocus: function() { return focusIndex; }, setFocus: function(index) { focusIndex = index; $rootScope.$broadcast('$focusChange'); } }; } }; });
{'content_hash': '53296dee1ad4d7ffbf0f6b279d6371e8', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 54, 'avg_line_length': 22.393939393939394, 'alnum_prop': 0.587956698240866, 'repo_name': 'wangzhe1995/interstellar', 'id': '781b8c9a16be26287c05c8b64acac3b9c31b093d', 'size': '1504', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/app/interstellar.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2833'}, {'name': 'JavaScript', 'bytes': '16052'}]}
var micka = { confirmURL: function(msg, url){ if(window.confirm(msg)){ window.location = url; } }, showSubsets: function(){ var target = $('#micka-subsets').get(0); var fid = $('#file-identifier').get(0).textContent; this._showSubsets(target, fid); }, _showSubsets(target, fid){ var that = this; $.get('../../csw/?REQUEST=GetRecords&FORMAT=application/json&query=ParentIdentifier%3D'+fid) .done(function(data){ $(target).html(''); for(var i=0;i<data.records.length;i++){ $(target).append('<div><a href="'+data.records[i].id+'"><span class="res-type '+data.records[i].trida+'"></span>'+data.records[i].title+'</a></div>'); $(target).append('<div style="margin-left:15px;" id="sub-'+data.records[i].id+'">loading....</div>'); that._showSubsets($("#sub-"+data.records[i].id), data.records[i].id); } }) } }
{'content_hash': 'ac00ddb43580c3237dc9069d6a6e0cb0', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 166, 'avg_line_length': 37.81481481481482, 'alnum_prop': 0.5142017629774731, 'repo_name': 'hsrs-cz/Micka', 'id': '4275cb01cd915df501f3465127542c468faaccd6', 'size': '1021', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scripts/micka.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '45657'}, {'name': 'HTML', 'bytes': '112384'}, {'name': 'JavaScript', 'bytes': '205191'}, {'name': 'PHP', 'bytes': '468302'}, {'name': 'TSQL', 'bytes': '4046552'}, {'name': 'XSLT', 'bytes': '1473790'}]}
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/utypes.h" #include <float.h> #if !UCONFIG_NO_FORMATTING #include "unicode/gregocal.h" #include "gregoimp.h" #include "umutex.h" #include "uassert.h" // ***************************************************************************** // class GregorianCalendar // ***************************************************************************** /** * Note that the Julian date used here is not a true Julian date, since * it is measured from midnight, not noon. This value is the Julian * day number of January 1, 1970 (Gregorian calendar) at noon UTC. [LIU] */ static const int16_t kNumDays[] = {0,31,59,90,120,151,181,212,243,273,304,334}; // 0-based, for day-in-year static const int16_t kLeapNumDays[] = {0,31,60,91,121,152,182,213,244,274,305,335}; // 0-based, for day-in-year static const int8_t kMonthLength[] = {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based static const int8_t kLeapMonthLength[] = {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based // setTimeInMillis() limits the Julian day range to +/-7F000000. // This would seem to limit the year range to: // ms=+183882168921600000 jd=7f000000 December 20, 5828963 AD // ms=-184303902528000000 jd=81000000 September 20, 5838270 BC // HOWEVER, CalendarRegressionTest/Test4167060 shows that the actual // range limit on the year field is smaller (~ +/-140000). [alan 3.0] static const int32_t kGregorianCalendarLimits[UCAL_FIELD_COUNT][4] = { // Minimum Greatest Least Maximum // Minimum Maximum { 0, 0, 1, 1}, // ERA { 1, 1, 140742, 144683}, // YEAR { 0, 0, 11, 11}, // MONTH { 1, 1, 52, 53}, // WEEK_OF_YEAR {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH { 1, 1, 28, 31}, // DAY_OF_MONTH { 1, 1, 365, 366}, // DAY_OF_YEAR {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK { -1, -1, 4, 5}, // DAY_OF_WEEK_IN_MONTH {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET { -140742, -140742, 140742, 144683}, // YEAR_WOY {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL { -140742, -140742, 140742, 144683}, // EXTENDED_YEAR {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // IS_LEAP_MONTH }; /* * <pre> * Greatest Least * Field name Minimum Minimum Maximum Maximum * ---------- ------- ------- ------- ------- * ERA 0 0 1 1 * YEAR 1 1 140742 144683 * MONTH 0 0 11 11 * WEEK_OF_YEAR 1 1 52 53 * WEEK_OF_MONTH 0 0 4 6 * DAY_OF_MONTH 1 1 28 31 * DAY_OF_YEAR 1 1 365 366 * DAY_OF_WEEK 1 1 7 7 * DAY_OF_WEEK_IN_MONTH -1 -1 4 5 * AM_PM 0 0 1 1 * HOUR 0 0 11 11 * HOUR_OF_DAY 0 0 23 23 * MINUTE 0 0 59 59 * SECOND 0 0 59 59 * MILLISECOND 0 0 999 999 * ZONE_OFFSET -12* -12* 12* 12* * DST_OFFSET 0 0 1* 1* * YEAR_WOY 1 1 140742 144683 * DOW_LOCAL 1 1 7 7 * </pre> * (*) In units of one-hour */ #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL) #include <stdio.h> #endif U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(GregorianCalendar) // 00:00:00 UTC, October 15, 1582, expressed in ms from the epoch. // Note that only Italy and other Catholic countries actually // observed this cutover. Most other countries followed in // the next few centuries, some as late as 1928. [LIU] // in Java, -12219292800000L //const UDate GregorianCalendar::kPapalCutover = -12219292800000L; static const uint32_t kCutoverJulianDay = 2299161; static const UDate kPapalCutover = (2299161.0 - kEpochStartAsJulianDay) * U_MILLIS_PER_DAY; //static const UDate kPapalCutoverJulian = (2299161.0 - kEpochStartAsJulianDay); // ------------------------------------- GregorianCalendar::GregorianCalendar(UErrorCode& status) : Calendar(status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(TimeZone* zone, UErrorCode& status) : Calendar(zone, Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(const TimeZone& zone, UErrorCode& status) : Calendar(zone, Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(const Locale& aLocale, UErrorCode& status) : Calendar(TimeZone::createDefault(), aLocale, status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(TimeZone* zone, const Locale& aLocale, UErrorCode& status) : Calendar(zone, aLocale, status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& status) : Calendar(zone, aLocale, status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date, UErrorCode& status) : Calendar(TimeZone::createDefault(), Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { set(UCAL_ERA, AD); set(UCAL_YEAR, year); set(UCAL_MONTH, month); set(UCAL_DATE, date); } // ------------------------------------- GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, UErrorCode& status) : Calendar(TimeZone::createDefault(), Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { set(UCAL_ERA, AD); set(UCAL_YEAR, year); set(UCAL_MONTH, month); set(UCAL_DATE, date); set(UCAL_HOUR_OF_DAY, hour); set(UCAL_MINUTE, minute); } // ------------------------------------- GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second, UErrorCode& status) : Calendar(TimeZone::createDefault(), Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { set(UCAL_ERA, AD); set(UCAL_YEAR, year); set(UCAL_MONTH, month); set(UCAL_DATE, date); set(UCAL_HOUR_OF_DAY, hour); set(UCAL_MINUTE, minute); set(UCAL_SECOND, second); } // ------------------------------------- GregorianCalendar::~GregorianCalendar() { } // ------------------------------------- GregorianCalendar::GregorianCalendar(const GregorianCalendar &source) : Calendar(source), fGregorianCutover(source.fGregorianCutover), fCutoverJulianDay(source.fCutoverJulianDay), fNormalizedGregorianCutover(source.fNormalizedGregorianCutover), fGregorianCutoverYear(source.fGregorianCutoverYear), fIsGregorian(source.fIsGregorian), fInvertGregorian(source.fInvertGregorian) { } // ------------------------------------- GregorianCalendar* GregorianCalendar::clone() const { return new GregorianCalendar(*this); } // ------------------------------------- GregorianCalendar & GregorianCalendar::operator=(const GregorianCalendar &right) { if (this != &right) { Calendar::operator=(right); fGregorianCutover = right.fGregorianCutover; fNormalizedGregorianCutover = right.fNormalizedGregorianCutover; fGregorianCutoverYear = right.fGregorianCutoverYear; fCutoverJulianDay = right.fCutoverJulianDay; } return *this; } // ------------------------------------- UBool GregorianCalendar::isEquivalentTo(const Calendar& other) const { // Calendar override. return Calendar::isEquivalentTo(other) && fGregorianCutover == ((GregorianCalendar*)&other)->fGregorianCutover; } // ------------------------------------- void GregorianCalendar::setGregorianChange(UDate date, UErrorCode& status) { if (U_FAILURE(status)) return; // Precompute two internal variables which we use to do the actual // cutover computations. These are the normalized cutover, which is the // midnight at or before the cutover, and the cutover year. The // normalized cutover is in pure date milliseconds; it contains no time // of day or timezone component, and it used to compare against other // pure date values. double cutoverDay = ClockMath::floorDivide(date, (double)kOneDay); // Handle the rare case of numeric overflow where the user specifies a time // outside of INT32_MIN .. INT32_MAX number of days. if (cutoverDay <= INT32_MIN) { cutoverDay = INT32_MIN; fGregorianCutover = fNormalizedGregorianCutover = cutoverDay * kOneDay; } else if (cutoverDay >= INT32_MAX) { cutoverDay = INT32_MAX; fGregorianCutover = fNormalizedGregorianCutover = cutoverDay * kOneDay; } else { fNormalizedGregorianCutover = cutoverDay * kOneDay; fGregorianCutover = date; } // Normalize the year so BC values are represented as 0 and negative // values. GregorianCalendar *cal = new GregorianCalendar(getTimeZone(), status); /* test for NULL */ if (cal == 0) { status = U_MEMORY_ALLOCATION_ERROR; return; } if(U_FAILURE(status)) return; cal->setTime(date, status); fGregorianCutoverYear = cal->get(UCAL_YEAR, status); if (cal->get(UCAL_ERA, status) == BC) fGregorianCutoverYear = 1 - fGregorianCutoverYear; fCutoverJulianDay = (int32_t)cutoverDay; delete cal; } void GregorianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) { int32_t eyear, month, dayOfMonth, dayOfYear, unusedRemainder; if(U_FAILURE(status)) { return; } #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: jd%d- (greg's %d)- [cut=%d]\n", __FILE__, __LINE__, julianDay, getGregorianDayOfYear(), fCutoverJulianDay); #endif if (julianDay >= fCutoverJulianDay) { month = getGregorianMonth(); dayOfMonth = getGregorianDayOfMonth(); dayOfYear = getGregorianDayOfYear(); eyear = getGregorianYear(); } else { // The Julian epoch day (not the same as Julian Day) // is zero on Saturday December 30, 0 (Gregorian). int32_t julianEpochDay = julianDay - (kJan1_1JulianDay - 2); eyear = (int32_t) ClockMath::floorDivide((4.0*julianEpochDay) + 1464.0, (int32_t) 1461, unusedRemainder); // Compute the Julian calendar day number for January 1, eyear int32_t january1 = 365*(eyear-1) + ClockMath::floorDivide(eyear-1, (int32_t)4); dayOfYear = (julianEpochDay - january1); // 0-based // Julian leap years occurred historically every 4 years starting // with 8 AD. Before 8 AD the spacing is irregular; every 3 years // from 45 BC to 9 BC, and then none until 8 AD. However, we don't // implement this historical detail; instead, we implement the // computatinally cleaner proleptic calendar, which assumes // consistent 4-year cycles throughout time. UBool isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0) // Common Julian/Gregorian calculation int32_t correction = 0; int32_t march1 = isLeap ? 60 : 59; // zero-based DOY for March 1 if (dayOfYear >= march1) { correction = isLeap ? 1 : 2; } month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month dayOfMonth = dayOfYear - (isLeap?kLeapNumDays[month]:kNumDays[month]) + 1; // one-based DOM ++dayOfYear; #if defined (U_DEBUG_CAL) // fprintf(stderr, "%d - %d[%d] + 1\n", dayOfYear, isLeap?kLeapNumDays[month]:kNumDays[month], month ); // fprintf(stderr, "%s:%d: greg's HCF %d -> %d/%d/%d not %d/%d/%d\n", // __FILE__, __LINE__,julianDay, // eyear,month,dayOfMonth, // getGregorianYear(), getGregorianMonth(), getGregorianDayOfMonth() ); fprintf(stderr, "%s:%d: doy %d (greg's %d)- [cut=%d]\n", __FILE__, __LINE__, dayOfYear, getGregorianDayOfYear(), fCutoverJulianDay); #endif } // [j81] if we are after the cutover in its year, shift the day of the year if((eyear == fGregorianCutoverYear) && (julianDay >= fCutoverJulianDay)) { //from handleComputeMonthStart int32_t gregShift = Grego::gregorianShift(eyear); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: gregorian shift %d ::: doy%d => %d [cut=%d]\n", __FILE__, __LINE__,gregShift, dayOfYear, dayOfYear+gregShift, fCutoverJulianDay); #endif dayOfYear += gregShift; } internalSet(UCAL_MONTH, month); internalSet(UCAL_DAY_OF_MONTH, dayOfMonth); internalSet(UCAL_DAY_OF_YEAR, dayOfYear); internalSet(UCAL_EXTENDED_YEAR, eyear); int32_t era = AD; if (eyear < 1) { era = BC; eyear = 1 - eyear; } internalSet(UCAL_ERA, era); internalSet(UCAL_YEAR, eyear); } // ------------------------------------- UDate GregorianCalendar::getGregorianChange() const { return fGregorianCutover; } // ------------------------------------- UBool GregorianCalendar::isLeapYear(int32_t year) const { // MSVC complains bitterly if we try to use Grego::isLeapYear here // NOTE: year&0x3 == year%4 return (year >= fGregorianCutoverYear ? (((year&0x3) == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian ((year&0x3) == 0)); // Julian } // ------------------------------------- int32_t GregorianCalendar::handleComputeJulianDay(UCalendarDateFields bestField) { fInvertGregorian = FALSE; int32_t jd = Calendar::handleComputeJulianDay(bestField); if((bestField == UCAL_WEEK_OF_YEAR) && // if we are doing WOY calculations, we are counting relative to Jan 1 *julian* (internalGet(UCAL_EXTENDED_YEAR)==fGregorianCutoverYear) && jd >= fCutoverJulianDay) { fInvertGregorian = TRUE; // So that the Julian Jan 1 will be used in handleComputeMonthStart return Calendar::handleComputeJulianDay(bestField); } // The following check handles portions of the cutover year BEFORE the // cutover itself happens. //if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) { /* cutoverJulianDay)) { */ if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) { /* cutoverJulianDay)) { */ #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: jd [invert] %d\n", __FILE__, __LINE__, jd); #endif fInvertGregorian = TRUE; jd = Calendar::handleComputeJulianDay(bestField); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: fIsGregorian %s, fInvertGregorian %s - ", __FILE__, __LINE__,fIsGregorian?"T":"F", fInvertGregorian?"T":"F"); fprintf(stderr, " jd NOW %d\n", jd); #endif } else { #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: jd [==] %d - %sfIsGregorian %sfInvertGregorian, %d\n", __FILE__, __LINE__, jd, fIsGregorian?"T":"F", fInvertGregorian?"T":"F", bestField); #endif } if(fIsGregorian && (internalGet(UCAL_EXTENDED_YEAR) == fGregorianCutoverYear)) { int32_t gregShift = Grego::gregorianShift(internalGet(UCAL_EXTENDED_YEAR)); if (bestField == UCAL_DAY_OF_YEAR) { #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: [DOY%d] gregorian shift of JD %d += %d\n", __FILE__, __LINE__, fFields[bestField],jd, gregShift); #endif jd -= gregShift; } else if ( bestField == UCAL_WEEK_OF_MONTH ) { int32_t weekShift = 14; #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: [WOY/WOM] gregorian week shift of %d += %d\n", __FILE__, __LINE__, jd, weekShift); #endif jd += weekShift; // shift by weeks for week based fields. } } return jd; } int32_t GregorianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool /* useMonth */) const { GregorianCalendar *nonConstThis = (GregorianCalendar*)this; // cast away const // If the month is out of range, adjust it into range, and // modify the extended year value accordingly. if (month < 0 || month > 11) { eyear += ClockMath::floorDivide(month, 12, month); } UBool isLeap = eyear%4 == 0; int64_t y = (int64_t)eyear-1; int64_t julianDay = 365*y + ClockMath::floorDivide(y, (int64_t)4) + (kJan1_1JulianDay - 3); nonConstThis->fIsGregorian = (eyear >= fGregorianCutoverYear); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: (hcms%d/%d) fIsGregorian %s, fInvertGregorian %s\n", __FILE__, __LINE__, eyear,month, fIsGregorian?"T":"F", fInvertGregorian?"T":"F"); #endif if (fInvertGregorian) { nonConstThis->fIsGregorian = !fIsGregorian; } if (fIsGregorian) { isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0)); // Add 2 because Gregorian calendar starts 2 days after // Julian calendar int32_t gregShift = Grego::gregorianShift(eyear); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: (hcms%d/%d) gregorian shift of %d += %d\n", __FILE__, __LINE__, eyear, month, julianDay, gregShift); #endif julianDay += gregShift; } // At this point julianDay indicates the day BEFORE the first // day of January 1, <eyear> of either the Julian or Gregorian // calendar. if (month != 0) { julianDay += isLeap?kLeapNumDays[month]:kNumDays[month]; } return static_cast<int32_t>(julianDay); } int32_t GregorianCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const { // If the month is out of range, adjust it into range, and // modify the extended year value accordingly. if (month < 0 || month > 11) { extendedYear += ClockMath::floorDivide(month, 12, month); } return isLeapYear(extendedYear) ? kLeapMonthLength[month] : kMonthLength[month]; } int32_t GregorianCalendar::handleGetYearLength(int32_t eyear) const { return isLeapYear(eyear) ? 366 : 365; } int32_t GregorianCalendar::monthLength(int32_t month) const { int32_t year = internalGet(UCAL_EXTENDED_YEAR); return handleGetMonthLength(year, month); } // ------------------------------------- int32_t GregorianCalendar::monthLength(int32_t month, int32_t year) const { return isLeapYear(year) ? kLeapMonthLength[month] : kMonthLength[month]; } // ------------------------------------- int32_t GregorianCalendar::yearLength(int32_t year) const { return isLeapYear(year) ? 366 : 365; } // ------------------------------------- int32_t GregorianCalendar::yearLength() const { return isLeapYear(internalGet(UCAL_YEAR)) ? 366 : 365; } // ------------------------------------- /** * After adjustments such as add(MONTH), add(YEAR), we don't want the * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar * 3, we want it to go to Feb 28. Adjustments which might run into this * problem call this method to retain the proper month. */ void GregorianCalendar::pinDayOfMonth() { int32_t monthLen = monthLength(internalGet(UCAL_MONTH)); int32_t dom = internalGet(UCAL_DATE); if(dom > monthLen) set(UCAL_DATE, monthLen); } // ------------------------------------- UBool GregorianCalendar::validateFields() const { for (int32_t field = 0; field < UCAL_FIELD_COUNT; field++) { // Ignore DATE and DAY_OF_YEAR which are handled below if (field != UCAL_DATE && field != UCAL_DAY_OF_YEAR && isSet((UCalendarDateFields)field) && ! boundsCheck(internalGet((UCalendarDateFields)field), (UCalendarDateFields)field)) return FALSE; } // Values differ in Least-Maximum and Maximum should be handled // specially. if (isSet(UCAL_DATE)) { int32_t date = internalGet(UCAL_DATE); if (date < getMinimum(UCAL_DATE) || date > monthLength(internalGet(UCAL_MONTH))) { return FALSE; } } if (isSet(UCAL_DAY_OF_YEAR)) { int32_t days = internalGet(UCAL_DAY_OF_YEAR); if (days < 1 || days > yearLength()) { return FALSE; } } // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero. // We've checked against minimum and maximum above already. if (isSet(UCAL_DAY_OF_WEEK_IN_MONTH) && 0 == internalGet(UCAL_DAY_OF_WEEK_IN_MONTH)) { return FALSE; } return TRUE; } // ------------------------------------- UBool GregorianCalendar::boundsCheck(int32_t value, UCalendarDateFields field) const { return value >= getMinimum(field) && value <= getMaximum(field); } // ------------------------------------- UDate GregorianCalendar::getEpochDay(UErrorCode& status) { complete(status); // Divide by 1000 (convert to seconds) in order to prevent overflow when // dealing with UDate(Long.MIN_VALUE) and UDate(Long.MAX_VALUE). double wallSec = internalGetTime()/1000 + (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET))/1000; return ClockMath::floorDivide(wallSec, kOneDay/1000.0); } // ------------------------------------- // ------------------------------------- /** * Compute the julian day number of the day BEFORE the first day of * January 1, year 1 of the given calendar. If julianDay == 0, it * specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian * or Gregorian). */ double GregorianCalendar::computeJulianDayOfYear(UBool isGregorian, int32_t year, UBool& isLeap) { isLeap = year%4 == 0; int32_t y = year - 1; double julianDay = 365.0*y + ClockMath::floorDivide(y, 4) + (kJan1_1JulianDay - 3); if (isGregorian) { isLeap = isLeap && ((year%100 != 0) || (year%400 == 0)); // Add 2 because Gregorian calendar starts 2 days after Julian calendar julianDay += Grego::gregorianShift(year); } return julianDay; } // /** // * Compute the day of week, relative to the first day of week, from // * 0..6, of the current DOW_LOCAL or DAY_OF_WEEK fields. This is // * equivalent to get(DOW_LOCAL) - 1. // */ // int32_t GregorianCalendar::computeRelativeDOW() const { // int32_t relDow = 0; // if (fStamp[UCAL_DOW_LOCAL] > fStamp[UCAL_DAY_OF_WEEK]) { // relDow = internalGet(UCAL_DOW_LOCAL) - 1; // 1-based // } else if (fStamp[UCAL_DAY_OF_WEEK] != kUnset) { // relDow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek(); // if (relDow < 0) relDow += 7; // } // return relDow; // } // /** // * Compute the day of week, relative to the first day of week, // * from 0..6 of the given julian day. // */ // int32_t GregorianCalendar::computeRelativeDOW(double julianDay) const { // int32_t relDow = julianDayToDayOfWeek(julianDay) - getFirstDayOfWeek(); // if (relDow < 0) { // relDow += 7; // } // return relDow; // } // /** // * Compute the DOY using the WEEK_OF_YEAR field and the julian day // * of the day BEFORE January 1 of a year (a return value from // * computeJulianDayOfYear). // */ // int32_t GregorianCalendar::computeDOYfromWOY(double julianDayOfYear) const { // // Compute DOY from day of week plus week of year // // Find the day of the week for the first of this year. This // // is zero-based, with 0 being the locale-specific first day of // // the week. Add 1 to get first day of year. // int32_t fdy = computeRelativeDOW(julianDayOfYear + 1); // return // // Compute doy of first (relative) DOW of WOY 1 // (((7 - fdy) < getMinimalDaysInFirstWeek()) // ? (8 - fdy) : (1 - fdy)) // // Adjust for the week number. // + (7 * (internalGet(UCAL_WEEK_OF_YEAR) - 1)) // // Adjust for the DOW // + computeRelativeDOW(); // } // ------------------------------------- double GregorianCalendar::millisToJulianDay(UDate millis) { return (double)kEpochStartAsJulianDay + ClockMath::floorDivide(millis, (double)kOneDay); } // ------------------------------------- UDate GregorianCalendar::julianDayToMillis(double julian) { return (UDate) ((julian - kEpochStartAsJulianDay) * (double) kOneDay); } // ------------------------------------- int32_t GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b) { return (((stamp_a != kUnset && stamp_b != kUnset) ? uprv_max(stamp_a, stamp_b) : (int32_t)kUnset)); } // ------------------------------------- /** * Roll a field by a signed amount. * Note: This will be made public later. [LIU] */ void GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) { roll((UCalendarDateFields) field, amount, status); } void GregorianCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) { if((amount == 0) || U_FAILURE(status)) { return; } // J81 processing. (gregorian cutover) UBool inCutoverMonth = FALSE; int32_t cMonthLen=0; // 'c' for cutover; in days int32_t cDayOfMonth=0; // no discontinuity: [0, cMonthLen) double cMonthStart=0.0; // in ms // Common code - see if we're in the cutover month of the cutover year if(get(UCAL_EXTENDED_YEAR, status) == fGregorianCutoverYear) { switch (field) { case UCAL_DAY_OF_MONTH: case UCAL_WEEK_OF_MONTH: { int32_t max = monthLength(internalGet(UCAL_MONTH)); UDate t = internalGetTime(); // We subtract 1 from the DAY_OF_MONTH to make it zero-based, and an // additional 10 if we are after the cutover. Thus the monthStart // value will be correct iff we actually are in the cutover month. cDayOfMonth = internalGet(UCAL_DAY_OF_MONTH) - ((t >= fGregorianCutover) ? 10 : 0); cMonthStart = t - ((cDayOfMonth - 1) * kOneDay); // A month containing the cutover is 10 days shorter. if ((cMonthStart < fGregorianCutover) && (cMonthStart + (cMonthLen=(max-10))*kOneDay >= fGregorianCutover)) { inCutoverMonth = TRUE; } } break; default: ; } } switch (field) { case UCAL_WEEK_OF_YEAR: { // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the // week. Also, rolling the week of the year can have seemingly // strange effects simply because the year of the week of year // may be different from the calendar year. For example, the // date Dec 28, 1997 is the first day of week 1 of 1998 (if // weeks start on Sunday and the minimal days in first week is // <= 3). int32_t woy = get(UCAL_WEEK_OF_YEAR, status); // Get the ISO year, which matches the week of year. This // may be one year before or after the calendar year. int32_t isoYear = get(UCAL_YEAR_WOY, status); int32_t isoDoy = internalGet(UCAL_DAY_OF_YEAR); if (internalGet(UCAL_MONTH) == UCAL_JANUARY) { if (woy >= 52) { isoDoy += handleGetYearLength(isoYear); } } else { if (woy == 1) { isoDoy -= handleGetYearLength(isoYear - 1); } } woy += amount; // Do fast checks to avoid unnecessary computation: if (woy < 1 || woy > 52) { // Determine the last week of the ISO year. // We do this using the standard formula we use // everywhere in this file. If we can see that the // days at the end of the year are going to fall into // week 1 of the next year, we drop the last week by // subtracting 7 from the last day of the year. int32_t lastDoy = handleGetYearLength(isoYear); int32_t lastRelDow = (lastDoy - isoDoy + internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek()) % 7; if (lastRelDow < 0) lastRelDow += 7; if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7; int32_t lastWoy = weekNumber(lastDoy, lastRelDow + 1); woy = ((woy + lastWoy - 1) % lastWoy) + 1; } set(UCAL_WEEK_OF_YEAR, woy); set(UCAL_YEAR_WOY,isoYear); return; } case UCAL_DAY_OF_MONTH: if( !inCutoverMonth ) { Calendar::roll(field, amount, status); return; } else { // [j81] 1582 special case for DOM // The default computation works except when the current month // contains the Gregorian cutover. We handle this special case // here. [j81 - aliu] double monthLen = cMonthLen * kOneDay; double msIntoMonth = uprv_fmod(internalGetTime() - cMonthStart + amount * kOneDay, monthLen); if (msIntoMonth < 0) { msIntoMonth += monthLen; } #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: roll DOM %d -> %.0lf ms \n", __FILE__, __LINE__,amount, cMonthLen, cMonthStart+msIntoMonth); #endif setTimeInMillis(cMonthStart + msIntoMonth, status); return; } case UCAL_WEEK_OF_MONTH: if( !inCutoverMonth ) { Calendar::roll(field, amount, status); return; } else { #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n", __FILE__, __LINE__,amount); #endif // NOTE: following copied from the old // GregorianCalendar::roll( WEEK_OF_MONTH ) code // This is tricky, because during the roll we may have to shift // to a different day of the week. For example: // s m t w r f s // 1 2 3 4 5 // 6 7 8 9 10 11 12 // When rolling from the 6th or 7th back one week, we go to the // 1st (assuming that the first partial week counts). The same // thing happens at the end of the month. // The other tricky thing is that we have to figure out whether // the first partial week actually counts or not, based on the // minimal first days in the week. And we have to use the // correct first day of the week to delineate the week // boundaries. // Here's our algorithm. First, we find the real boundaries of // the month. Then we discard the first partial week if it // doesn't count in this locale. Then we fill in the ends with // phantom days, so that the first partial week and the last // partial week are full weeks. We then have a nice square // block of weeks. We do the usual rolling within this block, // as is done elsewhere in this method. If we wind up on one of // the phantom days that we added, we recognize this and pin to // the first or the last day of the month. Easy, eh? // Another wrinkle: To fix jitterbug 81, we have to make all this // work in the oddball month containing the Gregorian cutover. // This month is 10 days shorter than usual, and also contains // a discontinuity in the days; e.g., the default cutover month // is Oct 1582, and goes from day of month 4 to day of month 15. // Normalize the DAY_OF_WEEK so that 0 is the first day of the week // in this locale. We have dow in 0..6. int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek(); if (dow < 0) dow += 7; // Find the day of month, compensating for cutover discontinuity. int32_t dom = cDayOfMonth; // Find the day of the week (normalized for locale) for the first // of the month. int32_t fdm = (dow - dom + 1) % 7; if (fdm < 0) fdm += 7; // Get the first day of the first full week of the month, // including phantom days, if any. Figure out if the first week // counts or not; if it counts, then fill in phantom days. If // not, advance to the first real full week (skip the partial week). int32_t start; if ((7 - fdm) < getMinimalDaysInFirstWeek()) start = 8 - fdm; // Skip the first partial week else start = 1 - fdm; // This may be zero or negative // Get the day of the week (normalized for locale) for the last // day of the month. int32_t monthLen = cMonthLen; int32_t ldm = (monthLen - dom + dow) % 7; // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here. // Get the limit day for the blocked-off rectangular month; that // is, the day which is one past the last day of the month, // after the month has already been filled in with phantom days // to fill out the last week. This day has a normalized DOW of 0. int32_t limit = monthLen + 7 - ldm; // Now roll between start and (limit - 1). int32_t gap = limit - start; int32_t newDom = (dom + amount*7 - start) % gap; if (newDom < 0) newDom += gap; newDom += start; // Finally, pin to the real start and end of the month. if (newDom < 1) newDom = 1; if (newDom > monthLen) newDom = monthLen; // Set the DAY_OF_MONTH. We rely on the fact that this field // takes precedence over everything else (since all other fields // are also set at this point). If this fact changes (if the // disambiguation algorithm changes) then we will have to unset // the appropriate fields here so that DAY_OF_MONTH is attended // to. // If we are in the cutover month, manipulate ms directly. Don't do // this in general because it doesn't work across DST boundaries // (details, details). This takes care of the discontinuity. setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status); return; } default: Calendar::roll(field, amount, status); return; } } // ------------------------------------- /** * Return the minimum value that this field could have, given the current date. * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). * @param field the time field. * @return the minimum value that this field could have, given the current date. * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. */ int32_t GregorianCalendar::getActualMinimum(EDateFields field) const { return getMinimum((UCalendarDateFields)field); } int32_t GregorianCalendar::getActualMinimum(EDateFields field, UErrorCode& /* status */) const { return getMinimum((UCalendarDateFields)field); } /** * Return the minimum value that this field could have, given the current date. * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). * @param field the time field. * @return the minimum value that this field could have, given the current date. * @draft ICU 2.6. */ int32_t GregorianCalendar::getActualMinimum(UCalendarDateFields field, UErrorCode& /* status */) const { return getMinimum(field); } // ------------------------------------ /** * Old year limits were least max 292269054, max 292278994. */ /** * @stable ICU 2.0 */ int32_t GregorianCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const { return kGregorianCalendarLimits[field][limitType]; } /** * Return the maximum value that this field could have, given the current date. * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, * for some years the actual maximum for MONTH is 12, and for others 13. * @stable ICU 2.0 */ int32_t GregorianCalendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const { /* It is a known limitation that the code here (and in getActualMinimum) * won't behave properly at the extreme limits of GregorianCalendar's * representable range (except for the code that handles the YEAR * field). That's because the ends of the representable range are at * odd spots in the year. For calendars with the default Gregorian * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT * zones. As a result, if the calendar is set to Aug 1 292278994 AD, * the actual maximum of DAY_OF_MONTH is 17, not 30. If the date is Mar * 31 in that year, the actual maximum month might be Jul, whereas is * the date is Mar 15, the actual maximum might be Aug -- depending on * the precise semantics that are desired. Similar considerations * affect all fields. Nonetheless, this effect is sufficiently arcane * that we permit it, rather than complicating the code to handle such * intricacies. - liu 8/20/98 * UPDATE: No longer true, since we have pulled in the limit values on * the year. - Liu 11/6/00 */ switch (field) { case UCAL_YEAR: /* The year computation is no different, in principle, from the * others, however, the range of possible maxima is large. In * addition, the way we know we've exceeded the range is different. * For these reasons, we use the special case code below to handle * this field. * * The actual maxima for YEAR depend on the type of calendar: * * Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD * Julian = Dec 2, 292269055 BC - Jan 3, 292272993 AD * Hybrid = Dec 2, 292269055 BC - Aug 17, 292278994 AD * * We know we've exceeded the maximum when either the month, date, * time, or era changes in response to setting the year. We don't * check for month, date, and time here because the year and era are * sufficient to detect an invalid year setting. NOTE: If code is * added to check the month and date in the future for some reason, * Feb 29 must be allowed to shift to Mar 1 when setting the year. */ { if(U_FAILURE(status)) return 0; Calendar *cal = clone(); if(!cal) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } cal->setLenient(TRUE); int32_t era = cal->get(UCAL_ERA, status); UDate d = cal->getTime(status); /* Perform a binary search, with the invariant that lowGood is a * valid year, and highBad is an out of range year. */ int32_t lowGood = kGregorianCalendarLimits[UCAL_YEAR][1]; int32_t highBad = kGregorianCalendarLimits[UCAL_YEAR][2]+1; while ((lowGood + 1) < highBad) { int32_t y = (lowGood + highBad) / 2; cal->set(UCAL_YEAR, y); if (cal->get(UCAL_YEAR, status) == y && cal->get(UCAL_ERA, status) == era) { lowGood = y; } else { highBad = y; cal->setTime(d, status); // Restore original fields } } delete cal; return lowGood; } default: return Calendar::getActualMaximum(field,status); } } int32_t GregorianCalendar::handleGetExtendedYear() { // the year to return int32_t year = kEpochYear; // year field to use int32_t yearField = UCAL_EXTENDED_YEAR; // There are three separate fields which could be used to // derive the proper year. Use the one most recently set. if (fStamp[yearField] < fStamp[UCAL_YEAR]) yearField = UCAL_YEAR; if (fStamp[yearField] < fStamp[UCAL_YEAR_WOY]) yearField = UCAL_YEAR_WOY; // based on the "best" year field, get the year switch(yearField) { case UCAL_EXTENDED_YEAR: year = internalGet(UCAL_EXTENDED_YEAR, kEpochYear); break; case UCAL_YEAR: { // The year defaults to the epoch start, the era to AD int32_t era = internalGet(UCAL_ERA, AD); if (era == BC) { year = 1 - internalGet(UCAL_YEAR, 1); // Convert to extended year } else { year = internalGet(UCAL_YEAR, kEpochYear); } } break; case UCAL_YEAR_WOY: year = handleGetExtendedYearFromWeekFields(internalGet(UCAL_YEAR_WOY), internalGet(UCAL_WEEK_OF_YEAR)); #if defined (U_DEBUG_CAL) // if(internalGet(UCAL_YEAR_WOY) != year) { fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] -> %d\n", __FILE__, __LINE__,internalGet(UCAL_YEAR_WOY),internalGet(UCAL_WEEK_OF_YEAR),year); //} #endif break; default: year = kEpochYear; } return year; } int32_t GregorianCalendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy) { // convert year to extended form int32_t era = internalGet(UCAL_ERA, AD); if(era == BC) { yearWoy = 1 - yearWoy; } return Calendar::handleGetExtendedYearFromWeekFields(yearWoy, woy); } // ------------------------------------- UBool GregorianCalendar::inDaylightTime(UErrorCode& status) const { if (U_FAILURE(status) || !getTimeZone().useDaylightTime()) return FALSE; // Force an update of the state of the Calendar. ((GregorianCalendar*)this)->complete(status); // cast away const return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : FALSE); } // ------------------------------------- /** * Return the ERA. We need a special method for this because the * default ERA is AD, but a zero (unset) ERA is BC. */ int32_t GregorianCalendar::internalGetEra() const { return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : (int32_t)AD; } const char * GregorianCalendar::getType() const { //static const char kGregorianType = "gregorian"; return "gregorian"; } /** * The system maintains a static default century start date and Year. They are * initialized the first time they are used. Once the system default century date * and year are set, they do not change. */ static UDate gSystemDefaultCenturyStart = DBL_MIN; static int32_t gSystemDefaultCenturyStartYear = -1; static icu::UInitOnce gSystemDefaultCenturyInit = U_INITONCE_INITIALIZER; UBool GregorianCalendar::haveDefaultCentury() const { return TRUE; } static void U_CALLCONV initializeSystemDefaultCentury() { // initialize systemDefaultCentury and systemDefaultCenturyYear based // on the current time. They'll be set to 80 years before // the current time. UErrorCode status = U_ZERO_ERROR; GregorianCalendar calendar(status); if (U_SUCCESS(status)) { calendar.setTime(Calendar::getNow(), status); calendar.add(UCAL_YEAR, -80, status); gSystemDefaultCenturyStart = calendar.getTime(status); gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status); } // We have no recourse upon failure unless we want to propagate the failure // out. } UDate GregorianCalendar::defaultCenturyStart() const { // lazy-evaluate systemDefaultCenturyStart umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury); return gSystemDefaultCenturyStart; } int32_t GregorianCalendar::defaultCenturyStartYear() const { // lazy-evaluate systemDefaultCenturyStartYear umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury); return gSystemDefaultCenturyStartYear; } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_FORMATTING */ //eof
{'content_hash': '077e4d89315d2e1ef2471d36990d9cf3', 'timestamp': '', 'source': 'github', 'line_count': 1283, 'max_line_length': 162, 'avg_line_length': 37.81605611847233, 'alnum_prop': 0.5825672946123088, 'repo_name': 'endlessm/chromium-browser', 'id': '6b15171c12b9ac4e2911f2749afaaaefe66d95c2', 'size': '50660', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'third_party/icu/source/i18n/gregocal.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package smo; /** * @author kilian mock * @version 08,11.15 * stellt controler dh.action listener für das lotto programm dar */ import java.awt.event.*; import javax.swing.JToggleButton; import javax.swing.plaf.basic.BasicBorders.ToggleButtonBorder; public class Controller implements ActionListener { // Attribute: Model und View private Model m; private View v; /** * Kontruktor: erzeugt Model und View */ public Controller() { this.m = new Model(); this.v = new View(this.m, this); } /** * @param e der event der den aufruf bewirkt hat * * überprüft von was er aufgerufen wurde und ruft demensprechend die richtigen methoden auf */ public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == "neue ziehung") { m.ziehen(); v.auswertung(); System.out.println("los"); return; } if (e.getActionCommand() == "auswerten") { v.auswertung(); return; } JToggleButton a = (JToggleButton) e.getSource(); v.addToTip(Integer.parseInt(a.getText())); } }
{'content_hash': '53be3f298c21808108a33b62f0466bdb', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 93, 'avg_line_length': 22.46808510638298, 'alnum_prop': 0.6628787878787878, 'repo_name': 'mockerl/A09_Teamarbeit2', 'id': 'e0fba846db2ffcabe20cd64a6062ccdaf5fd1fca', 'size': '1056', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/smo/Controller.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '7168'}]}
<?php namespace { from('Hoa') /** * \Hoa\Console\Cursor */ -> import('Console.Cursor') /** * \Hoa\Console\Window */ -> import('Console.Window'); } namespace Hoa\Console\Chrome { /** * Class \Hoa\Console\Chrome\Text. * * This class builts the text layout. * * @author Ivan Enderlin <[email protected]> * @copyright Copyright © 2007-2014 Ivan Enderlin. * @license New BSD License */ class Text { /** * Align the text to left. * * @const int */ const ALIGN_LEFT = 0; /** * Align the text to right. * * @const int */ const ALIGN_RIGHT = 1; /** * Align the text to center. * * @const int */ const ALIGN_CENTER = 2; /** * Colorize a portion of a text. * It is kind of a shortcut of \Hoa\Console\Color. * * @access public * @param string $text Text. * @param string $attributesBefore Style to apply. * @param string $attributesAfter Reset style. * @return string */ public static function colorize ( $text, $attributesBefore, $attributesAfter = 'normal' ) { ob_start(); \Hoa\Console\Cursor::colorize($attributesBefore); echo $text; \Hoa\Console\Cursor::colorize($attributesAfter); $out = ob_get_contents(); ob_end_clean(); return $out; } /** * Built column from an array. * The array has this structure : * array( * array('Firstname', 'Lastname', 'Love', 'Made' ), * array('Ivan', 'Enderlin', 'Hoa' ), * array('Rasmus', 'Lerdorf' ), * array(null, 'Berners-Lee', null, 'The Web') * ) * The cell can have a new-line character (\n). * The column can have a global alignement, a horizontal and a vertical * padding (this horizontal padding is actually the right padding), and a * separator. * Separator has this form : 'first-column|second-column|third-column|…'. * For example : '|: ', will set a ': ' between the first and second column, * and nothing for the other. * * @access public * @param Array $line The table represented by an array * (see the documentation). * @param int $alignement The global alignement of the text * in cell. * @param int $horizontalPadding The horizontal padding (right * padding). * @param int $verticalPadding The vertical padding. * @param string $separator String where each character is a * column separator. * @return string */ public static function columnize ( Array $line, $alignement = self::ALIGN_LEFT, $horizontalPadding = 2, $verticalPadding = 0, $separator = null ) { if(empty($line)) return ''; $separator = explode('|', $separator); $nbColumn = 0; $nbLine = count($line); $xtraWidth = 2 * ($verticalPadding + 2); // + separator // Get the number of column. foreach($line as $key => &$column) { if(!is_array($column)) $column = array(0 => $column); $handle = count($column); $handle > $nbColumn and $nbColumn = $handle; } $xtraWidth += $horizontalPadding * $nbColumn; // Get the column width. $columnWidth = array_fill(0, $nbColumn, 0); for($e = 0; $e < $nbColumn; $e++) { for($i = 0; $i < $nbLine; $i++) { if(!isset($line[$i][$e])) continue; $handle = self::getMaxLineWidth($line[$i][$e]); $handle > $columnWidth[$e] and $columnWidth[$e] = $handle; } } // If the sum of each column is greater than the window width, we reduce // all greaters columns. $window = \Hoa\Console\Window::getSize(); $envWindow = $window['x']; while($envWindow <= ($cWidthSum = $xtraWidth + array_sum($columnWidth))) { $diff = $cWidthSum - $envWindow; $max = max($columnWidth) - $xtraWidth; $newWidth = $max - $diff; $i = array_search(max($columnWidth), $columnWidth); $columnWidth[$i] = $newWidth; foreach($line as $key => &$c) if(isset($c[$i])) $c[$i] = self::wordwrap($c[$i], $newWidth); } // Manage the horizontal right padding. $columnWidth = array_map( function ( $x ) use ( $horizontalPadding ) { return $x + 2 * $horizontalPadding; }, $columnWidth ); // Prepare the new table, i.e. a new line (\n) must be a new line in the // array (structurally meaning). $newLine = array(); foreach($line as $key => $plpl) { $i = self::getMaxLineNumber($plpl); while($i-- >= 0) $newLine[] = array_fill(0, $nbColumn, null); } $yek = 0; foreach($line as $key => $col) { foreach($col as $kkey => $value) { if(false === strpos($value, "\n")) { $newLine[$yek][$kkey] = $value; continue; } foreach(explode("\n", $value) as $foo => $oof) $newLine[$yek + $foo][$kkey] = $oof; } $i = self::getMaxLineNumber($col); $i > 0 and $yek += $i; $yek++; } // Place the column separator. foreach($newLine as $key => $col) foreach($col as $kkey => $value) if(isset($separator[$kkey])) $newLine[$key][$kkey] = $separator[$kkey] . str_replace( "\n", "\n" . $separator[$kkey], $value ); $line = $newLine; unset($newLine); $nbLine = count($line); // Complete the table with empty cells. foreach($line as $key => &$column) { $handle = count($column); if($nbColumn - $handle > 0) $column += array_fill($handle, $nbColumn - $handle, null); } // Built ! $out = null; $dash = $alignement === self::ALIGN_LEFT ? '-' : ''; foreach($line as $key => $handle) { $format = null; foreach($handle as $i => $hand) if(preg_match_all('#(\\e\[[0-9]+m)#', $hand, $match)) { $a = $columnWidth[$i]; foreach($match as $m) $a += strlen($m[1]); $format .= '%' . $dash . ($a + floor(count($match) / 2)) . 's'; } else $format .= '%' . $dash . $columnWidth[$i] . 's'; $format .= str_repeat("\n", $verticalPadding + 1); array_unshift($handle, $format); $out .= call_user_func_array('sprintf', $handle); } return $out; } /** * Align a text according a “layer”. The layer width is given in arguments. * * @access public * @param string $text The text. * @param string $alignement The text alignement. * @param int $width The layer width. * @return string */ public static function align ( $text, $alignement = self::ALIGN_LEFT, $width = null ) { if(null === $width) { $window = \Hoa\Console\Window::getSize(); $width = $window['x']; } $out = null; switch($alignement) { case self::ALIGN_LEFT: $out .= sprintf('%-' . $width . 's', self::wordwrap($text, $width)); break; case self::ALIGN_CENTER: foreach(explode("\n", self::wordwrap($text, $width)) as $key => $value) $out .= str_repeat(' ', ceil(($width - strlen($value)) / 2)) . $value . "\n"; break; case self::ALIGN_RIGHT: default: foreach(explode("\n", self::wordwrap($text, $width)) as $key => $value) $out .= sprintf('%' . $width . 's' . "\n", $value); break; } return $out; } /** * Get the maximum line width. * * @access protected * @param mixed $lines The line (or group of lines). * @return int */ protected static function getMaxLineWidth ( $lines ) { if(!is_array($lines)) $lines = array(0 => $lines); $width = 0; foreach($lines as $foo => $line) foreach(explode("\n", $line) as $fooo => $lin) { $lin = preg_replace('#\\e\[[0-9]+m#', '', $lin); strlen($lin) > $width and $width = strlen($lin); } return $width; } /** * Get the maximum line number (count the new-line character). * * @access protected * @param mixed $lines The line (or group of lines). * @return int */ protected static function getMaxLineNumber ( $lines ) { if(!is_array($lines)) $lines = array(0 => $lines); $number = 0; foreach($lines as $foo => $line) substr_count($line, "\n") > $number and $number = substr_count($line, "\n"); return $number; } /** * My own wordwrap (just force the wordwrap() $cut parameter).. * * @access public * @param string $text Text to wrap. * @param int $width Line width. * @param string $break String to make the break. * @return string */ public static function wordwrap ( $text, $width = null, $break = "\n" ) { if(null === $width) { $window = \Hoa\Console\Window::getSize(); $width = $window['x']; } return wordwrap($text, $width, $break, true); } /** * Underline with a special string. * * @access public * @param string $text The text to underline. * @param string $pattern The string used to underline. * @return string */ public static function underline ( $text, $pattern = '*' ) { $text = explode("\n", $text); $card = strlen($pattern); foreach($text as $key => &$value) { $i = -1; $max = strlen($value); while($value{++$i} == ' ' && $i < $max); $underline = str_repeat(' ', $i) . str_repeat($pattern, strlen(trim($value)) / $card) . str_repeat(' ', strlen($value) - $i - strlen(trim($value))); $value .= "\n" . $underline; } return implode("\n", $text); } } }
{'content_hash': 'a80ad034bab4fa431de3cb1dc0baa3a4', 'timestamp': '', 'source': 'github', 'line_count': 399, 'max_line_length': 87, 'avg_line_length': 29.458646616541355, 'alnum_prop': 0.4438489025012762, 'repo_name': 'Hywan/Central', 'id': '00b22288c3c5a761a04a505ca5f00b6ee540ffc0', 'size': '13402', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Hoa/Console/Chrome/Text.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'f1b13be423898476ab3882c2181b09ae', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'bed68684234ce41d9d8d2e3eb36bcc50bbff8b6d', 'size': '185', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Poales/Bromeliaceae/Pitcairnia/Pitcairnia integrifolia/ Syn. Pitcairnia anthericoides/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
/* ========================================================================== * ALGO STREAK DETECTION * ========================================================================== */ /* ========================================================================== * MODULE FILE NAME: function.cpp * MODULE TYPE: * * FUNCTION: Function for image elaboration. * PURPOSE: * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * DESIGN ISSUE: None * INTERFACES: None * SUBORDINATES: None. * * HISTORY: See table below. * * 27-Jul-2016 | Francesco Diprima | 0.0 | * Initial creation of this file. * * ========================================================================== */ /* ========================================================================== * INCLUDES * ========================================================================== */ #include <iostream> #include <opencv2/opencv.hpp> #include <opencv/highgui.h> #include "opencv2/gpu/gpu.hpp" #include "externalClass.cu" // important to include .cu file, not header file #include "function_GPU.h" #include "macros.h" /* ========================================================================== * MODULE PRIVATE MACROS * ========================================================================== */ /* ========================================================================== * MODULE PRIVATE TYPE DECLARATIONS * ========================================================================== */ /* ========================================================================== * STATIC VARIABLES FOR MODULE * ========================================================================== */ /* ========================================================================== * STATIC MEMBERS * ========================================================================== */ /* ========================================================================== * NAME SPACE * ========================================================================== */ /* ========================================================================== * FUNCTION NAME: backgroundEstimation * FUNCTION DESCRIPTION: Background Estimation * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat backgroundEstimation(const cv::gpu::GpuMat& imgInOr, const cv::Point backCnt, cv::Mat& meanBg, cv::Mat& stdBg) { cv::gpu::GpuMat imgIn = imgInOr.clone(); size_t backSzR = static_cast<size_t>(::round(imgIn.rows / backCnt.y)); size_t backSzC = static_cast<size_t>(::round(imgIn.cols / backCnt.x)); std::vector<int> vBackSrow; std::vector<int> vBackScol; for (size_t o = 0; o < backCnt.y; ++o) { vBackSrow.push_back(backSzR*o); } vBackSrow.push_back(imgIn.rows); for (size_t o = 0; o < backCnt.x; ++o) { vBackScol.push_back(backSzC*o); } vBackScol.push_back(imgIn.cols); cv::gpu::GpuMat outImg = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); //in cpu braso a zero for (size_t i = 0; i < backCnt.y; ++i) { for (size_t j = 0; j < backCnt.x; ++j) { const cv::Point ptTL = {vBackScol.at(j), vBackSrow.at(i)}; const cv::Point ptBR = {vBackScol.at(j+1), vBackSrow.at(i+1)}; cv::Rect region_of_interest = cv::Rect(ptTL, ptBR); cv::gpu::GpuMat imgPart = imgIn(region_of_interest); cv::gpu::GpuMat imgPartTh = cv::gpu::createContinuous(imgPart.rows, imgPart.cols, imgPart.type()); //in cpu braso a zero cv::gpu::GpuMat imgPart2 = cv::gpu::createContinuous(imgPart.rows, imgPart.cols, imgPart.type()); float oldStd=0; float diffPercStd = 1; cv::Scalar bg_mean = 0; cv::Scalar bg_std = 0; cv::gpu::meanStdDev(imgPart, bg_mean, bg_std); meanBg.at<double>(i, j) = bg_mean.val[0]; //meanBg.at<double>(i,j) = *(cv::mean(imgPart, cv::noArray()).val); Not exist mean for gpu while (diffPercStd>0.2f) { cv::Scalar meanBGmod = 0; cv::Scalar stdBGs = 0; cv::gpu::meanStdDev(imgPart, meanBGmod, stdBGs); stdBg.at<double>(i,j) = stdBGs.val[0];//*(stdBGs.val); double threshH = meanBg.at<double>(i,j)+2.5*stdBg.at<double>(i,j);//3 double maxval = 1.0; double asdf = cv::gpu::threshold(imgPart, imgPartTh, threshH, maxval, cv::THRESH_BINARY_INV); cv::gpu::multiply(imgPart, imgPartTh, imgPart2, cv::gpu::Stream::Null()); diffPercStd = ::abs((stdBg.at<double>(i,j)-oldStd)/stdBg.at<double>(i,j)); oldStd=stdBg.at<double>(i,j); } /*cv::gpu::GpuMat img_RoI = outImg(region_of_interest); imgPart2.copyTo(img_RoI); //imgPart2.copyTo(outImg(region_of_interest).ptr());*/ /*externalClass kernelCUDA; kernelCUDA.fillImgCUDAKernel(imgPart2, outImg, ptTL.x, ptTL.y, ptBR.x, ptBR.y);*/ } } #if SPD_FIGURE_1 cv::Mat result_host; outImg.download(result_host); // Create a window for display. namedWindow("Background estimation", cv::WINDOW_NORMAL); imshow("Background estimation", result_host); cv::waitKey(0); #endif return outImg; } /* ========================================================================== * FUNCTION NAME: gaussianFilter * FUNCTION DESCRIPTION: Gaussian lowpass filter * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat gaussianFilter(const cv::gpu::GpuMat& imgIn, int hsize[2], double sigma) { //cv::gpu::GpuMat imgOut; cv::gpu::GpuMat imgOut = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); cv::Size h = { hsize[0], hsize[1] }; int columnBorderType=-1; cv::gpu::GaussianBlur(imgIn, imgOut, h, sigma, sigma, cv::BORDER_DEFAULT, columnBorderType); #if SPD_FIGURE_1 cv::Mat result_host; imgOut.download(result_host); // Create a window for display. namedWindow("Gaussain filter GPU", cv::WINDOW_NORMAL); imshow("Gaussain filter GPU", result_host); cv::waitKey(0); #endif return imgOut; } /* ========================================================================== * FUNCTION NAME: subtractImage * FUNCTION DESCRIPTION: Subtraction of images, matrix-matrix difference. * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat subtractImage(const cv::gpu::GpuMat& imgA, const cv::gpu::GpuMat& imgB) { cv::gpu::GpuMat imgOut = cv::gpu::createContinuous(imgA.rows, imgA.cols, imgA.type()); cv::gpu::subtract(imgA, imgB, imgOut); #if SPD_FIGURE_1 cv::Mat result_host; imgOut.download(result_host); // Create a window for display. namedWindow("Subtracted image GPU", cv::WINDOW_NORMAL); imshow("Subtracted image GPU", result_host); cv::waitKey(0); #endif return imgOut; } /* ========================================================================== * FUNCTION NAME: addiction * FUNCTION DESCRIPTION: Addiction of images, matrix-matrix addiction. * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat addiction(const cv::gpu::GpuMat& imgA, const cv::gpu::GpuMat& imgB) { cv::gpu::GpuMat imgOut = cv::gpu::createContinuous(imgA.rows, imgA.cols, imgA.type()); cv::gpu::add(imgA, imgB, imgOut); #if SPD_FIGURE_1 cv::Mat result_host; imgOut.download(result_host); // Create a window for display. namedWindow("Subtracted image GPU", cv::WINDOW_NORMAL); imshow("Subtracted image GPU", result_host); cv::waitKey(0); #endif return imgOut; } /* ========================================================================== * FUNCTION NAME: morphologyOpen * FUNCTION DESCRIPTION: Morphology opening * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat morphologyOpen(const cv::gpu::GpuMat& imgIn, int dimLine, double teta_streak) { //cv::gpu::GpuMat imgOut; cv::gpu::GpuMat imgOut = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); int iter = 1; cv::Point anchor = cv::Point(-1, -1); //InputArray kernel; cv::Mat horizontalStructure = getStructuringElement(cv::MORPH_RECT, cv::Size(dimLine, 1)); cv::gpu::morphologyEx(imgIn, imgOut, cv::MORPH_OPEN, horizontalStructure, anchor, iter); #if SPD_FIGURE_1 cv::Mat result_host; imgOut.download(result_host); // Create a window for display. namedWindow("Morphology opening with rectangular kernel GPU", cv::WINDOW_NORMAL); imshow("Morphology opening with rectangular kernel GPU", result_host); cv::waitKey(0); #endif return imgOut; } /* ========================================================================== * FUNCTION NAME: morphologyOpen * FUNCTION DESCRIPTION: Morphology opening with circular structuring element * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat morphologyOpen(const cv::gpu::GpuMat& imgIn, int rad) { cv::gpu::GpuMat imgOut = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); int iter = 1; cv::Point anchor = cv::Point(-1, -1); cv::Size size = cv::Size(rad, rad); //InputArray kernel; cv::Mat horizontalStructure = getStructuringElement(cv::MORPH_ELLIPSE, size, anchor); cv::gpu::morphologyEx(imgIn, imgOut, cv::MORPH_OPEN, horizontalStructure, anchor, iter); #if SPD_FIGURE_1 cv::Mat result_host; imgOut.download(result_host); // Create a window for display. namedWindow("Morphology opening with circular kernel", cv::WINDOW_NORMAL); imshow("Morphology opening with circular kernel", result_host); cv::waitKey(0); #endif return imgOut; } /* ========================================================================== * FUNCTION NAME: binarization * FUNCTION DESCRIPTION: Image binarization * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat binarization(const cv::gpu::GpuMat& imgIn) { //cv::gpu::GpuMat imgOut, binImg; cv::gpu::GpuMat imgOut = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); cv::gpu::GpuMat binImg = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); double maxval = 255.0; double level = 0.0; level = cv::gpu::threshold(imgIn, binImg, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY); level = level * 2.5;//1.5 cv::gpu::threshold(imgIn, imgOut, level, maxval, cv::THRESH_BINARY); #if SPD_FIGURE_1 /* Create a window for display. namedWindow("Binary image", WINDOW_NORMAL); imshow("Binary image", binImg);*/ cv::Mat result_host; imgOut.download(result_host); // Create a window for display. namedWindow("Binary image Otsu threshold GPU", cv::WINDOW_NORMAL); imshow("Binary image Otsu threshold GPU", result_host); cv::waitKey(0); #endif return imgOut; } /* ========================================================================== * FUNCTION NAME: binarizationZone * FUNCTION DESCRIPTION: Image binarization using user threshold * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat binarizationZone(const cv::gpu::GpuMat& imgIn, const cv::Point zoneCnt, const cv::Mat& level) { size_t zoneSzR = static_cast<size_t>(::round(imgIn.rows / zoneCnt.y)); size_t zoneSzC = static_cast<size_t>(::round(imgIn.cols / zoneCnt.x)); std::vector<int> vBackSrow; std::vector<int> vBackScol; for (size_t o = 0; o < zoneCnt.y; ++o) { vBackSrow.push_back(zoneSzR*o); } vBackSrow.push_back(imgIn.rows); for (size_t o = 0; o < zoneCnt.x; ++o) { vBackScol.push_back(zoneSzC*o); } vBackScol.push_back(imgIn.cols); cv::gpu::GpuMat outImg = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); for (size_t i = 0; i < zoneCnt.y; ++i) { for (size_t j = 0; j < zoneCnt.x; ++j) { const cv::Point ptTL = { vBackScol.at(j), vBackSrow.at(i) }; const cv::Point ptBR = { vBackScol.at(j + 1), vBackSrow.at(i + 1) }; cv::Rect region_of_interest = cv::Rect(ptTL, ptBR); cv::gpu::GpuMat imgPart = imgIn(region_of_interest); cv::gpu::GpuMat imgPartTh = cv::gpu::createContinuous(imgPart.rows, imgPart.cols, imgPart.type()); double maxval = 255.0; double asdf = cv::gpu::threshold(imgPart, imgPartTh, level.at<double>(i,j), maxval, cv::THRESH_BINARY); cv::gpu::GpuMat img_RoI = outImg(region_of_interest); imgPart.copyTo(img_RoI); } } #if SPD_FIGURE_1 cv::Mat result_host; outImg.download(result_host); namedWindow("Binary image user thresholdZones", cv::WINDOW_NORMAL); imshow("Binary image user thresholdZones", result_host); cv::waitKey(0); #endif return outImg; } #if 0 /* ========================================================================== * FUNCTION NAME: binarizationDiffTh * FUNCTION DESCRIPTION: Image binarization * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat binarizationDiffTh(cv::gpu::GpuMat& imgIn, int flag) { cv::gpu::GpuMat imgOut, binImg; cv::gpu::GpuMat subBImgTL, subBImgTR, subBImgBL, subBImgBR; cv::Point imgSz = { imgIn.rows, imgIn.cols }; /*int dims[] = { 5, 1 }; cv::Mat level(2, dims, CV_64F);*/ cv::gpu::GpuMat subImageTL(imgIn, cv::Rect(0, 0, imgIn.cols/2, imgIn.rows/2)); cv::gpu::GpuMat subImageTR(imgIn, cv::Rect(0, imgIn.rows/2, imgIn.cols/2, imgIn.rows/2)); cv::gpu::GpuMat subImageBL(imgIn, cv::Rect(0, imgIn.rows/2, imgIn.cols/2, imgIn.rows/2)); cv::gpu::GpuMat subImageBR(imgIn, cv::Rect(imgIn.cols/2, imgIn.rows/2, imgIn.cols/2, imgIn.rows/2)); double maxval = 1.0; double level1 = 0.0; double level2 = 0.0; double level3 = 0.0; double level4 = 0.0; double level5 = 0.0; level1 = cv::gpu::threshold(subImageTL, subBImgTL, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY); level2 = cv::gpu::threshold(subImageTR, subBImgTR, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY); level3 = cv::gpu::threshold(subImageBL, subBImgBL, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY); level4 = cv::gpu::threshold(subImageBR, subBImgBR, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY); level5 = cv::gpu::threshold(binImg , imgOut, cv::THRESH_OTSU, maxval, cv::THRESH_BINARY); level1 = level1 *1.5; level2 = level2 *1.5; level3 = level3 *1.5; level4 = level4 *1.5; level5 = level5 *1.5; /*media mediana ordinamento */ /*da completare*/ if (SPD_FIGURE_1) { // Create a window for display. namedWindow("Binary image", cv::WINDOW_NORMAL); imshow("Binary image", imgOut); } return imgOut; } #endif /* ========================================================================== * FUNCTION NAME: hough * FUNCTION DESCRIPTION: Hough transform * CREATION DATE: 20160911 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ std::vector<std::pair<float, int>> hough(const cv::gpu::GpuMat& imgIn) { double rho = 1; //0.5; double theta = 2*CV_PI / 180; //CV_PI / (2*180); r:pi=g:180 int threshold = 60; //std::vector<cv::Vec2f> houghVal; cv::gpu::GpuMat houghVal; bool doSort = true; int maxLines = 5; cv::gpu::HoughLines(imgIn, houghVal, rho, theta, threshold, doSort, maxLines); #if 0 // Select the inclination angles std::vector<float> angle; for (size_t i = 0; i < houghVal.size(); ++i) { angle.push_back(houghVal.at(i)[1]); } angle.push_back(CV_PI / 2); //Force research at 0\B0 int count = 0; std::vector<std::pair<float, int>> countAngle; for (size_t i = 0; i < houghVal.size(); ++i) { int a = std::count(angle.begin(), angle.end(), angle.at(i)); countAngle.push_back(std::make_pair(angle.at(i), a)); count = count + a; if (houghVal.size() == count) break; } #else std::vector<std::pair<float, int>> countAngle; #endif #if SPD_FIGURE_1 cv::Mat color_dst; cvtColor( imgIn, color_dst, CV_GRAY2BGR ); double minLineLength = 20; double maxLineGap = 1; std::vector<cv::Vec4i> lines; HoughLinesP(imgIn, lines, rho, theta, threshold, minLineLength, maxLineGap); for (size_t i = 0; i < lines.size(); i++) { line(color_dst, cv::Point(lines[i][0], lines[i][1]), cv::Point(lines[i][2], lines[i][3]), cv::Scalar(0, 0, 255), 3, 8); } // Create a window for display. namedWindow("Hough transform", cv::WINDOW_NORMAL); imshow("Hough transform", color_dst); cv::waitKey(0); #endif return countAngle; } /* ========================================================================== * FUNCTION NAME: convolution * FUNCTION DESCRIPTION: Image convolution * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ cv::gpu::GpuMat convolution(const cv::gpu::GpuMat& imgIn, const cv::Mat& kernel, double thresh) { //cv::gpu::GpuMat imgOut, convImg; cv::gpu::GpuMat imgOut = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type()); /*cv::gpu::GpuMat convImg = cv::gpu::createContinuous(imgIn.rows, imgIn.cols, imgIn.type());*/ cv::gpu::GpuMat convImg; /*kernel_size = 3 + 2 * (ind % 5); kernel = Mat::ones(kernel_size, kernel_size, CV_32F) / (float)(kernel_size*kernel_size);*/ int ddepth = -1; cv::Point anchor = cv::Point(-1, -1); cv::gpu::Stream stream; stream.Null(); std::cout << "prima di filter2d " << std::endl; cv::gpu::filter2D(imgIn, convImg, ddepth, kernel, anchor, cv::BORDER_DEFAULT); std::cout << "dopo di filter2d " << std::endl; /*thresh=1; cv::gpu::boxFilter(const_cast<const cv::gpu::GpuMat&>(imgIn), convImg, ddepth, kernel, anchor, stream); */ /*cv::Size ksize(3, 3); cv::gpu::blur(const_cast<const cv::gpu::GpuMat&>(imgIn), convImg, ksize, anchor, stream); */ double maxval = 255.0; cv::gpu::threshold(convImg, imgOut, thresh, maxval, cv::THRESH_BINARY); //cv::gpu::threshold(imgIn, imgOut, thresh, maxval, cv::THRESH_BINARY); #if SPD_FIGURE_1 cv::Mat result_host; imgOut.download(result_host); // Create a window for display. namedWindow("Convolution image GPU", cv::WINDOW_NORMAL); imshow("Convolution image GPU", result_host); #endif return imgOut; } /* ========================================================================== * FUNCTION NAME: iDivUp * FUNCTION DESCRIPTION: Rounded division * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ int iDivUp(int a, int b) { return ((a % b) != 0) ? (a / b + 1) : (a / b); } /* ========================================================================== * FUNCTION NAME: gpuErrchk * FUNCTION DESCRIPTION: CUDA error check * CREATION DATE: 20160727 * AUTHORS: Francesco Diprima * INTERFACES: None * SUBORDINATES: None * ========================================================================== */ #define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=true) { if (code != cudaSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } }
{'content_hash': '2895698cacea3d2c6915ef20b636aa4c', 'timestamp': '', 'source': 'github', 'line_count': 615, 'max_line_length': 126, 'avg_line_length': 33.702439024390245, 'alnum_prop': 0.5393448159405606, 'repo_name': 'franaisd1a/repo_diprima', 'id': 'bdfbc26b2e77de1c4948bf8cfd812f7504692ba8', 'size': '20727', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Dottorato/Algoritm_streak_detection/CPP/algoritm_streak_detection_cpp/src/function_GPU.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '2161'}, {'name': 'C', 'bytes': '9864'}, {'name': 'C++', 'bytes': '297610'}, {'name': 'CMake', 'bytes': '7886'}, {'name': 'Cuda', 'bytes': '82675'}, {'name': 'M', 'bytes': '1171'}, {'name': 'Matlab', 'bytes': '256744'}, {'name': 'Shell', 'bytes': '2584'}]}
<?php /** * PopStop is a PHP script that let's you stream your * movie collection to your browser. * * This software is distributed under the MIT License * http://www.opensource.org/licenses/mit-license.php * * Visit http://www.popstop.io for more information * * @author Sebastian de Kok */ class MovieController extends BaseController { /** * Get a movie from the database by ID * * @param array $params * @return array */ public function getMovieById($params) { $this->db->bind(["id" => $params['id']]); $movie = $this->db->fetch("SELECT * FROM movies WHERE movie_id = :id", true); return $movie; } /** * Get a random featured movie from the database * * @return array|string */ public function getFeaturedMovie() { $featured = $this->db->fetch('SELECT * FROM movies ORDER BY RANDOM()', true); if (!$featured) { return 'The database is empty, delete the database to start the installation process.'; } return $featured; } /** * Get all the movies and order them correctly * * @param array $params * @return array */ public function getMovies($params) { /** @var int $batch */ $batch = $this->getSettings()['batch']; switch($params['type']) { case "date": $query = "ORDER BY created_at desc"; break; case "rating": $query = "ORDER BY vote_average desc"; break; case "popular": $query = "ORDER BY popularity desc"; break; } //get current starting point of records $position = ($params['is_loaded']); $genre = (!empty($params['genre'])) ? $params['genre'] : ''; $cast = (!empty($params['cast'])) ? $params['cast'] : ''; $this->db->bind([ "position" => $position, "batch" => $batch, "genre" => "%$genre%", "cast" => "%$cast%" ]); $movies = $this->db->fetch("SELECT * FROM movies INNER JOIN files ON movies.movie_id = files.movie_id WHERE (',' || genres || ',') LIKE :genre AND (',' || casts || ',') LIKE :cast $query LIMIT :position, :batch"); return ['movies' => $movies, 'batch' => $batch]; } /** * Get the movie file location to play in the browser * * @param array $params * @return array */ public function playMovie($params) { $this->db->bind(["id" => $params['id']]); $result = $this->db->fetch("SELECT * FROM movies INNER JOIN files ON movies.movie_id = files.movie_id WHERE movies.movie_id = :id", true); return $result; } /** * Search the database for the movie * * @param array $params * @return array */ public function searchMovies($params) { $query = $params['query']; $this->db->bind(["query" => "$query*"]); $result = $this->db->fetch("SELECT * FROM movies WHERE movies MATCH :query"); return $result; } /** * Get all the movie genres in the database * * @return array */ public function getMovieGenres() { $genres = $this->db->fetch('SELECT genres FROM movies'); foreach($genres as $genre) { $genres_explode = explode(',', $genre['genres']); foreach($genres_explode as $genre) { $array[] = $genre; } } /** * Sort the genres on alphabetical order */ function sortAlphabetically($a, $b) { return strcmp($a, $b); } usort($array, "sortAlphabetically"); return array_count_values($array); } /** * Get the movie cast by ID * * @param array $params * @return array */ public function getMovieCastById($params) { $this->db->bind(["id" => $params['id']]); $movie = $this->db->fetch("SELECT casts FROM movies WHERE movie_id = :id", true); $movieCast = explode(',', $movie['casts']); $casts = []; foreach($movieCast as $castId) { $this->db->bind(["cast_id" => $castId]); $casts[] = $this->db->fetch("SELECT * FROM casts WHERE cast_id = :cast_id", true); } return ['casts' => $casts]; } /** * Get the movie file location to play in the browser * * @param array $params * @return array */ public function getMovieSubtitles($params) { $this->db->bind(["id" => $params['id']]); $result = $this->db->fetch("SELECT * FROM files WHERE movie_id = :id", true); return $this->scan->getSubtitles($result['path'], $result['alias']); } /** * Save the current time of the movie * * @param array $params * @return array */ public function saveCurrentTime($params) { $this->db->bind([ "current_at" => $params['current_time'], "movie_id" => $params['movie_id'] ]); $this->db->update("UPDATE movies SET resume_at = :current_at WHERE movie_id = :movie_id"); return ['saved' => true]; } /** * Clean the database with the files that don't exist * * @return array */ public function cleanDatabase() { $files = $this->db->fetch("SELECT docid, movies.movie_id, target FROM movies LEFT JOIN files ON movies.movie_id = files.movie_id"); $i = 0; foreach($files as $file) { $doc_id = $file['docid']; $movie_id = $file['movie_id']; if(!file_exists($file['target'])) { $this->db->query("DELETE FROM movies WHERE docid = $doc_id; DELETE FROM files WHERE movie_id = $movie_id"); $i++; } } return ['cleaned' => $i]; } }
{'content_hash': 'b715963582c19ab3015d62084eb57716', 'timestamp': '', 'source': 'github', 'line_count': 214, 'max_line_length': 123, 'avg_line_length': 28.72897196261682, 'alnum_prop': 0.5013012361743656, 'repo_name': 'sebas7dk/popstop', 'id': 'c83cf63d087c1f99d8131407b35a77167cf46534', 'size': '6148', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/Controllers/MovieController.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '47331'}, {'name': 'HTML', 'bytes': '4923'}, {'name': 'JavaScript', 'bytes': '54469'}, {'name': 'PHP', 'bytes': '36384'}]}
/* Includes ------------------------------------------------------------------*/ #include "usbh_ioreq.h" #include "usb_bsp.h" #include "usbh_hcs.h" #include "usbh_stdreq.h" #include "usbh_core.h" #include "usb_hcd_int.h" /** @addtogroup USBH_LIB * @{ */ /** @addtogroup USBH_LIB_CORE * @{ */ /** @defgroup USBH_CORE * @brief TThis file handles the basic enumaration when a device is connected * to the host. * @{ */ /** @defgroup USBH_CORE_Private_TypesDefinitions * @{ */ uint8_t USBH_Disconnected (USB_OTG_CORE_HANDLE *pdev); uint8_t USBH_Connected (USB_OTG_CORE_HANDLE *pdev); uint8_t USBH_SOF (USB_OTG_CORE_HANDLE *pdev); USBH_HCD_INT_cb_TypeDef USBH_HCD_INT_cb = { USBH_SOF, USBH_Connected, USBH_Disconnected, }; USBH_HCD_INT_cb_TypeDef *USBH_HCD_INT_fops = &USBH_HCD_INT_cb; /** * @} */ /** @defgroup USBH_CORE_Private_Defines * @{ */ /** * @} */ /** @defgroup USBH_CORE_Private_Macros * @{ */ /** * @} */ /** @defgroup USBH_CORE_Private_Variables * @{ */ /** * @} */ /** @defgroup USBH_CORE_Private_FunctionPrototypes * @{ */ static USBH_Status USBH_HandleEnum(USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost); USBH_Status USBH_HandleControl (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost); /** * @} */ /** @defgroup USBH_CORE_Private_Functions * @{ */ /** * @brief USBH_Connected * USB Connect callback function from the Interrupt. * @param selected device * @retval Status */ uint8_t USBH_Connected (USB_OTG_CORE_HANDLE *pdev) { pdev->host.ConnSts = 1; return 0; } /** * @brief USBH_Disconnected * USB Disconnect callback function from the Interrupt. * @param selected device * @retval Status */ uint8_t USBH_Disconnected (USB_OTG_CORE_HANDLE *pdev) { pdev->host.ConnSts = 0; return 0; } /** * @brief USBH_SOF * USB SOF callback function from the Interrupt. * @param selected device * @retval Status */ uint8_t USBH_SOF (USB_OTG_CORE_HANDLE *pdev) { /* This callback could be used to implement a scheduler process */ return 0; } /** * @brief USBH_Init * Host hardware and stack initializations * @param class_cb: Class callback structure address * @param usr_cb: User callback structure address * @retval None */ void USBH_Init(USB_OTG_CORE_HANDLE *pdev, USB_OTG_CORE_ID_TypeDef coreID, USBH_HOST *phost, USBH_Class_cb_TypeDef *class_cb, USBH_Usr_cb_TypeDef *usr_cb) { /* Hardware Init */ USB_OTG_BSP_Init(pdev); /* configure GPIO pin used for switching VBUS power */ USB_OTG_BSP_ConfigVBUS(0); /* Host de-initializations */ USBH_DeInit(pdev, phost); /*Register class and user callbacks */ phost->class_cb = class_cb; phost->usr_cb = usr_cb; /* Start the USB OTG core */ HCD_Init(pdev , coreID); /* Upon Init call usr call back */ phost->usr_cb->Init(); /* Enable Interrupts */ USB_OTG_BSP_EnableInterrupt(pdev); } /** * @brief USBH_DeInit * Re-Initialize Host * @param None * @retval status: USBH_Status */ USBH_Status USBH_DeInit(USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost) { /* Software Init */ phost->gState = HOST_IDLE; phost->gStateBkp = HOST_IDLE; phost->EnumState = ENUM_IDLE; phost->RequestState = CMD_SEND; phost->Control.state = CTRL_SETUP; phost->Control.ep0size = USB_OTG_MAX_EP0_SIZE; phost->device_prop.address = USBH_DEVICE_ADDRESS_DEFAULT; phost->device_prop.speed = HPRT0_PRTSPD_FULL_SPEED; USBH_Free_Channel (pdev, phost->Control.hc_num_in); USBH_Free_Channel (pdev, phost->Control.hc_num_out); return USBH_OK; } /** * @brief USBH_Process * USB Host core main state machine process * @param None * @retval None */ void USBH_Process(USB_OTG_CORE_HANDLE *pdev , USBH_HOST *phost) { volatile USBH_Status status = USBH_FAIL; /* check for Host port events */ if ((HCD_IsDeviceConnected(pdev) == 0)&& (phost->gState != HOST_IDLE)) { if(phost->gState != HOST_DEV_DISCONNECTED) { phost->gState = HOST_DEV_DISCONNECTED; } } switch (phost->gState) { case HOST_IDLE : if (HCD_IsDeviceConnected(pdev)) { phost->gState = HOST_DEV_ATTACHED; USB_OTG_BSP_mDelay(100); } break; case HOST_DEV_ATTACHED : phost->usr_cb->DeviceAttached(); phost->Control.hc_num_out = USBH_Alloc_Channel(pdev, 0x00); phost->Control.hc_num_in = USBH_Alloc_Channel(pdev, 0x80); /* Reset USB Device */ if ( HCD_ResetPort(pdev) == 0) { phost->usr_cb->ResetDevice(); /* Wait for USB USBH_ISR_PrtEnDisableChange() Host is Now ready to start the Enumeration */ phost->device_prop.speed = HCD_GetCurrentSpeed(pdev); phost->gState = HOST_ENUMERATION; phost->usr_cb->DeviceSpeedDetected(phost->device_prop.speed); /* Open Control pipes */ USBH_Open_Channel (pdev, phost->Control.hc_num_in, phost->device_prop.address, phost->device_prop.speed, EP_TYPE_CTRL, phost->Control.ep0size); /* Open Control pipes */ USBH_Open_Channel (pdev, phost->Control.hc_num_out, phost->device_prop.address, phost->device_prop.speed, EP_TYPE_CTRL, phost->Control.ep0size); } break; case HOST_ENUMERATION: /* Check for enumeration status */ if ( USBH_HandleEnum(pdev , phost) == USBH_OK) { /* The function shall return USBH_OK when full enumeration is complete */ /* user callback for end of device basic enumeration */ phost->usr_cb->EnumerationDone(); phost->gState = HOST_USR_INPUT; } break; case HOST_USR_INPUT: /*The function should return user response true to move to class state */ if ( phost->usr_cb->UserInput() == USBH_USR_RESP_OK) { if((phost->class_cb->Init(pdev, phost))\ == USBH_OK) { phost->gState = HOST_CLASS_REQUEST; } } break; case HOST_CLASS_REQUEST: /* process class standard contol requests state machine */ status = phost->class_cb->Requests(pdev, phost); if(status == USBH_OK) { phost->gState = HOST_CLASS; } else { USBH_ErrorHandle(phost, status); } break; case HOST_CLASS: /* process class state machine */ status = phost->class_cb->Machine(pdev, phost); USBH_ErrorHandle(phost, status); break; case HOST_CTRL_XFER: /* process control transfer state machine */ USBH_HandleControl(pdev, phost); break; case HOST_SUSPENDED: break; case HOST_ERROR_STATE: /* Re-Initilaize Host for new Enumeration */ USBH_DeInit(pdev, phost); phost->usr_cb->DeInit(); phost->class_cb->DeInit(pdev, &phost->device_prop); break; case HOST_DEV_DISCONNECTED : /* Manage User disconnect operations*/ phost->usr_cb->DeviceDisconnected(); /* Re-Initilaize Host for new Enumeration */ USBH_DeInit(pdev, phost); phost->usr_cb->DeInit(); phost->class_cb->DeInit(pdev, &phost->device_prop); USBH_DeAllocate_AllChannel(pdev); phost->gState = HOST_IDLE; break; default : break; } } /** * @brief USBH_ErrorHandle * This function handles the Error on Host side. * @param errType : Type of Error or Busy/OK state * @retval None */ void USBH_ErrorHandle(USBH_HOST *phost, USBH_Status errType) { /* Error unrecovered or not supported device speed */ if ( (errType == USBH_ERROR_SPEED_UNKNOWN) || (errType == USBH_UNRECOVERED_ERROR) ) { phost->usr_cb->UnrecoveredError(); phost->gState = HOST_ERROR_STATE; } /* USB host restart requested from application layer */ else if(errType == USBH_APPLY_DEINIT) { phost->gState = HOST_ERROR_STATE; /* user callback for initalization */ phost->usr_cb->Init(); } } /** * @brief USBH_HandleEnum * This function includes the complete enumeration process * @param pdev: Selected device * @retval USBH_Status */ static USBH_Status USBH_HandleEnum(USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost) { USBH_Status Status = USBH_BUSY; uint8_t Local_Buffer[64]; switch (phost->EnumState) { case ENUM_IDLE: /* Get Device Desc for only 1st 8 bytes : To get EP0 MaxPacketSize */ if ( USBH_Get_DevDesc(pdev , phost, 8) == USBH_OK) { phost->Control.ep0size = phost->device_prop.Dev_Desc.bMaxPacketSize; /* Issue Reset */ HCD_ResetPort(pdev); phost->EnumState = ENUM_GET_FULL_DEV_DESC; /* modify control channels configuration for MaxPacket size */ USBH_Modify_Channel (pdev, phost->Control.hc_num_out, 0, 0, 0, phost->Control.ep0size); USBH_Modify_Channel (pdev, phost->Control.hc_num_in, 0, 0, 0, phost->Control.ep0size); } break; case ENUM_GET_FULL_DEV_DESC: /* Get FULL Device Desc */ if ( USBH_Get_DevDesc(pdev, phost, USB_DEVICE_DESC_SIZE)\ == USBH_OK) { /* user callback for device descriptor available */ phost->usr_cb->DeviceDescAvailable(&phost->device_prop.Dev_Desc); phost->EnumState = ENUM_SET_ADDR; } break; case ENUM_SET_ADDR: /* set address */ if ( USBH_SetAddress(pdev, phost, USBH_DEVICE_ADDRESS) == USBH_OK) { USB_OTG_BSP_mDelay(2); phost->device_prop.address = USBH_DEVICE_ADDRESS; /* user callback for device address assigned */ phost->usr_cb->DeviceAddressAssigned(); phost->EnumState = ENUM_GET_CFG_DESC; /* modify control channels to update device address */ USBH_Modify_Channel (pdev, phost->Control.hc_num_in, phost->device_prop.address, 0, 0, 0); USBH_Modify_Channel (pdev, phost->Control.hc_num_out, phost->device_prop.address, 0, 0, 0); } break; case ENUM_GET_CFG_DESC: /* get standard configuration descriptor */ if ( USBH_Get_CfgDesc(pdev, phost, USB_CONFIGURATION_DESC_SIZE) == USBH_OK) { phost->EnumState = ENUM_GET_FULL_CFG_DESC; } break; case ENUM_GET_FULL_CFG_DESC: /* get FULL config descriptor (config, interface, endpoints) */ if (USBH_Get_CfgDesc(pdev, phost, phost->device_prop.Cfg_Desc.wTotalLength) == USBH_OK) { /* User callback for configuration descriptors available */ phost->usr_cb->ConfigurationDescAvailable(&phost->device_prop.Cfg_Desc, phost->device_prop.Itf_Desc, phost->device_prop.Ep_Desc[0]); phost->EnumState = ENUM_GET_MFC_STRING_DESC; } break; case ENUM_GET_MFC_STRING_DESC: if (phost->device_prop.Dev_Desc.iManufacturer != 0) { /* Check that Manufacturer String is available */ if ( USBH_Get_StringDesc(pdev, phost, phost->device_prop.Dev_Desc.iManufacturer, Local_Buffer , 0xff) == USBH_OK) { /* User callback for Manufacturing string */ phost->usr_cb->ManufacturerString(Local_Buffer); phost->EnumState = ENUM_GET_PRODUCT_STRING_DESC; } } else { phost->usr_cb->ManufacturerString("N/A"); phost->EnumState = ENUM_GET_PRODUCT_STRING_DESC; } break; case ENUM_GET_PRODUCT_STRING_DESC: if (phost->device_prop.Dev_Desc.iProduct != 0) { /* Check that Product string is available */ if ( USBH_Get_StringDesc(pdev, phost, phost->device_prop.Dev_Desc.iProduct, Local_Buffer, 0xff) == USBH_OK) { /* User callback for Product string */ phost->usr_cb->ProductString(Local_Buffer); phost->EnumState = ENUM_GET_SERIALNUM_STRING_DESC; } } else { phost->usr_cb->ProductString("N/A"); phost->EnumState = ENUM_GET_SERIALNUM_STRING_DESC; } break; case ENUM_GET_SERIALNUM_STRING_DESC: if (phost->device_prop.Dev_Desc.iSerialNumber != 0) { /* Check that Serial number string is available */ if ( USBH_Get_StringDesc(pdev, phost, phost->device_prop.Dev_Desc.iSerialNumber, Local_Buffer, 0xff) == USBH_OK) { /* User callback for Serial number string */ phost->usr_cb->SerialNumString(Local_Buffer); phost->EnumState = ENUM_SET_CONFIGURATION; } } else { phost->usr_cb->SerialNumString("N/A"); phost->EnumState = ENUM_SET_CONFIGURATION; } break; case ENUM_SET_CONFIGURATION: /* set configuration (default config) */ if (USBH_SetCfg(pdev, phost, phost->device_prop.Cfg_Desc.bConfigurationValue) == USBH_OK) { phost->EnumState = ENUM_DEV_CONFIGURED; } break; case ENUM_DEV_CONFIGURED: /* user callback for enumeration done */ Status = USBH_OK; break; default: break; } return Status; } /** * @brief USBH_HandleControl * Handles the USB control transfer state machine * @param pdev: Selected device * @retval Status */ USBH_Status USBH_HandleControl (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost) { uint8_t direction; static uint16_t timeout = 0; USBH_Status status = USBH_OK; URB_STATE URB_Status = URB_IDLE; phost->Control.status = CTRL_START; switch (phost->Control.state) { case CTRL_SETUP: /* send a SETUP packet */ USBH_CtlSendSetup (pdev, phost->Control.setup.d8 , phost->Control.hc_num_out); phost->Control.state = CTRL_SETUP_WAIT; break; case CTRL_SETUP_WAIT: URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_out); /* case SETUP packet sent successfully */ if(URB_Status == URB_DONE) { direction = (phost->Control.setup.b.bmRequestType & USB_REQ_DIR_MASK); /* check if there is a data stage */ if (phost->Control.setup.b.wLength.w != 0 ) { timeout = DATA_STAGE_TIMEOUT; if (direction == USB_D2H) { /* Data Direction is IN */ phost->Control.state = CTRL_DATA_IN; } else { /* Data Direction is OUT */ phost->Control.state = CTRL_DATA_OUT; } } /* No DATA stage */ else { timeout = NODATA_STAGE_TIMEOUT; /* If there is No Data Transfer Stage */ if (direction == USB_D2H) { /* Data Direction is IN */ phost->Control.state = CTRL_STATUS_OUT; } else { /* Data Direction is OUT */ phost->Control.state = CTRL_STATUS_IN; } } /* Set the delay timer to enable timeout for data stage completion */ phost->Control.timer = HCD_GetCurrentFrame(pdev); } else if(URB_Status == URB_ERROR) { phost->Control.state = CTRL_ERROR; phost->Control.status = CTRL_XACTERR; } break; case CTRL_DATA_IN: /* Issue an IN token */ USBH_CtlReceiveData(pdev, phost->Control.buff, phost->Control.length, phost->Control.hc_num_in); phost->Control.state = CTRL_DATA_IN_WAIT; break; case CTRL_DATA_IN_WAIT: URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_in); /* check is DATA packet transfered successfully */ if (URB_Status == URB_DONE) { phost->Control.state = CTRL_STATUS_OUT; } /* manage error cases*/ if (URB_Status == URB_STALL) { /* In stall case, return to previous machine state*/ phost->gState = phost->gStateBkp; } else if (URB_Status == URB_ERROR) { /* Device error */ phost->Control.state = CTRL_ERROR; } else if ((HCD_GetCurrentFrame(pdev)- phost->Control.timer) > timeout) { /* timeout for IN transfer */ phost->Control.state = CTRL_ERROR; } break; case CTRL_DATA_OUT: /* Start DATA out transfer (only one DATA packet)*/ pdev->host.hc[phost->Control.hc_num_out].toggle_out = 1; USBH_CtlSendData (pdev, phost->Control.buff, phost->Control.length , phost->Control.hc_num_out); phost->Control.state = CTRL_DATA_OUT_WAIT; break; case CTRL_DATA_OUT_WAIT: URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_out); if (URB_Status == URB_DONE) { /* If the Setup Pkt is sent successful, then change the state */ phost->Control.state = CTRL_STATUS_IN; } /* handle error cases */ else if (URB_Status == URB_STALL) { /* In stall case, return to previous machine state*/ phost->gState = phost->gStateBkp; phost->Control.state = CTRL_STALLED; } else if (URB_Status == URB_NOTREADY) { /* Nack received from device */ phost->Control.state = CTRL_DATA_OUT; } else if (URB_Status == URB_ERROR) { /* device error */ phost->Control.state = CTRL_ERROR; } break; case CTRL_STATUS_IN: /* Send 0 bytes out packet */ USBH_CtlReceiveData (pdev, 0, 0, phost->Control.hc_num_in); phost->Control.state = CTRL_STATUS_IN_WAIT; break; case CTRL_STATUS_IN_WAIT: URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_in); if ( URB_Status == URB_DONE) { /* Control transfers completed, Exit the State Machine */ phost->gState = phost->gStateBkp; phost->Control.state = CTRL_COMPLETE; } else if (URB_Status == URB_ERROR) { phost->Control.state = CTRL_ERROR; } else if((HCD_GetCurrentFrame(pdev)\ - phost->Control.timer) > timeout) { phost->Control.state = CTRL_ERROR; } else if(URB_Status == URB_STALL) { /* Control transfers completed, Exit the State Machine */ phost->gState = phost->gStateBkp; phost->Control.status = CTRL_STALL; status = USBH_NOT_SUPPORTED; } break; case CTRL_STATUS_OUT: pdev->host.hc[phost->Control.hc_num_out].toggle_out ^= 1; USBH_CtlSendData (pdev, 0, 0, phost->Control.hc_num_out); phost->Control.state = CTRL_STATUS_OUT_WAIT; break; case CTRL_STATUS_OUT_WAIT: URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_out); if (URB_Status == URB_DONE) { phost->gState = phost->gStateBkp; phost->Control.state = CTRL_COMPLETE; } else if (URB_Status == URB_NOTREADY) { phost->Control.state = CTRL_STATUS_OUT; } else if (URB_Status == URB_ERROR) { phost->Control.state = CTRL_ERROR; } break; case CTRL_ERROR: /* After a halt condition is encountered or an error is detected by the host, a control endpoint is allowed to recover by accepting the next Setup PID; i.e., recovery actions via some other pipe are not required for control endpoints. For the Default Control Pipe, a device reset will ultimately be required to clear the halt or error condition if the next Setup PID is not accepted. */ if (++ phost->Control.errorcount <= USBH_MAX_ERROR_COUNT) { /* Do the transmission again, starting from SETUP Packet */ phost->Control.state = CTRL_SETUP; } else { phost->Control.status = CTRL_FAIL; phost->gState = phost->gStateBkp; status = USBH_FAIL; } break; default: break; } return status; } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{'content_hash': '78b96866ad7d7509d189a3c0cdb3cac9', 'timestamp': '', 'source': 'github', 'line_count': 830, 'max_line_length': 85, 'avg_line_length': 26.898795180722892, 'alnum_prop': 0.5260234703932635, 'repo_name': 'james54068/stm32f429_learning', 'id': '5ddf2808f995a16d94ef78daec1395d4615810f7', 'size': '23546', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'USB_MSC_HOST/Libraries/STM32_USB_HOST_Library/Core/src/usbh_core.c', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '1781117'}, {'name': 'C', 'bytes': '39049950'}, {'name': 'C++', 'bytes': '2532831'}, {'name': 'CSS', 'bytes': '270876'}, {'name': 'JavaScript', 'bytes': '996886'}, {'name': 'Makefile', 'bytes': '24127'}, {'name': 'Objective-C', 'bytes': '11759'}, {'name': 'Shell', 'bytes': '9891'}]}
module Waitress # The DirHandler class is an instance of +Waitress::Handler+ that is responsible # for loading files from the filesystem and serving them if they exist in the VHost's # root. It automatically handles mimetypes, evaluation and almost everything about # the serving process for files in the FileSystem. class DirHandler < Handler attr_accessor :priority attr_accessor :directory # Get the instance of DirHandler that will load Waitress' resources # such as the default 404 and index pages, as well as CSS and JS def self.resources_handler @@resources_handler ||= Waitress::DirHandler.new(Waitress::Chef.resources_http, -1000) @@resources_handler end # Create a new DirHandler, with the given FileSystem directory as a root # and priority. def initialize directory, priority=50 @directory = File.absolute_path(directory) @priority = priority end def respond? request, vhost path = File.expand_path File.join("#{directory}", request.path) res = Waitress::Chef.find_file(path)[:result] path.include?(directory) && (res == :ok) end def serve request, response, client, vhost path = File.expand_path File.join("#{directory}", request.path) file = Waitress::Chef.find_file(path)[:file] Waitress::Chef.serve_file request, response, client, vhost, file end end end
{'content_hash': 'bca1e90430cb996f00165e7249d83e96', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 92, 'avg_line_length': 36.05128205128205, 'alnum_prop': 0.6998577524893315, 'repo_name': 'JacisNonsense/Waitress', 'id': 'f1010ea1cdb30727361983860e66e509ebcad53d', 'size': '1406', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/waitress/handlers/dirhandler.rb', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '42050'}, {'name': 'CSS', 'bytes': '3326'}, {'name': 'HTML', 'bytes': '826'}, {'name': 'Ragel in Ruby Host', 'bytes': '9946'}, {'name': 'Ruby', 'bytes': '95155'}]}
.class public abstract Landroid/app/ActivityView$ActivityViewCallback; .super Ljava/lang/Object; .source "ActivityView.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/app/ActivityView; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x409 name = "ActivityViewCallback" .end annotation # direct methods .method public constructor <init>()V .locals 0 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method # virtual methods .method public abstract onAllActivitiesComplete(Landroid/app/ActivityView;)V .end method .method public abstract onSurfaceAvailable(Landroid/app/ActivityView;)V .end method .method public abstract onSurfaceDestroyed(Landroid/app/ActivityView;)V .end method
{'content_hash': '0f78cf93d8152e7e7008fe981f505edd', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 76, 'avg_line_length': 23.085714285714285, 'alnum_prop': 0.7821782178217822, 'repo_name': 'BatMan-Rom/ModdedFiles', 'id': '0f364d8301a4c85b16aafa621f95f0809c01cf5c', 'size': '808', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'framework.jar.out/smali/android/app/ActivityView$ActivityViewCallback.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '15069'}, {'name': 'HTML', 'bytes': '139176'}, {'name': 'Smali', 'bytes': '541934400'}]}
package io.jvertx.core.eb; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; /** * @author YYL on 2017/7/19 */ public class App { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); EventBus eb = vertx.eventBus(); eb.consumer("im.msg", message ->{ System.out.println(message.body()); message.reply("ok"); }); // eb.publish("im.msg", "first message !"); // eb.send("im.msg", "second message !", result ->{ // if (result.succeeded()){ // System.out.println(result.result().body()); // } // }); EventBus bus = vertx.eventBus(); bus.send("im.msg", "other bus"); } }
{'content_hash': '7c95aac54c07ebae681db5fc81d58929', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 61, 'avg_line_length': 27.444444444444443, 'alnum_prop': 0.5303643724696356, 'repo_name': 'coxapp/jvertx', 'id': 'be986401c2a1fcf1553ad6f237a2c71bbb42b502', 'size': '741', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/io/jvertx/core/eb/App.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '143'}, {'name': 'Java', 'bytes': '6469'}]}
from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'docopt', 'python-wordpress-xmlrpc', 'requests', # TODO: put package requirements here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='wordpress_importer', version='0.1.0', description="Utility to import data into wordpress from CSV using a template.", long_description=readme + '\n\n' + history, author="James Brink", author_email='[email protected]', url='https://github.com/jamesbrink/wordpress_importer', packages=[ 'wordpress_importer', ], package_dir={'wordpress_importer': 'wordpress_importer'}, include_package_data=True, install_requires=requirements, license="MIT license", zip_safe=False, keywords='wordpress_importer', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], scripts=['scripts/wordpress_importer', ], test_suite='tests', tests_require=test_requirements )
{'content_hash': 'c19bc121351fab84bfe30315ff3846a2', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 83, 'avg_line_length': 30.074074074074073, 'alnum_prop': 0.6268472906403941, 'repo_name': 'urandomio/wordpress_importer', 'id': '22510665bfb9c8844abde60b6e8820b4e548fd1a', 'size': '1671', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'setup.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '2339'}, {'name': 'Python', 'bytes': '13184'}]}
/** * Autogenerated by Thrift Compiler (0.10.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "credential_store_data_models_constants.h" const credential_store_data_modelsConstants g_credential_store_data_models_constants; credential_store_data_modelsConstants::credential_store_data_modelsConstants() { DEFAULT_ID = "DO_NOT_SET_AT_CLIENTS"; }
{'content_hash': 'f5228bb44ba3e1a40ea9141f31818f6b', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 85, 'avg_line_length': 19.523809523809526, 'alnum_prop': 0.7390243902439024, 'repo_name': 'apache/airavata', 'id': '76cc416b77d50fbf345ee57161092e5a8aa37ca3', 'size': '1212', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'airavata-api/airavata-client-sdks/airavata-cpp-sdk/src/main/resources/lib/airavata/credential_store_data_models_constants.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2959'}, {'name': 'Blade', 'bytes': '640580'}, {'name': 'C', 'bytes': '29278'}, {'name': 'C++', 'bytes': '8274651'}, {'name': 'CSS', 'bytes': '34425'}, {'name': 'Dockerfile', 'bytes': '7386'}, {'name': 'HTML', 'bytes': '91922'}, {'name': 'Java', 'bytes': '36030164'}, {'name': 'JavaScript', 'bytes': '404261'}, {'name': 'Jinja', 'bytes': '234378'}, {'name': 'PHP', 'bytes': '1176284'}, {'name': 'Python', 'bytes': '633278'}, {'name': 'Shell', 'bytes': '153797'}, {'name': 'Thrift', 'bytes': '472909'}, {'name': 'XSLT', 'bytes': '3266'}]}
package org.asynchttpclient.providers.netty4; import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.async.IdleStateHandlerTest; public class NettyIdleStateHandlerTest extends IdleStateHandlerTest { @Override public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) { return NettyProviderUtil.nettyProvider(config); } }
{'content_hash': 'f176ab26a3c2fa4338f871c9ff26e64c', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 77, 'avg_line_length': 32.61538461538461, 'alnum_prop': 0.8301886792452831, 'repo_name': 'afelisatti/async-http-client', 'id': '107cb8b0d52b6b4d0406b076d588e17507284bc3', 'size': '1119', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'providers/netty4/src/test/java/org/asynchttpclient/providers/netty4/NettyIdleStateHandlerTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1925816'}]}
#ifndef HISTOGRAMS_HH #define HISTOGRAMS_HH #include <vector> /** * Save histogram data to file. * * Will save file with four data points for each histogram bin: * bin_start Low edge of bin * bin_end High edge of bin * count Absolute count of values in bin * relcount Relative count (i.e., divided by total number of values) * * Arguments: * v - Vector containing all values * dm - Bin width * filename - Name of file to save to **/ void save_histogram(const std::vector<double> &v, double dm, const char *filename); #endif
{'content_hash': '42aa97ff20d889bcb5d345f9242ee836', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 83, 'avg_line_length': 26.863636363636363, 'alnum_prop': 0.6446700507614214, 'repo_name': 'frxstrem/fys3150', 'id': '714c3718196e155e20f8d0ad34248565f5fd5605', 'size': '591', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'project5/code/histograms.hh', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '139141'}, {'name': 'Makefile', 'bytes': '4891'}, {'name': 'Python', 'bytes': '1544'}, {'name': 'Shell', 'bytes': '970'}, {'name': 'TeX', 'bytes': '133946'}]}
package com.bq.corbel.iam.service; import com.google.common.collect.Sets; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.bq.corbel.iam.auth.AuthorizationRequestContextFactory; import com.bq.corbel.iam.exception.UnauthorizedException; import com.bq.corbel.iam.model.Scope; import com.bq.corbel.iam.model.UserToken; import com.bq.corbel.iam.repository.UserTokenRepository; import com.bq.corbel.lib.token.TokenInfo; import com.bq.corbel.lib.token.reader.TokenReader; import net.oauth.jsontoken.JsonToken; import net.oauth.jsontoken.JsonTokenParser; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.security.SignatureException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class DefaultUpgradeTokenServiceTest { private static final String TEST_ASSERTION = "123.456.789"; private static final String TEST_TOKEN = "the_access_token"; private static final String TEST_CLIENT = "client"; private static final String TEST_DOMAIN = "domain"; private static final String TEST_USER = "user"; private static final String TEST_SCOPES = "SCOPE_1 SCOPE_2"; @Mock private JsonTokenParser jsonTokenParser; @Mock private AuthorizationRequestContextFactory contextFactory; @Mock private ScopeService scopeServiceMock; @Mock private TokenInfo accessToken; @Mock private TokenReader tokenReader; @Mock private UserTokenRepository userTokenRepositoryMock; private UpgradeTokenService upgradeTokenService; @Before public void setUp() { upgradeTokenService = new DefaultUpgradeTokenService(jsonTokenParser, scopeServiceMock, userTokenRepositoryMock); when(accessToken.getClientId()).thenReturn(TEST_CLIENT); when(accessToken.getUserId()).thenReturn(TEST_USER); when(accessToken.getDomainId()).thenReturn(TEST_DOMAIN); when(accessToken.toString()).thenReturn(TEST_TOKEN); when(tokenReader.getInfo()).thenReturn(accessToken); when(tokenReader.getToken()).thenReturn(TEST_TOKEN); } @Test public void upgradeTokenTest() throws SignatureException, UnauthorizedException { JsonToken validJsonToken = mock(JsonToken.class); JsonObject json = new JsonObject(); json.add("scope", new JsonPrimitive(TEST_SCOPES)); when(validJsonToken.getPayloadAsJsonObject()).thenReturn(json); Scope scope1 = mock(Scope.class); Scope scope2 = mock(Scope.class); Set<Scope> scopes = new HashSet<Scope>(Arrays.asList(scope1, scope2)); Set<String> scopesIds = new HashSet<String>(Arrays.asList("SCOPE_1", "SCOPE_2")); UserToken userToken = new UserToken(); userToken.setScopes(new HashSet<>()); when(scopeServiceMock.expandScopes(scopesIds)).thenReturn(scopes); when(scopeServiceMock.fillScopes(scopes, TEST_USER, TEST_CLIENT, TEST_DOMAIN)).thenReturn(scopes); when(userTokenRepositoryMock.findByToken(TEST_TOKEN)).thenReturn(userToken); when(jsonTokenParser.verifyAndDeserialize(TEST_ASSERTION)).thenReturn(validJsonToken); Set<String> scopesToAdd = upgradeTokenService.getScopesFromTokenToUpgrade(TEST_ASSERTION); upgradeTokenService.upgradeToken(TEST_ASSERTION, tokenReader, scopesToAdd); verify(scopeServiceMock).fillScopes(scopes, TEST_USER, TEST_CLIENT, TEST_DOMAIN); verify(scopeServiceMock).addAuthorizationRules(TEST_TOKEN, scopes); } @Test(expected = UnauthorizedException.class) public void upgradeTokenNonexistentScopeTest() throws SignatureException, UnauthorizedException { JsonToken validJsonToken = mock(JsonToken.class); JsonObject json = new JsonObject(); json.add("scope", new JsonPrimitive(TEST_SCOPES)); when(validJsonToken.getPayloadAsJsonObject()).thenReturn(json); doThrow(new IllegalStateException("Nonexistent scope scopeId")).when(scopeServiceMock).addAuthorizationRules(anyString(), anySet()); when(jsonTokenParser.verifyAndDeserialize(TEST_ASSERTION)).thenReturn(validJsonToken); Set<String> scopes = upgradeTokenService.getScopesFromTokenToUpgrade(TEST_ASSERTION); upgradeTokenService.upgradeToken(TEST_ASSERTION, tokenReader, scopes); } @Test public void upgradeTokenEmptyScopeTest() throws SignatureException, UnauthorizedException { Set<Scope> scopes = new HashSet<>(); JsonToken validJsonToken = mock(JsonToken.class); JsonObject json = new JsonObject(); json.add("scope", new JsonPrimitive("")); UserToken userToken = new UserToken(); userToken.setScopes(new HashSet<>()); when(validJsonToken.getPayloadAsJsonObject()).thenReturn(json); when(jsonTokenParser.verifyAndDeserialize(TEST_ASSERTION)).thenReturn(validJsonToken); when(userTokenRepositoryMock.findByToken(TEST_TOKEN)).thenReturn(userToken); when(scopeServiceMock.fillScopes(any(), any(), any(), any())).thenReturn(Sets.newHashSet()); Set<String> scopesToAdd = upgradeTokenService.getScopesFromTokenToUpgrade(TEST_ASSERTION); upgradeTokenService.upgradeToken(TEST_ASSERTION, tokenReader, scopesToAdd); verify(scopeServiceMock).fillScopes(scopes, TEST_USER, TEST_CLIENT, TEST_DOMAIN); verify(scopeServiceMock).addAuthorizationRules(TEST_TOKEN, scopes); } }
{'content_hash': 'c888595eb0785b226b5cda111fef1c3a', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 140, 'avg_line_length': 47.25423728813559, 'alnum_prop': 0.7474892395982783, 'repo_name': 'bq/corbel', 'id': 'aae98468b049d5553993b123996b0f3540cdb054', 'size': '5576', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'iam/src/test/java/com/bq/corbel/iam/service/DefaultUpgradeTokenServiceTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '27620'}, {'name': 'Java', 'bytes': '1627258'}, {'name': 'Shell', 'bytes': '246'}]}
package com.nebhale.buildmonitor.web; import com.nebhale.buildmonitor.ApplicationConfiguration; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; import javax.sql.DataSource; import javax.transaction.Transactional; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = ApplicationConfiguration.class) @Transactional @WebAppConfiguration public abstract class AbstractControllerTest { private volatile JdbcTemplate jdbcTemplate; volatile MockMvc mockMvc; @Autowired final void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Autowired final void setWebApplicationContext(WebApplicationContext webApplicationContext) { this.mockMvc = webAppContextSetup(webApplicationContext).build(); } final int countRowsInTable(String tableName) { return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName); } final String toJson(String... pairs) { StringBuilder sb = new StringBuilder("{ "); Set<String> entries = Arrays.stream(pairs).map(pair -> { String[] parts = StringUtils.split(pair, ":"); return String.format("\"%s\" : \"%s\"", parts[0], parts[1]); }).collect(Collectors.toSet()); sb.append(StringUtils.collectionToDelimitedString(entries, ", ")); return sb.append(" }").toString(); } }
{'content_hash': 'd5e89f4b952b5662936f644e9d6b7acb', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 92, 'avg_line_length': 33.935483870967744, 'alnum_prop': 0.7647338403041825, 'repo_name': 'nebhale/build-monitor', 'id': '544fa13e0369ecae134b30f63261ecd679544145', 'size': '2724', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'src/test/java/com/nebhale/buildmonitor/web/AbstractControllerTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3932'}, {'name': 'Java', 'bytes': '82100'}, {'name': 'JavaScript', 'bytes': '12134'}]}
.. _manual: User Guide ========== .. include:: installation.rst .. include:: basic_usage.rst .. include:: formats.rst .. include:: piped_output.rst .. include:: jupyter_notebooks.rst .. include:: styling.rst .. _attributes: .. include:: attributes.rst .. _node-ports-compass: .. include:: node_ports.rst .. _backslash-escapes: .. include:: escapes.rst .. _quoting-and-html-like-labels: .. include:: quoting.rst .. _subgraphs-clusters: .. include:: subgraphs_and_clusters.rst .. _engines: .. include:: engines.rst .. include:: neato_no_op.rst .. include:: unflatten.rst .. include:: custom_dot.rst .. _using-raw-dot: .. include:: raw_dot.rst .. include:: existing_files.rst .. include:: integration_with_viewers.rst
{'content_hash': 'e211dbc9fbcd237e0ef749d657f3fc4c', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 41, 'avg_line_length': 15.3125, 'alnum_prop': 0.6625850340136055, 'repo_name': 'xflr6/graphviz', 'id': '15952a0ca0d74313780d97b0e9a423f04ca05c50', 'size': '735', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/manual.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '196982'}]}
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.outlook.impl; import com.wilutions.com.*; @SuppressWarnings("all") @CoClass(guid="{C091A9EE-A463-DB41-5DAE-69E7A5F7FCBC}") public class SyncObjectEventsImpl extends Dispatch implements com.wilutions.mslib.outlook.SyncObjectEvents { @DeclDISPID(61441) public void onSyncStart() throws ComException { this._dispatchCall(61441,"SyncStart", DISPATCH_METHOD,null); } @DeclDISPID(61442) public void onProgress(final com.wilutions.mslib.outlook.OlSyncState State, final String Description, final Integer Value, final Integer Max) throws ComException { assert(State != null); assert(Description != null); assert(Value != null); assert(Max != null); this._dispatchCall(61442,"Progress", DISPATCH_METHOD,null,State.value,Description,Value,Max); } @DeclDISPID(61443) public void onOnError(final Integer Code, final String Description) throws ComException { assert(Code != null); assert(Description != null); this._dispatchCall(61443,"OnError", DISPATCH_METHOD,null,Code,Description); } @DeclDISPID(61444) public void onSyncEnd() throws ComException { this._dispatchCall(61444,"SyncEnd", DISPATCH_METHOD,null); } public SyncObjectEventsImpl(String progId) throws ComException { super(progId, "{00063085-0000-0000-C000-000000000046}"); } protected SyncObjectEventsImpl(long ndisp) { super(ndisp); } public String toString() { return "[SyncObjectEventsImpl" + super.toString() + "]"; } }
{'content_hash': '42d6ee11643ff73e5b8271bae9e76fa6', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 185, 'avg_line_length': 44.74285714285714, 'alnum_prop': 0.7171136653895275, 'repo_name': 'wolfgangimig/joa', 'id': 'f3b9228f8b21cec1422d2beeadbaa2b04432c367', 'size': '1566', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'java/joa/src-gen/com/wilutions/mslib/outlook/impl/SyncObjectEventsImpl.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1296'}, {'name': 'CSS', 'bytes': '792'}, {'name': 'HTML', 'bytes': '1337'}, {'name': 'Java', 'bytes': '9952275'}, {'name': 'VBScript', 'bytes': '338'}]}
<?php namespace PHPServices; class Module { public function getConfig() { return include __DIR__ . '/../../config/module.config.php'; } }
{'content_hash': '586c3a24fb04f085378a787e19cda2a3', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 67, 'avg_line_length': 15.9, 'alnum_prop': 0.5911949685534591, 'repo_name': 'insprintorob/phpservices', 'id': 'e0d11a1cfe16369488bf24c42dda66b42122646f', 'size': '159', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/PHPServices/Module.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '12761'}]}
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Runtime.Shared.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
{'content_hash': '131812860828c9a4139332fbc4c7fd5d', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 174, 'avg_line_length': 43.15873015873016, 'alnum_prop': 0.6355277675616036, 'repo_name': 'wessupermare/WCompiler', 'id': '04c7619c307d75729d69a0c653ad3d117fa0109f', 'size': '2721', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Runtime/Shared/My Project/Resources.Designer.vb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Visual Basic', 'bytes': '73129'}]}
import json import re import requests from datetime import datetime, timedelta import os from dateutil import parser from src.sgd.frontend import config BLOG_BASE_URL = 'https://public-api.wordpress.com/rest/v1.1/sites/yeastgenomeblog.wordpress.com/posts' BLOG_PAGE_SIZE = 10 HOMEPAGE_REQUEST_TIMEOUT = 2 URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' # from https://public-api.wordpress.com/rest/v1.1/sites/sgdblogtest.wordpress.com/categories wp_categories = [ { 'name': 'Conferences', 'slug': 'conferences' }, { 'name': 'Data updates', 'slug': 'data-updates' }, { 'name': 'Homologs', 'slug': 'homologs' }, { 'name': 'New Data', 'slug': 'new-data' }, { 'name': 'News and Views', 'slug': 'news-and-views' }, { 'name': 'Newsletter', 'slug': 'newsletter' }, { 'name': 'Research Spotlight', 'slug': 'research-spotlight' }, { 'name': 'Sequence', 'slug': 'sequence' }, { 'name': 'Tutorial', 'slug': 'tutorial' }, { 'name': 'Uncategorized', 'slug': 'uncategorized' }, { 'name': 'Website changes', 'slug': 'website-changes' }, { 'name': 'Yeast and Human Disease', 'slug': 'yeast-and-human-disease' }, { 'name': 'Announcements', 'slug': 'announcements' } ] def get_wp_categories(): return sorted(wp_categories, key=lambda k: k['name']) def get_archive_years(): now = datetime.now() this_year = now.year archive_years = [] for i in range(7): archive_years.append(this_year - i) return archive_years def get_recent_blog_posts(): wp_url = BLOG_BASE_URL + '?number=5' try: response = requests.get(wp_url, timeout=HOMEPAGE_REQUEST_TIMEOUT) blog_posts = json.loads(response.text)['posts'] for post in blog_posts: post = add_simple_date_to_post(post) except Exception as e: blog_posts = [] return blog_posts # fetch "SGD Public Events" google calendar data and format as needed for homepage def get_meetings(): try: calendar_url = config.google_calendar_api_url response = requests.get(calendar_url, timeout=HOMEPAGE_REQUEST_TIMEOUT) meetings = json.loads(response.text)['items'] # only get "all day" events meetings = [d for d in meetings if 'date' in list(d['start'].keys())] for meeting in meetings: if 'description' not in list(meeting.keys()): meeting['description'] = '' # get URL from description and remove URLs from description urls = re.findall(URL_REGEX, meeting['description']) if len(urls) > 0: url = urls[0] else: url = None meeting['url'] = url meeting['description'] = re.sub(URL_REGEX, '', meeting['description']) # format date as a string which is either a single day or range of dates start_date = datetime.strptime(meeting['start']['date'], '%Y-%m-%d') end_date = datetime.strptime(meeting['end']['date'], '%Y-%m-%d') - timedelta(days=1) meeting['start_date'] = start_date days_delta = (end_date - start_date).days if (days_delta >= 1): start_desc = start_date.strftime('%B %d') end_desc = end_date.strftime('%B %d, %Y') date_description = start_desc + ' to ' + end_desc else: date_description = start_date.strftime('%B %d, %Y') meeting['date_description'] = date_description # filter to only show future events now = datetime.now() meetings = [d for d in meetings if d['start_date'] > now] # sort by start date meetings = sorted(meetings, key=lambda d: d['start_date']) except Exception as e: meetings = [] return meetings def add_simple_date_to_post(raw): simple_date = parser.parse(raw['date']).strftime("%B %d, %Y") raw['simple_date'] = simple_date return raw
{'content_hash': 'f95f26cd79ef6d402ebdaedfa0eba573', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 102, 'avg_line_length': 30.52517985611511, 'alnum_prop': 0.5538534056092388, 'repo_name': 'yeastgenome/SGDFrontend', 'id': 'e8def9ecec5b341129be00b4284f9a8b6c2a85ee', 'size': '4243', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/sgd/frontend/yeastgenome/views/cms_helpers.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '41612'}, {'name': 'Dockerfile', 'bytes': '2910'}, {'name': 'Gherkin', 'bytes': '28036'}, {'name': 'HTML', 'bytes': '3745'}, {'name': 'JavaScript', 'bytes': '1008081'}, {'name': 'Jinja', 'bytes': '418101'}, {'name': 'Makefile', 'bytes': '1744'}, {'name': 'Python', 'bytes': '139124'}, {'name': 'Ruby', 'bytes': '4116'}, {'name': 'SCSS', 'bytes': '51067'}]}
use super::camera::*; use super::GameContext; use super::event_manager::*; use glium::glutin::{CursorState, ElementState, Event, MouseButton, VirtualKeyCode}; use std::rc::Rc; pub struct Ghost { cam: Camera, context: Rc<GameContext>, speed: f32, forward: bool, backward: bool, left: bool, right: bool, up: bool, down: bool, mouselock: bool, } // Speed per second const DEFAULT_SPEED: f32 = 12.0; const SHIFT_SPEED: f32 = 60.0; impl Ghost { pub fn new(context: Rc<GameContext>) -> Self { Ghost { cam: Camera::new(context.get_config().resolution.aspect_ratio()), context: context, speed: DEFAULT_SPEED, forward: false, backward: false, left: false, right: false, up: false, down: false, mouselock: false, } } pub fn update(&mut self, delta: f32) { let factored_speed = self.speed * delta; if self.forward { self.cam.move_forward(factored_speed); } if self.backward { self.cam.move_backward(factored_speed); } if self.left { self.cam.move_left(factored_speed); } if self.right { self.cam.move_right(factored_speed); } if self.up { self.cam.move_up(factored_speed); } if self.down { self.cam.move_down(factored_speed); } } pub fn get_camera(&self) -> Camera { self.cam } pub fn set_camera(&mut self, cam: Camera) { self.cam = cam; } } /// **Implements Controls** /// *W => FORWARD /// *A => LEFT /// *S => BACKWARDS /// *D => RIGHT /// *'Space' => UP /// *'LControl' => DOWN (only accepts one keystroke (cannot hold LControl to go /// down)) /// *'C' => DOWN (as a replacement for 'LControl') /// MouseMovement for changing the direction the camera looks impl EventHandler for Ghost { fn handle_event(&mut self, e: &Event) -> EventResponse { match *e { Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::W)) => { self.forward = true; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::W)) => { self.forward = false; EventResponse::Continue } Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::S)) => { self.backward = true; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::S)) => { self.backward = false; EventResponse::Continue } Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::A)) => { self.left = true; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::A)) => { self.left = false; EventResponse::Continue } Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::D)) => { self.right = true; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::D)) => { self.right = false; EventResponse::Continue } Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Space)) => { self.up = true; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::Space)) => { self.up = false; EventResponse::Continue } Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::LControl)) => { self.down = true; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::LControl)) => { self.down = false; EventResponse::Continue } Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::LShift)) => { self.speed = SHIFT_SPEED; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::LShift)) => { self.speed = DEFAULT_SPEED; EventResponse::Continue } Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::G)) => { EventResponse::Continue } Event::MouseInput(ElementState::Pressed, MouseButton::Left) => { if !self.mouselock { self.mouselock = true; if let Some(window) = self.context.get_facade().get_window() { window.set_cursor_state(CursorState::Hide) .expect("failed to set cursor state"); } else { warn!("Failed to obtain window from facade"); } } else if self.mouselock { self.mouselock = false; if let Some(window) = self.context.get_facade().get_window() { window.set_cursor_state(CursorState::Normal) .expect("failed to set cursor state"); } else { warn!("Failed to obtain window from facade"); } } EventResponse::Continue } Event::MouseMoved(x, y) => { if self.mouselock { if let Some(window) = self.context.get_facade().get_window() { // Possibility of mouse being outside of window without it resetting to the // middle? if let Some(middle) = window.get_inner_size_pixels() { let middle_x = (middle.0 as i32) / 2; let middle_y = (middle.1 as i32) / 2; let x_diff = x - middle_x; let y_diff = y - middle_y; self.cam.change_dir(y_diff as f32 / 300.0, -x_diff as f32 / 300.0); window.set_cursor_position(middle_x as i32, middle_y as i32) .expect("setting cursor position failed"); } } } EventResponse::Continue } _ => EventResponse::NotHandled, } } }
{'content_hash': '3480de1e340a5de51f322df900e30095', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 99, 'avg_line_length': 35.910526315789475, 'alnum_prop': 0.49728858273486737, 'repo_name': 'adRichter/plantex', 'id': '01273f3f1c6d4c3904c6118e687cd8d6f0f72e26', 'size': '6823', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/src/ghost.rs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '29595'}, {'name': 'Rust', 'bytes': '285892'}, {'name': 'Shell', 'bytes': '5131'}]}
package joshie.harvest.animals.type; import joshie.harvest.animals.HFAnimals; import joshie.harvest.animals.item.ItemAnimalProduct.Sizeable; import joshie.harvest.animals.item.ItemAnimalSpawner.Spawner; import joshie.harvest.api.animals.AnimalAction; import joshie.harvest.api.animals.AnimalStats; import joshie.harvest.core.helpers.SizeableHelper; import net.minecraft.item.ItemStack; import java.util.List; import static joshie.harvest.api.animals.AnimalFoodType.SEED; public class AnimalChicken extends AnimalAbstract { public AnimalChicken() { super("chicken", 3, 10, SEED); } @Override public ItemStack getIcon() { return HFAnimals.ANIMAL.getStackFromEnum(Spawner.CHICKEN); } @Override public int getRelationshipBonus(AnimalAction action) { switch (action) { case OUTSIDE: return 5; case FEED: return 100; } return super.getRelationshipBonus(action); } @Override public ItemStack getProduct(AnimalStats stats) { return SizeableHelper.getEgg(stats); } @Override public List<ItemStack> getProductsForDisplay(AnimalStats stats) { return SizeableHelper.getSizeablesForDisplay(stats, Sizeable.EGG); } @Override public int getDaysBetweenProduction() { return 1; } @Override public int getGenericTreatCount() { return 5; } @Override public int getTypeTreatCount() { return 26; } }
{'content_hash': 'f6e854f97d851222913793de0dfedbd1', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 74, 'avg_line_length': 25.305084745762713, 'alnum_prop': 0.6972538513060951, 'repo_name': 'PenguinSquad/Harvest-Festival', 'id': '277fd569e34006150094b248aff12b9fdf5e9518', 'size': '1493', 'binary': False, 'copies': '1', 'ref': 'refs/heads/1.10.2-0.6.X', 'path': 'src/main/java/joshie/harvest/animals/type/AnimalChicken.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2809556'}]}
require 'spec_helper' describe Marathon::Util do describe '.validate_choice' do subject { described_class } it 'passes with valid value' do described_class.validate_choice('foo', 'bar', %w[f00 bar], false) end it 'passes with nil value' do described_class.validate_choice('foo', nil, %w[f00], true) end it 'fails with nil value' do expect { described_class.validate_choice('foo', nil, %w[f00], false) }.to raise_error(Marathon::Error::ArgumentError) end it 'fails with invalid value' do expect { described_class.validate_choice('foo', 'bar', %w[f00], false) }.to raise_error(Marathon::Error::ArgumentError) end end describe '.add_choice' do subject { described_class } it 'validates choice first' do expect(described_class).to receive(:validate_choice).with('foo', 'bar', %w[f00 bar], false) described_class.add_choice({}, 'foo', 'bar', %w[f00 bar], false) end it 'adds choice' do opts = {} described_class.add_choice(opts, 'foo', 'bar', %w[f00 bar], false) expect(opts['foo']).to eq('bar') end end describe '.keywordize_hash!' do subject { described_class } it 'keywordizes the hash' do hash = { 'foo' => 'bar', 'f00' => {'w00h00' => 'yeah'}, 'bang' => [{'tricky' => 'one'}], 'env' => {'foo' => 'bar'}, 'null' => nil } expect(subject.keywordize_hash!(hash)).to eq({ :foo => 'bar', :f00 => {:w00h00 => 'yeah'}, :bang => [{:tricky => 'one'}], :env => {'foo' => 'bar'}, :null => nil }) # make sure, it changes the hash w/o creating a new one expect(hash[:foo]).to eq('bar') end end describe '.remove_keys' do subject { described_class } it 'removes keys from hash' do hash = { :foo => 'bar', :deleteme => {'w00h00' => 'yeah'}, :blah => [{:deleteme => :foo}, 1] } expect(subject.remove_keys(hash, [:deleteme])).to eq({ :foo => 'bar', :blah => [{}, 1] }) # make sure, it does not changes the original hash expect(hash.size).to eq(3) end end end
{'content_hash': '01f3807ccc9b3516efc9af95874cb857', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 97, 'avg_line_length': 26.04597701149425, 'alnum_prop': 0.5335392762577229, 'repo_name': 'yp-engineering/marathon-api', 'id': '472321938a50689d4a2ad4128401993ad703aaee', 'size': '2266', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/marathon/util_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '99503'}]}
package saltchannel.dev; public interface ServerSessionFactory { public ByteChannelServerSession createSession(); }
{'content_hash': '7fd8760b76c6adb91d1a7be8bde0bf94', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 52, 'avg_line_length': 24.2, 'alnum_prop': 0.8181818181818182, 'repo_name': 'assaabloy-ppi/salt-channel', 'id': '2776feae5250539c7480cd302930ab363c2bb9e0', 'size': '121', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/saltchannel/dev/ServerSessionFactory.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2311'}, {'name': 'Java', 'bytes': '600439'}]}
#include <CtrlLib/CtrlLib.h> using namespace Upp; #include <LogCtrl/LogCtrl.h> #define LAYOUTFILE <LogCtrlTest/LogCtrlTest.lay> #include <CtrlCore/lay.h> class LogCtrlTest : public WithLogCtrlTestLayout<TopWindow> { public: typedef LogCtrlTest CLASSNAME; LogCtrlTest(); void Clear() { log.Clear(); } void Save() { log.Save(); } LogCtrl log; }; #endif
{'content_hash': '395bbe885d804f6dfa4699086d7c9e6a', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 61, 'avg_line_length': 15.76, 'alnum_prop': 0.6700507614213198, 'repo_name': 'dreamsxin/ultimatepp', 'id': 'a34845f15b3173d02a9ecac9ac028f969d8a10b7', 'size': '466', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bazaar/LogCtrlTest/LogCtrlTest.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '8477'}, {'name': 'C', 'bytes': '47921993'}, {'name': 'C++', 'bytes': '28354499'}, {'name': 'CSS', 'bytes': '659'}, {'name': 'JavaScript', 'bytes': '7006'}, {'name': 'Objective-C', 'bytes': '178854'}, {'name': 'Perl', 'bytes': '65041'}, {'name': 'Python', 'bytes': '38142'}, {'name': 'Shell', 'bytes': '91097'}, {'name': 'Smalltalk', 'bytes': '101'}, {'name': 'Turing', 'bytes': '661569'}]}
<?php class ControllerSaleCustomer extends Controller { private $error = array(); public function index() { $this->language->load('sale/customer'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('sale/customer'); $this->getList(); } public function insert() { $this->language->load('sale/customer'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('sale/customer'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) { $this->model_sale_customer->addCustomer($this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_ip'])) { $url .= '&filter_ip=' . $this->request->get['filter_ip']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL')); } $this->getForm(); } public function update() { $this->language->load('sale/customer'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('sale/customer'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) { $this->model_sale_customer->editCustomer($this->request->get['customer_id'], $this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_ip'])) { $url .= '&filter_ip=' . $this->request->get['filter_ip']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL')); } $this->getForm(); } public function delete() { $this->language->load('sale/customer'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('sale/customer'); if (isset($this->request->post['selected']) && $this->validateDelete()) { foreach ($this->request->post['selected'] as $customer_id) { $this->model_sale_customer->deleteCustomer($customer_id); } $this->session->data['success'] = $this->language->get('text_success'); $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_ip'])) { $url .= '&filter_ip=' . $this->request->get['filter_ip']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL')); } $this->getList(); } public function approve() { $this->language->load('sale/customer'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('sale/customer'); if (!$this->user->hasPermission('modify', 'sale/customer')) { $this->error['warning'] = $this->language->get('error_permission'); } elseif (isset($this->request->post['selected'])) { $approved = 0; foreach ($this->request->post['selected'] as $customer_id) { $customer_info = $this->model_sale_customer->getCustomer($customer_id); if ($customer_info && !$customer_info['approved']) { $this->model_sale_customer->approve($customer_id); $approved++; } } $this->session->data['success'] = sprintf($this->language->get('text_approved'), $approved); $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_ip'])) { $url .= '&filter_ip=' . $this->request->get['filter_ip']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL')); } $this->getList(); } protected function getList() { if (isset($this->request->get['filter_name'])) { $filter_name = $this->request->get['filter_name']; } else { $filter_name = null; } if (isset($this->request->get['filter_email'])) { $filter_email = $this->request->get['filter_email']; } else { $filter_email = null; } if (isset($this->request->get['filter_customer_group_id'])) { $filter_customer_group_id = $this->request->get['filter_customer_group_id']; } else { $filter_customer_group_id = null; } if (isset($this->request->get['filter_status'])) { $filter_status = $this->request->get['filter_status']; } else { $filter_status = null; } if (isset($this->request->get['filter_approved'])) { $filter_approved = $this->request->get['filter_approved']; } else { $filter_approved = null; } if (isset($this->request->get['filter_ip'])) { $filter_ip = $this->request->get['filter_ip']; } else { $filter_ip = null; } if (isset($this->request->get['filter_date_added'])) { $filter_date_added = $this->request->get['filter_date_added']; } else { $filter_date_added = null; } if (isset($this->request->get['sort'])) { $sort = $this->request->get['sort']; } else { $sort = 'name'; } if (isset($this->request->get['order'])) { $order = $this->request->get['order']; } else { $order = 'ASC'; } if (isset($this->request->get['page'])) { $page = $this->request->get['page']; } else { $page = 1; } $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_ip'])) { $url .= '&filter_ip=' . $this->request->get['filter_ip']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'), 'separator' => ' :: ' ); $this->data['approve'] = $this->url->link('sale/customer/approve', 'token=' . $this->session->data['token'] . $url, 'SSL'); $this->data['insert'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL'); $this->data['delete'] = $this->url->link('sale/customer/delete', 'token=' . $this->session->data['token'] . $url, 'SSL'); $this->data['customers'] = array(); $data = array( 'filter_name' => $filter_name, 'filter_email' => $filter_email, 'filter_customer_group_id' => $filter_customer_group_id, 'filter_status' => $filter_status, 'filter_approved' => $filter_approved, 'filter_date_added' => $filter_date_added, 'filter_ip' => $filter_ip, 'sort' => $sort, 'order' => $order, 'start' => ($page - 1) * $this->config->get('config_admin_limit'), 'limit' => $this->config->get('config_admin_limit') ); $customer_total = $this->model_sale_customer->getTotalCustomers($data); $results = $this->model_sale_customer->getCustomers($data); foreach ($results as $result) { $action = array(); $action[] = array( 'text' => $this->language->get('text_edit'), 'href' => $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL') ); $this->data['customers'][] = array( 'customer_id' => $result['customer_id'], 'name' => $result['name'], 'email' => $result['email'], 'customer_group' => $result['customer_group'], 'status' => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')), 'approved' => ($result['approved'] ? $this->language->get('text_yes') : $this->language->get('text_no')), 'ip' => $result['ip'], 'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])), 'selected' => isset($this->request->post['selected']) && in_array($result['customer_id'], $this->request->post['selected']), 'action' => $action ); } $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_enabled'] = $this->language->get('text_enabled'); $this->data['text_disabled'] = $this->language->get('text_disabled'); $this->data['text_yes'] = $this->language->get('text_yes'); $this->data['text_no'] = $this->language->get('text_no'); $this->data['text_select'] = $this->language->get('text_select'); $this->data['text_default'] = $this->language->get('text_default'); $this->data['text_no_results'] = $this->language->get('text_no_results'); $this->data['column_name'] = $this->language->get('column_name'); $this->data['column_email'] = $this->language->get('column_email'); $this->data['column_customer_group'] = $this->language->get('column_customer_group'); $this->data['column_status'] = $this->language->get('column_status'); $this->data['column_approved'] = $this->language->get('column_approved'); $this->data['column_ip'] = $this->language->get('column_ip'); $this->data['column_date_added'] = $this->language->get('column_date_added'); $this->data['column_login'] = $this->language->get('column_login'); $this->data['column_action'] = $this->language->get('column_action'); $this->data['button_approve'] = $this->language->get('button_approve'); $this->data['button_insert'] = $this->language->get('button_insert'); $this->data['button_delete'] = $this->language->get('button_delete'); $this->data['button_filter'] = $this->language->get('button_filter'); $this->data['token'] = $this->session->data['token']; if (isset($this->error['warning'])) { $this->data['error_warning'] = $this->error['warning']; } else { $this->data['error_warning'] = ''; } if (isset($this->session->data['success'])) { $this->data['success'] = $this->session->data['success']; unset($this->session->data['success']); } else { $this->data['success'] = ''; } $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_ip'])) { $url .= '&filter_ip=' . $this->request->get['filter_ip']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if ($order == 'ASC') { $url .= '&order=DESC'; } else { $url .= '&order=ASC'; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $this->data['sort_name'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL'); $this->data['sort_email'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.email' . $url, 'SSL'); $this->data['sort_customer_group'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=customer_group' . $url, 'SSL'); $this->data['sort_status'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.status' . $url, 'SSL'); $this->data['sort_approved'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.approved' . $url, 'SSL'); $this->data['sort_ip'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.ip' . $url, 'SSL'); $this->data['sort_date_added'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.date_added' . $url, 'SSL'); $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_ip'])) { $url .= '&filter_ip=' . $this->request->get['filter_ip']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } $pagination = new Pagination(); $pagination->total = $customer_total; $pagination->page = $page; $pagination->limit = $this->config->get('config_admin_limit'); $pagination->text = $this->language->get('text_pagination'); $pagination->url = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL'); $this->data['pagination'] = $pagination->render(); $this->data['filter_name'] = $filter_name; $this->data['filter_email'] = $filter_email; $this->data['filter_customer_group_id'] = $filter_customer_group_id; $this->data['filter_status'] = $filter_status; $this->data['filter_approved'] = $filter_approved; $this->data['filter_ip'] = $filter_ip; $this->data['filter_date_added'] = $filter_date_added; $this->load->model('sale/customer_group'); $this->data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups(); $this->load->model('setting/store'); $this->data['stores'] = $this->model_setting_store->getStores(); $this->data['sort'] = $sort; $this->data['order'] = $order; $this->template = 'sale/customer_list.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render()); } protected function getForm() { $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_enabled'] = $this->language->get('text_enabled'); $this->data['text_disabled'] = $this->language->get('text_disabled'); $this->data['text_select'] = $this->language->get('text_select'); $this->data['text_none'] = $this->language->get('text_none'); $this->data['text_wait'] = $this->language->get('text_wait'); $this->data['text_no_results'] = $this->language->get('text_no_results'); $this->data['text_add_ban_ip'] = $this->language->get('text_add_ban_ip'); $this->data['text_remove_ban_ip'] = $this->language->get('text_remove_ban_ip'); $this->data['column_ip'] = $this->language->get('column_ip'); $this->data['column_total'] = $this->language->get('column_total'); $this->data['column_date_added'] = $this->language->get('column_date_added'); $this->data['column_action'] = $this->language->get('column_action'); $this->data['entry_firstname'] = $this->language->get('entry_firstname'); $this->data['entry_lastname'] = $this->language->get('entry_lastname'); $this->data['entry_email'] = $this->language->get('entry_email'); $this->data['entry_telephone'] = $this->language->get('entry_telephone'); $this->data['entry_fax'] = $this->language->get('entry_fax'); $this->data['entry_password'] = $this->language->get('entry_password'); $this->data['entry_confirm'] = $this->language->get('entry_confirm'); $this->data['entry_newsletter'] = $this->language->get('entry_newsletter'); $this->data['entry_customer_group'] = $this->language->get('entry_customer_group'); $this->data['entry_status'] = $this->language->get('entry_status'); $this->data['entry_company'] = $this->language->get('entry_company'); $this->data['entry_company_id'] = $this->language->get('entry_company_id'); $this->data['entry_tax_id'] = $this->language->get('entry_tax_id'); $this->data['entry_address_1'] = $this->language->get('entry_address_1'); $this->data['entry_address_2'] = $this->language->get('entry_address_2'); $this->data['entry_city'] = $this->language->get('entry_city'); $this->data['entry_postcode'] = $this->language->get('entry_postcode'); $this->data['entry_zone'] = $this->language->get('entry_zone'); $this->data['entry_country'] = $this->language->get('entry_country'); $this->data['entry_default'] = $this->language->get('entry_default'); $this->data['entry_comment'] = $this->language->get('entry_comment'); $this->data['entry_description'] = $this->language->get('entry_description'); $this->data['entry_amount'] = $this->language->get('entry_amount'); $this->data['entry_points'] = $this->language->get('entry_points'); $this->data['button_save'] = $this->language->get('button_save'); $this->data['button_cancel'] = $this->language->get('button_cancel'); $this->data['button_add_address'] = $this->language->get('button_add_address'); $this->data['button_add_history'] = $this->language->get('button_add_history'); $this->data['button_add_transaction'] = $this->language->get('button_add_transaction'); $this->data['button_add_reward'] = $this->language->get('button_add_reward'); $this->data['button_remove'] = $this->language->get('button_remove'); $this->data['tab_general'] = $this->language->get('tab_general'); $this->data['tab_address'] = $this->language->get('tab_address'); $this->data['tab_history'] = $this->language->get('tab_history'); $this->data['tab_transaction'] = $this->language->get('tab_transaction'); $this->data['tab_reward'] = $this->language->get('tab_reward'); $this->data['tab_ip'] = $this->language->get('tab_ip'); $this->data['token'] = $this->session->data['token']; if (isset($this->request->get['customer_id'])) { $this->data['customer_id'] = $this->request->get['customer_id']; } else { $this->data['customer_id'] = 0; } if (isset($this->error['warning'])) { $this->data['error_warning'] = $this->error['warning']; } else { $this->data['error_warning'] = ''; } if (isset($this->error['firstname'])) { $this->data['error_firstname'] = $this->error['firstname']; } else { $this->data['error_firstname'] = ''; } if (isset($this->error['lastname'])) { $this->data['error_lastname'] = $this->error['lastname']; } else { $this->data['error_lastname'] = ''; } if (isset($this->error['email'])) { $this->data['error_email'] = $this->error['email']; } else { $this->data['error_email'] = ''; } if (isset($this->error['telephone'])) { $this->data['error_telephone'] = $this->error['telephone']; } else { $this->data['error_telephone'] = ''; } if (isset($this->error['password'])) { $this->data['error_password'] = $this->error['password']; } else { $this->data['error_password'] = ''; } if (isset($this->error['confirm'])) { $this->data['error_confirm'] = $this->error['confirm']; } else { $this->data['error_confirm'] = ''; } if (isset($this->error['address_firstname'])) { $this->data['error_address_firstname'] = $this->error['address_firstname']; } else { $this->data['error_address_firstname'] = ''; } if (isset($this->error['address_lastname'])) { $this->data['error_address_lastname'] = $this->error['address_lastname']; } else { $this->data['error_address_lastname'] = ''; } if (isset($this->error['address_tax_id'])) { $this->data['error_address_tax_id'] = $this->error['address_tax_id']; } else { $this->data['error_address_tax_id'] = ''; } if (isset($this->error['address_address_1'])) { $this->data['error_address_address_1'] = $this->error['address_address_1']; } else { $this->data['error_address_address_1'] = ''; } if (isset($this->error['address_city'])) { $this->data['error_address_city'] = $this->error['address_city']; } else { $this->data['error_address_city'] = ''; } if (isset($this->error['address_postcode'])) { $this->data['error_address_postcode'] = $this->error['address_postcode']; } else { $this->data['error_address_postcode'] = ''; } if (isset($this->error['address_country'])) { $this->data['error_address_country'] = $this->error['address_country']; } else { $this->data['error_address_country'] = ''; } if (isset($this->error['address_zone'])) { $this->data['error_address_zone'] = $this->error['address_zone']; } else { $this->data['error_address_zone'] = ''; } $url = ''; if (isset($this->request->get['filter_name'])) { $url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_email'])) { $url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['filter_customer_group_id'])) { $url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id']; } if (isset($this->request->get['filter_status'])) { $url .= '&filter_status=' . $this->request->get['filter_status']; } if (isset($this->request->get['filter_approved'])) { $url .= '&filter_approved=' . $this->request->get['filter_approved']; } if (isset($this->request->get['filter_date_added'])) { $url .= '&filter_date_added=' . $this->request->get['filter_date_added']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'), 'separator' => ' :: ' ); if (!isset($this->request->get['customer_id'])) { $this->data['action'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL'); } else { $this->data['action'] = $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . $url, 'SSL'); } $this->data['cancel'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'); if (isset($this->request->get['customer_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) { $customer_info = $this->model_sale_customer->getCustomer($this->request->get['customer_id']); } if (isset($this->request->post['firstname'])) { $this->data['firstname'] = $this->request->post['firstname']; } elseif (!empty($customer_info)) { $this->data['firstname'] = $customer_info['firstname']; } else { $this->data['firstname'] = ''; } if (isset($this->request->post['lastname'])) { $this->data['lastname'] = $this->request->post['lastname']; } elseif (!empty($customer_info)) { $this->data['lastname'] = $customer_info['lastname']; } else { $this->data['lastname'] = ''; } if (isset($this->request->post['email'])) { $this->data['email'] = $this->request->post['email']; } elseif (!empty($customer_info)) { $this->data['email'] = $customer_info['email']; } else { $this->data['email'] = ''; } if (isset($this->request->post['telephone'])) { $this->data['telephone'] = $this->request->post['telephone']; } elseif (!empty($customer_info)) { $this->data['telephone'] = $customer_info['telephone']; } else { $this->data['telephone'] = ''; } if (isset($this->request->post['fax'])) { $this->data['fax'] = $this->request->post['fax']; } elseif (!empty($customer_info)) { $this->data['fax'] = $customer_info['fax']; } else { $this->data['fax'] = ''; } if (isset($this->request->post['newsletter'])) { $this->data['newsletter'] = $this->request->post['newsletter']; } elseif (!empty($customer_info)) { $this->data['newsletter'] = $customer_info['newsletter']; } else { $this->data['newsletter'] = ''; } $this->load->model('sale/customer_group'); $this->data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups(); if (isset($this->request->post['customer_group_id'])) { $this->data['customer_group_id'] = $this->request->post['customer_group_id']; } elseif (!empty($customer_info)) { $this->data['customer_group_id'] = $customer_info['customer_group_id']; } else { $this->data['customer_group_id'] = $this->config->get('config_customer_group_id'); } if (isset($this->request->post['status'])) { $this->data['status'] = $this->request->post['status']; } elseif (!empty($customer_info)) { $this->data['status'] = $customer_info['status']; } else { $this->data['status'] = 1; } if (isset($this->request->post['password'])) { $this->data['password'] = $this->request->post['password']; } else { $this->data['password'] = ''; } if (isset($this->request->post['confirm'])) { $this->data['confirm'] = $this->request->post['confirm']; } else { $this->data['confirm'] = ''; } $this->load->model('localisation/country'); $this->data['countries'] = $this->model_localisation_country->getCountries(); if (isset($this->request->post['address'])) { $this->data['addresses'] = $this->request->post['address']; } elseif (isset($this->request->get['customer_id'])) { $this->data['addresses'] = $this->model_sale_customer->getAddresses($this->request->get['customer_id']); } else { $this->data['addresses'] = array(); } if (isset($this->request->post['address_id'])) { $this->data['address_id'] = $this->request->post['address_id']; } elseif (!empty($customer_info)) { $this->data['address_id'] = $customer_info['address_id']; } else { $this->data['address_id'] = ''; } $this->data['ips'] = array(); if (!empty($customer_info)) { $results = $this->model_sale_customer->getIpsByCustomerId($this->request->get['customer_id']); foreach ($results as $result) { $ban_ip_total = $this->model_sale_customer->getTotalBanIpsByIp($result['ip']); $this->data['ips'][] = array( 'ip' => $result['ip'], 'total' => $this->model_sale_customer->getTotalCustomersByIp($result['ip']), 'date_added' => date('d/m/y', strtotime($result['date_added'])), 'filter_ip' => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&filter_ip=' . $result['ip'], 'SSL'), 'ban_ip' => $ban_ip_total ); } } $this->template = 'sale/customer_form.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render()); } protected function validateForm() { if (!$this->user->hasPermission('modify', 'sale/customer')) { $this->error['warning'] = $this->language->get('error_permission'); } if ((utf8_strlen($this->request->post['firstname']) < 1) || (utf8_strlen($this->request->post['firstname']) > 32)) { $this->error['firstname'] = $this->language->get('error_firstname'); } if ((utf8_strlen($this->request->post['lastname']) < 1) || (utf8_strlen($this->request->post['lastname']) > 32)) { $this->error['lastname'] = $this->language->get('error_lastname'); } if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) { $this->error['email'] = $this->language->get('error_email'); } $customer_info = $this->model_sale_customer->getCustomerByEmail($this->request->post['email']); if (!isset($this->request->get['customer_id'])) { if ($customer_info) { $this->error['warning'] = $this->language->get('error_exists'); } } else { if ($customer_info && ($this->request->get['customer_id'] != $customer_info['customer_id'])) { $this->error['warning'] = $this->language->get('error_exists'); } } if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) { $this->error['telephone'] = $this->language->get('error_telephone'); } if ($this->request->post['password'] || (!isset($this->request->get['customer_id']))) { if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) { $this->error['password'] = $this->language->get('error_password'); } if ($this->request->post['password'] != $this->request->post['confirm']) { $this->error['confirm'] = $this->language->get('error_confirm'); } } if (isset($this->request->post['address'])) { foreach ($this->request->post['address'] as $key => $value) { if ((utf8_strlen($value['firstname']) < 1) || (utf8_strlen($value['firstname']) > 32)) { $this->error['address_firstname'][$key] = $this->language->get('error_firstname'); } if ((utf8_strlen($value['lastname']) < 1) || (utf8_strlen($value['lastname']) > 32)) { $this->error['address_lastname'][$key] = $this->language->get('error_lastname'); } if ((utf8_strlen($value['address_1']) < 3) || (utf8_strlen($value['address_1']) > 128)) { $this->error['address_address_1'][$key] = $this->language->get('error_address_1'); } if ((utf8_strlen($value['city']) < 2) || (utf8_strlen($value['city']) > 128)) { $this->error['address_city'][$key] = $this->language->get('error_city'); } $this->load->model('localisation/country'); $country_info = $this->model_localisation_country->getCountry($value['country_id']); if ($country_info) { if ($country_info['postcode_required'] && (utf8_strlen($value['postcode']) < 2) || (utf8_strlen($value['postcode']) > 10)) { $this->error['address_postcode'][$key] = $this->language->get('error_postcode'); } // VAT Validation $this->load->helper('vat'); if ($this->config->get('config_vat') && $value['tax_id'] && (vat_validation($country_info['iso_code_2'], $value['tax_id']) == 'invalid')) { $this->error['address_tax_id'][$key] = $this->language->get('error_vat'); } } if ($value['country_id'] == '') { $this->error['address_country'][$key] = $this->language->get('error_country'); } if (!isset($value['zone_id']) || $value['zone_id'] == '') { $this->error['address_zone'][$key] = $this->language->get('error_zone'); } } } if ($this->error && !isset($this->error['warning'])) { $this->error['warning'] = $this->language->get('error_warning'); } if (!$this->error) { return true; } else { return false; } } protected function validateDelete() { if (!$this->user->hasPermission('modify', 'sale/customer')) { $this->error['warning'] = $this->language->get('error_permission'); } if (!$this->error) { return true; } else { return false; } } public function login() { $json = array(); if (isset($this->request->get['customer_id'])) { $customer_id = $this->request->get['customer_id']; } else { $customer_id = 0; } $this->load->model('sale/customer'); $customer_info = $this->model_sale_customer->getCustomer($customer_id); if ($customer_info) { $token = md5(mt_rand()); $this->model_sale_customer->editToken($customer_id, $token); if (isset($this->request->get['store_id'])) { $store_id = $this->request->get['store_id']; } else { $store_id = 0; } $this->load->model('setting/store'); $store_info = $this->model_setting_store->getStore($store_id); if ($store_info) { $this->redirect($store_info['url'] . 'index.php?route=account/login&token=' . $token); } else { $this->redirect(HTTP_CATALOG . 'index.php?route=account/login&token=' . $token); } } else { $this->language->load('error/not_found'); $this->document->setTitle($this->language->get('heading_title')); $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_not_found'] = $this->language->get('text_not_found'); $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => ' :: ' ); $this->template = 'error/not_found.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render()); } } public function history() { $this->language->load('sale/customer'); $this->load->model('sale/customer'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) { $this->model_sale_customer->addHistory($this->request->get['customer_id'], $this->request->post['comment']); $this->data['success'] = $this->language->get('text_success'); } else { $this->data['success'] = ''; } if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) { $this->data['error_warning'] = $this->language->get('error_permission'); } else { $this->data['error_warning'] = ''; } $this->data['text_no_results'] = $this->language->get('text_no_results'); $this->data['column_date_added'] = $this->language->get('column_date_added'); $this->data['column_comment'] = $this->language->get('column_comment'); if (isset($this->request->get['page'])) { $page = $this->request->get['page']; } else { $page = 1; } $this->data['histories'] = array(); $results = $this->model_sale_customer->getHistories($this->request->get['customer_id'], ($page - 1) * 10, 10); foreach ($results as $result) { $this->data['histories'][] = array( 'comment' => $result['comment'], 'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])) ); } $transaction_total = $this->model_sale_customer->getTotalHistories($this->request->get['customer_id']); $pagination = new Pagination(); $pagination->total = $transaction_total; $pagination->page = $page; $pagination->limit = 10; $pagination->text = $this->language->get('text_pagination'); $pagination->url = $this->url->link('sale/customer/history', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL'); $this->data['pagination'] = $pagination->render(); $this->template = 'sale/customer_history.tpl'; $this->response->setOutput($this->render()); } public function transaction() { $this->language->load('sale/customer'); $this->load->model('sale/customer'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) { $this->model_sale_customer->addTransaction($this->request->get['customer_id'], $this->request->post['description'], $this->request->post['amount']); $this->data['success'] = $this->language->get('text_success'); } else { $this->data['success'] = ''; } if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) { $this->data['error_warning'] = $this->language->get('error_permission'); } else { $this->data['error_warning'] = ''; } $this->data['text_no_results'] = $this->language->get('text_no_results'); $this->data['text_balance'] = $this->language->get('text_balance'); $this->data['column_date_added'] = $this->language->get('column_date_added'); $this->data['column_description'] = $this->language->get('column_description'); $this->data['column_amount'] = $this->language->get('column_amount'); if (isset($this->request->get['page'])) { $page = $this->request->get['page']; } else { $page = 1; } $this->data['transactions'] = array(); $results = $this->model_sale_customer->getTransactions($this->request->get['customer_id'], ($page - 1) * 10, 10); foreach ($results as $result) { $this->data['transactions'][] = array( 'amount' => $this->currency->format($result['amount'], $this->config->get('config_currency')), 'description' => $result['description'], 'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])) ); } $this->data['balance'] = $this->currency->format($this->model_sale_customer->getTransactionTotal($this->request->get['customer_id']), $this->config->get('config_currency')); $transaction_total = $this->model_sale_customer->getTotalTransactions($this->request->get['customer_id']); $pagination = new Pagination(); $pagination->total = $transaction_total; $pagination->page = $page; $pagination->limit = 10; $pagination->text = $this->language->get('text_pagination'); $pagination->url = $this->url->link('sale/customer/transaction', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL'); $this->data['pagination'] = $pagination->render(); $this->template = 'sale/customer_transaction.tpl'; $this->response->setOutput($this->render()); } public function reward() { $this->language->load('sale/customer'); $this->load->model('sale/customer'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) { $this->model_sale_customer->addReward($this->request->get['customer_id'], $this->request->post['description'], $this->request->post['points']); $this->data['success'] = $this->language->get('text_success'); } else { $this->data['success'] = ''; } if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) { $this->data['error_warning'] = $this->language->get('error_permission'); } else { $this->data['error_warning'] = ''; } $this->data['text_no_results'] = $this->language->get('text_no_results'); $this->data['text_balance'] = $this->language->get('text_balance'); $this->data['column_date_added'] = $this->language->get('column_date_added'); $this->data['column_description'] = $this->language->get('column_description'); $this->data['column_points'] = $this->language->get('column_points'); if (isset($this->request->get['page'])) { $page = $this->request->get['page']; } else { $page = 1; } $this->data['rewards'] = array(); $results = $this->model_sale_customer->getRewards($this->request->get['customer_id'], ($page - 1) * 10, 10); foreach ($results as $result) { $this->data['rewards'][] = array( 'points' => $result['points'], 'description' => $result['description'], 'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])) ); } $this->data['balance'] = $this->model_sale_customer->getRewardTotal($this->request->get['customer_id']); $reward_total = $this->model_sale_customer->getTotalRewards($this->request->get['customer_id']); $pagination = new Pagination(); $pagination->total = $reward_total; $pagination->page = $page; $pagination->limit = 10; $pagination->text = $this->language->get('text_pagination'); $pagination->url = $this->url->link('sale/customer/reward', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL'); $this->data['pagination'] = $pagination->render(); $this->template = 'sale/customer_reward.tpl'; $this->response->setOutput($this->render()); } public function addBanIP() { $this->language->load('sale/customer'); $json = array(); if (isset($this->request->post['ip'])) { if (!$this->user->hasPermission('modify', 'sale/customer')) { $json['error'] = $this->language->get('error_permission'); } else { $this->load->model('sale/customer'); $this->model_sale_customer->addBanIP($this->request->post['ip']); $json['success'] = $this->language->get('text_success'); } } $this->response->setOutput(json_encode($json)); } public function removeBanIP() { $this->language->load('sale/customer'); $json = array(); if (isset($this->request->post['ip'])) { if (!$this->user->hasPermission('modify', 'sale/customer')) { $json['error'] = $this->language->get('error_permission'); } else { $this->load->model('sale/customer'); $this->model_sale_customer->removeBanIP($this->request->post['ip']); $json['success'] = $this->language->get('text_success'); } } $this->response->setOutput(json_encode($json)); } public function autocomplete() { $json = array(); if (isset($this->request->get['filter_name'])) { $this->load->model('sale/customer'); $data = array( 'filter_name' => $this->request->get['filter_name'], 'start' => 0, 'limit' => 20 ); $results = $this->model_sale_customer->getCustomers($data); foreach ($results as $result) { $json[] = array( 'customer_id' => $result['customer_id'], 'customer_group_id' => $result['customer_group_id'], 'name' => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')), 'customer_group' => $result['customer_group'], 'firstname' => $result['firstname'], 'lastname' => $result['lastname'], 'email' => $result['email'], 'telephone' => $result['telephone'], 'fax' => $result['fax'], 'address' => $this->model_sale_customer->getAddresses($result['customer_id']) ); } } $sort_order = array(); foreach ($json as $key => $value) { $sort_order[$key] = $value['name']; } array_multisort($sort_order, SORT_ASC, $json); $this->response->setOutput(json_encode($json)); } public function country() { $json = array(); $this->load->model('localisation/country'); $country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']); if ($country_info) { $this->load->model('localisation/zone'); $json = array( 'country_id' => $country_info['country_id'], 'name' => $country_info['name'], 'iso_code_2' => $country_info['iso_code_2'], 'iso_code_3' => $country_info['iso_code_3'], 'address_format' => $country_info['address_format'], 'postcode_required' => $country_info['postcode_required'], 'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']), 'status' => $country_info['status'] ); } $this->response->setOutput(json_encode($json)); } public function address() { $json = array(); if (!empty($this->request->get['address_id'])) { $this->load->model('sale/customer'); $json = $this->model_sale_customer->getAddress($this->request->get['address_id']); } $this->response->setOutput(json_encode($json)); } } ?>
{'content_hash': 'c0d1a2940ce4b625a78a2f43335fdb99', 'timestamp': '', 'source': 'github', 'line_count': 1418, 'max_line_length': 188, 'avg_line_length': 35.38787023977433, 'alnum_prop': 0.5918294141092069, 'repo_name': 'chasemg/babybling', 'id': '8b297703188ea129b7c3ba7a8a09364175f45c20', 'size': '50180', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'admin/controller/sale/customer.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1197722'}, {'name': 'JavaScript', 'bytes': '1419011'}, {'name': 'PHP', 'bytes': '6105609'}]}
A Gem to fetch details of Indian city, district, state based on Indian postal codes from yaml data. ## Installation Add this line to your application's Gemfile: ```ruby gem 'indian_postal_codes' ``` And then execute: $ bundle Or install it yourself as: $ gem install indian_postal_codes ## Usage ```ruby IndianPostalCodes.details('562110') # => {:city=>"Devanhalli", :district=>"Channapatna", :state=>"Karnataka"} ``` <!-- ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). --> ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/DevilalDheer/indian_postal_codes. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
{'content_hash': '34f88e3f254eb147d574d6202cac7c28', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 328, 'avg_line_length': 34.829268292682926, 'alnum_prop': 0.7443977591036415, 'repo_name': 'DevilalDheer/indian_postal_codes', 'id': '001227a8ebfc5b706b30d20c7600c566b576cb2f', 'size': '1449', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '2743'}, {'name': 'Shell', 'bytes': '115'}]}
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'My Blog!' }); }); router.get('/pay', function(req, res) { res.render('pay', {title: "Where's my money, honey?"}); }); module.exports = router;
{'content_hash': 'ecc81ee99bd8b1e965e9ff5259ccf9fe', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 57, 'avg_line_length': 23.307692307692307, 'alnum_prop': 0.6105610561056105, 'repo_name': 'portlandcodeschool-jsi/my-first-blog', 'id': '51d3ebc9ecf902a7b90617ba98f80dfabf4de8b7', 'size': '303', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'routes/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '110'}, {'name': 'HTML', 'bytes': '2877'}, {'name': 'JavaScript', 'bytes': '2006'}]}
/***************************************************************************//** * \file cy_sysint.h * \version 1.60 * * \brief * Provides an API declaration of the SysInt driver * ******************************************************************************** * \copyright * Copyright 2016-2020 Cypress Semiconductor Corporation * SPDX-License-Identifier: Apache-2.0 * * 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. *******************************************************************************/ /** * \addtogroup group_sysint * \{ * The SysInt driver provides an API to configure the device peripheral interrupts. * It provides a lightweight interface to complement * the <a href="https://www.keil.com/pack/doc/CMSIS/Core/html/group__NVIC__gr.html">CMSIS core NVIC API</a>. * The provided functions are applicable for all cores in a device and they can * be used to configure and connect device peripheral interrupts to one or more * cores. * * The functions and other declarations used in this driver are in cy_sysint.h. * You can include cy_pdl.h to get access to all functions * and declarations in the PDL. * * \section group_sysint_vector_table Vector Table * \subsection group_sysint_CM0_CM4 CM0+/CM4 * The vector table defines the entry addresses of the processor exceptions and * the device specific interrupts. It is located at the start address of the flash * and is copied by the startup code to RAM. The symbol code __Vectors is the * address of the vector table in the startup code and the register SCB->VTOR * holds the start address of the vector table. See \ref group_system_config_device_vector_table * section for the implementation details. * The default interrupt handler functions are defined as weak functions to a dummy handler * in the startup file. The naming convention is \<interrupt_name\>_IRQHandler. * * Defining these in the user application allows the linker to place them in * the vector table in flash/ROM. For example: * \code * void ioss_interrupts_gpio_0_IRQHandler(void) * { * ... * } * \endcode * And can be used like this: * \snippet sysint/snippet/main.c snippet_Cy_SysInt_flashVT * Using this method avoids the need for a RAM vector table. However in this scenario, * interrupt handler re-location at run-time is not possible, unless the vector table is * relocated to RAM. * * \subsection group_sysint_CM33 CM33 * CM33 with Security extension supports two vector tables, one for secure world and another * for non-secure world. Secure interrupt vector table is placed in the secure ROM/FLASH, where as * non-secure interrupt vector table is placed in the non-secure ROM/FLASH. In both scenarios, * vector tables are copied by the startup code to secure and non-secure RAM respectively. * The symbol code __s_vector_table is the address of the secure vector table and * __ns_vector_table is for the non-secure world in the startup code. The register SCB->VTOR * holds the start address of the vector table. See \ref group_system_config_device_vector_table * section for the implementation details. * * CM33 without Security extension will support only non-secure interrupts. * * The default interrupt handler functions are defined to a dummy handler in the startup file. * The naming convention is \<interrupt_name\>_IRQHandler. * * * \section group_sysint_driver_usage Driver Usage * * \subsection group_sysint_initialization Initialization * * Interrupt numbers are defined in a device-specific header file, such as * cy8c68237bz_ble.h, and are consistent with interrupt handlers defined in the * vector table. * * To configure an interrupt, call Cy_SysInt_Init(). Populate * the configuration structure (cy_stc_sysint_t) and pass it as a parameter * along with the ISR address. This initializes the interrupt and * instructs the CPU to jump to the specified ISR vector upon a valid trigger. * For CM0+ core, the configuration structure (cy_stc_sysint_t) * must specify the device interrupt source (cm0pSrc) that feeds into the CM0+ NVIC * mux (intrSrc). * * For CM4/CM33 core, system interrupt source 'n' is connected to the * corresponding IRQn. Deep-sleep capable interrupts are allocated to Deep Sleep * capable IRQn channels. * * For CM0+ core, deep Sleep wakeup-capability is determined by the CPUSS_CM0_DPSLP_IRQ_NR * parameter, where the first N number of muxes (NvicMux0 ... NvicMuxN-1) have the * capability to trigger Deep Sleep interrupts. A Deep Sleep capable interrupt source * must be connected to one of these muxes to be able to trigger in Deep Sleep. * Refer to the IRQn_Type definition in the device header. * * 1. For CPUSS_ver1 the CM0+ core supports up to 32 interrupt channels (IRQn 0-31). To allow all device * interrupts to be routable to the NVIC of this core, there is a 240:1 multiplexer * at each of the 32 NVIC channels. * * 2. For CPUSS_ver2 the CM0+ core supports up to 8 hardware interrupt channels (IRQn 0-7) and software-only * interrupt channels (IRQn 8-15). The device has up to 1023 interrupts that can be connected to any of the * hardware interrupt channels. In this structure, multiple interrupt sources can be connected * simultaneously to one NVIC channel. The application must then query the interrupt source on the * channel and service the active interrupt(s). The priority of these interrupts is determined by the * interrupt number as defined in the cy_en_intr_t enum, where the lower number denotes higher priority * over the higher number. * * \subsection group_sysint_enable Enable * * After initializing an interrupt, use the CMSIS Core * <a href="https://www.keil.com/pack/doc/CMSIS/Core/html/group__NVIC__gr.html#ga530ad9fda2ed1c8b70e439ecfe80591f">NVIC_EnableIRQ()</a> function * to enable it. Given an initialization structure named config, * the function should be called as follows: * \code * NVIC_EnableIRQ(config.intrSrc) * \endcode * * \subsection group_sysint_service Writing an interrupt service routine * * Servicing interrupts in the Peripheral Drivers should follow a prescribed * recipe to ensure all interrupts are serviced and duplicate interrupts are not * received. Any peripheral-specific register that must be written to clear the * source of the interrupt should be written as soon as possible in the interrupt * service routine. However, note that due to buffering on the output bus to the * peripherals, the write clearing of the interrupt may be delayed. After performing * the normal interrupt service that should respond to the interrupting * condition, the interrupt register that was initially written to clear the * register should be read before returning from the interrupt service routine. * This read ensures that the initial write has been flushed out to the hardware. * Note, no additional processing should be performed based on the result of this * read, as this read is intended only to ensure the write operation is flushed. * * This final read may indicate a pending interrupt. What this means is that in * the interval between when the write actually happened at the peripheral and * when the read actually happened at the peripheral, an interrupting condition * occurred. This is ok and a return from the interrupt is still the correct * action. As soon as conditions warrant, meaning interrupts are enabled and * there are no higher priority interrupts pending, the interrupt will be * triggered again to service the additional condition. * * \section group_sysint_section_configuration_considerations Configuration Considerations * * Certain CM0+ <a href="https://www.keil.com/pack/doc/CMSIS/Core/html/group__NVIC__gr.html#ga7e1129cd8a196f4284d41db3e82ad5c8">NVIC IRQn</a> * channels are reserved for system use: * <table class="doxtable"> * <tr><th>NVIC channel (\ref IRQn_Type)</th><th>Interrupt source (\ref cy_en_intr_t)</th><th>Purpose</th></tr> * <tr><td>#0 (NvicMux0_IRQn)</td><td>IPC Interrupt #0 (cpuss_interrupts_ipc_0_IRQn)</td><td>System Calls to ROM</td></tr> * <tr><td>#1 (NvicMux1_IRQn)</td><td>IPC Interrupt #3 (cpuss_interrupts_ipc_3_IRQn)</td><td>System IPC pipe in the default startup</td></tr> * </table> * * \note For CPUSS_ver2, each NVIC channel can be shared between multiple interrupt sources. * However it is not recommended to share the application NVIC channel with the reserved channels. * * \section group_sysint_more_information More Information * * Refer to the technical reference manual (TRM) and the device datasheet. * * \section group_sysint_changelog Changelog * <table class="doxtable"> * <tr><th>Version</th><th>Changes</th><th>Reason for Change</th></tr> * <tr> * <td>1.60</td> * <td>Support for CM33.</td> * <td>New devices support.</td> * </tr> * <tr> * <td>1.50</td> * <td>Fixed MISRA 2012 violations.</td> * <td>MISRA 2012 compliance.</td> * </tr> * <tr> * <td>1.40</td> * <td>Updated the CY_SYSINT_IS_PC_0 macro to access the protected register * for the secure CYB06xx7 devices via \ref group_pra driver. * </td> * <td>Added PSoC 64 devices support.</td> * </tr> * <tr> * <td>1.30.1</td> * <td>Minor documentation updates.</td> * <td>Documentation enhancement.</td> * </tr> * <tr> * <td>1.30</td> * <td>The Cy_SysInt_SetNmiSource is updated with Protection Context check for CM0+.</td> * <td>User experience enhancement.</td> * </tr> * <tr> * <td>1.20.1</td> * <td>The Vector Table section is extended with a code snippet.</td> * <td>Documentation enhancement.</td> * </tr> * <tr> * <td rowspan="3">1.20</td> * <td>Flattened the organization of the driver source code into the single source directory and the single include directory.</td> * <td>Driver library directory-structure simplification.</td> * </tr> * <tr> * <td>Added CPUSS_ver2 support to the following API functions: * - \ref Cy_SysInt_SetInterruptSource * - \ref Cy_SysInt_SetNmiSource * - \ref Cy_SysInt_GetNmiSource * * Added new API functions: * - \ref Cy_SysInt_DisconnectInterruptSource * - \ref Cy_SysInt_GetNvicConnection * - \ref Cy_SysInt_GetInterruptActive * * Deprecated following functions: * - Cy_SysInt_SetIntSource * - Cy_SysInt_GetIntSource * - Cy_SysInt_SetIntSourceNMI * - Cy_SysInt_GetIntSourceNMI * </td> * <td>New devices support.</td> * </tr> * <tr> * <td>Added register access layer. Use register access macros instead * of direct register access using dereferenced pointers.</td> * <td>Makes register access device-independent, so that the PDL does * not need to be recompiled for each supported part number.</td> * </tr> * <tr> * <td>1.10</td> * <td>Cy_SysInt_GetState() function is redefined to call NVIC_GetEnableIRQ()</td> * <td></td> * </tr> * <tr> * <td>1.0</td> * <td>Initial version</td> * <td></td> * </tr> * </table> * * \defgroup group_sysint_macros Macros * \defgroup group_sysint_globals Global variables * \defgroup group_sysint_functions Functions * \defgroup group_sysint_data_structures Data Structures * \defgroup group_sysint_enums Enumerated Types */ #if !defined (CY_SYSINT_H) #define CY_SYSINT_H #include "cy_device.h" #if defined (CY_IP_M33SYSCPUSS) || defined (CY_IP_M4CPUSS) #include <stddef.h> #include "cy_syslib.h" #if defined(CY_DEVICE_SECURE) && defined(CY_DEVICE_PSOC6ABLE2) #include "cy_pra.h" #endif /* defined(CY_DEVICE_SECURE) && defined(CY_DEVICE_PSOC6ABLE2) */ #include "cy_device_headers.h" #if defined(__cplusplus) extern "C" { #endif /*************************************** * Global Variable ***************************************/ /** * \addtogroup group_sysint_globals * \{ */ #if defined (CY_IP_M4CPUSS) CY_MISRA_DEVIATE_BLOCK_START('MISRA C-2012 Rule 8.6', 2, \ 'Coverity does not check the .S assembly files, the definition is a part of startup_psoc6_04_cm4.s file.'); extern const cy_israddress __Vectors[]; /**< Vector table in flash */ extern cy_israddress __ramVectors[]; /**< Relocated vector table in SRAM */ CY_MISRA_BLOCK_END('MISRA C-2012 Rule 8.6'); #endif /* CY_IP_M4CPUSS */ #if defined (CY_SECURE_WORLD) || defined (CY_DOXYGEN) extern uint32_t *__s_vector_table_rw; /**< Secure vector table in flash/ROM */ #endif #if !defined (CY_SECURE_WORLD) || defined (CY_DOXYGEN) CY_MISRA_DEVIATE_BLOCK_START('MISRA C-2012 Rule 8.6', 2, \ 'Coverity does not check the .S assembly files, the definition is a part of startup_psoc6_04_cm4.s file.'); extern uint32_t *__ns_vector_table_rw; /**< Non-secure vector table in flash/ROM */ CY_MISRA_BLOCK_END('MISRA C-2012 Rule 8.6'); #endif /** \} group_sysint_globals */ /*************************************** * Global Interrupt ***************************************/ /** * \addtogroup group_sysint_macros * \{ */ /** Driver major version */ #define CY_SYSINT_DRV_VERSION_MAJOR 2 /** Driver minor version */ #define CY_SYSINT_DRV_VERSION_MINOR 0 /** SysInt driver ID */ #define CY_SYSINT_ID CY_PDL_DRV_ID (0x15U) /** \} group_sysint_macros */ /*************************************** * Enumeration ***************************************/ /** * \addtogroup group_sysint_enums * \{ */ /** * SysInt Driver error codes */ typedef enum { CY_SYSINT_SUCCESS = 0x0UL, /**< Returned successful */ CY_SYSINT_BAD_PARAM = CY_SYSINT_ID | CY_PDL_STATUS_ERROR | 0x1UL, /**< Bad parameter was passed */ } cy_en_sysint_status_t; /** NMI connection input */ typedef enum { CY_SYSINT_NMI1 = 1UL, /**< NMI source input 1 */ CY_SYSINT_NMI2 = 2UL, /**< NMI source input 2 */ CY_SYSINT_NMI3 = 3UL, /**< NMI source input 3 */ CY_SYSINT_NMI4 = 4UL, /**< NMI source input 4 */ } cy_en_sysint_nmi_t; /** \} group_sysint_enums */ /*************************************** * Configuration Structure ***************************************/ /** * \addtogroup group_sysint_data_structures * \{ */ /** * Initialization configuration structure for a single interrupt channel */ typedef struct { IRQn_Type intrSrc; /**< Interrupt source */ #if (CY_CPU_CORTEX_M0P) cy_en_intr_t cm0pSrc; /**< Maps cm0pSrc device interrupt to intrSrc */ #endif /* CY_CPU_CORTEX_M0P */ uint32_t intrPriority; /**< Interrupt priority number (Refer to __NVIC_PRIO_BITS) */ } cy_stc_sysint_t; /** \} group_sysint_data_structures */ /*************************************** * Constants ***************************************/ /** \cond INTERNAL */ #define CY_INT_IRQ_BASE (16U) /**< Start location of interrupts in the vector table */ #define CY_SYSINT_STATE_MASK (1UL) /**< Mask for interrupt state */ #define CY_SYSINT_STIR_MASK (0xFFUL) /**< Mask for software trigger interrupt register */ #define CY_SYSINT_DISABLE (0UL) /**< Disable interrupt */ #define CY_SYSINT_ENABLE (1UL) /**< Enable interrupt */ #define CY_SYSINT_INT_STATUS_MSK (0x7UL) #if defined (CY_IP_M4CPUSS) /*(CY_IP_M4CPUSS_VERSION == 1u) */ #define CY_SYSINT_CM0P_MUX_MASK (0xFFUL) /**< CM0+ NVIC multiplexer mask */ #define CY_SYSINT_CM0P_MUX_SHIFT (2U) /**< CM0+ NVIC multiplexer shift */ #define CY_SYSINT_CM0P_MUX_SCALE (3U) /**< CM0+ NVIC multiplexer scaling value */ #define CY_SYSINT_CM0P_MUX0 (0U) /**< CM0+ NVIC multiplexer register 0 */ #define CY_SYSINT_CM0P_MUX1 (1U) /**< CM0+ NVIC multiplexer register 1 */ #define CY_SYSINT_CM0P_MUX2 (2U) /**< CM0+ NVIC multiplexer register 2 */ #define CY_SYSINT_CM0P_MUX3 (3U) /**< CM0+ NVIC multiplexer register 3 */ #define CY_SYSINT_CM0P_MUX4 (4U) /**< CM0+ NVIC multiplexer register 4 */ #define CY_SYSINT_CM0P_MUX5 (5U) /**< CM0+ NVIC multiplexer register 5 */ #define CY_SYSINT_CM0P_MUX6 (6U) /**< CM0+ NVIC multiplexer register 6 */ #define CY_SYSINT_CM0P_MUX7 (7U) /**< CM0+ NVIC multiplexer register 7 */ #define CY_SYSINT_MUX_REG_MSK (0x7UL) #endif /* CY_IP_M4CPUSS */ /* Parameter validation macros */ #define CY_SYSINT_IS_PRIORITY_VALID(intrPriority) ((uint32_t)(1UL << __NVIC_PRIO_BITS) > (intrPriority)) #define CY_SYSINT_IS_VECTOR_VALID(userIsr) (NULL != (userIsr)) #define CY_SYSINT_IS_NMI_NUM_VALID(nmiNum) (((nmiNum) == CY_SYSINT_NMI1) || \ ((nmiNum) == CY_SYSINT_NMI2) || \ ((nmiNum) == CY_SYSINT_NMI3) || \ ((nmiNum) == CY_SYSINT_NMI4)) #if defined (CY_IP_M4CPUSS) #if CY_CPU_CORTEX_M4 && defined(CY_DEVICE_SECURE) && defined(CY_DEVICE_PSOC6ABLE2) #define CY_SYSINT_IS_PC_0 (0UL == _FLD2VAL(PROT_MPU_MS_CTL_PC, \ CY_PRA_REG32_GET(CY_PRA_INDX_PROT_MPU_MS_CTL))) #else #define CY_SYSINT_IS_PC_0 (0UL == _FLD2VAL(PROT_MPU_MS_CTL_PC, PROT_MPU_MS_CTL(0U))) #endif #endif /* CY_IP_M4CPUSS */ /** \endcond */ /*************************************** * Function Prototypes ***************************************/ /** * \addtogroup group_sysint_functions * \{ */ /******************************************************************************* * Function Name: Cy_SysInt_Init ****************************************************************************//** * * \brief Initializes the referenced interrupt by setting the priority and the * interrupt vector. * In case of CM33 with Security Extension eanbled, if this function is called * from secure world then, the parameters are used to configure secure interrupt. * If it is called form non-secure world then the parameters are used to configure * non-secure interrupt. In case of CM33 without Security Extension, this function * alwasys configures the non-secure interrupt. * * Use the CMSIS core function NVIC_EnableIRQ(config.intrSrc) to enable the interrupt. * * \param config * Interrupt configuration structure * * \param userIsr * Address of the ISR * * \return * Initialization status * * \note CM0+/CM4 <br/> * The interrupt vector will be relocated only if the vector table was * moved to __ramVectors in SRAM. Otherwise it is ignored. * * \note CM33<br/> * The interrupt vector will be relocated only if the vector table was * moved to __s_vector_table_rw and __ns_vector_table_rw for secure and * non-secure world respectively. * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_Init * *******************************************************************************/ cy_en_sysint_status_t Cy_SysInt_Init(const cy_stc_sysint_t* config, cy_israddress userIsr); /******************************************************************************* * Function Name: Cy_SysInt_SetVector ****************************************************************************//** * * \brief Changes the ISR vector for the interrupt. * * CM0+/CM4:<br/> * This function relies on the assumption that the vector table is * relocated to __ramVectors[RAM_VECTORS_SIZE] in SRAM. Otherwise it will * return the address of the default ISR location in the flash vector table. * * CM33:<br/> * When called from secure world. this function relies on the assumption that the * vector table is relocated to __s_vector_table_rw[] in secure SRAM. Otherwise it will * return the address of the default ISR location in the secure flash/ROM vector table. * * When called from non-secure world. this function relies on the assumption that * the vector table is relocated to __ns_vector_table_rw[] in non-secure SRAM. * Otherwise it will return the address of the default ISR location in the non-secure * flash/ROM vector table. * * Use the CMSIS core function NVIC_EnableIRQ(config.intrSrc) to enable the interrupt. * \param IRQn * Interrupt source * * \param userIsr * Address of the ISR to set in the interrupt vector table * * \return * Previous address of the ISR in the interrupt vector table * * \note For CM0+, this function sets the interrupt vector for the interrupt * channel on the NVIC. * * \note In case of CM33 with Security Extension eanbled, if this function is called * from secure world then, it sets the interrupt vector for the secure world. * If it is called form non-secure world then it sets the interrupt vector for the * non-secure world. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SetVector * *******************************************************************************/ cy_israddress Cy_SysInt_SetVector(IRQn_Type IRQn, cy_israddress userIsr); /******************************************************************************* * Function Name: Cy_SysInt_GetVector ****************************************************************************//** * * \brief Gets the address of the current ISR vector for the interrupt. * * CM0+/CM4:<br/> * This function relies on the assumption that the vector table is * relocated to __ramVectors[RAM_VECTORS_SIZE] in SRAM. Otherwise it will * return the address of the default ISR location in the flash vector table. * * CM33:<br/> * When called from the secure world, this function relies on the assumption that * the vector table is relocated to __ns_vector_table_rw[] in non-secure SRAM. * Otherwise it will return the address of the default ISR location in the * flash/ROM vector table. * * \param IRQn * Interrupt source * * \return * Address of the ISR in the interrupt vector table * * \note CM0+:<br/> This function returns the interrupt vector for the interrupt * channel on the NVIC. * * \note CM33:<br/>In case of CM33 with Security Extension eanbled, if this function is called * from secure world then, it returns the interrupt vector for the secure world. * If it is called form non-secure world then it returns the interrupt vector * for the non-secure world. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SetVector * *******************************************************************************/ cy_israddress Cy_SysInt_GetVector(IRQn_Type IRQn); #if (CY_CPU_CORTEX_M0P) || defined (CY_DOXYGEN) /******************************************************************************* * Function Name: Cy_SysInt_SetInterruptSource ****************************************************************************//** * * \brief Configures the interrupt selection for the specified NVIC channel. * * To disconnect the interrupt source from the NVIC channel * use the \ref Cy_SysInt_DisconnectInterruptSource. * * \param IRQn * NVIC channel number connected to the CPU core. * * \param devIntrSrc * Device interrupt to be routed to the NVIC channel. * * \note This function is available for CM0+ core only. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SetInterruptSource * *******************************************************************************/ void Cy_SysInt_SetInterruptSource(IRQn_Type IRQn, cy_en_intr_t devIntrSrc); /******************************************************************************* * Function Name: Cy_SysInt_GetInterruptSource ****************************************************************************//** * * \brief Gets the interrupt source of the NVIC channel. * * \param IRQn * NVIC channel number connected to the CPU core * * \return * Device interrupt connected to the NVIC channel. A returned value of * "disconnected_IRQn" indicates that the interrupt source is disconnected. * * \note This function is available for CM0+ core only. * * \note This function supports only devices using CPUSS_ver1. For all * other devices, use the Cy_SysInt_GetNvicConnection() function. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SetInterruptSource * *******************************************************************************/ cy_en_intr_t Cy_SysInt_GetInterruptSource(IRQn_Type IRQn); /******************************************************************************* * Function Name: Cy_SysInt_GetNvicConnection ****************************************************************************//** * * \brief Gets the NVIC channel to which the interrupt source is connected. * * \param devIntrSrc * Device interrupt that is potentially connected to the NVIC channel. * * \return * NVIC channel number connected to the CPU core. A returned value of * "unconnected_IRQn" indicates that the interrupt source is disabled. * * \note This function is available for CM0+ core only. * * \note This function supports only devices using CPUSS_ver2 or higher. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SetInterruptSource * *******************************************************************************/ IRQn_Type Cy_SysInt_GetNvicConnection(cy_en_intr_t devIntrSrc); /******************************************************************************* * Function Name: Cy_SysInt_GetInterruptActive ****************************************************************************//** * * \brief Gets the highest priority active interrupt for the selected NVIC channel. * * The priority of the interrupt in a given channel is determined by the index * value of the interrupt in the cy_en_intr_t enum. The lower the index, the * higher the priority. E.g. Consider a case where an interrupt source with value * 29 and an interrupt source with value 46 both source the same NVIC channel. If * both are active (triggered) at the same time, calling Cy_SysInt_GetInterruptActive() * will return 29 as the active interrupt. * * \param IRQn * NVIC channel number connected to the CPU core * * \return * Device interrupt connected to the NVIC channel. A returned value of * "disconnected_IRQn" indicates that there are no active (pending) interrupts * on this NVIC channel. * * \note This function is available for CM0+ core only. * * \note This function supports only devices using CPUSS_ver2 or higher. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_GetInterruptActive * *******************************************************************************/ cy_en_intr_t Cy_SysInt_GetInterruptActive(IRQn_Type IRQn); /******************************************************************************* * Function Name: Cy_SysInt_DisconnectInterruptSource ****************************************************************************//** * * \brief Disconnect the interrupt source from the specified NVIC channel. * * \param IRQn * NVIC channel number connected to the CPU core. * This parameter is ignored for devices using CPUSS_ver2. * * \param devIntrSrc * Device interrupt routed to the NVIC channel. * This parameter is ignored for devices using CPUSS_ver1. * * \note This function is available for CM0+ core only. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_DisconnectInterruptSource * *******************************************************************************/ void Cy_SysInt_DisconnectInterruptSource(IRQn_Type IRQn, cy_en_intr_t devIntrSrc); #endif /*************************************** * Functions ***************************************/ /******************************************************************************* * Function Name: Cy_SysInt_SetNmiSource ****************************************************************************//** * * \brief Sets the interrupt source of the CPU core NMI. * * The interrupt source must be a positive number. Setting the value to * "unconnected_IRQn" or "disconnected_IRQn" disconnects the interrupt source * from the NMI. Depending on the device, the number of interrupt sources that * can provide the NMI trigger signal to the core can vary. * * \param nmiNum * NMI source number. * CPUSS_ver2 allows up to 4 sources to trigger the core NMI. * CPUSS_ver1 allows only one source to trigger the core NMI and * the specified NMI number is ignored. * * \param intrSrc * Interrupt source. This parameter can either be of type cy_en_intr_t or IRQn_Type * for CM0+ and CM4/CM33 respectively. * * \note CM0+ may call this function only at PC=0, CM4 may set its NMI handler at any PC. * \note The CM0+ NMI is used for performing system calls that execute out of ROM. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SetNmiSource * *******************************************************************************/ CY_MISRA_FP_BLOCK_START('MISRA C-2012 Rule 8.6', 2, 'Only one prototype will be pciked for compilation'); CY_MISRA_FP_BLOCK_START('MISRA C-2012 Rule 8.5', 2, 'Only one prototype will be pciked for compilation'); CY_MISRA_FP_BLOCK_START('MISRA C-2012 Rule 8.3', 2, 'Only one prototype will be pciked for compilation'); #if (!CY_CPU_CORTEX_M0P) || defined (CY_DOXYGEN) void Cy_SysInt_SetNmiSource(cy_en_sysint_nmi_t nmiNum, IRQn_Type intrSrc); #else void Cy_SysInt_SetNmiSource(cy_en_sysint_nmi_t nmiNum, cy_en_intr_t devIntrSrc); #endif /******************************************************************************* * Function Name: Cy_SysInt_GetIntSourceNMI ****************************************************************************//** * * \brief Gets the interrupt source of the CPU core NMI for the given NMI source * number. * * \param nmiNum * NMI source number. * CPUSS_ver2 allows up to 4 sources to trigger the core NMI (i.e. #1, 2, 3, 4). * CPUSS_ver1 allows only 1 source to trigger the core NMI (i.e #1). * * \return * Interrupt Source. This parameter can either be of type cy_en_intr_t or IRQn_Type * for CM0+ and CM4/CM33 respectively. * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SetNmiSource * *******************************************************************************/ #if (!CY_CPU_CORTEX_M0P) || defined (CY_DOXYGEN) IRQn_Type Cy_SysInt_GetNmiSource(cy_en_sysint_nmi_t nmiNum); #else cy_en_intr_t Cy_SysInt_GetNmiSource(cy_en_sysint_nmi_t nmiNum); #endif CY_MISRA_BLOCK_END('MISRA C-2012 Rule 8.3'); CY_MISRA_BLOCK_END('MISRA C-2012 Rule 8.5'); CY_MISRA_BLOCK_END('MISRA C-2012 Rule 8.6'); /******************************************************************************* * Function Name: Cy_SysInt_SoftwareTrig ****************************************************************************//** * * \brief Triggers an interrupt using software (Not applicable for CM0+). * * \param IRQn * Interrupt source * * \funcusage * \snippet sysint/snippet/main.c snippet_Cy_SysInt_SoftwareTrig * * \note Only privileged software can enable unprivileged access to the * Software Trigger Interrupt Register (STIR). * *******************************************************************************/ void Cy_SysInt_SoftwareTrig(IRQn_Type IRQn); /** \} group_sysint_functions */ /** \cond INTERNAL */ /*************************************** * Deprecated functions ***************************************/ /******************************************************************************* * Function Name: Cy_SysInt_GetState ****************************************************************************//** * * This function is deprecated. It invokes the NVIC_GetEnableIRQ() function. * *******************************************************************************/ #define Cy_SysInt_GetState NVIC_GetEnableIRQ /******************************************************************************* * Function Name: Cy_SysInt_SetIntSource ****************************************************************************//** * * This function is deprecated. It invokes the Cy_SysInt_SetInterruptSource() function. * *******************************************************************************/ #define Cy_SysInt_SetIntSource(intrSrc, devIntrSrc) Cy_SysInt_SetInterruptSource(intrSrc, devIntrSrc) /******************************************************************************* * Function Name: Cy_SysInt_GetIntSource ****************************************************************************//** * * This function is deprecated. It invokes the Cy_SysInt_GetInterruptSource() function. * *******************************************************************************/ #define Cy_SysInt_GetIntSource(intrSrc) Cy_SysInt_GetInterruptSource(intrSrc) /******************************************************************************* * Function Name: Cy_SysInt_SetIntSourceNMI ****************************************************************************//** * * This function is deprecated. It invokes the Cy_SysInt_SetNmiSource() function. * *******************************************************************************/ #define Cy_SysInt_SetIntSourceNMI(srcParam) Cy_SysInt_SetNmiSource(CY_SYSINT_NMI1, srcParam) /******************************************************************************* * Function Name: Cy_SysInt_GetIntSourceNMI ****************************************************************************//** * * This function is deprecated. It invokes the Cy_SysInt_GetNmiSource() function. * *******************************************************************************/ #define Cy_SysInt_GetIntSourceNMI() Cy_SysInt_GetNmiSource(CY_SYSINT_NMI1) /** \endcond */ #if defined(__cplusplus) } #endif #endif /* CY_IP_M33SYSCPUSS */ #endif /* CY_SYSINT_H */ /** \} group_sysint */ /* [] END OF FILE */
{'content_hash': 'a70775fbdb072d2cb77a18a4144de1c5', 'timestamp': '', 'source': 'github', 'line_count': 843, 'max_line_length': 143, 'avg_line_length': 40.194543297746144, 'alnum_prop': 0.6135344115216621, 'repo_name': 'mbedmicro/mbed', 'id': '53de4ccfb800bbdd8e9a5f1b1eb5d46c31fad336', 'size': '33884', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'targets/TARGET_Cypress/TARGET_PSOC6/mtb-pdl-cat1/drivers/include/cy_sysint.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '5511149'}, {'name': 'C', 'bytes': '152405192'}, {'name': 'C++', 'bytes': '7777242'}, {'name': 'CMake', 'bytes': '27635'}, {'name': 'HTML', 'bytes': '1531100'}, {'name': 'Makefile', 'bytes': '131050'}, {'name': 'Objective-C', 'bytes': '169382'}, {'name': 'Python', 'bytes': '7913'}, {'name': 'Shell', 'bytes': '24790'}, {'name': 'XSLT', 'bytes': '11192'}]}
export interface IModel { name: string; body: IField[]; description?: string; } export interface IField { field: IInfo; input?: IInfo; } export interface IInfo { name: string; type: string; }
{'content_hash': '73591dc7e8eaf1fa55ce2a1b578bf836', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 25, 'avg_line_length': 14.8, 'alnum_prop': 0.6261261261261262, 'repo_name': 'itaied246/daas', 'id': '56aba480741755be30883383d8ad7ad263a080c1', 'size': '222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/models/interfaces/index.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'TypeScript', 'bytes': '26378'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (version 1.7.0_40) on Thu Jan 02 16:44:32 CST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>类 org.apache.giraph.io.formats.TextVertexInputFormat.TextVertexReaderFromEachLine的使用 (Apache Giraph Core 1.0.0 API)</title> <meta name="date" content="2014-01-02"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="类 org.apache.giraph.io.formats.TextVertexInputFormat.TextVertexReaderFromEachLine的使用 (Apache Giraph Core 1.0.0 API)"; } //--> </script> <noscript> <div>您的浏览器已禁用 JavaScript。</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="跳过导航链接"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../../../overview-summary.html">概览</a></li> <li><a href="../package-summary.html">程序包</a></li> <li><a href="../../../../../../org/apache/giraph/io/formats/TextVertexInputFormat.TextVertexReaderFromEachLine.html" title="org.apache.giraph.io.formats中的类">类</a></li> <li class="navBarCell1Rev">使用</li> <li><a href="../package-tree.html">树</a></li> <li><a href="../../../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../../../index-all.html">索引</a></li> <li><a href="../../../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>上一个</li> <li>下一个</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/giraph/io/formats/class-use/TextVertexInputFormat.TextVertexReaderFromEachLine.html" target="_top">框架</a></li> <li><a href="TextVertexInputFormat.TextVertexReaderFromEachLine.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="类 org.apache.giraph.io.formats.TextVertexInputFormat.TextVertexReaderFromEachLine 的使用" class="title">类 org.apache.giraph.io.formats.TextVertexInputFormat.TextVertexReaderFromEachLine<br>的使用</h2> </div> <div class="classUseContainer">没有org.apache.giraph.io.formats.TextVertexInputFormat.TextVertexReaderFromEachLine的用法</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="跳过导航链接"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../../../../../../overview-summary.html">概览</a></li> <li><a href="../package-summary.html">程序包</a></li> <li><a href="../../../../../../org/apache/giraph/io/formats/TextVertexInputFormat.TextVertexReaderFromEachLine.html" title="org.apache.giraph.io.formats中的类">类</a></li> <li class="navBarCell1Rev">使用</li> <li><a href="../package-tree.html">树</a></li> <li><a href="../../../../../../deprecated-list.html">已过时</a></li> <li><a href="../../../../../../index-all.html">索引</a></li> <li><a href="../../../../../../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>上一个</li> <li>下一个</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/giraph/io/formats/class-use/TextVertexInputFormat.TextVertexReaderFromEachLine.html" target="_top">框架</a></li> <li><a href="TextVertexInputFormat.TextVertexReaderFromEachLine.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2011-2014 <a href="http://www.apache.org">The Apache Software Foundation</a>. All Rights Reserved.</small></p> </body> </html>
{'content_hash': 'c7509145beda3b20f4d5109476462052', 'timestamp': '', 'source': 'github', 'line_count': 117, 'max_line_length': 205, 'avg_line_length': 40.23931623931624, 'alnum_prop': 0.633177570093458, 'repo_name': 'zfighter/giraph-research', 'id': 'c771f6b7a0f8d36737b2542861615c338d4b1449', 'size': '4932', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'giraph-core/target/munged/apidocs/org/apache/giraph/io/formats/class-use/TextVertexInputFormat.TextVertexReaderFromEachLine.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '78939'}, {'name': 'Java', 'bytes': '7580660'}, {'name': 'Shell', 'bytes': '35741'}]}
package org.apache.commons.chain2.testutils; import org.apache.commons.chain2.Context; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; /** * A matcher that checks if a {@link Context} contains a log with the given contents. * This matcher assumes that the context has a context value of type {@link StringBuilder} * registered for key {@code log}. * */ public class HasLog extends TypeSafeDiagnosingMatcher<Context> { private String expectedContent; public HasLog(String expectedContent) { this.expectedContent = expectedContent; } @Factory public static Matcher<? super Context> hasLog(final String logContent) { return new HasLog(logContent); } @Override protected boolean matchesSafely(Context item, Description mismatchDescription) { StringBuilder log = (StringBuilder) item.get("log"); if (log == null) { mismatchDescription.appendText("context has no log "); return false; } String actualContent = log.toString(); if (!actualContent.equals(expectedContent)) { mismatchDescription.appendText("log has content ").appendValue(actualContent); return false; } return true; } @Override public void describeTo(Description description) { description.appendText("log has content ").appendValue(expectedContent); } }
{'content_hash': '79bf0ba88ba196bfe71e18750e032a9c', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 90, 'avg_line_length': 29.88, 'alnum_prop': 0.6921017402945113, 'repo_name': 'apache/commons-chain', 'id': '908034e40bab31ff2c7d9c456cfd74aff5bff1b7', 'size': '2295', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'test-utils/src/main/java/org/apache/commons/chain2/testutils/HasLog.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '15147'}, {'name': 'Java', 'bytes': '655989'}, {'name': 'Shell', 'bytes': '157'}]}
<?php use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\URI; use CodeIgniter\Router\Exceptions\RouterException; use Config\App; use Config\Services; // CodeIgniter URL Helpers if (! function_exists('_get_uri')) { /** * Used by the other URL functions to build a * framework-specific URI based on the App config. * * @internal Outside of the framework this should not be used directly. * * @param string $relativePath May include queries or fragments * * @throws InvalidArgumentException For invalid paths or config */ function _get_uri(string $relativePath = '', ?App $config = null): URI { $config ??= config('App'); if ($config->baseURL === '') { throw new InvalidArgumentException('_get_uri() requires a valid baseURL.'); } // If a full URI was passed then convert it if (is_int(strpos($relativePath, '://'))) { $full = new URI($relativePath); $relativePath = URI::createURIString(null, null, $full->getPath(), $full->getQuery(), $full->getFragment()); } $relativePath = URI::removeDotSegments($relativePath); // Build the full URL based on $config and $relativePath $url = rtrim($config->baseURL, '/ ') . '/'; // Check for an index page if ($config->indexPage !== '') { $url .= $config->indexPage; // Check if we need a separator if ($relativePath !== '' && $relativePath[0] !== '/' && $relativePath[0] !== '?') { $url .= '/'; } } $url .= $relativePath; $uri = new URI($url); // Check if the baseURL scheme needs to be coerced into its secure version if ($config->forceGlobalSecureRequests && $uri->getScheme() === 'http') { $uri->setScheme('https'); } return $uri; } } if (! function_exists('site_url')) { /** * Returns a site URL as defined by the App config. * * @param mixed $relativePath URI string or array of URI segments * @param App|null $config Alternate configuration to use */ function site_url($relativePath = '', ?string $scheme = null, ?App $config = null): string { // Convert array of segments to a string if (is_array($relativePath)) { $relativePath = implode('/', $relativePath); } $uri = _get_uri($relativePath, $config); return URI::createURIString($scheme ?? $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment()); } } if (! function_exists('base_url')) { /** * Returns the base URL as defined by the App config. * Base URLs are trimmed site URLs without the index page. * * @param mixed $relativePath URI string or array of URI segments * @param string $scheme */ function base_url($relativePath = '', ?string $scheme = null): string { $config = clone config('App'); $config->indexPage = ''; return rtrim(site_url($relativePath, $scheme, $config), '/'); } } if (! function_exists('current_url')) { /** * Returns the current full URL based on the IncomingRequest. * String returns ignore query and fragment parts. * * @param bool $returnObject True to return an object instead of a string * @param IncomingRequest|null $request A request to use when retrieving the path * * @return string|URI */ function current_url(bool $returnObject = false, ?IncomingRequest $request = null) { $request ??= Services::request(); $path = $request->getPath(); // Append queries and fragments if ($query = $request->getUri()->getQuery()) { $path .= '?' . $query; } if ($fragment = $request->getUri()->getFragment()) { $path .= '#' . $fragment; } $uri = _get_uri($path); return $returnObject ? $uri : URI::createURIString($uri->getScheme(), $uri->getAuthority(), $uri->getPath()); } } if (! function_exists('previous_url')) { /** * Returns the previous URL the current visitor was on. For security reasons * we first check in a saved session variable, if it exists, and use that. * If that's not available, however, we'll use a sanitized url from $_SERVER['HTTP_REFERER'] * which can be set by the user so is untrusted and not set by certain browsers/servers. * * @return mixed|string|URI */ function previous_url(bool $returnObject = false) { // Grab from the session first, if we have it, // since it's more reliable and safer. // Otherwise, grab a sanitized version from $_SERVER. $referer = $_SESSION['_ci_previous_url'] ?? Services::request()->getServer('HTTP_REFERER', FILTER_SANITIZE_URL); $referer ??= site_url('/'); return $returnObject ? new URI($referer) : $referer; } } if (! function_exists('uri_string')) { /** * URL String * * Returns the path part of the current URL * * @param bool $relative Whether the resulting path should be relative to baseURL */ function uri_string(bool $relative = false): string { return $relative ? ltrim(Services::request()->getPath(), '/') : Services::request()->getUri()->getPath(); } } if (! function_exists('index_page')) { /** * Index page * * Returns the "index_page" from your config file * * @param App|null $altConfig Alternate configuration to use */ function index_page(?App $altConfig = null): string { // use alternate config if provided, else default one $config = $altConfig ?? config(App::class); return $config->indexPage; } } if (! function_exists('anchor')) { /** * Anchor Link * * Creates an anchor based on the local URL. * * @param mixed $uri URI string or array of URI segments * @param string $title The link title * @param mixed $attributes Any attributes * @param App|null $altConfig Alternate configuration to use */ function anchor($uri = '', string $title = '', $attributes = '', ?App $altConfig = null): string { // use alternate config if provided, else default one $config = $altConfig ?? config(App::class); $siteUrl = is_array($uri) ? site_url($uri, null, $config) : (preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config)); // eliminate trailing slash $siteUrl = rtrim($siteUrl, '/'); if ($title === '') { $title = $siteUrl; } if ($attributes !== '') { $attributes = stringify_attributes($attributes); } return '<a href="' . $siteUrl . '"' . $attributes . '>' . $title . '</a>'; } } if (! function_exists('anchor_popup')) { /** * Anchor Link - Pop-up version * * Creates an anchor based on the local URL. The link * opens a new window based on the attributes specified. * * @param string $uri the URL * @param string $title the link title * @param mixed $attributes any attributes * @param App|null $altConfig Alternate configuration to use */ function anchor_popup($uri = '', string $title = '', $attributes = false, ?App $altConfig = null): string { // use alternate config if provided, else default one $config = $altConfig ?? config(App::class); $siteUrl = preg_match('#^(\w+:)?//#i', $uri) ? $uri : site_url($uri, null, $config); $siteUrl = rtrim($siteUrl, '/'); if ($title === '') { $title = $siteUrl; } if ($attributes === false) { return '<a href="' . $siteUrl . '" onclick="window.open(\'' . $siteUrl . "', '_blank'); return false;\">" . $title . '</a>'; } if (! is_array($attributes)) { $attributes = [$attributes]; // Ref: http://www.w3schools.com/jsref/met_win_open.asp $windowName = '_blank'; } elseif (! empty($attributes['window_name'])) { $windowName = $attributes['window_name']; unset($attributes['window_name']); } else { $windowName = '_blank'; } foreach (['width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'menubar' => 'no', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0'] as $key => $val) { $atts[$key] = $attributes[$key] ?? $val; unset($attributes[$key]); } $attributes = stringify_attributes($attributes); return '<a href="' . $siteUrl . '" onclick="window.open(\'' . $siteUrl . "', '" . $windowName . "', '" . stringify_attributes($atts, true) . "'); return false;\"" . $attributes . '>' . $title . '</a>'; } } if (! function_exists('mailto')) { /** * Mailto Link * * @param string $email the email address * @param string $title the link title * @param mixed $attributes any attributes */ function mailto(string $email, string $title = '', $attributes = ''): string { if (trim($title) === '') { $title = $email; } return '<a href="mailto:' . $email . '"' . stringify_attributes($attributes) . '>' . $title . '</a>'; } } if (! function_exists('safe_mailto')) { /** * Encoded Mailto Link * * Create a spam-protected mailto link written in Javascript * * @param string $email the email address * @param string $title the link title * @param mixed $attributes any attributes */ function safe_mailto(string $email, string $title = '', $attributes = ''): string { if (trim($title) === '') { $title = $email; } $x = str_split('<a href="mailto:', 1); for ($i = 0, $l = strlen($email); $i < $l; $i++) { $x[] = '|' . ord($email[$i]); } $x[] = '"'; if ($attributes !== '') { if (is_array($attributes)) { foreach ($attributes as $key => $val) { $x[] = ' ' . $key . '="'; for ($i = 0, $l = strlen($val); $i < $l; $i++) { $x[] = '|' . ord($val[$i]); } $x[] = '"'; } } else { for ($i = 0, $l = mb_strlen($attributes); $i < $l; $i++) { $x[] = mb_substr($attributes, $i, 1); } } } $x[] = '>'; $temp = []; for ($i = 0, $l = strlen($title); $i < $l; $i++) { $ordinal = ord($title[$i]); if ($ordinal < 128) { $x[] = '|' . $ordinal; } else { if (empty($temp)) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; if (count($temp) === $count) { $number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64); $x[] = '|' . $number; $count = 1; $temp = []; } } } $x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>'; $x = array_reverse($x); // improve obfuscation by eliminating newlines & whitespace $output = '<script type="text/javascript">' . 'var l=new Array();'; foreach ($x as $i => $value) { $output .= 'l[' . $i . "] = '" . $value . "';"; } return $output . ('for (var i = l.length-1; i >= 0; i=i-1) {' . "if (l[i].substring(0, 1) === '|') document.write(\"&#\"+unescape(l[i].substring(1))+\";\");" . 'else document.write(unescape(l[i]));' . '}' . '</script>'); } } if (! function_exists('auto_link')) { /** * Auto-linker * * Automatically links URL and Email addresses. * Note: There's a bit of extra code here to deal with * URLs or emails that end in a period. We'll strip these * off and add them after the link. * * @param string $str the string * @param string $type the type: email, url, or both * @param bool $popup whether to create pop-up links */ function auto_link(string $str, string $type = 'both', bool $popup = false): string { // Find and replace any URLs. if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[^\s()<>;]+\w#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { // Set our target HTML if using popup links. $target = ($popup) ? ' target="_blank"' : ''; // We process the links in reverse order (last -> first) so that // the returned string offsets from preg_match_all() are not // moved as we add more HTML. foreach (array_reverse($matches) as $match) { // $match[0] is the matched string/link // $match[1] is either a protocol prefix or 'www.' // // With PREG_OFFSET_CAPTURE, both of the above is an array, // where the actual value is held in [0] and its offset at the [1] index. $a = '<a href="' . (strpos($match[1][0], '/') ? '' : 'http://') . $match[0][0] . '"' . $target . '>' . $match[0][0] . '</a>'; $str = substr_replace($str, $a, $match[0][1], strlen($match[0][0])); } } // Find and replace any emails. if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE)) { foreach (array_reverse($matches[0]) as $match) { if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== false) { $str = substr_replace($str, safe_mailto($match[0]), $match[1], strlen($match[0])); } } } return $str; } } if (! function_exists('prep_url')) { /** * Prep URL - Simply adds the http:// or https:// part if no scheme is included. * * Formerly used URI, but that does not play nicely with URIs missing * the scheme. * * @param string $str the URL * @param bool $secure set true if you want to force https:// */ function prep_url(string $str = '', bool $secure = false): string { if (in_array($str, ['http://', 'https://', '//', ''], true)) { return ''; } if (parse_url($str, PHP_URL_SCHEME) === null) { $str = 'http://' . ltrim($str, '/'); } // force replace http:// with https:// if ($secure) { $str = preg_replace('/^(?:http):/i', 'https:', $str); } return $str; } } if (! function_exists('url_title')) { /** * Create URL Title * * Takes a "title" string as input and creates a * human-friendly URL string with a "separator" string * as the word separator. * * @param string $str Input string * @param string $separator Word separator (usually '-' or '_') * @param bool $lowercase Whether to transform the output string to lowercase */ function url_title(string $str, string $separator = '-', bool $lowercase = false): string { $qSeparator = preg_quote($separator, '#'); $trans = [ '&.+?;' => '', '[^\w\d\pL\pM _-]' => '', '\s+' => $separator, '(' . $qSeparator . ')+' => $separator, ]; $str = strip_tags($str); foreach ($trans as $key => $val) { $str = preg_replace('#' . $key . '#iu', $val, $str); } if ($lowercase === true) { $str = mb_strtolower($str); } return trim(trim($str, $separator)); } } if (! function_exists('mb_url_title')) { /** * Create URL Title that takes into account accented characters * * Takes a "title" string as input and creates a * human-friendly URL string with a "separator" string * as the word separator. * * @param string $str Input string * @param string $separator Word separator (usually '-' or '_') * @param bool $lowercase Whether to transform the output string to lowercase */ function mb_url_title(string $str, string $separator = '-', bool $lowercase = false): string { helper('text'); return url_title(convert_accented_characters($str), $separator, $lowercase); } } if (! function_exists('url_to')) { /** * Get the full, absolute URL to a controller method * (with additional arguments) * * @param mixed ...$args * * @throws RouterException */ function url_to(string $controller, ...$args): string { if (! $route = route_to($controller, ...$args)) { $explode = explode('::', $controller); if (isset($explode[1])) { throw RouterException::forControllerNotFound($explode[0], $explode[1]); } throw RouterException::forInvalidRoute($controller); } return site_url($route); } } if (! function_exists('url_is')) { /** * Determines if current url path contains * the given path. It may contain a wildcard (*) * which will allow any valid character. * * Example: * if (url_is('admin*)) ... */ function url_is(string $path): bool { // Setup our regex to allow wildcards $path = '/' . trim(str_replace('*', '(\S)*', $path), '/ '); $currentPath = '/' . trim(uri_string(true), '/ '); return (bool) preg_match("|^{$path}$|", $currentPath, $matches); } }
{'content_hash': '34f9510dfde0fdab76d88e64647042d1', 'timestamp': '', 'source': 'github', 'line_count': 555, 'max_line_length': 192, 'avg_line_length': 32.81261261261261, 'alnum_prop': 0.5078798528361979, 'repo_name': 'bcit-ci/CodeIgniter4', 'id': '98dd596c1a4d172fc47f8f3dc83159e660a60559', 'size': '18454', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'system/Helpers/url_helper.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'BlitzBasic', 'bytes': '2795'}, {'name': 'CSS', 'bytes': '143659'}, {'name': 'HTML', 'bytes': '24162'}, {'name': 'Hack', 'bytes': '2832'}, {'name': 'JavaScript', 'bytes': '23661'}, {'name': 'Makefile', 'bytes': '4622'}, {'name': 'PHP', 'bytes': '2728879'}, {'name': 'Python', 'bytes': '11561'}, {'name': 'Shell', 'bytes': '10172'}]}
import { Component } from "@angular/core"; @Component({ moduleId: module.id, templateUrl: "./nested-routers.component.html" }) export class NestedRoutersComponent { }
{'content_hash': '4d7852b12d7079f6c97b69745e661ffd', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 50, 'avg_line_length': 25.142857142857142, 'alnum_prop': 0.7102272727272727, 'repo_name': 'NativeScript/nativescript-sdk-examples-ng', 'id': '30444ab3b0d2de768379270f2274fa4591df0d3e', 'size': '176', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/ng-framework-modules-category/routing/nested-routers/nested-routers.component.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '7924'}, {'name': 'HTML', 'bytes': '92854'}, {'name': 'JavaScript', 'bytes': '25328'}, {'name': 'Shell', 'bytes': '66'}, {'name': 'TypeScript', 'bytes': '222192'}]}
[![npm version](https://badge.fury.io/js/react-state-hoc.svg)](https://badge.fury.io/js/react-state-hoc) [![Build Status](https://travis-ci.org/troch/react-state-hoc.svg?branch=v1.0.4)](https://travis-ci.org/troch/react-state-hoc) # React state component (higher-order) > A React higher-order component for abstracting away state Keep your components simple, testable, and composable by using higher-order components. This higher-order component will abstract state away from components, so you can keep using functional stateless components. ## Installation ```sh npm install --save react-state-hoc # or yarn add react-state-hoc ``` ## API ### withState(initialState, mapSetStateToProps?, mergeProps?)(BaseComponent) Wraps your `BaseComponent` with a stateful component, passing the state into the `BaseComponent` as props. By default, state will be spread into the component's props, plus the `setState` function is passed through. If you specify a `mapSetStateToProps` function, `setState` will not be passed through. Two optional arguments allow you to a) define state creators, and b) customise which props are passed into the `BaseComponent`. * `initialState` can be either: * An object, to be used as the component's initial state. ```js withState({ visible: true })(BaseComponent) ``` * A function, which maps initial props to initial state. ```js withState(props => ({ visible: props.visible }))(BaseComponent) ``` * `mapSetStateToProps` can be either: * An object, containing state creators. Each state creator is a function which maps input arguments to new state. State creators are a convenient shorthand which automatically binds `setState` into smaller functions. Functions can also be provided as well as objects: they are supported by `setState` (see [https://reactjs.org/docs/react-component.html#setstate](https://reactjs.org/docs/react-component.html#setstate)) ```js withState( { visible: true }, { setVisibility: visible => ({ visible }) } )(BaseComponent) ``` * A function, mapping `initialProps` and `setState` to state creators. ```js withState({ state: null }, initialProps => setState => ({ setValue: value => setState({ someState: initialProps.mapValue(value) }) }))(BaseComponent) ``` **Default:** ```js () => setState => ({ setState }) ``` * `mergeProps`: A function mapping the current `props`, `state` and `stateCreators` into the `BaseComponent`'s props. ```js withState( { visible: true }, { setVisibility: visible => ({ visible }) }, (props, state, stateCreators) => ({ ...state, ...stateCreators // deliberately not passing props through to BaseComponent }) )(BaseComponent) ``` **Default:** ```js (props, state, stateCreators) => ({ ...props, ...state, ...stateCreators }) ``` ## Example ```javascript import React from 'react' import ReactDOM from 'react-dom' import withState from 'react-state-hoc' function StatelessButton({ counter, setCounter }) { return ( <button onClick={() => setCounter(counter + 1)}> Clicked {counter} times. </button> ) } const mapSetStateToProps = () => setState => ({ setCounter: counter => setState({ counter }) }) const StatefulButton1 = withState({ counter: 0 }, mapSetStateToProps)( StatelessButton ) const StatefulButton2 = withState({ counter: 10 }, mapSetStateToProps)( StatelessButton ) ReactDOM.render( <div> <StatefulButton1 /> <StatefulButton2 /> </div>, document.getElementById('app') ) ```
{'content_hash': 'ba3d4ac48625d84c3b18110e3b2dcdd3', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 423, 'avg_line_length': 31.520661157024794, 'alnum_prop': 0.6489250131095963, 'repo_name': 'troch/react-state-hoc', 'id': 'a5a3c6869e2745c772a82e8d012a77f0650b2fdc', 'size': '3814', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '591'}, {'name': 'TypeScript', 'bytes': '9364'}]}
package com.github.gwtmaterialdesign.client.application.sidenavmini; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Widget; import com.gwtplatform.mvp.client.ViewImpl; import javax.inject.Inject; public class MiniSideNavView extends ViewImpl implements MiniSideNavPresenter.MyView { interface Binder extends UiBinder<Widget, MiniSideNavView> { } @Inject MiniSideNavView(Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); } }
{'content_hash': '1c6a199f86ccd0ffc93bb991ed10be14', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 86, 'avg_line_length': 24.333333333333332, 'alnum_prop': 0.776908023483366, 'repo_name': 'GwtMaterialDesign/gwt-material-patterns', 'id': 'a873733cce5d7c82b5f76767c6903cca9c98519e', 'size': '1163', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/github/gwtmaterialdesign/client/application/sidenavmini/MiniSideNavView.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '27'}, {'name': 'HTML', 'bytes': '1264'}, {'name': 'Java', 'bytes': '148725'}, {'name': 'Shell', 'bytes': '1325'}]}
export { default as Title } from './title';
{'content_hash': '44f287de1dad4e8ec30b708e354813ce', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 43, 'avg_line_length': 44.0, 'alnum_prop': 0.6590909090909091, 'repo_name': 'bullet-app/bullet-app', 'id': 'a28ccdbbbaf67d111fd065025e8e91867adc0ba5', 'size': '44', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/components/title/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '4944'}]}
package com.github.gquintana.beepbeep.script; import com.github.gquintana.beepbeep.TestConsumer; import com.github.gquintana.beepbeep.pipeline.ScriptStartEvent; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class ResourceScriptScannerGlobTest { @Test public void testFileGlob() throws IOException { checkResourceGlobScan("*.sql", 1); checkResourceGlobScan("**/*.sql", 11); checkResourceGlobScan("com/github/gquintana/**/*.sql", 10); checkResourceGlobScan("com/github/gquintana/beepbeep/sql/init/*.sql", 2); } private void checkResourceGlobScan(String fileGlob, int fileNb) throws IOException { TestConsumer<ScriptStartEvent> end = new TestConsumer<>(); ResourceScriptScanner.resourceGlob(getClass().getClassLoader(), fileGlob, end).scan(); assertThat(end.events).hasSize(fileNb); } }
{'content_hash': '158d2d9e8d1c081c4fde603cea0af98f', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 94, 'avg_line_length': 36.46153846153846, 'alnum_prop': 0.7331223628691983, 'repo_name': 'gquintana/beepbeep', 'id': '074a9a905f67f6642383a6255dbe0db7b4fb4370', 'size': '948', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/github/gquintana/beepbeep/script/ResourceScriptScannerGlobTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '340'}, {'name': 'Java', 'bytes': '295513'}, {'name': 'Shell', 'bytes': '421'}]}
using System; using System.IO; using System.Reflection; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Imaging; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Input; namespace API { public static class Text { private static GraphicsContext graphics; private static ShaderProgram textureShaderProgram; private static ShaderProgram colorShaderProgram; private static Matrix4 projectionMatrix; private static Matrix4 viewMatrix; private static VertexBuffer rectVertices; private static VertexBuffer circleVertices; private static Dictionary<string, TextSprite> spriteDict; private static int spriteNamelessCount; private static Font defaultFont; private static Font currentFont; public static bool Init(GraphicsContext graphicsContext, Stopwatch swInit = null) { graphics = graphicsContext; textureShaderProgram = createSimpleTextureShader(); colorShaderProgram = createSimpleColorShader(); projectionMatrix = Matrix4.Ortho(0, Width, 0, Height, 0.0f, 32768.0f); viewMatrix = Matrix4.LookAt(new Vector3(0, Height, 0), new Vector3(0, Height, 1), new Vector3(0, -1, 0)); rectVertices = new VertexBuffer(4, VertexFormat.Float3); rectVertices.SetVertices(0, new float[]{0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0}); circleVertices = new VertexBuffer(36, VertexFormat.Float3); float[] circleVertex = new float[3 * 36]; for (int i = 0; i < 36; i++) { float radian = ((i * 10) / 180.0f * FMath.PI); circleVertex[3 * i + 0] = FMath.Cos(radian); circleVertex[3 * i + 1] = FMath.Sin(radian); circleVertex[3 * i + 2] = 0.0f; } circleVertices.SetVertices(0, circleVertex); defaultFont = new Font(FontAlias.System, 24, FontStyle.Regular); SetDefaultFont(); spriteDict = new Dictionary<string, TextSprite>(); spriteNamelessCount = 0; return true; } /// Terminate public static void Term() { ClearSprite(); defaultFont.Dispose(); circleVertices.Dispose(); rectVertices.Dispose(); colorShaderProgram.Dispose(); textureShaderProgram.Dispose(); graphics = null; } public static int Width { get {return graphics.GetFrameBuffer().Width;} } public static int Height { get {return graphics.GetFrameBuffer().Height;} } /// Touch coordinates -> screen coordinates conversion : X public static int TouchPixelX(TouchData touchData) { return (int)((touchData.X + 0.5f) * Width); } /// Touch coordinates -> screen coordinates conversion : Y public static int TouchPixelY(TouchData touchData) { return (int)((touchData.Y + 0.5f) * Height); } public static void AddSprite(TextSprite sprite) { AddSprite("[nameless]:" + spriteNamelessCount, sprite); spriteNamelessCount++; } public static void AddSprite(string key, TextSprite sprite) { if (spriteDict.ContainsKey(key) == false) { spriteDict.Add(key, sprite); } } /// Register a sprite that draws text public static void AddSprite(string key, string text, uint argb, Font font, int positionX, int positionY) { if (spriteDict.ContainsKey(text) == false) { AddSprite(key, new TextSprite(text, argb, font, positionX, positionY)); } } /// Register a sprite that draws text public static void AddSprite(string text, uint argb, int positionX, int positionY) { AddSprite(text, text, argb, currentFont, positionX, positionY); } public static void RemoveSprite(string key) { if (spriteDict.ContainsKey(key)) { spriteDict[key].Dispose(); spriteDict.Remove(key); } } public static void ClearSprite() { foreach (string key in spriteDict.Keys) { spriteDict[key].Dispose(); } spriteDict.Clear(); spriteNamelessCount = 0; } // if use Text's method, please call this method. public static void Update() { int keyNo = 0; string[] removeKey = new string[spriteDict.Count]; foreach (var key in spriteDict.Keys) { if(false == spriteDict[key].CheckLifeTimer()) { removeKey[keyNo] = key; keyNo++; } } for(int i = 0; i < keyNo; i++) { if(removeKey[i] != null) { RemoveSprite(removeKey[i]); } } } public static void DrawSprite(string key) { if (spriteDict.ContainsKey(key)) { DrawSprite(spriteDict[key]); } } public static void DrawSprite(TextSprite sprite) { var modelMatrix = sprite.CreateModelMatrix(); var worldViewProj = projectionMatrix * viewMatrix * modelMatrix; textureShaderProgram.SetUniformValue(0, ref worldViewProj); graphics.SetShaderProgram(textureShaderProgram); graphics.SetVertexBuffer(0, sprite.Vertices); graphics.SetTexture(0, sprite.Texture); graphics.Enable(EnableMode.Blend); graphics.SetBlendFunc(BlendFuncMode.Add, BlendFuncFactor.SrcAlpha, BlendFuncFactor.OneMinusSrcAlpha); graphics.DrawArrays(DrawMode.TriangleFan, 0, 4); sprite.SetLifeTimer(); } public static Font CurrentFont { get {return currentFont;} } public static Font SetDefaultFont() { return SetFont(defaultFont); } public static Font SetFont(Font font) { Font previousFont = currentFont; currentFont = font; return previousFont; } public static void DrawText(string text, uint argb, Font font, int positionX, int positionY) { AddSprite(text, text, argb, font, positionX, positionY); DrawSprite(text); } public static void DrawText(string text, uint argb, int positionX, int positionY) { AddSprite(text, text, argb, currentFont, positionX, positionY); DrawSprite(text); } public static void FillVertices(VertexBuffer vertices, uint argb, float positionX, float positionY, float scaleX, float scaleY) { var transMatrix = Matrix4.Translation(new Vector3(positionX, positionY, 0.0f)); var scaleMatrix = Matrix4.Scale(new Vector3(scaleX, scaleY, 1.0f)); var modelMatrix = transMatrix * scaleMatrix; var worldViewProj = projectionMatrix * viewMatrix * modelMatrix; colorShaderProgram.SetUniformValue(0, ref worldViewProj); Vector4 color = new Vector4((float)((argb >> 16) & 0xff) / 0xff, (float)((argb >> 8) & 0xff) / 0xff, (float)((argb >> 0) & 0xff) / 0xff, (float)((argb >> 24) & 0xff) / 0xff); colorShaderProgram.SetUniformValue(colorShaderProgram.FindUniform("MaterialColor"), ref color); graphics.SetShaderProgram(colorShaderProgram); graphics.SetVertexBuffer(0, vertices); graphics.DrawArrays(DrawMode.TriangleFan, 0, vertices.VertexCount); } public static Texture2D createTexture(string text, Font font, uint argb) { int width = font.GetTextWidth(text, 0, text.Length); int height = font.Metrics.Height; var image = new Image(ImageMode.Rgba, new ImageSize(width, height), new ImageColor(0, 0, 0, 0)); image.DrawText(text, new ImageColor((int)((argb >> 16) & 0xff), (int)((argb >> 8) & 0xff), (int)((argb >> 0) & 0xff), (int)((argb >> 24) & 0xff)), font, new ImagePosition(0, 0)); var texture = new Texture2D(width, height, false, PixelFormat.Rgba); texture.SetPixels(0, image.ToBuffer()); image.Dispose(); return texture; } private static ShaderProgram createSimpleTextureShader() { string ResourceName = "API.shaders.Texture.cgx"; Assembly resourceAssembly = Assembly.GetExecutingAssembly(); if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null) { throw new FileNotFoundException("File not found.", ResourceName); } Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName); Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length]; fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length); var shaderProgram = new ShaderProgram(dataBufferVertex); // var shaderProgram = new ShaderProgram("/Application/shaders/Texture.cgx"); shaderProgram.SetAttributeBinding(0, "a_Position"); shaderProgram.SetAttributeBinding(1, "a_TexCoord"); shaderProgram.SetUniformBinding(0, "WorldViewProj"); return shaderProgram; } private static ShaderProgram createSimpleColorShader() { string ResourceName = "API.shaders.Simple.cgx"; Assembly resourceAssembly = Assembly.GetExecutingAssembly(); if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null) { throw new FileNotFoundException("File not found.", ResourceName); } Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName); Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length]; fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length); var shaderProgram = new ShaderProgram(dataBufferVertex); // var shaderProgram = new ShaderProgram("/Application/shaders/Simple.cgx"); shaderProgram.SetAttributeBinding(0, "a_Position"); //shaderProgram.SetAttributeBinding(1, "a_Color0"); shaderProgram.SetUniformBinding(0, "WorldViewProj"); return shaderProgram; } } }
{'content_hash': 'd9b09619ac8c9a163edf7bdd2fdc75d9', 'timestamp': '', 'source': 'github', 'line_count': 330, 'max_line_length': 132, 'avg_line_length': 32.43030303030303, 'alnum_prop': 0.6007288357316389, 'repo_name': 'Reisor/SpaceShips', 'id': '404862fbd8331d19530153c7eaca74be0bbbeb36', 'size': '10703', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'API/Text.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '164145'}]}
""" Low-level classes for managing data transfer. """ from __future__ import print_function from collections import namedtuple, Counter from concurrent.futures import ThreadPoolExecutor import logging import multiprocessing import signal import sys import threading import time import uuid import operator import os from .exceptions import DatalakeIncompleteTransferException logger = logging.getLogger(__name__) class StateManager(object): """ Manages state for any hashable object. When tracking multiple files and their chunks, each file/chunk can be in any valid state for that particular type. At the simplest level, we need to set and retrieve an object's current state, while only allowing valid states to be used. In addition, we also need to give statistics about a group of objects (are all objects in one state? how many objects are in each available state?). Parameters ---------- states : list of valid states Managed objects can only use these defined states. Examples -------- >>> StateManager('draft', 'review', 'complete') # doctest: +SKIP <StateManager: draft=0 review=0 complete=0> >>> mgr = StateManager('off', 'on') >>> mgr['foo'] = 'on' >>> mgr['bar'] = 'off' >>> mgr['quux'] = 'on' >>> mgr # doctest: +SKIP <StateManager: off=1 on=2> >>> mgr.contains_all('on') False >>> mgr['bar'] = 'on' >>> mgr.contains_all('on') True >>> mgr.contains_none('off') True Internal class used by `ADLTransferClient`. """ def __init__(self, *states): self._states = {state: set() for state in states} self._objects = {} @property def states(self): return list(self._states) @property def objects(self): return list(self._objects) def __iter__(self): return iter(self._objects.items()) def __getitem__(self, obj): return self._objects[obj] def __setitem__(self, obj, state): if obj in self._objects: self._states[self._objects[obj]].discard(obj) self._states[state].add(obj) self._objects[obj] = state def contains_all(self, state): """ Return whether all managed objects are in the given state """ objs = self._states[state] return len(objs) > 0 and len(self.objects) - len(objs) == 0 def contains_none(self, *states): """ Return whether no managed objects are in the given states """ return all([len(self._states[state]) == 0 for state in states]) def __str__(self): status = " ".join( ["%s=%d" % (s, len(self._states[s])) for s in self._states]) return "<StateManager: " + status + ">" __repr__ = __str__ # Named tuples used to serialize client progress File = namedtuple('File', 'src dst state length chunks exception') Chunk = namedtuple('Chunk', 'name state offset expected actual exception') class ADLTransferClient(object): """ Client for transferring data from/to Azure DataLake Store This is intended as the underlying class for `ADLDownloader` and `ADLUploader`. If necessary, it can be used directly for additional control. Parameters ---------- adlfs: ADL filesystem instance name: str Unique ID used for persistence. transfer: callable Function or callable object invoked when transferring chunks. See ``Function Signatures``. merge: callable [None] Function or callable object invoked when merging chunks. For each file containing only one chunk, no merge function will be called, even if provided. If None, then merging is skipped. See ``Function Signatures``. nthreads: int [None] Number of threads to use (minimum is 1). If None, uses the number of cores. chunksize: int [2**28] Number of bytes for a chunk. Large files are split into chunks. Files smaller than this number will always be transferred in a single thread. buffersize: int [2**25] Number of bytes for internal buffer. This block cannot be bigger than a chunk and cannot be smaller than a block. blocksize: int [2**25] Number of bytes for a block. Within each chunk, we write a smaller block for each API call. This block cannot be bigger than a chunk. chunked: bool [True] If set, each transferred chunk is stored in a separate file until chunks are gathered into a single file. Otherwise, each chunk will be written into the same destination file. unique_temporary: bool [True] If set, transferred chunks are written into a unique temporary directory. persist_path: str [None] Path used for persisting a client's state. If None, then `save()` and `load()` will be empty operations. delimiter: byte(s) or None If set, will transfer blocks using delimiters, as well as split files for transferring on that delimiter. parent: ADLDownloader, ADLUploader or None In typical usage, the transfer client is created in the context of an upload or download, which can be persisted between sessions. Temporary Files --------------- When a merge step is available, the client will write chunks to temporary files before merging. The exact temporary file looks like this in pseudo-BNF: >>> # {dirname}/{basename}.segments[.{unique_str}]/{basename}_{offset} Function Signatures ------------------- To perform the actual work needed by the client, the user must pass in two callables, `transfer` and `merge`. If merge is not provided, then the merge step will be skipped. The `transfer` callable has the function signature, `fn(adlfs, src, dst, offset, size, buffersize, blocksize, shutdown_event)`. `adlfs` is the ADL filesystem instance. `src` and `dst` refer to the source and destination of the respective file transfer. `offset` is the location in `src` to read `size` bytes from. `buffersize` is the number of bytes used for internal buffering before transfer. `blocksize` is the number of bytes in a chunk to write at one time. The callable should return an integer representing the number of bytes written. The `merge` callable has the function signature, `fn(adlfs, outfile, files, shutdown_event)`. `adlfs` is the ADL filesystem instance. `outfile` is the result of merging `files`. For both callables, `shutdown_event` is optional. In particular, `shutdown_event` is a `threading.Event` that is passed to the callable. The event will be set when a shutdown is requested. It is good practice to listen for this. Internal State -------------- self._fstates: StateManager This captures the current state of each transferred file. self._files: dict Using a tuple of the file source/destination as the key, this dictionary stores the file metadata and all chunk states. The dictionary key is `(src, dst)` and the value is `dict(length, cstates, exception)`. self._chunks: dict Using a tuple of the chunk name/offset as the key, this dictionary stores the chunk metadata and has a reference to the chunk's parent file. The dictionary key is `(name, offset)` and the value is `dict(parent=(src, dst), expected, actual, exception)`. self._ffutures: dict Using a Future object as the key, this dictionary provides a reverse lookup for the file associated with the given future. The returned value is the file's primary key, `(src, dst)`. self._cfutures: dict Using a Future object as the key, this dictionary provides a reverse lookup for the chunk associated with the given future. The returned value is the chunk's primary key, `(name, offset)`. See Also -------- azure.datalake.store.multithread.ADLDownloader azure.datalake.store.multithread.ADLUploader """ def __init__(self, adlfs, transfer, merge=None, nthreads=None, chunksize=2**28, blocksize=2**25, chunked=True, unique_temporary=True, delimiter=None, parent=None, verbose=False, buffersize=2**25): self._adlfs = adlfs self._parent = parent self._transfer = transfer self._merge = merge self._nthreads = max(1, nthreads or multiprocessing.cpu_count()) self._chunksize = chunksize self._buffersize = buffersize self._blocksize = blocksize self._chunked = chunked self._unique_temporary = unique_temporary self._unique_str = uuid.uuid4().hex self.verbose = verbose # Internal state tracking files/chunks/futures self._files = {} self._chunks = {} self._ffutures = {} self._cfutures = {} self._fstates = StateManager( 'pending', 'transferring', 'merging', 'finished', 'cancelled', 'errored') def submit(self, src, dst, length): """ Split a given file into chunks. All submitted files/chunks start in the `pending` state until `run()` is called. """ cstates = StateManager( 'pending', 'running', 'finished', 'cancelled', 'errored') # Create unique temporary directory for each file if self._chunked: if self._unique_temporary: filename = "{}.segments.{}".format(dst.name, self._unique_str) else: filename = "{}.segments".format(dst.name) tmpdir = dst.parent/filename else: tmpdir = None # TODO: might need xrange support for py2 offsets = range(0, length, self._chunksize) # in the case of empty files, ensure that the initial offset of 0 is properly added. if not offsets: if not length: offsets = [0] else: raise DatalakeIncompleteTransferException('Could not compute offsets for source: {}, with destination: {} and expected length: {}.'.format(src, dst, length)) tmpdir_and_offsets = tmpdir and len(offsets) > 1 for offset in offsets: if tmpdir_and_offsets: name = tmpdir / "{}_{}".format(dst.name, offset) else: name = dst cstates[(name, offset)] = 'pending' self._chunks[(name, offset)] = { "parent": (src, dst), "expected": min(length - offset, self._chunksize), "actual": 0, "exception": None} logger.debug("Submitted %s, byte offset %d", name, offset) self._fstates[(src, dst)] = 'pending' self._files[(src, dst)] = { "length": length, "cstates": cstates, "exception": None} def _submit(self, fn, *args, **kwargs): kwargs['shutdown_event'] = self._shutdown_event future = self._pool.submit(fn, *args, **kwargs) future.add_done_callback(self._update) return future def _start(self, src, dst): key = (src, dst) self._fstates[key] = 'transferring' for obj in self._files[key]['cstates'].objects: name, offset = obj cs = self._files[key]['cstates'] if obj in cs.objects and cs[obj] == 'finished': continue cs[obj] = 'running' future = self._submit( self._transfer, self._adlfs, src, name, offset, self._chunks[obj]['expected'], self._buffersize, self._blocksize) self._cfutures[future] = obj @property def active(self): """ Return whether the transfer is active """ return not self._fstates.contains_none('pending', 'transferring', 'merging') @property def successful(self): """ Return whether the transfer completed successfully. It will raise AssertionError if the transfer is active. """ assert not self.active return self._fstates.contains_all('finished') @property def progress(self): """ Return a summary of all transferred file/chunks """ files = [] for key in self._files: src, dst = key chunks = [] for obj in self._files[key]['cstates'].objects: name, offset = obj chunks.append(Chunk( name=name, offset=offset, state=self._files[key]['cstates'][obj], expected=self._chunks[obj]['expected'], actual=self._chunks[obj]['actual'], exception=self._chunks[obj]['exception'])) files.append(File( src=src, dst=dst, state=self._fstates[key], length=self._files[key]['length'], chunks=chunks, exception=self._files[key]['exception'])) return files def _rename_file(self, src, dst, overwrite=False): """ Rename a file from file_name.inprogress to just file_name. Invoked once download completes on a file. Internal function used by `download`. """ try: # we do a final check to make sure someone didn't create the destination file while download was occuring # if the user did not specify overwrite. if os.path.isfile(dst): if not overwrite: raise FileExistsError(dst) os.remove(dst) os.rename(src, dst) except Exception as e: logger.error('Rename failed for source file: %r; %r', src, e) raise e logger.debug('Renamed %r to %r', src, dst) def _update(self, future): if future in self._cfutures: obj = self._cfutures[future] parent = self._chunks[obj]['parent'] cstates = self._files[parent]['cstates'] src, dst = parent if future.cancelled(): cstates[obj] = 'cancelled' elif future.exception(): self._chunks[obj]['exception'] = repr(future.exception()) cstates[obj] = 'errored' else: nbytes, exception = future.result() self._chunks[obj]['actual'] = nbytes self._chunks[obj]['exception'] = exception if exception: cstates[obj] = 'errored' elif self._chunks[obj]['expected'] != nbytes: name, offset = obj cstates[obj] = 'errored' exception = DatalakeIncompleteTransferException( 'chunk {}, offset {}: expected {} bytes, transferred {} bytes'.format( name, offset, self._chunks[obj]['expected'], self._chunks[obj]['actual'])) self._chunks[obj]['exception'] = exception logger.error("Incomplete transfer: %s -> %s, %s", src, dst, repr(exception)) else: cstates[obj] = 'finished' if cstates.contains_all('finished'): logger.debug("Chunks transferred") if self._merge and len(cstates.objects) > 1: logger.debug("Merging file: %s", self._fstates[parent]) self._fstates[parent] = 'merging' merge_future = self._submit( self._merge, self._adlfs, dst, [chunk for chunk, _ in sorted(cstates.objects, key=operator.itemgetter(1))], overwrite=self._parent._overwrite) self._ffutures[merge_future] = parent else: if not self._chunked and str(dst).endswith('.inprogress'): logger.debug("Renaming file to remove .inprogress: %s", self._fstates[parent]) self._fstates[parent] = 'merging' self._rename_file(dst, dst.replace('.inprogress',''), overwrite=self._parent._overwrite) dst = dst.replace('.inprogress', '') self._fstates[parent] = 'finished' logger.info("Transferred %s -> %s", src, dst) elif cstates.contains_none('running'): logger.error("Transfer failed: %s -> %s", src, dst) self._fstates[parent] = 'errored' elif future in self._ffutures: src, dst = self._ffutures[future] if future.cancelled(): self._fstates[(src, dst)] = 'cancelled' elif future.exception(): self._files[(src, dst)]['exception'] = repr(future.exception()) self._fstates[(src, dst)] = 'errored' else: exception = future.result() self._files[(src, dst)]['exception'] = exception if exception: self._fstates[(src, dst)] = 'errored' else: self._fstates[(src, dst)] = 'finished' logger.info("Transferred %s -> %s", src, dst) # TODO: Re-enable progress saving when a less IO intensive solution is available. # See issue: https://github.com/Azure/azure-data-lake-store-python/issues/117 #self.save() if self.verbose: print('\b' * 200, self.status, end='') sys.stdout.flush() @property def status(self): c = sum([Counter([c.state for c in f.chunks]) for f in self.progress], Counter()) return dict(c) def run(self, nthreads=None, monitor=True, before_start=None): self._pool = ThreadPoolExecutor(self._nthreads) self._shutdown_event = threading.Event() self._nthreads = nthreads or self._nthreads self._ffutures = {} self._cfutures = {} for src, dst in self._files: if before_start: before_start(self._adlfs, src, dst) self._start(src, dst) before_start = None if monitor: self.monitor() has_errors = False error_list = [] for f in self.progress: for chunk in f.chunks: if chunk.state == 'finished': continue if chunk.exception: error_string = '{} -> {}, chunk {} {}: {}, {}'.format( f.src, f.dst, chunk.name, chunk.offset, chunk.state, repr(chunk.exception)) logger.error(error_string) has_errors = True error_list.append(error_string) else: error_string = '{} -> {}, chunk {} {}: {}'.format( f.src, f.dst, chunk.name, chunk.offset, chunk.state) logger.error(error_string) error_list.append(error_string) has_errors = True if has_errors: raise DatalakeIncompleteTransferException('One more more exceptions occured during transfer, resulting in an incomplete transfer. \n\n List of exceptions and errors:\n {}'.format('\n'.join(error_list))) def _wait(self, poll=0.1, timeout=0): start = time.time() while self.active: if timeout > 0 and time.time() - start > timeout: break time.sleep(poll) def _clear(self): self._cfutures = {} self._ffutures = {} self._pool = None def shutdown(self): """ Shutdown task threads in an orderly fashion. Within the context of this method, we disable Ctrl+C keystroke events until all threads have exited. We re-enable Ctrl+C keystroke events before leaving. """ handler = signal.signal(signal.SIGINT, signal.SIG_IGN) try: logger.debug("Shutting down worker threads") self._shutdown_event.set() self._pool.shutdown(wait=True) except Exception as e: logger.error("Unexpected exception occurred during shutdown: %s", repr(e)) else: logger.debug("Shutdown complete") finally: signal.signal(signal.SIGINT, handler) def monitor(self, poll=0.1, timeout=0): """ Wait for download to happen """ try: self._wait(poll, timeout) except KeyboardInterrupt: logger.warning("%s suspended and persisted", self) self.shutdown() self._clear() # TODO: Re-enable progress saving when a less IO intensive solution is available. # See issue: https://github.com/Azure/azure-data-lake-store-python/issues/117 #self.save() def __getstate__(self): dic2 = self.__dict__.copy() dic2.pop('_cfutures', None) dic2.pop('_ffutures', None) dic2.pop('_pool', None) dic2.pop('_shutdown_event', None) dic2['_files'] = dic2.get('_files', {}).copy() dic2['_chunks'] = dic2.get('_chunks', {}).copy() return dic2 def save(self, keep=True): if self._parent is not None: self._parent.save(keep=keep)
{'content_hash': '4efc3bdce92f539df4f291dc02893cb9', 'timestamp': '', 'source': 'github', 'line_count': 555, 'max_line_length': 218, 'avg_line_length': 39.04504504504504, 'alnum_prop': 0.5697738809413936, 'repo_name': 'begoldsm/azure-data-lake-store-python', 'id': '4ee3454232e95401e75a688950be85dcb7b7d62f', 'size': '22021', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'azure/datalake/store/transfer.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '191637'}]}
#pragma once #include <algorithm> #include <cstdint> #include <vector> namespace mirrage::util { template <class T> class sorted_vector { public: using const_iterator = typename std::vector<T>::const_iterator; using const_reverse_iterator = typename std::vector<T>::const_reverse_iterator; sorted_vector() = default; sorted_vector(std::vector<T> data) : _data(data) { std::sort(data.begin(), data.end()); } template <class U, typename = std::enable_if_t<std::is_same_v<std::remove_reference_t<U>, T>>> auto insert(U&& v) -> T& { auto lb = std::lower_bound(_data.begin(), _data.end(), v); return *_data.insert(lb, std::forward<U>(v)); } template <class Key, class... Args, typename = std::enable_if_t<!std::is_same_v<std::remove_reference_t<Key>, T>>> auto emplace(const Key& key, Args&&... args) -> T& { auto lb = std::lower_bound(_data.begin(), _data.end(), key); return *_data.emplace(lb, std::forward<Args>(args)...); } void erase(const T& v) { auto lb = std::lower_bound(_data.begin(), _data.end(), v); if(lb != _data.end() && *lb == v) { _data.erase(lb); } } template <class Key> auto find(const Key& key) -> const_iterator { auto iter = std::lower_bound(begin(), end(), key); return iter != end() && *iter == key ? iter : end(); } void erase(const_iterator iter) { _data.erase(iter); } void erase(const_iterator begin, const_iterator end) { _data.erase(begin, end); } auto pop_back() -> T { auto v = back(); _data.pop_back(); return v; } auto front() { return _data.front(); } auto back() { return _data.back(); } auto clear() { return _data.clear(); } void reserve(std::size_t n) { _data.reserve(n); } auto size() const { return _data.size(); } auto empty() const { return _data.empty(); } auto begin() const { return _data.begin(); } auto end() const { return _data.end(); } auto rbegin() const { return _data.rbegin(); } auto rend() const { return _data.rend(); } decltype(auto) operator[](std::int64_t i) { return _data.at(i); } private: std::vector<T> _data; }; } // namespace mirrage::util
{'content_hash': '37dac9b36f4e63d3a4f262ba3e988d71', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 96, 'avg_line_length': 27.49367088607595, 'alnum_prop': 0.5994475138121547, 'repo_name': 'lowkey42/mirrage', 'id': 'bb7feafa674339e816025062fb6cba97b7e76365', 'size': '2646', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/mirrage/utils/include/mirrage/utils/sorted_vector.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '168007'}, {'name': 'C++', 'bytes': '1882762'}, {'name': 'CMake', 'bytes': '41342'}, {'name': 'GLSL', 'bytes': '165858'}, {'name': 'Shell', 'bytes': '706'}]}
echo "Challenge 1" TEST=`diff -wBq ../my_files/nsorts.txt ../my_files/asorts.txt` VAL="Files my_files/nsorts.txt and my_files/asorts.txt differ" if [ $"VAL"=$"TEST" ] ; then echo ...passed ; else echo ...failed ; fi echo "Challenge 2" if [ `cat ../my_files/asia_count` -eq 77301 ] ; then echo ...passed ; else echo ...failed ; fi echo "Challenge 3" echo "bear\ndeer\nfox\nrabbit\nraccoon" > test TEST=`diff -wBq test ../my_files/unique_animals.txt` VAL="Files test and my_files/unique_animals do not differ" if [ $"VAL"=$"TEST" ] ; then echo ...passed ; else echo ...failed ; fi
{'content_hash': 'ba26f410dcfe4332acd1ff3cca5336d4', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 62, 'avg_line_length': 19.129032258064516, 'alnum_prop': 0.657672849915683, 'repo_name': 'dlab-berkeley/cornerstone-2015-unix-FUNdamentals', 'id': '71f75bc4ef5af998a0f6739a25d6c542b56877a4', 'size': '606', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/1-3_test.sh', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Shell', 'bytes': '1649'}]}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenTK; using System.Drawing; using Sharp2D; using Sharp2D.Core; using Sharp2D.Core.Interfaces; using Sharp2D.Game.Worlds; namespace Sharp2D.Game.Sprites { public sealed class TileSprite : Sprite, ICollidable { public TiledWorld World { get; private set; } public int ID { get; private set; } public TileSet TileSet { get; private set; } public Layer ParentLayer { get; private set; } public bool FlippedDiagonally { get; internal set; } public bool FlippedHorizontally { get; internal set; } public bool FlippedVertically { get; internal set; } public TileSprite(int ID, TileSet parent, Layer parentLayer, int data_index, TiledWorld world) { this.World = world; this.ID = ID; this.TileSet = parent; this.ParentLayer = parentLayer; Width = TileSet.TileWidth; Height = TileSet.TileHeight; X = data_index % parentLayer.Width; Y = data_index / parentLayer.Width; X *= TileSet.TileWidth; Y *= TileSet.TileHeight; Layer = 1f/ParentLayer.LayerNumber; IsStatic = !(parent.TileProperties.ContainsKey(ID) && parent.TileProperties[ID].ContainsKey("static") && parent.TileProperties[ID]["static"].ToLower() == "true"); _setTexCoords(); Texture = TileSet.TileTexture; if (IsCollidable) { Hitbox = new Hitbox("Space", new List<Vector2> { new Vector2(0, 0), new Vector2(Width, 0), new Vector2(Width, Height), new Vector2(0, Height) }); Hitbox.AddCollidable(this); } } public bool IsCollidable { get { return TileSet.TileProperties.ContainsKey(ID) && TileSet.TileProperties[ID].ContainsKey("collide"); } } public override bool HasAlpha { get { return TileHasAlpha; } } public bool HasProperty(string key) { return TileSet.TileProperties.ContainsKey(ID) && TileSet.TileProperties[ID].ContainsKey(key); } public string GetProperty(string key) { return !HasProperty(key) ? null : TileSet.TileProperties[ID][key]; } private void _setTexCoords() { if (World.texcoords_cache.ContainsKey(ID)) { TexCoords = World.texcoords_cache[ID]; return; } int tilepos = (ID - TileSet.FirstGID) + 1; float x, y, width, height; int step = (tilepos - 1) % TileSet.TilesPerRow, row = 0; for (int i = 0; i != ID; i++) { if (i % TileSet.TilesPerRow == 0 && i != 0) row++; } x = TileSet.TileWidth * step; y = TileSet.TileHeight * row; y = TileSet.TileTexture.TextureHeight + y; width = x + TileSet.TileWidth; height = y + TileSet.TileHeight; TexCoords = new TexCoords(x, y, width, height, TileSet.TileTexture); World.texcoords_cache.Add(ID, TexCoords); IsStatic = true; } public bool TileHasAlpha { get { if (TileSet.containsAlpha.ContainsKey(ID)) return TileSet.containsAlpha[ID]; int tilepos = (ID - TileSet.FirstGID) + 1; int step = (tilepos - 1) % TileSet.TilesPerRow, row = 0; for (int i = 0; i != ID; i++) { if (i % TileSet.TilesPerRow == 0 && i != 0) row++; } int x = TileSet.TileWidth * step; int y = TileSet.TileHeight * row; int width = TileSet.TileWidth; int height = TileSet.TileHeight; var testBmp = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(testBmp)) { g.DrawImage(Texture.Bitmap, new RectangleF(0, 0, width, height), new RectangleF(x, y, width, height), GraphicsUnit.Pixel); } bool cached_alpha_answer = testBmp.ContainsAlpha(); TileSet.containsAlpha.Add(ID, cached_alpha_answer); testBmp.Dispose(); return cached_alpha_answer; } } protected override void OnLoad() { //TODO Do some loading of something } protected override void OnUnload() { //TODO Do some unloading of something } protected override void OnDispose() { //TODO Dispose something.. } protected override void OnDisplay() { //TODO Display related stuff (badpokerface) } protected override void BeforeDraw() { //TODO Do something before it's drawn } public event EventHandler OnCollision; public Hitbox Hitbox { get; set; } public CollisionResult CollidesWith(ICollidable c) { return new CollisionResult {Intersecting = false, WillIntersect = false, TranslationVector = new Vector2()}; } public override string Name { get { return "Tile #" + ID; } } } }
{'content_hash': '8724662b8586f6ef72e82eb74f6e4df5', 'timestamp': '', 'source': 'github', 'line_count': 192, 'max_line_length': 174, 'avg_line_length': 29.666666666666668, 'alnum_prop': 0.522998595505618, 'repo_name': 'CatinaCupGames/Sharp2D', 'id': '6ff64883efdc8614df465a4187285d3982f76a21', 'size': '5698', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Sharp2D/Sharp2D/Game/Sprites/TileSprite.cs', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '324190'}, {'name': 'GLSL', 'bytes': '4939'}]}
<link rel="import" href="../bower_components/polymer/polymer.html"> <link rel="import" href="app-theme.html"> <dom-module id="total-price"> <style include="app-theme"> :host { --paper-menu: { padding: 0px; } } paper-icon-item { --paper-item-icon-width: 36px; @apply(--total-price-styles); color: var(--alt-text-color); } paper-menu { @apply(--total-price-styles); } paper-icon-item.iron-selected { @apply(--shadow-elevation-6dp); background-color: var(--light-alt-accent-color); z-index: 2; } paper-menu paper-submenu paper-menu paper-icon-item { padding-left: 25px; } paper-menu paper-submenu paper-menu paper-icon-item.iron-selected { @apply(--shadow-elevation-2dp); background-color: var(--alt-background-color); z-index: 1; } paper-item-body { text-align: left; } paper-material { padding: 8px 8px; margin: auto; margin-top: 16px; margin-bottom: 16px; max-width: 300px; box-sizing: border-box; display: inline-block; width: 90%; text-align: center; @apply(--total-price-styles); } #tabelize { display: table-cell; } #proceedToCartButton { margin: 10px auto 10px auto; } iron-icon, #boldColoredMoney { color: var(--darker-alt-accent-color); } iron-icon#cart { width: 35px; height: 35px; } h3 { color: inherit; } </style> <template> <firebase-document path="/categories" data="{{categories}}"> </firebase-document> <firebase-document path="/stores/[[storeId]]/stock" data="{{data}}"> </firebase-document> <!--<div id="grid">--> <paper-material id="tabelize" elevation="1" animated class$="[[passedDownClass]]"> <paper-menu><template is="dom-repeat" items="[[getObjectValues(categories)]]"> <paper-submenu disabled="[[emptySubCart(item, data, quantities)]]"> <paper-icon-item class="menu-trigger" disabled="[[shouldDisable(item, data, quantities)]]"> <iron-icon icon="my-icons:tag" item-icon></iron-icon> <paper-item-body><div><h3>[[capitalize(item)]]<template is="dom-if" if="[[notStore(store)]]"></template></h3></div></paper-item-body> <template is="dom-if" if="[[store]]"> <div><h3><b>[[getCategoryTotalQuanta(item, data, quantities)]]</b></h3></div> </template> <template is="dom-if" if="[[notStore(store)]]"> <div><h3><b>[[getCategoryTotal(item, data, quantities)]]</b></h3></div> </template> </paper-icon-item> <paper-menu class="menu-content" selected="0"> <template is="dom-repeat" items="[[getSubCart(item, data, quantities)]]"> <paper-icon-item> <iron-icon icon="my-icons:shopping-basket" item-icon></iron-icon> <paper-item-body two-line> <div>[[capitalize(item.id)]]</div> <div secondary>[[item.quanta]] units in Cart</div> </paper-item-body> <div><h4><b>[[parseMoney(item.price)]]</b></h4></div> </paper-icon-item> </template> </paper-menu> </paper-submenu> </template></paper-menu> <template is="dom-if" if="[[store]]"> <a href="/cart" tabindex="-1"> <paper-button id="proceedToCartButton" raised> <iron-icon icon="my-icons:cart"></iron-icon> Proceed to Cart </paper-button> </a> </template> <template is="dom-if" if="[[notStoreTracking(store, tracking)]]"> <paper-material elevation="2" animated> <h2><iron-icon id="cart" icon="my-icons:cart"></iron-icon>Cart Total: <b id="boldColoredMoney">[[cartTotal]]</b></h2> </paper-material> </template> </paper-material> <!--<template is="dom-if" if="[[checkout]]">--> <!--Implement Credit Card Selector--> <!--</template>--> <!--</div>--> <!--<paper-textarea label="Total Price Data" value="[[parseJson(cart, checkout, storeId, userId, quantities, categories, data)]]"></paper-textarea>--> </template> <script> Polymer({ is: 'total-price', properties: { store: { type: Boolean, value: false }, cart: { type: Boolean, value: false }, checkout: { type: Boolean, value: false }, tracking: { type: Boolean, value: false }, cartTotal: { type: String, notify: true, computed: "getTotal(categories, data, quantities)" } }, notStore: function(s) { return !s; }, notStoreTracking: function(s, t) { return !s && !t; }, shouldDisable: function (item, data, quantities) { return this.getCategoryTotalQuanta(item, data, quantities) == 0; }, getSubCart: function (category, data, quantas) { log("================================GET SUB CART FUNCTION================================"); log("getSubCart: category"); log(category); log("getSubCart: quantas"); log(quantas); log("getSubCart: data"); log(data); log("!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object"); log(!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object); var rtn = []; if (!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object) return rtn; for (var i in data) if (data[i].category === category && isInt(quantas[this.storeId][data[i].id]) && parseInt(quantas[this.storeId][data[i].id]) > 0) rtn.push({"id": data[i].id, "quanta": quantas[this.storeId][data[i].id], "price": parseInt(quantas[this.storeId][data[i].id]) * parseFloat(data[i].price)}); log("Sub Cart Return"); log(rtn); log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); return rtn; }, emptySubCart: function (category, data, quantas) { return parseFloat(this.getCategoryTotal(category, data, quantas).substring(1)) <= 0; }, getTotal: function (categories, data, quantas) { return this.getCategoryTotal("all", data, quantas); }, getCategoryTotal: function (category, data, quantas) { log("=============================GET CATEGORY TOTAL FUNCTION============================="); log("getCategoryTotal: category"); log(category); log("getCategoryTotal: quantas"); log(quantas); log("getCategoryTotal: data"); log(data); log("getCategoryTotal: this.storeId"); log(this.storeId); log("!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object"); log(!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object); var total = 0; if (!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object) return parseMoney(total); for (var i in data) if (isInt(quantas[this.storeId][data[i].id]) && parseInt(quantas[this.storeId][data[i].id]) > 0 && (category === "all" || data[i].category == category)) total += data[i].price * quantas[this.storeId][data[i].id]; log("Category Total"); log(total); log("Parsed Category Total"); log(parseMoney(total)); log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); return parseMoney(total); }, getCategoryTotalQuanta: function (category, data, quantas) { log("=========================GET CATEGORY TOTAL QUANTA FUNCTION=========================="); log("getCategoryTotalQuanta: category"); log(category); log("getCategoryTotalQuanta: quantas"); log(quantas); log("getCategoryTotalQuanta: data"); log(data); log("!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object"); log(!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object); var total = 0; if (!this.storeId || !category || !quantas || !data || Object.keys(data).length === 0 && data.constructor === Object) return total; for (var i in data) if (isInt(quantas[this.storeId][data[i].id]) && parseInt(quantas[this.storeId][data[i].id]) > 0 && (category === "all" || data[i].category == category)) total += 1; //quantas[this.storeId][data[i].id]; log("Category Total Quanta"); log(total); log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); return total; }, capitalize: function (str) { return capitalize(str); }, getObjectKeys: function (items) { return getObjectKeys(items); }, getObjectValues: function (items) { return getObjectValues(items); }, isInt: function (value) { return isInt(value); }, flattenJson: function (data) { return flattenJson(data); }, parseMoney: function (money) { return parseMoney(money); }, parseJson: function () { var items = [].slice.apply(arguments); return items.reduce(function (acc, item) { return acc + "\nObject\n" + JSON.stringify(item, null, 4); }, ""); } }); function parseJson() { var items = [].slice.apply(arguments); return items.reduce(function (acc, item) { return acc + "\nObject\n" + JSON.stringify(item, null, 4); }, ""); } </script> </dom-module>
{'content_hash': '527eab6dbd411e5a5838c6418fa6b845', 'timestamp': '', 'source': 'github', 'line_count': 260, 'max_line_length': 180, 'avg_line_length': 45.78076923076923, 'alnum_prop': 0.4546752919432076, 'repo_name': 'Organic-Food-Store/ofs-client', 'id': '800a805d012c8299202c5db229dd9fcaca10b7ae', 'size': '11903', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/total-price.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '150804'}, {'name': 'JavaScript', 'bytes': '1803'}]}
module SugoiAliasesUpdator class AliasesParser attr_accessor :changed_labels def initialize(filepath) @native_lines = File.readlines(filepath) @changed_labels = [] end def add(target_email, to) check_labels!(to) to.each do |x| unless label_mails_hash[x].include?(target_email) label_mails_hash[x].push(target_email) @changed_labels << x end end render! end def rm(target_email, from) if ['ALL'] == from label_mails_hash.each do |label, emails| if emails.include?(target_email) label_mails_hash[label].delete(target_email) @changed_labels << label end end return render! end check_labels!(from) from.each do |label| if label_mails_hash[label].include?(target_email) label_mails_hash[label].delete(target_email) @changed_labels << label end end render! end def list(target_email) finded = [] label_mails_hash.each do |key, value| finded.push(key) if value.include?(target_email) end finded.join(',') end def render! new_lines = [] @native_lines.each do |line| line_paser = LineParser.new(line) if line_paser.is_aliaes_line && @changed_labels.include?(line_paser.label) line = "#{line_paser.label}:#{line_paser.margin}#{label_mails_hash[line_paser.label].join(", ")}\n" end new_lines << line end new_lines.join end private def label_mails_hash @label_mails_hash ||= {}.tap do |h| @native_lines.each do |line| line_paser = LineParser.new(line) if line_paser.is_aliaes_line emails_line = line_paser.emails_line h[line_paser.label] = line_paser.emails_line.split(/\,\s?/) end end end end def check_labels!(inputed_labels) unknown_labels = inputed_labels - label_mails_hash.keys if unknown_labels.size > 0 raise("unknown labels #{unknown_labels.join(', ')}") end end end end
{'content_hash': '17bfb98a93e2d98e7a20c949f78886f5', 'timestamp': '', 'source': 'github', 'line_count': 84, 'max_line_length': 109, 'avg_line_length': 25.761904761904763, 'alnum_prop': 0.5702402957486137, 'repo_name': 'jiikko/sugoi-aliases-updator', 'id': '3e2bce697dde6b919803443ccbaf90548e31f8c8', 'size': '2164', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/sugoi_aliases_updator/aliases_parser.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '11611'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'e002c4f3ca72e218fdb50f24bb14043c', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '2b0f3a632a2f0742fb00e7dc18d6d219b18cd5b0', 'size': '187', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Coffea/Coffea mauritiana/ Syn. Coffea nossikumbaensis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
/*! * numbro.js language configuration * language : German * locale: Austria * author : Tim McIntosh (StayinFront NZ) */ (function () { 'use strict'; var language = { langLocaleCode: 'de-AT', cultureCode: 'de-AT', delimiters: { thousands: ' ', decimal: ',' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function () { return '.'; }, currency: { symbol: '€', code: 'EUR' } }; // Node if (typeof module !== 'undefined' && module.exports) { module.exports = language; } // Browser if (typeof window !== 'undefined' && window.numbro && window.numbro.culture) { window.numbro.culture(language.cultureCode, language); } }.call(typeof window === 'undefined' ? this : window));
{'content_hash': '69bc1a66bc125bcc0328fce4231093cb', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 82, 'avg_line_length': 23.975, 'alnum_prop': 0.4848800834202294, 'repo_name': 'foretagsplatsen/numbro', 'id': '3729988027cf6c901648dbde35d6e33be34c0608', 'size': '961', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'languages/de-AT.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '339793'}]}
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Leptogium adpressum Nyl. ### Remarks null
{'content_hash': '0b3aed3a0e419b63e2997fdf8bc57032', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 11.846153846153847, 'alnum_prop': 0.7142857142857143, 'repo_name': 'mdoering/backbone', 'id': '5c90742ece71b053fd0fc6a4d545d2caec8eb23b', 'size': '202', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Collemataceae/Leptogium/Leptogium adpressum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
/** * Loads the update static resource page * * @class MODx.page.UpdateStatic * @extends MODx.Component * @param {Object} config An object of config properties * @xtype modx-page-static-update */ MODx.page.UpdateStatic = function(config) { config = config || {record:{}}; config.record = config.record || {}; Ext.apply(config.record,{ 'parent-cmb': config.record['parent'] }); Ext.applyIf(config,{ url: MODx.config.connectors_url+'resource/index.php' ,which_editor: 'none' ,formpanel: 'modx-panel-resource' ,id: 'modx-page-update-resource' ,action: 'update' ,actions: { 'new': MODx.action['resource/create'] ,edit: MODx.action['resource/update'] ,preview: MODx.action['resource/preview'] ,cancel: MODx.action['welcome'] } ,components: [{ xtype: 'modx-panel-static' ,renderTo: 'modx-panel-static-div' ,resource: config.resource ,record: config.record || {} ,publish_document: config.publish_document ,access_permissions: config.access_permissions ,show_tvs: config.show_tvs ,url: config.url }] ,loadStay: true ,buttons: this.getButtons(config) }); MODx.page.UpdateStatic.superclass.constructor.call(this,config); }; Ext.extend(MODx.page.UpdateStatic,MODx.Component,{ preview: function() { window.open(this.config.preview_url); return false; } ,duplicateResource: function(btn,e) { MODx.msg.confirm({ text: _('resource_duplicate_confirm') ,url: MODx.config.connectors_url+'resource/index.php' ,params: { action: 'duplicate' ,id: this.config.resource } ,listeners: { success: {fn:function(r) { MODx.loadPage(MODx.action['resource/update'], 'id='+r.object.id); },scope:this} } }); } ,deleteResource: function(btn,e) { MODx.msg.confirm({ text: _('resource_delete_confirm') ,url: MODx.config.connectors_url+'resource/index.php' ,params: { action: 'delete' ,id: this.config.resource } ,listeners: { success: {fn:function(r) { MODx.loadPage(MODx.action['resource/update'], 'id='+r.object.id); },scope:this} } }); } ,cancel: function(btn,e) { var fp = Ext.getCmp(this.config.formpanel); if (fp && fp.isDirty()) { Ext.Msg.confirm(_('warning'),_('resource_cancel_dirty_confirm'),function(e) { if (e == 'yes') { MODx.releaseLock(MODx.request.id); MODx.sleep(400); MODx.loadPage(MODx.action['welcome']); } },this); } else { MODx.releaseLock(MODx.request.id); MODx.loadPage(MODx.action['welcome']); } } ,getButtons: function(cfg) { var btns = []; if (cfg.canSave == 1) { btns.push({ process: 'update' ,id: 'modx-abtn-save' ,text: _('save') ,method: 'remote' ,checkDirty: cfg.richtext || MODx.request.reload ? false : true ,keys: [{ key: MODx.config.keymap_save || 's' ,ctrl: true }] }); btns.push('-'); } else { btns.push({ text: cfg.lockedText || _('locked') ,handler: Ext.emptyFn ,disabled: true ,id: 'modx-abtn-locked' }); btns.push('-'); } if (cfg.canCreate == 1) { btns.push({ process: 'duplicate' ,text: _('duplicate') ,handler: this.duplicateResource ,scope:this ,id: 'modx-abtn-duplicate' }); btns.push('-'); } if (cfg.canDelete == 1 && !cfg.locked) { btns.push({ process: 'delete' ,text: _('delete') ,handler: this.deleteResource ,scope:this ,id: 'modx-abtn-delete' }); btns.push('-'); } btns.push({ process: 'preview' ,text: _('view') ,handler: this.preview ,scope: this ,id: 'modx-abtn-preview' }); btns.push('-'); btns.push({ process: 'cancel' ,text: _('cancel') ,handler: this.cancel ,scope: this ,id: 'modx-abtn-cancel' }); btns.push('-'); btns.push({ text: _('help_ex') ,handler: MODx.loadHelpPane ,id: 'modx-abtn-help' }); return btns; } }); Ext.reg('modx-page-static-update',MODx.page.UpdateStatic);
{'content_hash': '278ff7215a5b13625669d836642a1d84', 'timestamp': '', 'source': 'github', 'line_count': 164, 'max_line_length': 89, 'avg_line_length': 31.49390243902439, 'alnum_prop': 0.4681510164569216, 'repo_name': 'timsvoice/great_green_sources', 'id': '8aa3400f26c5e0d8bbbc5ddedd12cb0dce26d512', 'size': '5165', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'manager/assets/modext/sections/resource/static/update.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '718852'}, {'name': 'Java', 'bytes': '11903'}, {'name': 'JavaScript', 'bytes': '1641637'}, {'name': 'PHP', 'bytes': '13315560'}, {'name': 'Perl', 'bytes': '25276'}]}
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Iterator component to be used to display a list of entities, using a single field * * @example Display all the books by the current author * <ReferenceManyField reference="books" target="author_id"> * <SingleFieldList> * <ChipField source="title" /> * </SingleFieldList> * </ReferenceManyField> */ var SingleFieldList = function SingleFieldList(_ref) { var ids = _ref.ids, data = _ref.data, resource = _ref.resource, basePath = _ref.basePath, children = _ref.children; return _react2.default.createElement( 'div', { style: { display: 'flex', flexWrap: 'wrap' } }, ids.map(function (id) { return _react2.default.cloneElement(children, { key: id, record: data[id], resource: resource, basePath: basePath }); }) ); }; SingleFieldList.propTypes = { children: _react.PropTypes.element.isRequired }; exports.default = SingleFieldList; module.exports = exports['default'];
{'content_hash': '89991f5b650692351a5cde081b2bdbca', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 95, 'avg_line_length': 27.604166666666668, 'alnum_prop': 0.6083018867924528, 'repo_name': 'epwqice/admin-on-rest-old-man', 'id': '790aa079ecac628c1979182cdadfca4b2862fd12', 'size': '1325', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/mui/list/SingleFieldList.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '698283'}, {'name': 'Makefile', 'bytes': '1207'}, {'name': 'PowerShell', 'bytes': '4033'}]}
@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
{'content_hash': 'feca7399da0e346d03627873da4da13d', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 60, 'avg_line_length': 23.2, 'alnum_prop': 0.7931034482758621, 'repo_name': 'I-SYST/iOS', 'id': '1e4c2946bd5df26d98b8f99e18e65670911444e8', 'size': '272', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'UartBle/UartBle/AppDelegate.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Objective-C', 'bytes': '56928'}, {'name': 'Swift', 'bytes': '20327'}]}
import {Injectable} from "angular2/core"; import {CONTACTS} from "./mocks/data"; import {Contact} from "./contact"; @Injectable() export class ContactService{ getContacts(){ return Promise.resolve(CONTACTS); } getContactById(id){ return Promise.resolve(CONTACTS.find(x=>x.id == id)); } insertContact(contact:Contact){ Promise.resolve(CONTACTS) .then( (contacts:Contact[])=> contacts.push(contact) ); } }
{'content_hash': '361e940c1a8390c20d8d5780c6a3f8b6', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 57, 'avg_line_length': 23.63157894736842, 'alnum_prop': 0.6636971046770601, 'repo_name': 'Pishtiko/ANGULAR-2-TEMPLATE', 'id': 'e40d690a267c38f73ef77c35c633407fac04bee3', 'size': '590', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dev/contacts/contact.service.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1227'}, {'name': 'HTML', 'bytes': '4933'}, {'name': 'JavaScript', 'bytes': '14954'}, {'name': 'TypeScript', 'bytes': '8483'}]}
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/web_applications/web_app_sync_bridge.h" #include <memory> #include <vector> #include "base/barrier_closure.h" #include "base/bind.h" #include "base/containers/contains.h" #include "base/containers/cxx20_erase.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/bind.h" #include "chrome/browser/web_applications/os_integration/os_integration_manager.h" #include "chrome/browser/web_applications/test/fake_web_app_database_factory.h" #include "chrome/browser/web_applications/test/fake_web_app_provider.h" #include "chrome/browser/web_applications/test/web_app_sync_test_utils.h" #include "chrome/browser/web_applications/test/web_app_test.h" #include "chrome/browser/web_applications/test/web_app_test_observers.h" #include "chrome/browser/web_applications/test/web_app_test_utils.h" #include "chrome/browser/web_applications/user_display_mode.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/browser/web_applications/web_app_command_manager.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_install_manager.h" #include "chrome/browser/web_applications/web_app_registry_update.h" #include "chrome/browser/web_applications/web_app_utils.h" #include "components/sync/model/data_batch.h" #include "components/sync/model/entity_change.h" #include "components/sync/protocol/web_app_specifics.pb.h" #include "components/sync/test/mock_model_type_change_processor.h" #include "components/webapps/browser/install_result_code.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkColor.h" namespace web_app { namespace { using testing::_; using AppsList = std::vector<std::unique_ptr<WebApp>>; void RemoveWebAppFromAppsList(AppsList* apps_list, const AppId& app_id) { base::EraseIf(*apps_list, [app_id](const std::unique_ptr<WebApp>& app) { return app->app_id() == app_id; }); } bool IsSyncDataEqualIfApplied(const WebApp& expected_app, std::unique_ptr<WebApp> app_to_apply_sync_data, const syncer::EntityData& entity_data) { if (!entity_data.specifics.has_web_app()) return false; const GURL sync_start_url(entity_data.specifics.web_app().start_url()); if (expected_app.app_id() != GenerateAppId(/*manifest_id=*/absl::nullopt, sync_start_url)) return false; // ApplySyncDataToApp enforces kSync source on |app_to_apply_sync_data|. ApplySyncDataToApp(entity_data.specifics.web_app(), app_to_apply_sync_data.get()); app_to_apply_sync_data->SetName(entity_data.name); return expected_app == *app_to_apply_sync_data; } bool IsSyncDataEqual(const WebApp& expected_app, const syncer::EntityData& entity_data) { auto app_to_apply_sync_data = std::make_unique<WebApp>(expected_app.app_id()); return IsSyncDataEqualIfApplied( expected_app, std::move(app_to_apply_sync_data), entity_data); } bool RegistryContainsSyncDataBatchChanges( const Registry& registry, std::unique_ptr<syncer::DataBatch> data_batch) { if (!data_batch || !data_batch->HasNext()) return registry.empty(); while (data_batch->HasNext()) { syncer::KeyAndData key_and_data = data_batch->Next(); auto web_app_iter = registry.find(key_and_data.first); if (web_app_iter == registry.end()) { LOG(ERROR) << "App not found in registry: " << key_and_data.first; return false; } if (!IsSyncDataEqual(*web_app_iter->second, *key_and_data.second)) return false; } return true; } std::unique_ptr<WebApp> CreateWebAppWithSyncOnlyFields(const std::string& url) { const GURL start_url(url); const AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, start_url); auto web_app = std::make_unique<WebApp>(app_id); web_app->AddSource(WebAppManagement::kSync); web_app->SetStartUrl(start_url); web_app->SetName("Name"); web_app->SetUserDisplayMode(UserDisplayMode::kStandalone); return web_app; } AppsList CreateAppsList(const std::string& base_url, int num_apps) { AppsList apps_list; for (int i = 0; i < num_apps; ++i) { apps_list.push_back( CreateWebAppWithSyncOnlyFields(base_url + base::NumberToString(i))); } return apps_list; } void InsertAppIntoRegistry(Registry* registry, std::unique_ptr<WebApp> app) { AppId app_id = app->app_id(); ASSERT_FALSE(base::Contains(*registry, app_id)); registry->emplace(std::move(app_id), std::move(app)); } void InsertAppsListIntoRegistry(Registry* registry, const AppsList& apps_list) { for (const std::unique_ptr<WebApp>& app : apps_list) registry->emplace(app->app_id(), std::make_unique<WebApp>(*app)); } void ConvertAppToEntityChange(const WebApp& app, syncer::EntityChange::ChangeType change_type, syncer::EntityChangeList* sync_data_list) { std::unique_ptr<syncer::EntityChange> entity_change; switch (change_type) { case syncer::EntityChange::ACTION_ADD: entity_change = syncer::EntityChange::CreateAdd( app.app_id(), std::move(*CreateSyncEntityData(app))); break; case syncer::EntityChange::ACTION_UPDATE: entity_change = syncer::EntityChange::CreateUpdate( app.app_id(), std::move(*CreateSyncEntityData(app))); break; case syncer::EntityChange::ACTION_DELETE: entity_change = syncer::EntityChange::CreateDelete(app.app_id()); break; } sync_data_list->push_back(std::move(entity_change)); } void ConvertAppsListToEntityChangeList( const AppsList& apps_list, syncer::EntityChangeList* sync_data_list) { for (auto& app : apps_list) { ConvertAppToEntityChange(*app, syncer::EntityChange::ACTION_ADD, sync_data_list); } } // Returns true if the app converted from entity_data exists in the apps_list. bool RemoveEntityDataAppFromAppsList(const std::string& storage_key, const syncer::EntityData& entity_data, AppsList* apps_list) { for (auto& app : *apps_list) { if (app->app_id() == storage_key) { if (!IsSyncDataEqual(*app, entity_data)) return false; RemoveWebAppFromAppsList(apps_list, storage_key); return true; } } return false; } void RunCallbacksOnInstall( const std::vector<WebApp*>& apps, const WebAppInstallManager::RepeatingInstallCallback& callback, webapps::InstallResultCode code) { for (WebApp* app : apps) callback.Run(app->app_id(), code); } } // namespace class WebAppSyncBridgeTest : public WebAppTest { public: void SetUp() override { WebAppTest::SetUp(); command_manager_ = std::make_unique<WebAppCommandManager>( profile(), FakeWebAppProvider::Get(profile())); install_manager_ = std::make_unique<WebAppInstallManager>(profile()); registrar_mutable_ = std::make_unique<WebAppRegistrarMutable>(profile()); sync_bridge_ = std::make_unique<WebAppSyncBridge>( registrar_mutable_.get(), mock_processor_.CreateForwardingProcessor()); database_factory_ = std::make_unique<FakeWebAppDatabaseFactory>(); sync_bridge_->SetSubsystems(database_factory_.get(), install_manager_.get(), command_manager_.get()); install_manager_->Start(); ON_CALL(mock_processor_, IsTrackingMetadata()) .WillByDefault(testing::Return(true)); } void TearDown() override { DestroyManagers(); WebAppTest::TearDown(); } void InitSyncBridge() { base::RunLoop loop; sync_bridge_->Init(loop.QuitClosure()); loop.Run(); } void InitSyncBridgeFromAppList(const AppsList& apps_list) { Registry registry; InsertAppsListIntoRegistry(&registry, apps_list); database_factory().WriteRegistry(registry); InitSyncBridge(); } void MergeSyncData(const AppsList& merged_apps) { syncer::EntityChangeList entity_data_list; ConvertAppsListToEntityChangeList(merged_apps, &entity_data_list); EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); sync_bridge().MergeSyncData(sync_bridge().CreateMetadataChangeList(), std::move(entity_data_list)); } bool IsDatabaseRegistryEqualToRegistrar() { Registry registry = database_factory().ReadRegistry(); return IsRegistryEqual(registrar_registry(), registry); } void SetSyncInstallDelegateFailureIfCalled() { install_manager().SetInstallWebAppsAfterSyncDelegateForTesting( base::BindLambdaForTesting( [&](std::vector<WebApp*> apps_to_install, WebAppInstallManager::RepeatingInstallCallback callback) { ADD_FAILURE(); })); install_manager().SetUninstallFromSyncDelegateForTesting( base::BindLambdaForTesting( [&](const std::vector<AppId>& apps_to_uninstall, WebAppInstallManager::RepeatingUninstallCallback callback) { ADD_FAILURE(); })); } void CommitUpdate(std::unique_ptr<WebAppRegistryUpdate> update) { base::RunLoop run_loop; sync_bridge().CommitUpdate( std::move(update), base::BindLambdaForTesting([&run_loop](bool success) { ASSERT_TRUE(success); run_loop.Quit(); })); run_loop.Run(); } protected: void DestroyManagers() { if (command_manager_) { command_manager_->Shutdown(); command_manager_.reset(); } if (install_manager_) { install_manager_.reset(); } if (registrar_mutable_) { registrar_mutable_.reset(); } if (sync_bridge_) { sync_bridge_.reset(); } if (database_factory_) { database_factory_.reset(); } } syncer::MockModelTypeChangeProcessor& processor() { return mock_processor_; } FakeWebAppDatabaseFactory& database_factory() { return *database_factory_; } WebAppRegistrar& registrar() { return *registrar_mutable_; } WebAppSyncBridge& sync_bridge() { return *sync_bridge_; } WebAppInstallManager& install_manager() { return *install_manager_; } Registry& registrar_registry() { return registrar_mutable_->registry(); } private: std::unique_ptr<WebAppCommandManager> command_manager_; std::unique_ptr<WebAppInstallManager> install_manager_; std::unique_ptr<WebAppRegistrarMutable> registrar_mutable_; std::unique_ptr<WebAppSyncBridge> sync_bridge_; std::unique_ptr<FakeWebAppDatabaseFactory> database_factory_; testing::NiceMock<syncer::MockModelTypeChangeProcessor> mock_processor_; }; // Tests that the WebAppSyncBridge correctly reports data from the // WebAppDatabase. TEST_F(WebAppSyncBridgeTest, GetData) { Registry registry; std::unique_ptr<WebApp> synced_app1 = CreateWebAppWithSyncOnlyFields("https://example.com/app1/"); { WebApp::SyncFallbackData sync_fallback_data; sync_fallback_data.name = "Sync Name"; sync_fallback_data.theme_color = SK_ColorCYAN; synced_app1->SetSyncFallbackData(std::move(sync_fallback_data)); } InsertAppIntoRegistry(&registry, std::move(synced_app1)); std::unique_ptr<WebApp> synced_app2 = CreateWebAppWithSyncOnlyFields("https://example.com/app2/"); // sync_fallback_data is empty for this app. InsertAppIntoRegistry(&registry, std::move(synced_app2)); std::unique_ptr<WebApp> policy_app = test::CreateWebApp( GURL("https://example.org/"), WebAppManagement::kPolicy); InsertAppIntoRegistry(&registry, std::move(policy_app)); database_factory().WriteRegistry(registry); EXPECT_CALL(processor(), ModelReadyToSync(_)).Times(1); InitSyncBridge(); { WebAppSyncBridge::StorageKeyList storage_keys; // Add an unknown key to test this is handled gracefully. storage_keys.push_back("unknown"); for (const Registry::value_type& id_and_web_app : registry) storage_keys.push_back(id_and_web_app.first); base::RunLoop run_loop; sync_bridge().GetData( std::move(storage_keys), base::BindLambdaForTesting( [&](std::unique_ptr<syncer::DataBatch> data_batch) { EXPECT_TRUE(RegistryContainsSyncDataBatchChanges( registry, std::move(data_batch))); run_loop.Quit(); })); run_loop.Run(); } { base::RunLoop run_loop; sync_bridge().GetAllDataForDebugging(base::BindLambdaForTesting( [&](std::unique_ptr<syncer::DataBatch> data_batch) { EXPECT_TRUE(RegistryContainsSyncDataBatchChanges( registry, std::move(data_batch))); run_loop.Quit(); })); run_loop.Run(); } } // Tests that the client & storage tags are correct for entity data. TEST_F(WebAppSyncBridgeTest, Identities) { std::unique_ptr<WebApp> app = CreateWebAppWithSyncOnlyFields("https://example.com/"); std::unique_ptr<syncer::EntityData> entity_data = CreateSyncEntityData(*app); EXPECT_EQ(app->app_id(), sync_bridge().GetClientTag(*entity_data)); EXPECT_EQ(app->app_id(), sync_bridge().GetStorageKey(*entity_data)); } // Test that a empty local data results in no changes sent to the sync system. TEST_F(WebAppSyncBridgeTest, MergeSyncData_LocalSetAndServerSetAreEmpty) { InitSyncBridge(); syncer::EntityChangeList sync_data_list; EXPECT_CALL(processor(), Put(_, _, _)).Times(0); sync_bridge().MergeSyncData(sync_bridge().CreateMetadataChangeList(), std::move(sync_data_list)); } TEST_F(WebAppSyncBridgeTest, MergeSyncData_LocalSetEqualsServerSet) { AppsList apps = CreateAppsList("https://example.com/", 10); Registry registry; InsertAppsListIntoRegistry(&registry, apps); database_factory().WriteRegistry(registry); InitSyncBridge(); // The incoming list of apps from the sync server. syncer::EntityChangeList sync_data_list; ConvertAppsListToEntityChangeList(apps, &sync_data_list); // The local app state is the same as the server state, so no changes should // be sent. EXPECT_CALL(processor(), Put(_, _, _)).Times(0); sync_bridge().MergeSyncData(sync_bridge().CreateMetadataChangeList(), std::move(sync_data_list)); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, MergeSyncData_LocalSetGreaterThanServerSet) { AppsList local_and_server_apps = CreateAppsList("https://example.com/", 10); AppsList expected_local_apps_to_upload = CreateAppsList("https://example.org/", 10); Registry registry; InsertAppsListIntoRegistry(&registry, local_and_server_apps); InsertAppsListIntoRegistry(&registry, expected_local_apps_to_upload); database_factory().WriteRegistry(registry); InitSyncBridge(); auto metadata_change_list = sync_bridge().CreateMetadataChangeList(); syncer::MetadataChangeList* metadata_ptr = metadata_change_list.get(); syncer::EntityChangeList sync_data_list; ConvertAppsListToEntityChangeList(local_and_server_apps, &sync_data_list); // MergeSyncData below should send |expected_local_apps_to_upload| to the // processor() to upload to USS. base::RunLoop run_loop; ON_CALL(processor(), Put(_, _, _)) .WillByDefault([&](const std::string& storage_key, std::unique_ptr<syncer::EntityData> entity_data, syncer::MetadataChangeList* metadata) { EXPECT_EQ(metadata_ptr, metadata); EXPECT_TRUE(RemoveEntityDataAppFromAppsList( storage_key, *entity_data, &expected_local_apps_to_upload)); if (expected_local_apps_to_upload.empty()) run_loop.Quit(); }); sync_bridge().MergeSyncData(std::move(metadata_change_list), std::move(sync_data_list)); run_loop.Run(); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, MergeSyncData_LocalSetLessThanServerSet) { AppsList local_and_server_apps = CreateAppsList("https://example.com/", 10); AppsList expected_apps_to_install = CreateAppsList("https://example.org/", 10); // These fields are not synced, these are just expected values. for (std::unique_ptr<WebApp>& expected_app_to_install : expected_apps_to_install) { expected_app_to_install->SetIsLocallyInstalled( AreAppsLocallyInstalledBySync()); expected_app_to_install->SetIsFromSyncAndPendingInstallation(true); } Registry registry; InsertAppsListIntoRegistry(&registry, local_and_server_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); syncer::EntityChangeList sync_data_list; ConvertAppsListToEntityChangeList(expected_apps_to_install, &sync_data_list); ConvertAppsListToEntityChangeList(local_and_server_apps, &sync_data_list); EXPECT_CALL(processor(), Put(_, _, _)).Times(0); base::RunLoop run_loop; // This is called after apps are installed from sync in MergeSyncData() below. install_manager().SetInstallWebAppsAfterSyncDelegateForTesting( base::BindLambdaForTesting( [&](std::vector<WebApp*> apps_to_install, WebAppInstallManager::RepeatingInstallCallback callback) { for (WebApp* app_to_install : apps_to_install) { // The app must be registered. EXPECT_TRUE(registrar().GetAppById(app_to_install->app_id())); // Add the app copy to the expected registry. registry.emplace(app_to_install->app_id(), std::make_unique<WebApp>(*app_to_install)); // Find the app in expected_apps_to_install set and remove the // entry. bool found = false; for (const std::unique_ptr<WebApp>& expected_app_to_install : expected_apps_to_install) { if (expected_app_to_install->app_id() == app_to_install->app_id()) { EXPECT_EQ(*expected_app_to_install, *app_to_install); RemoveWebAppFromAppsList(&expected_apps_to_install, expected_app_to_install->app_id()); found = true; break; } } EXPECT_TRUE(found); } EXPECT_TRUE(expected_apps_to_install.empty()); RunCallbacksOnInstall( apps_to_install, callback, webapps::InstallResultCode::kSuccessNewInstall); run_loop.Quit(); })); sync_bridge().MergeSyncData(sync_bridge().CreateMetadataChangeList(), std::move(sync_data_list)); run_loop.Run(); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_EmptyEntityChanges) { AppsList merged_apps = CreateAppsList("https://example.com/", 10); Registry registry; InsertAppsListIntoRegistry(&registry, merged_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); MergeSyncData(merged_apps); syncer::EntityChangeList entity_changes; EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); SetSyncInstallDelegateFailureIfCalled(); sync_bridge().ApplySyncChanges(sync_bridge().CreateMetadataChangeList(), std::move(entity_changes)); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_AddUpdateDelete) { // 20 initial apps with DisplayMode::kStandalone user display mode. AppsList merged_apps = CreateAppsList("https://example.com/", 20); Registry registry; InsertAppsListIntoRegistry(&registry, merged_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); MergeSyncData(merged_apps); syncer::EntityChangeList entity_changes; for (std::unique_ptr<WebApp>& app_to_add : CreateAppsList("https://example.org/", 10)) { app_to_add->SetIsLocallyInstalled(AreAppsLocallyInstalledBySync()); app_to_add->SetIsFromSyncAndPendingInstallation(true); ConvertAppToEntityChange(*app_to_add, syncer::EntityChange::ACTION_ADD, &entity_changes); } // Update first 5 initial apps. for (int i = 0; i < 5; ++i) { auto app_to_update = std::make_unique<WebApp>(*merged_apps[i]); // Update user display mode field. app_to_update->SetUserDisplayMode(UserDisplayMode::kBrowser); ConvertAppToEntityChange( *app_to_update, syncer::EntityChange::ACTION_UPDATE, &entity_changes); // Override the app in the expected registry. registry[app_to_update->app_id()] = std::move(app_to_update); } // Delete next 5 initial apps. Leave the rest unchanged. for (int i = 5; i < 10; ++i) { const WebApp& app_to_delete = *merged_apps[i]; ConvertAppToEntityChange(app_to_delete, syncer::EntityChange::ACTION_DELETE, &entity_changes); } // There should be no changes sent to USS in the next ApplySyncChanges() // operation. EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); base::RunLoop run_loop; base::RepeatingClosure barrier_closure = base::BarrierClosure(2, run_loop.QuitClosure()); install_manager().SetInstallWebAppsAfterSyncDelegateForTesting( base::BindLambdaForTesting( [&](std::vector<WebApp*> apps_to_install, WebAppInstallManager::RepeatingInstallCallback callback) { for (WebApp* app_to_install : apps_to_install) { // The app must be registered. EXPECT_TRUE(registrar().GetAppById(app_to_install->app_id())); // Add the app copy to the expected registry. registry.emplace(app_to_install->app_id(), std::make_unique<WebApp>(*app_to_install)); } RunCallbacksOnInstall( apps_to_install, callback, webapps::InstallResultCode::kSuccessNewInstall); barrier_closure.Run(); })); install_manager().SetUninstallFromSyncDelegateForTesting( base::BindLambdaForTesting( [&](const std::vector<AppId>& apps_to_uninstall, WebAppInstallManager::RepeatingUninstallCallback callback) { EXPECT_EQ(5ul, apps_to_uninstall.size()); for (const AppId& app_to_uninstall : apps_to_uninstall) { // The app must be registered. const WebApp* app = registrar().GetAppById(app_to_uninstall); // Sync expects that the apps are deleted by the delegate. EXPECT_TRUE(app); EXPECT_TRUE(app->is_uninstalling()); EXPECT_TRUE(app->GetSources().none()); registry.erase(app_to_uninstall); { ScopedRegistryUpdate update(&sync_bridge()); update->DeleteApp(app_to_uninstall); } callback.Run(app_to_uninstall, webapps::UninstallResultCode::kSuccess); } barrier_closure.Run(); })); sync_bridge().ApplySyncChanges(sync_bridge().CreateMetadataChangeList(), std::move(entity_changes)); run_loop.Run(); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_DeleteHappensExternally) { // 5 initial apps. AppsList merged_apps = CreateAppsList("https://example.com/", 5); Registry registry; InsertAppsListIntoRegistry(&registry, merged_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); MergeSyncData(merged_apps); syncer::EntityChangeList entity_changes; // Delete next 5 initial apps. Leave the rest unchanged. for (int i = 0; i < 5; ++i) { const WebApp& app_to_delete = *merged_apps[i]; ConvertAppToEntityChange(app_to_delete, syncer::EntityChange::ACTION_DELETE, &entity_changes); } // There should be no changes sent to USS in the next ApplySyncChanges() // operation. EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); base::RunLoop run_loop; std::vector<AppId> to_uninstall; WebAppInstallManager::RepeatingUninstallCallback uninstall_complete_callback; install_manager().SetUninstallFromSyncDelegateForTesting( base::BindLambdaForTesting( [&](const std::vector<AppId>& apps_to_uninstall, WebAppInstallManager::RepeatingUninstallCallback callback) { to_uninstall = apps_to_uninstall; uninstall_complete_callback = callback; run_loop.Quit(); })); sync_bridge().ApplySyncChanges(sync_bridge().CreateMetadataChangeList(), std::move(entity_changes)); run_loop.Run(); EXPECT_EQ(5ul, to_uninstall.size()); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); for (const AppId& app_to_uninstall : to_uninstall) { const WebApp* app = registrar().GetAppById(app_to_uninstall); EXPECT_TRUE(app); EXPECT_TRUE(app->is_uninstalling()); EXPECT_TRUE(app->GetSources().none()); } } TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_UpdateOnly) { AppsList merged_apps = CreateAppsList("https://example.com/", 10); Registry registry; InsertAppsListIntoRegistry(&registry, merged_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); MergeSyncData(merged_apps); syncer::EntityChangeList entity_changes; // Update last 5 initial apps. for (int i = 5; i < 10; ++i) { auto app_to_update = std::make_unique<WebApp>(*merged_apps[i]); app_to_update->SetUserDisplayMode(UserDisplayMode::kStandalone); WebApp::SyncFallbackData sync_fallback_data; sync_fallback_data.name = "Sync Name"; sync_fallback_data.theme_color = SK_ColorYELLOW; app_to_update->SetSyncFallbackData(std::move(sync_fallback_data)); ConvertAppToEntityChange( *app_to_update, syncer::EntityChange::ACTION_UPDATE, &entity_changes); // Override the app in the expected registry. registry[app_to_update->app_id()] = std::move(app_to_update); } EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); // No installs or uninstalls are made here, only app updates. SetSyncInstallDelegateFailureIfCalled(); sync_bridge().ApplySyncChanges(sync_bridge().CreateMetadataChangeList(), std::move(entity_changes)); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_AddSyncAppsWithOverlappingPolicyApps) { AppsList policy_apps; for (int i = 0; i < 10; ++i) { std::unique_ptr<WebApp> policy_app = test::CreateWebApp( GURL("https://example.com/" + base::NumberToString(i)), WebAppManagement::kPolicy); policy_apps.push_back(std::move(policy_app)); } Registry registry; InsertAppsListIntoRegistry(&registry, policy_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); syncer::EntityChangeList entity_changes; // Install 5 kSync apps over existing kPolicy apps. Leave the rest unchanged. for (int i = 0; i < 5; ++i) { const WebApp& app_to_install = *policy_apps[i]; ConvertAppToEntityChange(app_to_install, syncer::EntityChange::ACTION_ADD, &entity_changes); } EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); SetSyncInstallDelegateFailureIfCalled(); sync_bridge().ApplySyncChanges(sync_bridge().CreateMetadataChangeList(), std::move(entity_changes)); // Modify the registry with the results that we expect. for (int i = 0; i < 5; ++i) { std::unique_ptr<WebApp>& expected_sync_and_policy_app = registry[policy_apps[i]->app_id()]; expected_sync_and_policy_app->AddSource(WebAppManagement::kSync); } EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_UpdateSyncAppsWithOverlappingPolicyApps) { AppsList policy_and_sync_apps; for (int i = 0; i < 10; ++i) { std::unique_ptr<WebApp> policy_and_sync_app = test::CreateWebApp( GURL("https://example.com/" + base::NumberToString(i))); policy_and_sync_app->AddSource(WebAppManagement::kPolicy); policy_and_sync_app->AddSource(WebAppManagement::kSync); policy_and_sync_apps.push_back(std::move(policy_and_sync_app)); } Registry registry; InsertAppsListIntoRegistry(&registry, policy_and_sync_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); MergeSyncData(policy_and_sync_apps); syncer::EntityChangeList entity_changes; // Update first 5 kSync apps which are shared with kPolicy. Leave the rest // unchanged. AppsList apps_to_update; for (int i = 0; i < 5; ++i) { auto app_to_update = std::make_unique<WebApp>(*policy_and_sync_apps[i]); app_to_update->SetUserDisplayMode(UserDisplayMode::kBrowser); WebApp::SyncFallbackData sync_fallback_data; sync_fallback_data.name = "Updated Sync Name"; sync_fallback_data.theme_color = SK_ColorWHITE; app_to_update->SetSyncFallbackData(std::move(sync_fallback_data)); ConvertAppToEntityChange( *app_to_update, syncer::EntityChange::ACTION_UPDATE, &entity_changes); apps_to_update.push_back(std::move(app_to_update)); } EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); SetSyncInstallDelegateFailureIfCalled(); sync_bridge().ApplySyncChanges(sync_bridge().CreateMetadataChangeList(), std::move(entity_changes)); // Modify the registry with the results that we expect. for (int i = 0; i < 5; ++i) registry[policy_and_sync_apps[i]->app_id()] = std::move(apps_to_update[i]); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } // Tests that if a policy app is installed, and that app is also in 'sync' and // is uninstalled through sync, then it should remain on the system as a policy // app. TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_DeleteSyncAppsWithOverlappingPolicyApps) { AppsList policy_and_sync_apps; for (int i = 0; i < 10; ++i) { std::unique_ptr<WebApp> policy_and_sync_app = test::CreateWebApp( GURL("https://example.com/" + base::NumberToString(i))); policy_and_sync_app->AddSource(WebAppManagement::kPolicy); policy_and_sync_app->AddSource(WebAppManagement::kSync); policy_and_sync_apps.push_back(std::move(policy_and_sync_app)); } Registry registry; InsertAppsListIntoRegistry(&registry, policy_and_sync_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); MergeSyncData(policy_and_sync_apps); syncer::EntityChangeList entity_changes; // Uninstall 5 kSync apps which are shared with kPolicy. Leave the rest // unchanged. for (int i = 0; i < 5; ++i) { const WebApp& app_to_uninstall = *policy_and_sync_apps[i]; ConvertAppToEntityChange( app_to_uninstall, syncer::EntityChange::ACTION_DELETE, &entity_changes); } EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); SetSyncInstallDelegateFailureIfCalled(); sync_bridge().ApplySyncChanges(sync_bridge().CreateMetadataChangeList(), std::move(entity_changes)); // Modify the registry with the results that we expect. for (int i = 0; i < 5; ++i) { std::unique_ptr<WebApp>& expected_policy_app = registry[policy_and_sync_apps[i]->app_id()]; expected_policy_app->RemoveSource(WebAppManagement::kSync); } EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } // Commits local data (e.g. installed web apps) before sync is hooked up. This // tests that the web apps are correctly sent to USS after MergeSyncData is // called. TEST_F(WebAppSyncBridgeTest, CommitUpdate_CommitWhileNotTrackingMetadata) { EXPECT_CALL(processor(), ModelReadyToSync(_)).Times(1); InitSyncBridge(); AppsList sync_apps = CreateAppsList("https://example.com/", 10); Registry expected_registry; InsertAppsListIntoRegistry(&expected_registry, sync_apps); EXPECT_CALL(processor(), Put(_, _, _)).Times(0); EXPECT_CALL(processor(), Delete(_, _)).Times(0); EXPECT_CALL(processor(), IsTrackingMetadata()) .WillOnce(testing::Return(false)); std::unique_ptr<WebAppRegistryUpdate> update = sync_bridge().BeginUpdate(); for (const std::unique_ptr<WebApp>& app : sync_apps) update->CreateApp(std::make_unique<WebApp>(*app)); CommitUpdate(std::move(update)); testing::Mock::VerifyAndClear(&processor()); // Do MergeSyncData next. base::RunLoop run_loop; ON_CALL(processor(), Put(_, _, _)) .WillByDefault([&](const std::string& storage_key, std::unique_ptr<syncer::EntityData> entity_data, syncer::MetadataChangeList* metadata) { EXPECT_TRUE(RemoveEntityDataAppFromAppsList(storage_key, *entity_data, &sync_apps)); if (sync_apps.empty()) run_loop.Quit(); }); EXPECT_CALL(processor(), Delete(_, _)).Times(0); EXPECT_CALL(processor(), IsTrackingMetadata()) .WillOnce(testing::Return(true)); sync_bridge().MergeSyncData(sync_bridge().CreateMetadataChangeList(), syncer::EntityChangeList{}); run_loop.Run(); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), expected_registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, CommitUpdate_CreateSyncApp) { InitSyncBridge(); AppsList sync_apps = CreateAppsList("https://example.com/", 10); Registry expected_registry; InsertAppsListIntoRegistry(&expected_registry, sync_apps); ON_CALL(processor(), Put(_, _, _)) .WillByDefault([&](const std::string& storage_key, std::unique_ptr<syncer::EntityData> entity_data, syncer::MetadataChangeList* metadata) { ASSERT_TRUE(base::Contains(expected_registry, storage_key)); const std::unique_ptr<WebApp>& expected_app = expected_registry.at(storage_key); EXPECT_TRUE(IsSyncDataEqual(*expected_app, *entity_data)); RemoveWebAppFromAppsList(&sync_apps, storage_key); }); EXPECT_CALL(processor(), Delete(_, _)).Times(0); EXPECT_CALL(processor(), IsTrackingMetadata()) .WillOnce(testing::Return(true)); std::unique_ptr<WebAppRegistryUpdate> update = sync_bridge().BeginUpdate(); for (const std::unique_ptr<WebApp>& app : sync_apps) update->CreateApp(std::make_unique<WebApp>(*app)); CommitUpdate(std::move(update)); EXPECT_TRUE(sync_apps.empty()); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), expected_registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, CommitUpdate_UpdateSyncApp) { AppsList sync_apps = CreateAppsList("https://example.com/", 10); Registry registry; InsertAppsListIntoRegistry(&registry, sync_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); ON_CALL(processor(), Put(_, _, _)) .WillByDefault([&](const std::string& storage_key, std::unique_ptr<syncer::EntityData> entity_data, syncer::MetadataChangeList* metadata) { ASSERT_TRUE(base::Contains(registry, storage_key)); const std::unique_ptr<WebApp>& expected_app = registry.at(storage_key); EXPECT_TRUE(IsSyncDataEqual(*expected_app, *entity_data)); RemoveWebAppFromAppsList(&sync_apps, storage_key); }); EXPECT_CALL(processor(), Delete(_, _)).Times(0); std::unique_ptr<WebAppRegistryUpdate> update = sync_bridge().BeginUpdate(); for (const std::unique_ptr<WebApp>& app : sync_apps) { // Obtain a writeable handle. WebApp* sync_app = update->UpdateApp(app->app_id()); WebApp::SyncFallbackData sync_fallback_data; sync_fallback_data.name = "Updated Sync Name"; sync_fallback_data.theme_color = SK_ColorBLACK; sync_app->SetSyncFallbackData(std::move(sync_fallback_data)); sync_app->SetUserDisplayMode(UserDisplayMode::kBrowser); // Override the app in the expected registry. registry[sync_app->app_id()] = std::make_unique<WebApp>(*sync_app); } CommitUpdate(std::move(update)); EXPECT_TRUE(sync_apps.empty()); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, CommitUpdate_DeleteSyncApp) { AppsList sync_apps = CreateAppsList("https://example.com/", 10); Registry registry; InsertAppsListIntoRegistry(&registry, sync_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); EXPECT_CALL(processor(), Put(_, _, _)).Times(0); ON_CALL(processor(), Delete(_, _)) .WillByDefault([&](const std::string& storage_key, syncer::MetadataChangeList* metadata) { EXPECT_TRUE(base::Contains(registry, storage_key)); RemoveWebAppFromAppsList(&sync_apps, storage_key); // Delete the app in the expected registry. registry.erase(storage_key); }); std::unique_ptr<WebAppRegistryUpdate> update = sync_bridge().BeginUpdate(); for (const std::unique_ptr<WebApp>& app : sync_apps) update->DeleteApp(app->app_id()); CommitUpdate(std::move(update)); EXPECT_TRUE(sync_apps.empty()); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, CommitUpdate_CreateSyncAppWithOverlappingPolicyApp) { AppsList policy_apps; for (int i = 0; i < 10; ++i) { std::unique_ptr<WebApp> policy_app = test::CreateWebApp( GURL("https://example.com/" + base::NumberToString(i)), WebAppManagement::kPolicy); policy_apps.push_back(std::move(policy_app)); } Registry registry; InsertAppsListIntoRegistry(&registry, policy_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); ON_CALL(processor(), Put(_, _, _)) .WillByDefault([&](const std::string& storage_key, std::unique_ptr<syncer::EntityData> entity_data, syncer::MetadataChangeList* metadata) { ASSERT_TRUE(base::Contains(registry, storage_key)); const WebApp& expected_app = *registry.at(storage_key); // kPolicy and Name is the difference for the sync "view". Add them to // make operator== work. std::unique_ptr<WebApp> entity_data_app = std::make_unique<WebApp>(expected_app.app_id()); entity_data_app->AddSource(WebAppManagement::kPolicy); entity_data_app->SetName("Name"); EXPECT_TRUE(IsSyncDataEqualIfApplied( expected_app, std::move(entity_data_app), *entity_data)); RemoveWebAppFromAppsList(&policy_apps, storage_key); }); EXPECT_CALL(processor(), Delete(_, _)).Times(0); std::unique_ptr<WebAppRegistryUpdate> update = sync_bridge().BeginUpdate(); for (int i = 0; i < 10; ++i) { WebApp* app_to_update = update->UpdateApp(policy_apps[i]->app_id()); // Add kSync source to first 5 apps. Modify the rest 5 apps locally. if (i < 5) app_to_update->AddSource(WebAppManagement::kSync); else app_to_update->SetDescription("Local policy app"); // Override the app in the expected registry. registry[app_to_update->app_id()] = std::make_unique<WebApp>(*app_to_update); } CommitUpdate(std::move(update)); EXPECT_EQ(5u, policy_apps.size()); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } TEST_F(WebAppSyncBridgeTest, CommitUpdate_DeleteSyncAppWithOverlappingPolicyApp) { AppsList policy_and_sync_apps; for (int i = 0; i < 10; ++i) { std::unique_ptr<WebApp> policy_and_sync_app = test::CreateWebApp( GURL("https://example.com/" + base::NumberToString(i))); policy_and_sync_app->AddSource(WebAppManagement::kPolicy); policy_and_sync_app->AddSource(WebAppManagement::kSync); policy_and_sync_apps.push_back(std::move(policy_and_sync_app)); } Registry registry; InsertAppsListIntoRegistry(&registry, policy_and_sync_apps); database_factory().WriteRegistry(registry); InitSyncBridge(); ON_CALL(processor(), Put(_, _, _)) .WillByDefault([&](const std::string& storage_key, std::unique_ptr<syncer::EntityData> entity_data, syncer::MetadataChangeList* metadata) { // Local changes to synced apps cause excessive |Put|. // See TODO in WebAppSyncBridge::UpdateSync. RemoveWebAppFromAppsList(&policy_and_sync_apps, storage_key); }); ON_CALL(processor(), Delete(_, _)) .WillByDefault([&](const std::string& storage_key, syncer::MetadataChangeList* metadata) { ASSERT_TRUE(base::Contains(registry, storage_key)); RemoveWebAppFromAppsList(&policy_and_sync_apps, storage_key); }); std::unique_ptr<WebAppRegistryUpdate> update = sync_bridge().BeginUpdate(); for (int i = 0; i < 10; ++i) { WebApp* app_to_update = update->UpdateApp(policy_and_sync_apps[i]->app_id()); // Remove kSync source from first 5 apps. Modify the rest 5 apps locally. if (i < 5) app_to_update->RemoveSource(WebAppManagement::kSync); else app_to_update->SetDescription("Local policy app"); // Override the app in the expected registry. registry[app_to_update->app_id()] = std::make_unique<WebApp>(*app_to_update); } CommitUpdate(std::move(update)); EXPECT_TRUE(policy_and_sync_apps.empty()); EXPECT_TRUE(IsRegistryEqual(registrar_registry(), registry)); EXPECT_TRUE(IsDatabaseRegistryEqualToRegistrar()); } // Test that any apps that are still pending install from sync (or, // |is_from_sync_and_pending_installation|) are continued to be installed when // the bridge initializes. TEST_F(WebAppSyncBridgeTest, InstallAppsFromSyncAndPendingInstallation) { AppsList apps_in_sync_install = CreateAppsList("https://example.com/", 10); for (std::unique_ptr<WebApp>& app : apps_in_sync_install) { app->SetIsLocallyInstalled(AreAppsLocallyInstalledBySync()); app->SetIsFromSyncAndPendingInstallation(true); } Registry registry; InsertAppsListIntoRegistry(&registry, apps_in_sync_install); database_factory().WriteRegistry(registry); base::RunLoop run_loop; install_manager().SetInstallWebAppsAfterSyncDelegateForTesting( base::BindLambdaForTesting( [&](std::vector<WebApp*> apps_to_install, WebAppInstallManager::RepeatingInstallCallback callback) { for (WebApp* app_to_install : apps_to_install) { // The app must be registered. EXPECT_TRUE(registrar().GetAppById(app_to_install->app_id())); RemoveWebAppFromAppsList(&apps_in_sync_install, app_to_install->app_id()); } EXPECT_TRUE(apps_in_sync_install.empty()); RunCallbacksOnInstall( apps_to_install, callback, webapps::InstallResultCode::kSuccessNewInstall); run_loop.Quit(); })); InitSyncBridge(); run_loop.Run(); } // Tests that OnWebAppsWillBeUpdatedFromSync observer notification is called // properly. TEST_F(WebAppSyncBridgeTest, ApplySyncChanges_OnWebAppsWillBeUpdatedFromSync) { AppsList initial_registry_apps = CreateAppsList("https://example.com/", 10); for (std::unique_ptr<WebApp>& app : initial_registry_apps) app->SetUserDisplayMode(UserDisplayMode::kBrowser); InitSyncBridgeFromAppList(initial_registry_apps); WebAppTestRegistryObserverAdapter observer{&registrar()}; base::RunLoop run_loop; observer.SetWebAppWillBeUpdatedFromSyncDelegate(base::BindLambdaForTesting( [&](const std::vector<const WebApp*>& new_apps_state) { EXPECT_EQ(5u, new_apps_state.size()); for (const WebApp* new_app_state : new_apps_state) { const WebApp* old_app_state = registrar().GetAppById(new_app_state->app_id()); EXPECT_NE(*old_app_state, *new_app_state); EXPECT_EQ(old_app_state->user_display_mode(), UserDisplayMode::kBrowser); EXPECT_EQ(new_app_state->user_display_mode(), UserDisplayMode::kStandalone); // new and old states must be equal if diff fixed: auto old_app_state_no_diff = std::make_unique<WebApp>(*old_app_state); old_app_state_no_diff->SetUserDisplayMode( UserDisplayMode::kStandalone); EXPECT_EQ(*old_app_state_no_diff, *new_app_state); RemoveWebAppFromAppsList(&initial_registry_apps, new_app_state->app_id()); } run_loop.Quit(); })); AppsList apps_server_state; // Update first 5 apps: change user_display_mode field only. for (int i = 0; i < 5; ++i) { auto app_server_state = std::make_unique<WebApp>(*initial_registry_apps[i]); app_server_state->SetUserDisplayMode(UserDisplayMode::kStandalone); apps_server_state.push_back(std::move(app_server_state)); } sync_bridge_test_utils::UpdateApps(sync_bridge(), apps_server_state); run_loop.Run(); // 5 other apps left unchanged: EXPECT_EQ(5u, initial_registry_apps.size()); for (int i = 0; i < 5; ++i) { EXPECT_EQ(UserDisplayMode::kBrowser, initial_registry_apps[i]->user_display_mode()); } } TEST_F(WebAppSyncBridgeTest, RetryIncompleteUninstalls) { AppsList initial_registry_apps = CreateAppsList("https://example.com/", 5); std::vector<AppId> initial_app_ids; for (std::unique_ptr<WebApp>& app : initial_registry_apps) { app->SetUserDisplayMode(UserDisplayMode::kBrowser); app->SetIsUninstalling(true); initial_app_ids.push_back(app->app_id()); } SetSyncInstallDelegateFailureIfCalled(); base::RunLoop run_loop; install_manager().SetRetryIncompleteUninstallsDelegateForTesting( base::BindLambdaForTesting( [&](const base::flat_set<AppId>& apps_to_uninstall) { EXPECT_EQ(apps_to_uninstall.size(), 5ul); EXPECT_THAT(apps_to_uninstall, ::testing::UnorderedElementsAreArray( apps_to_uninstall)); run_loop.Quit(); })); InitSyncBridgeFromAppList(initial_registry_apps); run_loop.Run(); } } // namespace web_app
{'content_hash': '54bebc8b5973ec66e042af23c143900f', 'timestamp': '', 'source': 'github', 'line_count': 1267, 'max_line_length': 82, 'avg_line_length': 37.45067087608524, 'alnum_prop': 0.6689567966280295, 'repo_name': 'chromium/chromium', 'id': 'fbd66c1e0682c6af25ffe98aac26e6763dc21cad', 'size': '47450', 'binary': False, 'copies': '5', 'ref': 'refs/heads/main', 'path': 'chrome/browser/web_applications/web_app_sync_bridge_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
import re import numpy from datetime import datetime from processing_components.visibility.msv2supp import cmp_to_total, STOKES_CODES, NUMERIC_STOKES, merge_baseline, \ geo_to_ecef, get_eci_transform from data_models.memory_data_models import Visibility, BlockVisibility, Configuration import logging log = logging.getLogger(__name__) __version__ = '0.1' __revision__ = '$Rev$' __all__ = ['STOKES_CODES', 'NUMERIC_STOKES', 'Stand', 'Observatory', 'Antenna', 'BaseData'] try: from casacore.tables import table, tableutil @cmp_to_total class Stand(object): """ Object to store the information (location and ID) about a stand. Stores stand: * ID number (id) * Position relative to the center stake in meters (x,y,z) The x, y, and z positions can also be accessed through subscripts: Stand[0] = x Stand[1] = y Stand[2] = z """ def __init__(self, id, x, y, z): self.id = id self.x = float(x) self.y = float(y) self.z = float(z) def __lt__(self, y): if self.id < y.id: return True else: return False def __le__(self, y): if self.id <= y.id: return True else: return False def __eq__(self, y): if self.id == y.id: return True else: return False def __gt__(self, y): if self.id > y.id: return True else: return False def __ge__(self, y): if self.id >= y.id: return True else: return False def __cmp__(self, y): if self.id > y.id: return 1 elif self.id < y.id: return -1 else: return 0 def __str__(self): return "Stand %i: x=%+.2f m, y=%+.2f m, z=%+.2f m" % (self.id, self.x, self.y, self.z) def __reduce__(self): return (Stand, (self.id, self.x, self.y, self.z)) def __getitem__(self, key): if key == 0: return self.x elif key == 1: return self.y elif key == 2: return self.z else: raise ValueError("Subscript %i out of range" % key) def __setitem__(self, key, value): if key == 0: self.x = float(value) elif key == 1: self.y = float(value) elif key == 2: self.z = float(value) else: raise ValueError("Subscript %i out of range" % key) def __add__(self, std): try: # If its a Stand instance, do this out = (self.x + std.x, self.y + std.y, self.z + std.z) except AttributeError: try: # Maybe it is a list/tuple, so do this out = (self.x + std[0], self.y + std[1], self.z + std[2]) except TypeError: out = (self.x + std, self.y + std, self.z + std) return out def __sub__(self, std): try: # If its a Stand instance, do this out = (self.x - std.x, self.y - std.y, self.z - std.z) except AttributeError: try: # Maybe it is a list/tuple, so do this out = (self.x - std[0], self.y - std[1], self.z - std[2]) except TypeError: out = (self.x - std, self.y - std, self.z - std) return out class Observatory(object): def __init__(self, name, lon, lat, alt): self.name = name self.lon = lon self.lat = lat self.alt = alt class Antenna(object): """ Object to store the information about an antenna. Stores antenna: * ID number (id) * Stand instance the antenna is part of (stand) * Polarization (0 == N-S; pol) * Antenna vertical mis-alignment in degrees (theta) * Antenna rotation mis-alignment in degrees (phi) * Fee instance the antenna is attached to (fee) * Port of the FEE used for the antenna (feePort) * Cable instance used to connect the antenna (cable) Some arguments are designed for future extension """ def __init__(self, id, stand=None, pol=0, theta=0.0, phi=0.0, fee=None, feePort=1, cable=None): self.id = int(id) if stand is None: self.stand = Stand(0, 0, 0, 0) else: self.stand = stand self.pol = int(pol) self.theta = float(theta) self.phi = float(phi) self.FEE = fee self.feePort = feePort self.cable = cable def __str__(self): return "Antenna %i: stand=%i, polarization=%i; " % (self.id, self.stand.id, self.pol) def __reduce__(self): return (Antenna, ( self.id, self.stand, self.pol, self.theta, self.phi, self.fee, self.feePort, self.cable)) def __lt__(self, y): if self.id < y.id: return True else: return False def __le__(self, y): if self.id <= y.id: return True else: return False def __eq__(self, y): if self.id == y.id: return True else: return False def __gt__(self, y): if self.id > y.id: return True else: return False def __ge__(self, y): if self.id >= y.id: return True else: return False def __cmp__(self, y): if self.id > y.id: return 1 elif self.id < y.id: return -1 else: return 0 class Frequency: """ Information about the frequency setup used in the file. """ def __init__(self, bandFreq, channelWidth, bandwidth): self.id = 1 self.bandFreq = bandFreq self.chWidth = channelWidth self.totalBW = bandwidth self.sideBand = 1 self.baseBand = 0 @cmp_to_total class MS_UVData(object): """ UV visibility data set for a given observation time. """ def __init__(self, obstime, inttime, baselines, visibilities, weights=None, pol=STOKES_CODES['XX'], source=None, phasecentre=None, uvw=None): self.obstime = obstime self.inttime = inttime self.baselines = baselines self.visibilities = visibilities self.weights = weights self.pol = pol self.source = source self.phasecentre = phasecentre self.uvw = uvw def __lt__(self, y): sID = (self.obstime, abs(self.pol)) yID = (y.obstime, abs(y.pol)) if sID > yID: return False else: return True def __le__(self, y): sID = (self.obstime, abs(self.pol)) yID = (y.obstime, abs(y.pol)) if sID <= yID: return True else: return False def __ge__(self, y): sID = (self.obstime, abs(self.pol)) yID = (y.obstime, abs(y.pol)) if sID >= yID: return True else: return False def __gt__(self, y): sID = (self.obstime, abs(self.pol)) yID = (y.obstime, abs(y.pol)) if sID < yID: return False else: return True def __eq__(self, y): sID = (self.obstime, abs(self.pol)) yID = (y.obstime, abs(y.pol)) if sID == yID: return True else: return False def __cmp__(self, y): """ Function to sort the self.data list in order of time and then polarization code. """ sID = (self.obstime, abs(self.pol)) yID = (y.obstime, abs(y.pol)) if sID > yID: return 1 elif sID < yID: return -1 else: return 0 def time(self): return self.obstime def get_uvw(self, HA, dec, obs): Nbase = len(self.baselines) uvw = numpy.zeros((Nbase, 3), dtype=numpy.float32) # Phase center coordinates # Convert numbers to radians and, for HA, hours to degrees HA2 = HA * 15.0 * numpy.pi / 180 dec2 = dec * numpy.pi / 180 lat2 = obs.location.geodetic[1].to('rad').value # Coordinate transformation matrices trans1 = numpy.array([[0, -numpy.sin(lat2), numpy.cos(lat2)], [1, 0, 0], [0, numpy.cos(lat2), numpy.sin(lat2)]]) trans2 = numpy.array([[numpy.sin(HA2), numpy.cos(HA2), 0], [-numpy.sin(dec2) * numpy.cos(HA2), numpy.sin(dec2) * numpy.sin(HA2), numpy.cos(dec2)], [numpy.cos(dec2) * numpy.cos(HA2), -numpy.cos(dec2) * numpy.sin(HA2), numpy.sin(dec2)]]) for i, (a1, a2) in enumerate(self.baselines): # Go from a east, north, up coordinate system to a celestial equation, # east, north celestial pole system xyzPrime = a1.stand - a2.stand xyz = trans1 @ numpy.array([[xyzPrime[0]], [xyzPrime[1]], [xyzPrime[2]]]) # Go from CE, east, NCP to u, v, w temp = trans2 @ xyz uvw[i, :] = numpy.squeeze(temp) # / speed_of_light return uvw def argsort(self, mapper=None, shift=16): packed = [] for a1, a2 in self.baselines: if mapper is None: s1, s2 = a1.stand.id, a2.stand.id else: s1, s2 = mapper.index(a1.stand.id), mapper.index(a2.stand.id) packed.append(merge_baseline(s1, s2, shift=shift)) packed = numpy.array(packed, dtype=numpy.int32) return numpy.argsort(packed) class BaseData(object): """ Base Data class: For an observation of interferometer, we should have: Antenna, Frequency, Visibility Funcation, UVW """ _MAX_ANTS = 255 _PACKING_BIT_SHIFT = 8 _STOKES_CODES = STOKES_CODES class _Antenna(object): """ Holds information describing the location and properties of an antenna. """ def __init__(self, id, x, y, z, bits=8, name=None): self.id = id self.x = x self.y = y self.z = z self.levels = bits self.name = name def getName(self): if self.name is None: if isinstance(self.id, str): return self.id else: return "AT%03i" % self.id else: return self.name def parse_time(self, ref_time): """ Given a time as either a integer, float, string, or datetime object, convert it to a string in the formation 'YYYY-MM-DDTHH:MM:SS'. """ # Valid time string (modulo the 'T') timeRE = re.compile(r'\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d+)?') if type(ref_time) in (int, float): refDateTime = datetime.utcfromtimestamp(ref_time) ref_time = refDateTime.strftime("%Y-%m-%dT%H:%M:%S") elif type(ref_time) == datetime: ref_time = ref_time.strftime("%Y-%m-%dT%H:%M:%S") elif type(ref_time) == str: # Make sure that the string times are of the correct format if re.match(timeRE, ref_time) is None: raise RuntimeError("Malformed date/time provided: %s" % ref_time) else: ref_time = ref_time.replace(' ', 'T', 1) else: raise RuntimeError("Unknown time format provided.") return ref_time def __init__(self, filename, ref_time=0.0, source_name = None, frame='ITRF', verbose=False): # File-specific information self.filename = filename self.verbose = verbose self.site_config = None # Observatory-specific information self.siteName = 'Unknown' self.frame = frame self.source_name = source_name # Observation-specific information self.ref_time = self.parse_time(ref_time) self.nant = 0 self.nchan = 0 self.nstokes = 0 self.refVal = 0 self.refPix = 0 self.channel_width = 0 # Parameters that store the meta-data and data self.array = [] self.freq = [] self.stokes = [] self.data = [] self.uvw_arl = None def __enter__(self): return self def __exit__(self, type, value, tb): self.write() self.close() def set_stokes(self, polList): """ Given a list of Stokes parameters, update the object's parameters. """ for pol in polList: if type(pol) == str: numericPol = self._STOKES_CODES[pol.upper()] else: numericPol = pol if numericPol not in self.stokes: self.stokes.append(numericPol) # Sort into order of 'XX', 'YY', 'XY', and 'YX' or 'I', 'Q', 'U', and 'V' self.stokes.sort() if self.stokes[0] < 0: self.stokes.reverse() self.nStokes = len(self.stokes) def set_frequency(self, freq, channel_width): """ Given a numpy array of frequencies, set the relevant common observation parameters and add an entry to the self.freq list. """ if self.nchan == 0: self.nchan = len(freq) self.refVal = freq[0] self.refPix = 1 self.channelWidth = channel_width[0] offset = 0.0 else: assert (len(freq) == self.nchan) offset = freq[0] - self.refVal self.channelWidth = channel_width[0] if self.nchan == 1: totalWidth = self.channel_width else: totalWidth = numpy.abs(freq[-1] - freq[0]) freqSetup = Frequency(offset, self.channelWidth, totalWidth) self.freq.append(freqSetup) def set_geometry(self, *args, **kwds): """ Given a station and an array of stands, set the relevant common observation parameters and add entries to the self.array list. """ raise NotImplementedError def add_data_set(self, obstime, inttime, baselines, visibilities, weights=None, pol='XX', source=None): """ Create a UVData object to store a collection of visibilities. """ if type(pol) == str: numericPol = self._STOKES_CODES[pol.upper()] else: numericPol = pol self.data.append( MS_UVData(obstime, inttime, baselines, visibilities, weights=weights, pol=numericPol, source=source)) def write(self): """ Fill in the file will all of the required supporting metadata. """ raise NotImplementedError def close(self): """ Close out the file. """ raise NotImplementedError except ImportError: import warnings warnings.warn('Cannot import casacore.tables, MS support disabled', ImportWarning) raise RuntimeError("Cannot import casacore.tables, MS support disabled")
{'content_hash': '6d3ad0b6118aa05109b83f1030fd1736', 'timestamp': '', 'source': 'github', 'line_count': 534, 'max_line_length': 120, 'avg_line_length': 31.49063670411985, 'alnum_prop': 0.47127735490009515, 'repo_name': 'SKA-ScienceDataProcessor/algorithm-reference-library', 'id': '3f3c4c4574b55fffee85f94d95adc6091da337d9', 'size': '16883', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'processing_components/visibility/msv2fund.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '171056'}, {'name': 'C++', 'bytes': '520'}, {'name': 'Dockerfile', 'bytes': '4686'}, {'name': 'Java', 'bytes': '748'}, {'name': 'Jupyter Notebook', 'bytes': '8158663'}, {'name': 'Makefile', 'bytes': '19263'}, {'name': 'Nix', 'bytes': '3599'}, {'name': 'Python', 'bytes': '1854561'}, {'name': 'Shell', 'bytes': '73453'}, {'name': 'Smarty', 'bytes': '1057'}]}
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2013 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. --> <android.support.v7.internal.widget.FitWindowsLinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/action_bar_root" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:fitsSystemWindows="true"> <android.support.v7.internal.widget.ViewStubCompat android:id="@+id/action_mode_bar_stub" android:inflatedId="@+id/action_mode_bar" android:layout="@layout/abc_action_mode_bar" android:layout_width="match_parent" android:layout_height="wrap_content" /> <include layout="@layout/abc_screen_content_include" /> </android.support.v7.internal.widget.FitWindowsLinearLayout> <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-sdk-release/frameworks/support/v7/appcompat/res/layout/abc_screen_simple.xml --><!-- From: file:/Users/bkon4208/Documents/workspace/AdMobBannerProject/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/layout/abc_screen_simple.xml -->
{'content_hash': '0b3fe933491fdae92b8b2aebfec338b0', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 392, 'avg_line_length': 51.371428571428574, 'alnum_prop': 0.7352614015572859, 'repo_name': 'billykonesavanh17/AdMobBannerProject', 'id': 'c536baec71f76e57930367fd23ece7fdb9ec601b', 'size': '1798', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/build/intermediates/res/merged/debug/layout/abc_screen_simple.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '500974'}]}
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" #################### # GLOBAL VARIABLES # #################### TEST_EXIT_CODE=0 CAT_FILE_LIST="" ####################### # AUXILIARY FUNCTIONS # ####################### function cookbook_check { TEST_RESULT=$? TEST_CASE=$1 TEST_CASE_DETAILS=$2 CAT_FILE=$3 if [ "$TEST_RESULT" -ne "0" ] then echo "ERROR: $TEST_CASE $TEST_CASE_DETAILS" TEST_EXIT_CODE=1 if [ "$CAT_FILE" != "" ] then CAT_FILE_LIST="$CAT_FILE_LIST $CAT_FILE" fi else echo "PASS: $TEST_CASE $TEST_CASE_DETAILS" fi } function simple_testcase { TESTCASE=$1 LOGFILE=${TESTCASE,,}.log ./bin/${TESTCASE,,} \ >& ./log/$LOGFILE cookbook_check "$TESTCASE" "(run check)" diff ./ref/$LOGFILE ./log/$LOGFILE >& ./log/diff_$LOGFILE cookbook_check "$TESTCASE" "(logfile check)" "./log/diff_$LOGFILE" } function check_wavinfo { TESTCASE=$1 WAVFILE=$2 LOGFILE=${TESTCASE,,}_wavinfo.log wavinfo ./out/$WAVFILE >& ./log/$LOGFILE cookbook_check "$TESTCASE" "(wavinfo)" diff ./ref/$LOGFILE ./log/$LOGFILE >& ./log/diff_$LOGFILE cookbook_check "$TESTCASE" "(wavinfo logfile check)" "./log/diff_$LOGFILE" } function check_wavefile { TESTCASE=$1 WAVFILE=$2 LOGFILE=${TESTCASE,,}.log diff ./ref/$WAVFILE ./out/$WAVFILE >& ./log/diff_$LOGFILE cookbook_check "$TESTCASE" "(wavfile check)" "" } function cleanup_data { rm log/* rm out/* rm src/* rm cookbook.ada } ################ # PREPARATIONS # ################ # Change to cookbook directory cd $DIR/../cookbook # Create .ada file based on Markdown file sed -n '/^~~~~~~~~~~/,/^~~~~~~~~~~/ p' < cookbook.md | sed '/^~~~~~~~~~~/ d' > cookbook.ada cookbook_check "PREPARATIONS" "(sed)" "" # Create source-code files based on cookbook file gnatchop -wr cookbook.ada ./src >& ./log/gnatchop.log cookbook_check "PREPARATIONS" "(gnatchop)" "./log/gnatchop.log" # Set GPR environment variable AUDIO_WAVEFILES_PATH=$(cd .. && pwd) if [ -z "$GPR_PROJECT_PATH" ] then export GPR_PROJECT_PATH=${AUDIO_WAVEFILES_PATH} else export GPR_PROJECT_PATH="${GPR_PROJECT_PATH}:${AUDIO_WAVEFILES_PATH}" fi echo "GPR_PROJECT_PATH = $GPR_PROJECT_PATH" >& ./log/gprbuild_env.log # Build application for each source-code file gprbuild ./cookbook.gpr >& ./log/gprbuild.log cookbook_check "PREPARATIONS" "(gprbuild)" "./log/gprbuild.log" ############## # RUN & TEST # ############## simple_testcase Open_Close_Wavefile_For_Reading simple_testcase Open_Close_Wavefile_For_Writing check_wavinfo Open_Close_Wavefile_For_Writing "test.wav" simple_testcase Display_Errors_For_Wavefiles simple_testcase List_Errors_For_Wavefiles simple_testcase Display_RIFF_Chunks simple_testcase Read_Display_Wavefile_Data simple_testcase Write_Mono_Silence_Wavefile check_wavinfo Write_Mono_Silence_Wavefile "1ch_silence.wav" check_wavefile Write_Mono_Silence_Wavefile "1ch_silence.wav" simple_testcase Write_Stereo_Sine_Wavefile check_wavinfo Write_Stereo_Sine_Wavefile "2ch_sine.wav" check_wavefile Write_Stereo_Sine_Wavefile "2ch_sine.wav" simple_testcase Write_5_1_Channel_Sine_Wavefile check_wavinfo Write_5_1_Channel_Sine_Wavefile "5_1ch_sine.wav" check_wavefile Write_5_1_Channel_Sine_Wavefile "5_1ch_sine.wav" simple_testcase Write_7_1_4_Channel_Sine_Wavefile check_wavinfo Write_7_1_4_Channel_Sine_Wavefile "7_1_4ch_sine.wav" check_wavefile Write_7_1_4_Channel_Sine_Wavefile "7_1_4ch_sine.wav" simple_testcase Display_Channel_Config simple_testcase Append_Wavefile check_wavinfo Append_Wavefile "2ch_sine_append.wav" check_wavefile Append_Wavefile "2ch_sine_append.wav" simple_testcase Copy_Wavefile check_wavinfo Copy_Wavefile "2ch_sine.wav" check_wavefile Copy_Wavefile "2ch_sine.wav" simple_testcase Copy_Wavefile_Using_Fixed_Point_Buffer check_wavinfo Copy_Wavefile_Using_Fixed_Point_Buffer "2ch_sine.wav" check_wavefile Copy_Wavefile_Using_Fixed_Point_Buffer "2ch_sine.wav" simple_testcase Copy_Parts_Of_Wavefile check_wavinfo Copy_Parts_Of_Wavefile "looped_clip.wav" check_wavefile Copy_Parts_Of_Wavefile "looped_clip.wav" simple_testcase Convert_Fixed_To_Float_Wavefile check_wavinfo Convert_Fixed_To_Float_Wavefile "2ch_float_sine.wav" check_wavefile Convert_Fixed_To_Float_Wavefile "2ch_float_sine.wav" simple_testcase Downmix_Stereo_To_Mono_Wavefile check_wavinfo Downmix_Stereo_To_Mono_Wavefile "1ch_dmx_sine.wav" check_wavefile Downmix_Stereo_To_Mono_Wavefile "1ch_dmx_sine.wav" simple_testcase Downmix_5_1_To_2_0_Wavefile check_wavinfo Downmix_5_1_To_2_0_Wavefile "2_0ch_dmx_sine.wav" check_wavefile Downmix_5_1_To_2_0_Wavefile "2_0ch_dmx_sine.wav" simple_testcase Downmix_7_1_4_To_5_1_Wavefile check_wavinfo Downmix_7_1_4_To_5_1_Wavefile "5_1ch_dmx_sine.wav" check_wavefile Downmix_7_1_4_To_5_1_Wavefile "5_1ch_dmx_sine.wav" simple_testcase Direct_Copy_Wavefile check_wavinfo Direct_Copy_Wavefile "2ch_sine.wav" check_wavefile Direct_Copy_Wavefile "2ch_sine.wav" simple_testcase Direct_Copy_Float_Wavefile check_wavinfo Direct_Copy_Float_Wavefile "2ch_float_sine.wav" check_wavefile Direct_Copy_Float_Wavefile "2ch_float_sine.wav" simple_testcase Convert_8_Bit_To_16_Bit_Wavefile simple_testcase Read_To_Memory_Channel_Interleaved simple_testcase Read_To_Memory_Per_Channel simple_testcase Extract_XML_Chunk check_wavefile Extract_XML_Chunk "2020-08-09.xml" ################ # FINALIZATION # ################ if [ "$CAT_FILE_LIST" != "" ] then for cat_file in $CAT_FILE_LIST do echo "------------------------------------------" echo $cat_file echo "------------------------------------------" cat $cat_file done fi # cleanup_data exit $TEST_EXIT_CODE
{'content_hash': '1ce080d3dc6a98a90c4e981a1b568724', 'timestamp': '', 'source': 'github', 'line_count': 208, 'max_line_length': 91, 'avg_line_length': 29.677884615384617, 'alnum_prop': 0.635995464117933, 'repo_name': 'gusthoff/wavefiles', 'id': '7723f6afa09dbc841a634536f01dbccbb219150c', 'size': '6186', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'scripts/test_cookbook.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Ada', 'bytes': '452266'}, {'name': 'PowerShell', 'bytes': '263'}, {'name': 'Shell', 'bytes': '12387'}]}
namespace TestRoom { partial class Mainform { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.bTestVirtualDesktop = new System.Windows.Forms.Button(); this.bTestLoaderService = new System.Windows.Forms.Button(); this.bWcf = new System.Windows.Forms.Button(); this.bTestCfg = new System.Windows.Forms.Button(); this.bShowTaskbar = new System.Windows.Forms.Button(); this.SuspendLayout(); // // bTestVirtualDesktop // this.bTestVirtualDesktop.Location = new System.Drawing.Point(12, 12); this.bTestVirtualDesktop.Name = "bTestVirtualDesktop"; this.bTestVirtualDesktop.Size = new System.Drawing.Size(151, 23); this.bTestVirtualDesktop.TabIndex = 0; this.bTestVirtualDesktop.Text = "Test Virtual Desktop"; this.bTestVirtualDesktop.UseVisualStyleBackColor = true; this.bTestVirtualDesktop.Click += new System.EventHandler(this.bTestVirtualDesktop_Click); // // bTestLoaderService // this.bTestLoaderService.Location = new System.Drawing.Point(12, 41); this.bTestLoaderService.Name = "bTestLoaderService"; this.bTestLoaderService.Size = new System.Drawing.Size(151, 23); this.bTestLoaderService.TabIndex = 1; this.bTestLoaderService.Text = "Test Loader Service"; this.bTestLoaderService.UseVisualStyleBackColor = true; this.bTestLoaderService.Click += new System.EventHandler(this.bTestLoaderService_Click); // // bWcf // this.bWcf.Location = new System.Drawing.Point(12, 70); this.bWcf.Name = "bWcf"; this.bWcf.Size = new System.Drawing.Size(151, 23); this.bWcf.TabIndex = 1; this.bWcf.Text = "Test Wcf"; this.bWcf.UseVisualStyleBackColor = true; this.bWcf.Click += new System.EventHandler(this.bWcf_Click); // // bTestCfg // this.bTestCfg.Location = new System.Drawing.Point(12, 99); this.bTestCfg.Name = "bTestCfg"; this.bTestCfg.Size = new System.Drawing.Size(151, 23); this.bTestCfg.TabIndex = 2; this.bTestCfg.Text = "Test Cfg"; this.bTestCfg.UseVisualStyleBackColor = true; this.bTestCfg.Click += new System.EventHandler(this.bTestCfg_Click); // // bShowTaskbar // this.bShowTaskbar.Location = new System.Drawing.Point(12, 128); this.bShowTaskbar.Name = "bShowTaskbar"; this.bShowTaskbar.Size = new System.Drawing.Size(151, 23); this.bShowTaskbar.TabIndex = 3; this.bShowTaskbar.Text = "Show Taskbar"; this.bShowTaskbar.UseVisualStyleBackColor = true; this.bShowTaskbar.Click += new System.EventHandler(this.bShowTaskbar_Click); // // Mainform // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(863, 629); this.Controls.Add(this.bShowTaskbar); this.Controls.Add(this.bTestCfg); this.Controls.Add(this.bWcf); this.Controls.Add(this.bTestLoaderService); this.Controls.Add(this.bTestVirtualDesktop); this.Name = "Mainform"; this.Text = "Test Room"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button bTestVirtualDesktop; private System.Windows.Forms.Button bTestLoaderService; private System.Windows.Forms.Button bWcf; private System.Windows.Forms.Button bTestCfg; private System.Windows.Forms.Button bShowTaskbar; } }
{'content_hash': 'dfc221bf8b71e360c8de79de84758c17', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 107, 'avg_line_length': 42.52212389380531, 'alnum_prop': 0.591675338189386, 'repo_name': 'mind0n/hive', 'id': '854d2b0f2ef2af882166f1affe4850744d472e36', 'size': '4807', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Product/Server/HostNode/Joy/TestRoom/Mainform.Designer.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '670329'}, {'name': 'ActionScript', 'bytes': '7830'}, {'name': 'ApacheConf', 'bytes': '47'}, {'name': 'Batchfile', 'bytes': '18096'}, {'name': 'C', 'bytes': '19746409'}, {'name': 'C#', 'bytes': '258148996'}, {'name': 'C++', 'bytes': '48534520'}, {'name': 'CSS', 'bytes': '933736'}, {'name': 'ColdFusion', 'bytes': '10780'}, {'name': 'GLSL', 'bytes': '3935'}, {'name': 'HTML', 'bytes': '4631854'}, {'name': 'Java', 'bytes': '10881'}, {'name': 'JavaScript', 'bytes': '10250558'}, {'name': 'Logos', 'bytes': '1526844'}, {'name': 'MAXScript', 'bytes': '18182'}, {'name': 'Mathematica', 'bytes': '1166912'}, {'name': 'Objective-C', 'bytes': '2937200'}, {'name': 'PHP', 'bytes': '81898'}, {'name': 'Perl', 'bytes': '9496'}, {'name': 'PowerShell', 'bytes': '44339'}, {'name': 'Python', 'bytes': '188058'}, {'name': 'Shell', 'bytes': '758'}, {'name': 'Smalltalk', 'bytes': '5818'}, {'name': 'TypeScript', 'bytes': '50090'}]}
DIRECTORY=$(dirname $0) PROGRAM=$(basename $0) NEWLINE=$'\n' # define the error function function die { echo "$1" 1>&2 exit 1 } # make sure that the right number of command line arguments were passed in test $# -eq 4 || die "Usage: ${PROGRAM} <environment name> <client name> <ca directory path> <subject> ${NEWLINE}Example: ${PROGRAM} Sandbox CoffeeBucks /some/secret/path/ 'CN=http://acmecoffee.com,O=Acme Coffee,C=US'" # generate a new client certificate keystore for the environment java -classpath "${DIRECTORY}/../lib/*" craterdog.security.ClientCertificateGenerator "$@"
{'content_hash': '4a8ba3c4aef6d644be6c45f041aa9399', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 218, 'avg_line_length': 39.2, 'alnum_prop': 0.7193877551020408, 'repo_name': 'craterdog/java-security-framework', 'id': 'a6095600be7fd198c51910efc14b7e7002365e60', 'size': '2007', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'java-certificate-generation/src/main/scripts/generate-client-certificate.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '119135'}, {'name': 'Shell', 'bytes': '13685'}]}
package com.englishtown.promises.impl; import javax.inject.Inject; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Asynchronous executor that uses a fixed thread pool */ public class AsyncExecutor implements Executor { private ExecutorService executorService = Executors.newFixedThreadPool(20); @Inject public AsyncExecutor() { } /** * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the {@code Executor} implementation. * * @param command the runnable task * @throws java.util.concurrent.RejectedExecutionException if this task cannot be * accepted for execution * @throws NullPointerException if command is null */ @Override public void execute(Runnable command) { executorService.execute(command); } }
{'content_hash': '97daa0ceb6b018d444c3e6b7bbad6df1', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 85, 'avg_line_length': 31.794117647058822, 'alnum_prop': 0.6651248843663274, 'repo_name': 'englishtown/when.java', 'id': 'f15e7c678a405371aa9862d3224cc4b26c2ac040', 'size': '1081', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'when.java/src/main/java/com/englishtown/promises/impl/AsyncExecutor.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '179308'}]}
package demo.java.v2c08javabean.ChartBean.com.horstmann.corejava; import java.awt.*; import java.awt.font.*; import java.awt.geom.*; import java.beans.*; /** * A custom editor for an array of floating-point numbers. * @version 1.21 2007-10-03 * @author Cay Horstmann */ public class DoubleArrayEditor extends PropertyEditorSupport { @Override public void setValue(Object value) { super.setValue(value); } public Component getCustomEditor() { return new DoubleArrayEditorPanel(this); } public boolean supportsCustomEditor() { return true; } public boolean isPaintable() { return true; } public String getAsText() { return null; } public void paintValue(Graphics g, Rectangle box) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); double[] values = (double[]) getValue(); StringBuilder s = new StringBuilder(); for (int i = 0; i < 3; i++) { if (values.length > i) s.append(values[i]); if (values.length > i + 1) s.append(", "); } if (values.length > 3) s.append("..."); g2.setPaint(Color.white); g2.fill(box); g2.setPaint(Color.black); FontRenderContext context = g2.getFontRenderContext(); Rectangle2D stringBounds = g2.getFont().getStringBounds(s.toString(), context); double w = stringBounds.getWidth(); double x = box.x; if (w < box.width) x += (box.width - w) / 2; double ascent = -stringBounds.getY(); double y = box.y + (box.height - stringBounds.getHeight()) / 2 + ascent; g2.drawString(s.toString(), (float) x, (float) y); } public String getJavaInitializationString() { double[] values = (double[]) getValue(); StringBuilder s = new StringBuilder(); s.append("new double[] {"); for (int i = 0; i < values.length; i++) { if (i > 0) s.append(", "); s.append(values[i]); } s.append("}"); return s.toString(); } }
{'content_hash': 'c41baf7092675892ecd0ca226e9a3c7f', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 85, 'avg_line_length': 27.209876543209877, 'alnum_prop': 0.5812159709618875, 'repo_name': 'myid999/javademo', 'id': '9ac7a4360c955940bee8183fafade38a861bb707', 'size': '2204', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/demo/java/v2c08javabean/ChartBean/com/horstmann/corejava/DoubleArrayEditor.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '23149'}, {'name': 'C++', 'bytes': '2165'}, {'name': 'HTML', 'bytes': '1835'}, {'name': 'Java', 'bytes': '889869'}, {'name': 'XSLT', 'bytes': '1368'}]}
CREATE TABLE [tbl_Task_List] ( [Location_ID] VARCHAR (50), [Request_date] DATETIME , [Task_desc] VARCHAR (100), [Requested_by] VARCHAR (50), [Task_status] VARCHAR (50), [Date_completed] DATETIME , [Followup_by] VARCHAR (50), [Task_notes] LONGTEXT , [Followup_notes] LONGTEXT , CONSTRAINT [pk_tbl_Task_List] PRIMARY KEY ([Location_ID], [Request_date], [Task_desc]) )
{'content_hash': '6af315cb3af9b8326684f3c1dff04fc6', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 89, 'avg_line_length': 32.25, 'alnum_prop': 0.6640826873385013, 'repo_name': 'envisionnw/targetlists', 'id': '4c034206d3dc79fa809ddf19e9a767366622dbdf', 'size': '387', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/tbldef/tbl_Task_List.sql', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Visual Basic', 'bytes': '739429'}]}
require 'rails_helper' describe GamesHelper, :type => :helper do end
{'content_hash': '6f07a43c0a4edef773acd856271742a2', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 41, 'avg_line_length': 17.5, 'alnum_prop': 0.7428571428571429, 'repo_name': 'randomcodenz/canasta', 'id': 'e2928ff4c0bc203ee7aa91f7813897cc33d49c96', 'size': '70', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/helpers/games_helper_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1849'}, {'name': 'CoffeeScript', 'bytes': '1266'}, {'name': 'Cucumber', 'bytes': '4757'}, {'name': 'HTML', 'bytes': '8457'}, {'name': 'JavaScript', 'bytes': '661'}, {'name': 'Ruby', 'bytes': '158587'}]}
package com.example.android.tvleanback2.ui; import android.app.Activity; import android.app.FragmentManager; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v17.leanback.app.GuidedStepFragment; import android.support.v17.leanback.widget.GuidanceStylist; import android.support.v17.leanback.widget.GuidanceStylist.Guidance; import android.support.v17.leanback.widget.GuidedAction; import com.example.android.tvleanback2.R; import java.util.List; /** * Activity that showcases different aspects of GuidedStepFragments. */ public class GuidedStepActivity extends Activity { private static final int CONTINUE = 0; private static final int BACK = 1; private static final int OPTION_CHECK_SET_ID = 10; private static final String[] OPTION_NAMES = {"Option A", "Option B", "Option C"}; private static final String[] OPTION_DESCRIPTIONS = {"Here's one thing you can do", "Here's another thing you can do", "Here's one more thing you can do"}; private static final int[] OPTION_DRAWABLES = {R.drawable.ic_guidedstep_option_a, R.drawable.ic_guidedstep_option_b, R.drawable.ic_guidedstep_option_c}; private static final boolean[] OPTION_CHECKED = {true, false, false}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (null == savedInstanceState) { GuidedStepFragment.addAsRoot(this, new FirstStepFragment(), android.R.id.content); } } private static void addAction(List<GuidedAction> actions, long id, String title, String desc) { actions.add(new GuidedAction.Builder() .id(id) .title(title) .description(desc) .build()); } private static void addCheckedAction(List<GuidedAction> actions, int iconResId, Context context, String title, String desc, boolean checked) { GuidedAction guidedAction = new GuidedAction.Builder() .title(title) .description(desc) .checkSetId(OPTION_CHECK_SET_ID) .iconResourceId(iconResId, context) .build(); guidedAction.setChecked(checked); actions.add(guidedAction); } public static class FirstStepFragment extends GuidedStepFragment { @Override public int onProvideTheme() { return R.style.Theme_Example_Leanback_GuidedStep_First; } @Override @NonNull public Guidance onCreateGuidance(@NonNull Bundle savedInstanceState) { String title = getString(R.string.guidedstep_first_title); String breadcrumb = getString(R.string.guidedstep_first_breadcrumb); String description = getString(R.string.guidedstep_first_description); Drawable icon = getActivity().getDrawable(R.drawable.ic_main_icon); return new Guidance(title, description, breadcrumb, icon); } @Override public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) { addAction(actions, CONTINUE, getResources().getString(R.string.guidedstep_continue), getResources().getString(R.string.guidedstep_letsdoit)); addAction(actions, BACK, getResources().getString(R.string.guidedstep_cancel), getResources().getString(R.string.guidedstep_nevermind)); } @Override public void onGuidedActionClicked(GuidedAction action) { FragmentManager fm = getFragmentManager(); if (action.getId() == CONTINUE) { GuidedStepFragment.add(fm, new SecondStepFragment()); } else { getActivity().finishAfterTransition(); } } } public static class SecondStepFragment extends GuidedStepFragment { @Override @NonNull public Guidance onCreateGuidance(Bundle savedInstanceState) { String title = getString(R.string.guidedstep_second_title); String breadcrumb = getString(R.string.guidedstep_second_breadcrumb); String description = getString(R.string.guidedstep_second_description); Drawable icon = getActivity().getDrawable(R.drawable.ic_main_icon); return new Guidance(title, description, breadcrumb, icon); } @Override public GuidanceStylist onCreateGuidanceStylist() { return new GuidanceStylist() { @Override public int onProvideLayoutId() { return R.layout.guidedstep_second_guidance; } }; } @Override public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) { String desc = getResources().getString(R.string.guidedstep_action_description); actions.add(new GuidedAction.Builder() .title(getResources().getString(R.string.guidedstep_action_title)) .description(desc) .multilineDescription(true) .infoOnly(true) .enabled(false) .build()); for (int i = 0; i < OPTION_NAMES.length; i++) { addCheckedAction(actions, OPTION_DRAWABLES[i], getActivity(), OPTION_NAMES[i], OPTION_DESCRIPTIONS[i], OPTION_CHECKED[i]); } } @Override public void onGuidedActionClicked(GuidedAction action) { FragmentManager fm = getFragmentManager(); ThirdStepFragment next = ThirdStepFragment.newInstance(getSelectedActionPosition() - 1); GuidedStepFragment.add(fm, next); } } public static class ThirdStepFragment extends GuidedStepFragment { private final static String ARG_OPTION_IDX = "arg.option.idx"; public static ThirdStepFragment newInstance(final int option) { final ThirdStepFragment f = new ThirdStepFragment(); final Bundle args = new Bundle(); args.putInt(ARG_OPTION_IDX, option); f.setArguments(args); return f; } @Override @NonNull public Guidance onCreateGuidance(Bundle savedInstanceState) { String title = getString(R.string.guidedstep_third_title); String breadcrumb = getString(R.string.guidedstep_third_breadcrumb); String description = getString(R.string.guidedstep_third_command) + OPTION_NAMES[getArguments().getInt(ARG_OPTION_IDX)]; Drawable icon = getActivity().getDrawable(R.drawable.ic_main_icon); return new Guidance(title, description, breadcrumb, icon); } @Override public void onCreateActions(@NonNull List<GuidedAction> actions, Bundle savedInstanceState) { addAction(actions, CONTINUE, "Done", "All finished"); addAction(actions, BACK, "Back", "Forgot something..."); } @Override public void onGuidedActionClicked(GuidedAction action) { if (action.getId() == CONTINUE) { getActivity().finishAfterTransition(); } else { getFragmentManager().popBackStack(); } } } }
{'content_hash': 'caafc1cd4708ce82285b0c6389add889', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 101, 'avg_line_length': 40.194736842105264, 'alnum_prop': 0.6207935053031295, 'repo_name': 'SeanPONeil/HyprMX-AndroidTV-Leanback', 'id': '0e8c04d1743a73cd385f16520a106b42132b6300', 'size': '8256', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/example/android/tvleanback2/ui/GuidedStepActivity.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '153566'}]}
If your function returns a type that implements `MyTrait`, you can write its return type as `-> impl MyTrait`. This can help simplify your type signatures quite a lot! ```rust,editable use std::iter; use std::vec::IntoIter; // This function combines two `Vec<i32>` and returns an iterator over it. // Look how complicated its return type is! fn combine_vecs_explicit_return_type( v: Vec<i32>, u: Vec<i32>, ) -> iter::Cycle<iter::Chain<IntoIter<i32>, IntoIter<i32>>> { v.into_iter().chain(u.into_iter()).cycle() } // This is the exact same function, but its return type uses `impl Trait`. // Look how much simpler it is! fn combine_vecs( v: Vec<i32>, u: Vec<i32>, ) -> impl Iterator<Item=i32> { v.into_iter().chain(u.into_iter()).cycle() } fn main() { let v1 = vec![1, 2, 3]; let v2 = vec![4, 5]; let mut v3 = combine_vecs(v1, v2); assert_eq!(Some(1), v3.next()); assert_eq!(Some(2), v3.next()); assert_eq!(Some(3), v3.next()); assert_eq!(Some(4), v3.next()); assert_eq!(Some(5), v3.next()); println!("all done"); } ``` More importantly, some Rust types can't be written out. For example, every closure has its own unnamed concrete type. Before `impl Trait` syntax, you had to allocate on the heap in order to return a closure. But now you can do it all statically, like this: ```rust,editable // Returns a function that adds `y` to its input fn make_adder_function(y: i32) -> impl Fn(i32) -> i32 { let closure = move |x: i32| { x + y }; closure } fn main() { let plus_one = make_adder_function(1); assert_eq!(plus_one(2), 3); } ``` You can also use `impl Trait` to return an iterator that uses `map` or `filter` closures! This makes using `map` and `filter` easier. Because closure types don't have names, you can't write out an explicit return type if your function returns iterators with closures. But with `impl Trait` you can do this easily: ```rust,editable fn double_positives<'a>(numbers: &'a Vec<i32>) -> impl Iterator<Item = i32> + 'a { numbers .iter() .filter(|x| x > &&0) .map(|x| x * 2) } ```
{'content_hash': 'b824e0f0149513c37c3e4ab9840088a5', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 90, 'avg_line_length': 30.695652173913043, 'alnum_prop': 0.647780925401322, 'repo_name': 'rust-lang-cn/rust-by-example-cn', 'id': '7b87bd2e9c5261598db5d150e406b49af377f543', 'size': '2134', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'english/src/trait/impl_trait.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '1803'}, {'name': 'Shell', 'bytes': '399'}]}