text
stringlengths
2
1.04M
meta
dict
package com.vsct.dt.strowgr.admin.core.security.model; import java.security.Principal; /** * Created by william_montaz on 12/11/2014. */ public class User implements Principal { /** * Convenient 'untracked user' information */ public static final User UNTRACKED = new User(Platform.PRODUCTION.value(),"untracked", false); private final String username; private final boolean prodUser; private final String platformValue; public User(final String platformValue, final String username, boolean prodUser) { this.username = username; this.prodUser = prodUser; this.platformValue = platformValue; } public String getUsername() { return username; } /** * @TODO: Duplicate: remove one of them.. */ @Override public String getName() { return username; } public boolean isProdUser() { return prodUser; } public String getPlatformValue() { return platformValue; } @Override public String toString() { return "User [username=" + username + ", prodUser=" + prodUser + ", platformValue=" + platformValue + "]"; } }
{ "content_hash": "0079e7ac9688a3f65cc387b813b01d72", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 108, "avg_line_length": 21.64814814814815, "alnum_prop": 0.6449957228400343, "repo_name": "voyages-sncf-technologies/strowgr", "id": "212f1f36a36db695fc984aa0059dc04c1d0837f1", "size": "1950", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "admin/admin-core/src/main/java/com/vsct/dt/strowgr/admin/core/security/model/User.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "119002" }, { "name": "Java", "bytes": "583270" }, { "name": "Makefile", "bytes": "578" }, { "name": "Shell", "bytes": "718" } ], "symlink_target": "" }
<?php namespace Ytranslator\Exception; class InvalidMethodsException { public function __construct($method, $find, $delimiter='::') { $expl = explode($delimiter, $method); if (end($expl) !== $find) { throw new InvalidArgumentException(sprintf("The method \"db\" not was found, instead: \"%s\"", $method)); } } }
{ "content_hash": "005ca6d898a22751119a1175544e1a6b", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 117, "avg_line_length": 17.5, "alnum_prop": 0.561038961038961, "repo_name": "roggeo/ytranslator", "id": "ff48290026ba8db8b6d6f06d0a01369e0aa3afb7", "size": "546", "binary": false, "copies": "1", "ref": "refs/heads/1.1", "path": "src/Exception/InvalidMethodsException.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "19352" } ], "symlink_target": "" }
<?php namespace CodeIgniter\Debug; use CodeIgniter\Config\BaseConfig; /** * Debug Toolbar * * Displays a toolbar with bits of stats to aid a developer in debugging. * * Inspiration: http://prophiler.fabfuel.de * * @package CodeIgniter\Debug */ class Toolbar { /** * Collectors to be used and displayed. * * @var array */ protected $collectors = []; /** * @var float App start time */ protected $startTime; //-------------------------------------------------------------------- /** * Constructor * * @param BaseConfig $config */ public function __construct(BaseConfig $config) { foreach ($config->toolbarCollectors as $collector) { if ( ! class_exists($collector)) { // @todo Log this! continue; } $this->collectors[] = new $collector(); } } //-------------------------------------------------------------------- /** * Run * * @param type $startTime * @param type $totalTime * @param type $startMemory * @param type $request * @param type $response * @return type */ public function run($startTime, $totalTime, $startMemory, $request, $response): string { $this->startTime = $startTime; // Data items used within the view. $collectors = $this->collectors; $totalTime = $totalTime * 1000; $totalMemory = number_format((memory_get_peak_usage() - $startMemory) / 1048576, 3); $segmentDuration = $this->roundTo($totalTime / 7, 5); $segmentCount = (int)ceil($totalTime / $segmentDuration); $varData = $this->collectVarData(); ob_start(); include(__DIR__.'/Toolbar/View/toolbar.tpl.php'); $output = ob_get_contents(); ob_end_clean(); return $output; } //-------------------------------------------------------------------- /** * Called within the view to display the timeline itself. * * @param int $segmentCount * @param int $segmentDuration * @return string */ protected function renderTimeline(int $segmentCount, int $segmentDuration): string { $displayTime = $segmentCount * $segmentDuration; $rows = $this->collectTimelineData(); $output = ''; foreach ($rows as $row) { $output .= "<tr>"; $output .= "<td>{$row['name']}</td>"; $output .= "<td>{$row['component']}</td>"; $output .= "<td style='text-align: right'>".number_format($row['duration'] * 1000, 2)." ms</td>"; $output .= "<td colspan='{$segmentCount}' style='overflow: hidden'>"; $offset = ((($row['start'] - $this->startTime) * 1000) / $displayTime) * 100; $length = (($row['duration'] * 1000) / $displayTime) * 100; $output .= "<span class='timer' style='left: {$offset}%; width: {$length}%;' title='".number_format($length, 2)."%'></span>"; $output .= "</td>"; $output .= "</tr>"; } return $output; } //-------------------------------------------------------------------- /** * Returns a sorted array of timeline data arrays from the collectors. * * @return array */ protected function collectTimelineData(): array { $data = []; // Collect it foreach ($this->collectors as $collector) { if (! $collector->hasTimelineData()) { continue; } $data = array_merge($data, $collector->timelineData()); } // Sort it return $data; } //-------------------------------------------------------------------- /** * Returns an array of data from all of the modules * that should be displayed in the 'Vars' tab. * * @return array */ protected function collectVarData()// : array { $data = []; foreach ($this->collectors as $collector) { if (! $collector->hasVarData()) { continue; } $data = array_merge($data, $collector->getVarData()); } return $data; } //-------------------------------------------------------------------- /** * Rounds a number to the nearest incremental value. * * @param $number * @param int $increments * * @return float */ protected function roundTo($number, $increments = 5) { $increments = 1 / $increments; return (ceil($number * $increments) / $increments); } //-------------------------------------------------------------------- }
{ "content_hash": "66f04d667b5f7afa1bb9178a3cc23733", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 128, "avg_line_length": 22.512953367875646, "alnum_prop": 0.5113924050632911, "repo_name": "wuzheng40/ci4t", "id": "e43fdbf9162710ea1c827cef50be2f260ea884ed", "size": "4345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "system/Debug/Toolbar.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "45414" }, { "name": "HTML", "bytes": "1107" }, { "name": "JavaScript", "bytes": "21460" }, { "name": "PHP", "bytes": "1508336" } ], "symlink_target": "" }
ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in null #### Original name null ### Remarks null
{ "content_hash": "eebc960787a9f13c81ee427caf9fefb5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 47, "avg_line_length": 10.923076923076923, "alnum_prop": 0.7183098591549296, "repo_name": "mdoering/backbone", "id": "f58fdd22a3acb80420e35a55ff059d4142a31cba", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Pericopsoxylon/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4X3/include/IfcLabel.h" #include "ifcpp/IFC4X3/include/IfcPresentationLayerAssignment.h" #include "ifcpp/IFC4X3/include/IfcProductRepresentation.h" #include "ifcpp/IFC4X3/include/IfcRepresentation.h" #include "ifcpp/IFC4X3/include/IfcRepresentationContext.h" #include "ifcpp/IFC4X3/include/IfcRepresentationItem.h" #include "ifcpp/IFC4X3/include/IfcRepresentationMap.h" // ENTITY IfcRepresentation IFC4X3::IfcRepresentation::IfcRepresentation( int tag ) { m_tag = tag; } shared_ptr<BuildingObject> IFC4X3::IfcRepresentation::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcRepresentation> copy_self( new IfcRepresentation() ); if( m_ContextOfItems ) { if( options.shallow_copy_IfcRepresentationContext ) { copy_self->m_ContextOfItems = m_ContextOfItems; } else { copy_self->m_ContextOfItems = dynamic_pointer_cast<IfcRepresentationContext>( m_ContextOfItems->getDeepCopy(options) ); } } if( m_RepresentationIdentifier ) { copy_self->m_RepresentationIdentifier = dynamic_pointer_cast<IfcLabel>( m_RepresentationIdentifier->getDeepCopy(options) ); } if( m_RepresentationType ) { copy_self->m_RepresentationType = dynamic_pointer_cast<IfcLabel>( m_RepresentationType->getDeepCopy(options) ); } for( size_t ii=0; ii<m_Items.size(); ++ii ) { auto item_ii = m_Items[ii]; if( item_ii ) { copy_self->m_Items.emplace_back( dynamic_pointer_cast<IfcRepresentationItem>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IFC4X3::IfcRepresentation::getStepLine( std::stringstream& stream ) const { stream << "#" << m_tag << "= IFCREPRESENTATION" << "("; if( m_ContextOfItems ) { stream << "#" << m_ContextOfItems->m_tag; } else { stream << "$"; } stream << ","; if( m_RepresentationIdentifier ) { m_RepresentationIdentifier->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_RepresentationType ) { m_RepresentationType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; writeEntityList( stream, m_Items ); stream << ");"; } void IFC4X3::IfcRepresentation::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_tag; } void IFC4X3::IfcRepresentation::readStepArguments( const std::vector<std::string>& args, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream ) { const size_t num_args = args.size(); if( num_args != 4 ){ std::stringstream err; err << "Wrong parameter count for entity IfcRepresentation, expecting 4, having " << num_args << ". Entity ID: " << m_tag << std::endl; throw BuildingException( err.str().c_str() ); } readEntityReference( args[0], m_ContextOfItems, map, errorStream ); m_RepresentationIdentifier = IfcLabel::createObjectFromSTEP( args[1], map, errorStream ); m_RepresentationType = IfcLabel::createObjectFromSTEP( args[2], map, errorStream ); readEntityReferenceList( args[3], m_Items, map, errorStream ); } void IFC4X3::IfcRepresentation::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { vec_attributes.emplace_back( std::make_pair( "ContextOfItems", m_ContextOfItems ) ); vec_attributes.emplace_back( std::make_pair( "RepresentationIdentifier", m_RepresentationIdentifier ) ); vec_attributes.emplace_back( std::make_pair( "RepresentationType", m_RepresentationType ) ); if( !m_Items.empty() ) { shared_ptr<AttributeObjectVector> Items_vec_object( new AttributeObjectVector() ); std::copy( m_Items.begin(), m_Items.end(), std::back_inserter( Items_vec_object->m_vec ) ); vec_attributes.emplace_back( std::make_pair( "Items", Items_vec_object ) ); } } void IFC4X3::IfcRepresentation::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { if( !m_RepresentationMap_inverse.empty() ) { shared_ptr<AttributeObjectVector> RepresentationMap_inverse_vec_obj( new AttributeObjectVector() ); for( size_t i=0; i<m_RepresentationMap_inverse.size(); ++i ) { if( !m_RepresentationMap_inverse[i].expired() ) { RepresentationMap_inverse_vec_obj->m_vec.emplace_back( shared_ptr<IfcRepresentationMap>( m_RepresentationMap_inverse[i] ) ); } } vec_attributes_inverse.emplace_back( std::make_pair( "RepresentationMap_inverse", RepresentationMap_inverse_vec_obj ) ); } if( !m_LayerAssignments_inverse.empty() ) { shared_ptr<AttributeObjectVector> LayerAssignments_inverse_vec_obj( new AttributeObjectVector() ); for( size_t i=0; i<m_LayerAssignments_inverse.size(); ++i ) { if( !m_LayerAssignments_inverse[i].expired() ) { LayerAssignments_inverse_vec_obj->m_vec.emplace_back( shared_ptr<IfcPresentationLayerAssignment>( m_LayerAssignments_inverse[i] ) ); } } vec_attributes_inverse.emplace_back( std::make_pair( "LayerAssignments_inverse", LayerAssignments_inverse_vec_obj ) ); } if( !m_OfProductRepresentation_inverse.empty() ) { shared_ptr<AttributeObjectVector> OfProductRepresentation_inverse_vec_obj( new AttributeObjectVector() ); for( size_t i=0; i<m_OfProductRepresentation_inverse.size(); ++i ) { if( !m_OfProductRepresentation_inverse[i].expired() ) { OfProductRepresentation_inverse_vec_obj->m_vec.emplace_back( shared_ptr<IfcProductRepresentation>( m_OfProductRepresentation_inverse[i] ) ); } } vec_attributes_inverse.emplace_back( std::make_pair( "OfProductRepresentation_inverse", OfProductRepresentation_inverse_vec_obj ) ); } } void IFC4X3::IfcRepresentation::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { shared_ptr<IfcRepresentation> ptr_self = dynamic_pointer_cast<IfcRepresentation>( ptr_self_entity ); if( !ptr_self ) { throw BuildingException( "IfcRepresentation::setInverseCounterparts: type mismatch" ); } if( m_ContextOfItems ) { m_ContextOfItems->m_RepresentationsInContext_inverse.emplace_back( ptr_self ); } } void IFC4X3::IfcRepresentation::unlinkFromInverseCounterparts() { if( m_ContextOfItems ) { std::vector<weak_ptr<IfcRepresentation> >& RepresentationsInContext_inverse = m_ContextOfItems->m_RepresentationsInContext_inverse; for( auto it_RepresentationsInContext_inverse = RepresentationsInContext_inverse.begin(); it_RepresentationsInContext_inverse != RepresentationsInContext_inverse.end(); ) { weak_ptr<IfcRepresentation> self_candidate_weak = *it_RepresentationsInContext_inverse; if( self_candidate_weak.expired() ) { ++it_RepresentationsInContext_inverse; continue; } shared_ptr<IfcRepresentation> self_candidate( *it_RepresentationsInContext_inverse ); if( self_candidate.get() == this ) { it_RepresentationsInContext_inverse= RepresentationsInContext_inverse.erase( it_RepresentationsInContext_inverse ); } else { ++it_RepresentationsInContext_inverse; } } } }
{ "content_hash": "cfdaab5754b4925587ca1246e47144b9", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 228, "avg_line_length": 48.74657534246575, "alnum_prop": 0.738372909933961, "repo_name": "ifcquery/ifcplusplus", "id": "fb69416e46463f8a63d2938e7fa1b9cd5b3e033f", "size": "7117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IfcPlusPlus/src/ifcpp/IFC4X3/lib/IfcRepresentation.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1270" }, { "name": "C++", "bytes": "10988148" }, { "name": "CMake", "bytes": "6507" }, { "name": "Dockerfile", "bytes": "951" } ], "symlink_target": "" }
title: My PhoneGap Day 2012 Talk is Online date: 2012-09-20 15:56:00 Z tags: - PhoneGap Network type: post format: html external: true link: http://simonmacdonald.blogspot.com/2012/09/my-phonegap-day-2012-talk-is-online.html status: publish author: Simon MacDonald --- So at PhoneGap Day US 2012 I talked about a side project I was working on to help make Cordova better by adding some extra UI bits. Since then a number of the pieces I was working on have been nominated to go into core so I will be revisiting my side project soon to bring it up to date. In&nbsp;the meantime have a good chuckle and don't be afraid to get involved in PhoneGap/Cordova development.<br /><br /> <div class="video-wrapper"> <iframe allowfullscreen="allowfullscreen" frameborder="0"src="http://www.youtube.com/embed/zhwcE6ZyoQo"></iframe> </div> <br /><br />Here are&nbsp;the <a href="https://github.com/macdonst/corinthian/blob/master/Corinthian.pdf?raw=true">slides</a> that go along with my talk.<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/72386855013225666-5662170183806761077?l=simonmacdonald.blogspot.com' alt='' /></div>
{ "content_hash": "1527347ad1988db892fbb0c802785bf0", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 409, "avg_line_length": 69.3529411764706, "alnum_prop": 0.7659033078880407, "repo_name": "phonegap/blog", "id": "5fd1bce327d67bccc986880b5a77fb2963d03511", "size": "1183", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_posts/network/macdonst/2012-09-20-my-phonegap-day-2012-talk-is-online.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4713" }, { "name": "CoffeeScript", "bytes": "1507" }, { "name": "HTML", "bytes": "738102" }, { "name": "Ruby", "bytes": "8298" } ], "symlink_target": "" }
include BenchHelpers bench_log "Run sync session, forces source adapter query on every sync request" @datasize = 100 @expected = Bench.get_test_data(@datasize) @all_objects = "[{\"version\":3},{\"token\":\"%s\"},{\"count\":%i},{\"progress_count\":0},{\"total_count\":%i},{\"insert\":""}]" @ack_token = "[{\"version\":3},{\"token\":\"\"},{\"count\":0},{\"progress_count\":%i},{\"total_count\":%i},{}]" Bench.config do |config| config.concurrency = 5 config.iterations = 2 config.user_name = "benchuser" config.password = "password" config.adapter_name = 'MockAdapter' config.get_test_server config.reset_app config.set_server_state("test_db_storage:application:#{config.user_name}",@expected) config.reset_refresh_time('MockAdapter',0) end Bench.test do |config,session| sleep rand(10) session.post "clientlogin", "#{config.host}/rc/#{Rhoconnect::API_VERSION}/app/login", :content_type => :json do {:login => config.user_name, :password => config.password}.to_json end sleep rand(10) session.post "clientcreate", "#{config.host}/rc/#{Rhoconnect::API_VERSION}/clients" client_id = JSON.parse(session.last_result.body)['client']['client_id'] session.get "get-cud", "#{config.host}/app/#{Rhoconnect::API_VERSION}/#{config.adapter_name}", {'X-RhoConnect-CLIENT-ID' => client_id} do {'p_size' => @datasize} end sleep rand(10) token = JSON.parse(session.last_result.body)[1]['token'] session.last_result.verify_body([{:version => 3},{:token => token}, {:count => @datasize},{:progress_count => 0},{:total_count => @datasize}, {:insert => @expected}].to_json) sleep rand(10) session.get "ack-cud", "#{config.host}/app/#{Rhoconnect::API_VERSION}/#{config.adapter_name}", {'X-RhoConnect-CLIENT-ID' => client_id} do {'token' => token} end session.last_result.verify_code(200) session.last_result.verify_body([{:version => 3},{:token => ''},{:count => 0}, {:progress_count => 0},{:total_count => @datasize},{}].to_json) end
{ "content_hash": "40eda16e3e7b3cb1bf94e5845a430d68", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 128, "avg_line_length": 39.90196078431372, "alnum_prop": 0.6388206388206388, "repo_name": "rhomobile/rhoconnect", "id": "e058d6c6c1156b57ed58d6d6d4aed594711b9ccc", "size": "2035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bench/scripts/query_md_script.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "106" }, { "name": "HTML", "bytes": "9860" }, { "name": "JavaScript", "bytes": "404471" }, { "name": "NSIS", "bytes": "28763" }, { "name": "Ruby", "bytes": "875664" }, { "name": "Shell", "bytes": "16814" } ], "symlink_target": "" }
package config import ( . "gopkg.in/check.v1" "github.com/go-git/go-git/v5/plumbing" ) type ConfigSuite struct{} var _ = Suite(&ConfigSuite{}) func (s *ConfigSuite) TestUnmarshal(c *C) { input := []byte(`[core] bare = true worktree = foo commentchar = bar [pack] window = 20 [remote "origin"] url = git@github.com:mcuadros/go-git.git fetch = +refs/heads/*:refs/remotes/origin/* [remote "alt"] url = git@github.com:mcuadros/go-git.git url = git@github.com:src-d/go-git.git fetch = +refs/heads/*:refs/remotes/origin/* fetch = +refs/pull/*:refs/remotes/origin/pull/* [remote "win-local"] url = X:\\Git\\ [submodule "qux"] path = qux url = https://github.com/foo/qux.git branch = bar [branch "master"] remote = origin merge = refs/heads/master `) cfg := NewConfig() err := cfg.Unmarshal(input) c.Assert(err, IsNil) c.Assert(cfg.Core.IsBare, Equals, true) c.Assert(cfg.Core.Worktree, Equals, "foo") c.Assert(cfg.Core.CommentChar, Equals, "bar") c.Assert(cfg.Pack.Window, Equals, uint(20)) c.Assert(cfg.Remotes, HasLen, 3) c.Assert(cfg.Remotes["origin"].Name, Equals, "origin") c.Assert(cfg.Remotes["origin"].URLs, DeepEquals, []string{"git@github.com:mcuadros/go-git.git"}) c.Assert(cfg.Remotes["origin"].Fetch, DeepEquals, []RefSpec{"+refs/heads/*:refs/remotes/origin/*"}) c.Assert(cfg.Remotes["alt"].Name, Equals, "alt") c.Assert(cfg.Remotes["alt"].URLs, DeepEquals, []string{"git@github.com:mcuadros/go-git.git", "git@github.com:src-d/go-git.git"}) c.Assert(cfg.Remotes["alt"].Fetch, DeepEquals, []RefSpec{"+refs/heads/*:refs/remotes/origin/*", "+refs/pull/*:refs/remotes/origin/pull/*"}) c.Assert(cfg.Remotes["win-local"].Name, Equals, "win-local") c.Assert(cfg.Remotes["win-local"].URLs, DeepEquals, []string{"X:\\Git\\"}) c.Assert(cfg.Submodules, HasLen, 1) c.Assert(cfg.Submodules["qux"].Name, Equals, "qux") c.Assert(cfg.Submodules["qux"].URL, Equals, "https://github.com/foo/qux.git") c.Assert(cfg.Submodules["qux"].Branch, Equals, "bar") c.Assert(cfg.Branches["master"].Remote, Equals, "origin") c.Assert(cfg.Branches["master"].Merge, Equals, plumbing.ReferenceName("refs/heads/master")) } func (s *ConfigSuite) TestMarshal(c *C) { output := []byte(`[core] bare = true worktree = bar [pack] window = 20 [remote "alt"] url = git@github.com:mcuadros/go-git.git url = git@github.com:src-d/go-git.git fetch = +refs/heads/*:refs/remotes/origin/* fetch = +refs/pull/*:refs/remotes/origin/pull/* [remote "origin"] url = git@github.com:mcuadros/go-git.git [remote "win-local"] url = "X:\\Git\\" [submodule "qux"] url = https://github.com/foo/qux.git [branch "master"] remote = origin merge = refs/heads/master `) cfg := NewConfig() cfg.Core.IsBare = true cfg.Core.Worktree = "bar" cfg.Pack.Window = 20 cfg.Remotes["origin"] = &RemoteConfig{ Name: "origin", URLs: []string{"git@github.com:mcuadros/go-git.git"}, } cfg.Remotes["alt"] = &RemoteConfig{ Name: "alt", URLs: []string{"git@github.com:mcuadros/go-git.git", "git@github.com:src-d/go-git.git"}, Fetch: []RefSpec{"+refs/heads/*:refs/remotes/origin/*", "+refs/pull/*:refs/remotes/origin/pull/*"}, } cfg.Remotes["win-local"] = &RemoteConfig{ Name: "win-local", URLs: []string{"X:\\Git\\"}, } cfg.Submodules["qux"] = &Submodule{ Name: "qux", URL: "https://github.com/foo/qux.git", } cfg.Branches["master"] = &Branch{ Name: "master", Remote: "origin", Merge: "refs/heads/master", } b, err := cfg.Marshal() c.Assert(err, IsNil) c.Assert(string(b), Equals, string(output)) } func (s *ConfigSuite) TestUnmarshalMarshal(c *C) { input := []byte(`[core] bare = true worktree = foo custom = ignored [pack] window = 20 [remote "origin"] url = git@github.com:mcuadros/go-git.git fetch = +refs/heads/*:refs/remotes/origin/* mirror = true [remote "win-local"] url = "X:\\Git\\" [branch "master"] remote = origin merge = refs/heads/master `) cfg := NewConfig() err := cfg.Unmarshal(input) c.Assert(err, IsNil) output, err := cfg.Marshal() c.Assert(err, IsNil) c.Assert(string(output), DeepEquals, string(input)) } func (s *ConfigSuite) TestValidateConfig(c *C) { config := &Config{ Remotes: map[string]*RemoteConfig{ "bar": { Name: "bar", URLs: []string{"http://foo/bar"}, }, }, Branches: map[string]*Branch{ "bar": { Name: "bar", }, "foo": { Name: "foo", Remote: "origin", Merge: plumbing.ReferenceName("refs/heads/foo"), }, }, } c.Assert(config.Validate(), IsNil) } func (s *ConfigSuite) TestValidateInvalidRemote(c *C) { config := &Config{ Remotes: map[string]*RemoteConfig{ "foo": {Name: "foo"}, }, } c.Assert(config.Validate(), Equals, ErrRemoteConfigEmptyURL) } func (s *ConfigSuite) TestValidateInvalidRemoteKey(c *C) { config := &Config{ Remotes: map[string]*RemoteConfig{ "bar": {Name: "foo"}, }, } c.Assert(config.Validate(), Equals, ErrInvalid) } func (s *ConfigSuite) TestRemoteConfigValidateMissingURL(c *C) { config := &RemoteConfig{Name: "foo"} c.Assert(config.Validate(), Equals, ErrRemoteConfigEmptyURL) } func (s *ConfigSuite) TestRemoteConfigValidateMissingName(c *C) { config := &RemoteConfig{} c.Assert(config.Validate(), Equals, ErrRemoteConfigEmptyName) } func (s *ConfigSuite) TestRemoteConfigValidateDefault(c *C) { config := &RemoteConfig{Name: "foo", URLs: []string{"http://foo/bar"}} c.Assert(config.Validate(), IsNil) fetch := config.Fetch c.Assert(fetch, HasLen, 1) c.Assert(fetch[0].String(), Equals, "+refs/heads/*:refs/remotes/foo/*") } func (s *ConfigSuite) TestValidateInvalidBranchKey(c *C) { config := &Config{ Branches: map[string]*Branch{ "foo": { Name: "bar", Remote: "origin", Merge: plumbing.ReferenceName("refs/heads/bar"), }, }, } c.Assert(config.Validate(), Equals, ErrInvalid) } func (s *ConfigSuite) TestValidateInvalidBranch(c *C) { config := &Config{ Branches: map[string]*Branch{ "bar": { Name: "bar", Remote: "origin", Merge: plumbing.ReferenceName("refs/heads/bar"), }, "foo": { Name: "foo", Remote: "origin", Merge: plumbing.ReferenceName("baz"), }, }, } c.Assert(config.Validate(), Equals, errBranchInvalidMerge) } func (s *ConfigSuite) TestRemoteConfigDefaultValues(c *C) { config := NewConfig() c.Assert(config.Remotes, HasLen, 0) c.Assert(config.Branches, HasLen, 0) c.Assert(config.Submodules, HasLen, 0) c.Assert(config.Raw, NotNil) c.Assert(config.Pack.Window, Equals, DefaultPackWindow) }
{ "content_hash": "401dd194c10720a4fe9bff2966ebcde6", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 140, "avg_line_length": 26.043650793650794, "alnum_prop": 0.6577784549748591, "repo_name": "mcuadros/go-git", "id": "e5e3be543b4160116ef31c11fade2cfa322b8b39", "size": "6563", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/config_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1440866" }, { "name": "Makefile", "bytes": "1150" }, { "name": "Shell", "bytes": "2266" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Fri Aug 22 03:43:49 EDT 2003 --> <TITLE> Uses of Package org.apache.struts.tiles.beans (Apache Struts API Documentation) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <SCRIPT> function asd() { parent.document.title="Uses of Package org.apache.struts.tiles.beans (Apache Struts API Documentation)"; } </SCRIPT> <BODY BGCOLOR="white" onload="asd();"> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_top"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" TARGET="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp; <SCRIPT> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <CENTER> <H2> <B>Uses of Package<br>org.apache.struts.tiles.beans</B></H2> </CENTER> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/apache/struts/tiles/beans/package-summary.html">org.apache.struts.tiles.beans</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.struts.tiles.beans"><B>org.apache.struts.tiles.beans</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.struts.tiles.beans"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Classes in <A HREF="../../../../../org/apache/struts/tiles/beans/package-summary.html">org.apache.struts.tiles.beans</A> used by <A HREF="../../../../../org/apache/struts/tiles/beans/package-summary.html">org.apache.struts.tiles.beans</A><TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../org/apache/struts/tiles/beans/class-use/MenuItem.html#org.apache.struts.tiles.beans"><B>MenuItem</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Interface for MenuItems.</TD> </TR> </FONT></TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_bottom"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" TARGET="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp; <SCRIPT> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html" TARGET=""><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> Copyright © 2000-2003 - Apache Software Foundation </BODY> </HTML>
{ "content_hash": "0c882349f43a13fc1157c85676613962", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 280, "avg_line_length": 42.12582781456954, "alnum_prop": 0.6145260179217105, "repo_name": "codelibs/cl-struts", "id": "88cda1f40bba633fe139917422d5e93415efd52e", "size": "6361", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "legacy/api-1.1/org/apache/struts/tiles/beans/package-use.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "42594" }, { "name": "GAP", "bytes": "7214" }, { "name": "HTML", "bytes": "17088052" }, { "name": "Java", "bytes": "6592773" }, { "name": "XSLT", "bytes": "36989" } ], "symlink_target": "" }
Register-PSFTeppScriptblock -Name PSMD_dotNetTemplatesInstall -ScriptBlock { Get-PSFTaskEngineCache -Module PSModuleDevelopment -Name "dotNetTemplates" }
{ "content_hash": "8b916c442f9329afc9343ca88c0ba0bd", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 77, "avg_line_length": 51.666666666666664, "alnum_prop": 0.8516129032258064, "repo_name": "FriedrichWeinmann/PSModuleDevelopment", "id": "a4b04e5426dc65331379df7440815dbb6e9d4c50", "size": "157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PSModuleDevelopment/internal/tabcompletion/scriptblocks/dotNetTemplatesInstall.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "10471" }, { "name": "PowerShell", "bytes": "111772" } ], "symlink_target": "" }
<?php namespace BaleenTest\Migrations\Service\DomainBus\Migrate\Single; use Baleen\Migrations\Migration\OptionsInterface; use Baleen\Migrations\Service\DomainBus\Migrate\AbstractRunnerHandler; use Baleen\Migrations\Service\DomainBus\Migrate\Single\SingleHandler; use Baleen\Migrations\Service\Runner\Event\Migration\MigrateAfterEvent; use Baleen\Migrations\Service\Runner\MigrationRunner; use Baleen\Migrations\Service\Runner\MigrationRunnerInterface; use Baleen\Migrations\Service\Runner\RunnerInterface; use Baleen\Migrations\Common\Event\Context\ContextInterface; use Baleen\Migrations\Common\Event\DomainEventInterface; use Baleen\Migrations\Delta\Repository\VersionRepositoryInterface; use Baleen\Migrations\Delta\DeltaInterface; use BaleenTest\Migrations\Service\DomainBus\Migrate\HandlerTestCase; use Mockery as m; /** * Class SingleHandlerTest * @author Gabriel Somoza <gabriel@strategery.io> */ class SingleHandlerTest extends HandlerTestCase { /** * testHandle * @return void */ public function testHandle() { $handler = $this->createHandler(); /** @var DeltaInterface|m\Mock $version */ $version = m::mock(DeltaInterface::class); /** @var DomainEventInterface|m\Mock $afterEvent */ $afterEvent = m::mock(DomainEventInterface::class, [ 'getTarget' => $version, ]); /** @var RunnerInterface|m\Mock $runner */ $runner = $this->invokeMethod('getRunner', $handler); $runner->shouldReceive('run') ->with( m::type(DeltaInterface::class), m::type(OptionsInterface::class) ) ->once() ->andReturn($afterEvent); $runner->shouldReceive('withContext') ->with(m::type(ContextInterface::class)) ->once() ->andReturnSelf(); $command = SingleCommandTest::createMockedCommand(); /** @var VersionRepositoryInterface|m\Mock $storage */ $storage = $command->getVersionRepository(); $storage->shouldReceive('update')->with($version)->once()->andReturn('foo'); $result = $handler->handle($command); $this->assertEquals('foo', $result); } /** * createHandler * @param RunnerInterface $runner * @return SingleHandler */ protected function createHandler(RunnerInterface $runner = null) { if (null === $runner) { /** @var MigrationRunnerInterface|m\Mock $runner */ $runner = m::mock(MigrationRunnerInterface::class); } return new SingleHandler($runner); } }
{ "content_hash": "3a61d3d879cde1745da8889bce3be9c6", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 84, "avg_line_length": 33.21518987341772, "alnum_prop": 0.6627286585365854, "repo_name": "baleen/migrations", "id": "68a7598d32eeb261687876e7fc2975d5eb61a276", "size": "3605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/Service/DomainBus/Migrate/Single/SingleHandlerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "319900" } ], "symlink_target": "" }
package filesystem import ( "bytes" "crypto/md5" "encoding/hex" "errors" "flag" "os" "path/filepath" "reflect" "testing" "time" "github.com/adelowo/onecache" ) var _ onecache.Store = MustNewFSStore("./") var _ onecache.GarbageCollector = MustNewFSStore("./") var fileCache *FSStore func TestMain(m *testing.M) { fileCache = MustNewFSStore("./../cache") flag.Parse() os.Exit(m.Run()) } func TestMustNewFSStore(t *testing.T) { defer func() { recover() }() _ = MustNewFSStore("/hh") } var sampleData = []byte("Lanre") func TestFSStore_Set(t *testing.T) { err := fileCache.Set("name", sampleData, time.Minute*2) if err != nil { t.Fatal(err) } } func TestFSStore_Get(t *testing.T) { val, err := fileCache.Get("name") if err != nil { t.Fatal(err) } if !reflect.DeepEqual(val, sampleData) { t.Fatalf( `Values are not equal.. Expected %v \n Got %v`, sampleData, val) } } func TestFSStore_GetUnknownKey(t *testing.T) { val, err := fileCache.Get("unknown") if err == nil { t.Fatal("Expected an error for a file that doesn't exist on the filesystem") } if val != nil { t.Fatalf("Expected a nil item to be return ... Got %v instead", val) } if err != onecache.ErrCacheMiss { t.Fatalf("unexpected error found...Expected %v , got %v", onecache.ErrCacheMiss, err) } } func TestFSStore_GarbageCollection(t *testing.T) { err := fileCache.Set("xyz", []byte("Elon Musk"), onecache.EXPIRES_DEFAULT) if err != nil { t.Fatalf("An error occurred... %v", err) } data, err := fileCache.Get("xyz") if err != onecache.ErrCacheMiss { t.Fatal("Cached data is supposed to be expired") } if data != nil { t.Fatal("Garbage collected item is supposed to be empty") } } func TestFSStore_Flush(t *testing.T) { if err := fileCache.Flush(); err != nil { t.Fatalf("The cache directory, %s could not be flushed... %v", fileCache.baseDir, err) } } func TestFilePathForKey(t *testing.T) { key := "page_hits" b := md5.Sum([]byte(key)) s := hex.EncodeToString(b[:]) path := filepath.Join(fileCache.baseDir, s[0:2], s[2:4], s[4:6], s) if x := fileCache.filePathFor("page_hits"); path != x && FilePathKeyFunc(key) != path { t.Fatalf("Path differs.. Expected %s. Got %s instead", path, x) } } type mockSerializer struct { } func (b *mockSerializer) Serialize(i interface{}) ([]byte, error) { return nil, errors.New("Yup an error occurred") } func (b *mockSerializer) DeSerialize(data []byte, i interface{}) error { return errors.New("Yet another error") } func TestFSStore_GetFailsBecauseOfBytesMarshalling(t *testing.T) { fileCache.Set("test", []byte("test"), time.Second*1) fs, err := New(BaseDirectory("./cache"), Serializer(&mockSerializer{})) if err != nil { t.Fatal(err) } _, err = fs.Get("test") if err == nil { t.Fatalf( `Expected a cache miss.. Got %v`, err) } } func TestFSStore_SetFailsBecauseOfBytesMarshalling(t *testing.T) { fs, err := New(BaseDirectory("./cache"), Serializer(&mockSerializer{})) if err != nil { t.Fatal(err) } defer fs.Flush() err = fs.Set("test", []byte("test"), time.Nanosecond*4) if err == nil { t.Fatalf( `Expected an error from bytes marshalling.. Got %v`, err) } } func TestFSStore_Delete(t *testing.T) { if err := fileCache.Delete("name"); err != nil { t.Fatalf("Could not delete the cached data... %v", err) } } func TestFSStore_GC(t *testing.T) { store := MustNewFSStore("./../cache") defer store.Flush() tableTests := []struct { key, value string expires time.Duration }{ {"name", "Onecache", time.Microsecond}, {"number", "Fourty two", time.Microsecond}, {"x", "yz", time.Microsecond}, } for _, v := range tableTests { store.Set(v.key, []byte(v.value), v.expires) } ticker := time.NewTicker(time.Millisecond) <-ticker.C store.GC() var filePath string for _, v := range tableTests { filePath = store.filePathFor(v.key) if _, err := os.Stat(filePath); err == nil { t.Fatal( `File exists when it isn't supposed to since there was a garbage collection`) } } } func TestFSStore_Has(t *testing.T) { store := MustNewFSStore("./../cache") defer store.Flush() if ok := store.Has("name"); ok { t.Fatalf("Key %s is not supposed to exist in the cache", "name") } store.Set("name", []byte("Lanre"), time.Hour*10) if ok := store.Has("name"); !ok { t.Fatalf(`Expected store to have an item with key %s since that key was persisted secs ago`, "name") } } func BenchmarkFSStore_Get(b *testing.B) { store := MustNewFSStore("./../cache") key := "life" answer := []byte("42") err := store.Set(key, answer, time.Minute*10) if err != nil { b.Fatalf("an error occurred while setting key in cache store... %v", err) } b.ResetTimer() equals := func(a, b []byte) bool { return bytes.Equal(a, b) } for i := 0; i <= b.N; i++ { buf, err := store.Get(key) if err != nil { b.Fatalf("an error happened while reading from cache.... %v", err) } if !equals(answer, buf) { b.Fatalf(`Data does not match... Expected %v \n Got %v`, answer, buf) } } }
{ "content_hash": "f37cd3629429b822080f502ffb35ea0b", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 88, "avg_line_length": 20.17063492063492, "alnum_prop": 0.6380090497737556, "repo_name": "adelowo/onecache", "id": "992e9b1f3b2bc7e307008f7cbfd2ef2b910c38cf", "size": "5083", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "filesystem/fs_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "35422" }, { "name": "Makefile", "bytes": "593" } ], "symlink_target": "" }
from __future__ import absolute_import from __future__ import unicode_literals
{ "content_hash": "58f214f084d82c07089cb83aab70d9fb", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 39, "avg_line_length": 20.25, "alnum_prop": 0.7530864197530864, "repo_name": "huogerac/django-onedeploy", "id": "ab8d1e9ec07473f222717db244fe2c3e893e57bb", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "onedeploy/urls.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "1573" }, { "name": "Python", "bytes": "11605" } ], "symlink_target": "" }
from blacksalt import BlackSalt iptables = BlackSalt() # When creating a BlackSalt instance you can pass in keyword arguments # of arguments, the allowed arguments are: # iptables = "BIN LOCATION HERE" # This defaults to /sbin/iptables # printmode = True or False # This defaults to True and will print the rules # # to stdout when generating the tables. # scriptfile = "Name and location of file" #If set, generating rule will output # # to this file # These can be set after creation, by just setting the variables i.e. # iptables.printmode = False # iptables.scriptfile = "/usr/local/scripts/firewall" # iptables.iptables = "/usr/local/bin/iptables" SUBNETS = ["192.168.10.0/24", "192.168.11.0/24", "192.168.12.0/24"] SERVICES = {"SSH": "22", "SMTP": "25", "HTTP": "80", "MYSQL": "3306"} # Here we'll add connection tracking and ftp connection tracking, they # can be added anywhere in a blacksalt script, they will always appear # at the top. iptables.setmodule(["ip_conntrack", "ip_conntrack_ftp"]) # Flush tables iptables.flush() # Set default policies iptables.policy([("input", "drop"), ("output", "accept"), ("forward", "drop")]) # Allow everything on loop back interface iptables.setrule(chain="input", interface={"name": "lo", "direction": "in"}, target="accept") iptables.setrule(chain="output", interface={"name": "lo", "direction": "out"}, target="accept") # Allow everything on local subnets for subnet in SUBNETS: iptables.setrule(chain="input", interface={"direction": "in", "name": "eth0"}, subnet=subnet, target="accept", state="new, related, established") iptables.setrule(chain="output", interface={"direction": "out", "name": "eth0"}, subnet=subnet, target="accept", state="new, related, established") # Allow ICMP Ping iptables.setrule(chain="input", interface={"direction": "in", "name": "eth0"}, target="accept", state="new, related, established", icmp=8) # Allow all ESTABLISHED, RELATED connections going out iptables.setrule(chain="output", interface={"direction": "out", "name": "eth0"}, state="established, related", target="accept") # Allow all HTTP connections going in in iptables.setrule(chain="input", interface={"direction": "in", "name": "eth0"}, dst="80", state="new, established, related", target="accept") # Drop all NEW connections coming in iptables.setrule(chain="input", interface={"direction": "in", "name": "eth0"}, state="new", target="drop") # Generate the script, but first disable outputting to the console, and save it in a scriptfile iptables.printmode = False iptables.scriptfile = "firewall.sh" iptables.generate()
{ "content_hash": "0bac4f164102450c564aef3d6a108029", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 106, "avg_line_length": 49.767857142857146, "alnum_prop": 0.6641550053821313, "repo_name": "nonapod/blacksalt", "id": "d6e4c7dfb588c7f2ce29ac90709cf5b5c0382830", "size": "2880", "binary": false, "copies": "1", "ref": "refs/heads/0.2.2", "path": "firewall.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "31911" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="cardview_toolbar_spacer">80dp</dimen> <dimen name="toolbar_double_height">96dp</dimen> </resources>
{ "content_hash": "5233e76beb51e5b8e083e9a95261fefb", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 54, "avg_line_length": 24.714285714285715, "alnum_prop": 0.6820809248554913, "repo_name": "Suleiman19/Android-Material-Design-for-pre-Lollipop", "id": "c349b18b933fef3787043a32def4276efd72a294", "size": "173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MaterialSample/app/src/main/res/values-land/dimens.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "83172" } ], "symlink_target": "" }
[![Code Climate](https://codeclimate.com/github/puneethrai/OWE-Reimagined/badges/gpa.svg)](https://codeclimate.com/github/puneethrai/OWE-Reimagined) This is totally reimagined version of my original OWE app https://github.com/puneethrai/OWE Demo: http://puneethrai.github.io/OWE-Reimagined
{ "content_hash": "45ac26dfe8462cf4b51455b5791249bf", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 148, "avg_line_length": 73, "alnum_prop": 0.797945205479452, "repo_name": "puneethrai/OWE-Reimagined", "id": "43b92d5771d0c261d8c868ecfbdb8e2bea02b15f", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OWE/www/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "116170" }, { "name": "HTML", "bytes": "13145" }, { "name": "JavaScript", "bytes": "199989" } ], "symlink_target": "" }
<?php include_once "init.inc.php"; include_once "utils.inc.php"; function auth_fingerprint($username) { $username_encoded = urlencode($username); $result = mysql_query("SELECT password FROM users WHERE username = '$username_encoded'") or die(mysql_error()); if (mysql_num_rows($result) != 1) { return False; } $row = mysql_fetch_array($result); $password_encoded = $row["password"]; return hash("sha512", $password_encoded.$_SERVER["HTTP_USER_AGENT"].$_SERVER["REMOTE_ADDR"]."fingerprint"); } function auth_check_password($username, $password) { $username_encoded = urlencode($username); $result = mysql_query("SELECT salt, password FROM users WHERE username = '$username_encoded'") or die(mysql_error()); if (mysql_num_rows($result) != 1) { return False; } $row = mysql_fetch_array($result); $salt = $row["salt"]; $password_encoded = hash("sha512", $password.$salt); if ($password_encoded != $row["password"]) { return False; } return True; } function auth_add_user($username, $password, $is_admin=false) { $username_encoded = urlencode($username); $salt = hash("sha512", uniqid(mt_rand(1, mt_getrandmax()), true)); $password_encoded = hash("sha512", $password.$salt); mysql_query("INSERT INTO users (username, password, salt, is_admin) VALUES ('$username_encoded', '$password_encoded', '$salt', '$is_admin')") or die(mysql_error()); } function auth_remove_user($username) { $username_encoded = urlencode($username); mysql_query("DELETE FROM users WHERE username = '$username_encoded'") or die(mysql_error()); } function auth_change_password($username, $password) { $username_encoded = urlencode($username); $salt = hash("sha512", uniqid(mt_rand(1, mt_getrandmax()), true)); $password_encoded = hash("sha512", $password.$salt); mysql_query("UPDATE users SET salt = '$salt', password = '$password_encoded' WHERE username = '$username_encoded'") or die(mysql_error()); } function auth_change_is_admin($username, $is_admin) { $username_encoded = urlencode($username); mysql_query("UPDATE users SET is_admin = $is_admin WHERE username = '$username_encoded'") or die(mysql_error()); } function authenticate($username, $password) { if (! auth_check_password($username, $password)) { return False; } $_SESSION["username"] = $username; $_SESSION["fingerprint"] = auth_fingerprint($username); return True; } function deauthenticate() { unset($_SESSION["username"]); unset($_SESSION["fingerprint"]); } function is_logged() { if (!isset($_SESSION["username"])) { return False; } $username_encoded = urlencode($_SESSION["username"]); $result = mysql_query("SELECT password FROM users WHERE username = '$username_encoded'") or die(mysql_error()); if (mysql_num_rows($result) != 1) { return False; } $row = mysql_fetch_array($result); $password_encoded = $row["password"]; $fingerprint = auth_fingerprint($_SESSION["username"]); return $fingerprint == $_SESSION["fingerprint"]; } function is_admin() { if (!is_logged()) { return false; } $username_encoded = urlencode($_SESSION["username"]); $result = mysql_query("SELECT is_admin FROM users WHERE username = '$username_encoded'") or die(mysql_error()); if (mysql_num_rows($result) != 1) { die("something gone wrong"); } $row = mysql_fetch_array($result); $is_admin = $row["is_admin"]; return $is_admin; } function username() { if (is_logged()) { return $_SESSION["username"]; } return NULL; } function assert_is_admin() { if (!is_admin()) { redirect_site("login.php"); exit; } } function assert_is_logged() { if (!is_logged()) { redirect_site("login.php"); exit; } } ?>
{ "content_hash": "6a8bee652086bda6216f298bb5292913", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 166, "avg_line_length": 26.85611510791367, "alnum_prop": 0.6530940262523439, "repo_name": "KMSUJ/archive", "id": "46fa0ee193082fc3ee059c468f595baaeb8ebefd", "size": "3733", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "auth.inc.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2469" }, { "name": "HTML", "bytes": "31712" }, { "name": "PHP", "bytes": "33753" } ], "symlink_target": "" }
import { VO } from './VO'; declare let window:Window; declare let knalledge:any; declare let global:any; declare let module:any; /** * @classdesc VKMap is data representation of the knowledge (KnAllEdge) map. * It is stored on the server and it connects with other maps through edges * represented with kEdges * @class KMap */ export class KMap extends VO { //name that is displayed, when map is visualized is inherited from the VO class rootNodeId:string = null; parentMapId:string = ""; participants:string[] = []; //status = ; // // TODO:ng2 TS needs dataContent declared, // we should check if this makes dataContent ending up // at the server even when is it empty dataContent:any = null; //additional data is stored in this object // dataContent.property = null; // value of map content (Additional Info) visual:any = {}; constructor() { super(); this.init(); } init():void { super.init(); this.isPublic = false; } static mapFactory(obj:any):KMap { //TODO:remove - kept only for legacy of the old code return KMap.factory(obj); } static factory(obj:any):KMap { return VO.VOfactory<KMap>(obj, KMap); } fill(obj:any):void { if(obj){ super.fill(obj); if("rootNodeId" in obj){this.rootNodeId = obj.rootNodeId;} if("parentMapId" in obj){this.parentMapId = obj.parentMapId;} if("participants" in obj){this.participants = obj.participants;} //TODO deep copy of array? if("dataContent" in obj){this.dataContent = obj.dataContent;} //TODO: deep copy? if("visual" in obj){this.visual = obj.visual;} //TODO: deep copy? } } } // map support (export) if (typeof module !== 'undefined'){ // workarround for TypeScript's `module.exports` readonly if('exports' in module){ if (typeof module.exports !== 'undefined'){ module.exports.KMap = KMap; } }else{ module.exports = KMap; } }
{ "content_hash": "d978d4bbbf77ee4883dd6858b4306cc6", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 95, "avg_line_length": 27.63768115942029, "alnum_prop": 0.6680650235972732, "repo_name": "mprinc/KnAllEdge", "id": "2fdce44144b3dd2c774170bccd036ae188b13c02", "size": "1907", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/frontend/dev_puzzles/knalledge/core/code/knalledge/kMap.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "924" }, { "name": "CSS", "bytes": "224333" }, { "name": "HTML", "bytes": "415842" }, { "name": "JavaScript", "bytes": "2069178" }, { "name": "Makefile", "bytes": "715" }, { "name": "Ruby", "bytes": "503" }, { "name": "Shell", "bytes": "16268" }, { "name": "TypeScript", "bytes": "350360" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ccs: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.dev / ccs - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ccs <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-08-11 14:39:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-11 14:39:01 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/ccs&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/CCS&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: Labelled Transitions Systems&quot; &quot;keyword: Process Algebra&quot; &quot;keyword: Calculus of Concurrent Process (CCS)&quot; &quot;category: Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems&quot; ] authors: [ &quot;Solange Coupet-Grimal&quot; ] bug-reports: &quot;https://github.com/coq-contribs/ccs/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/ccs.git&quot; synopsis: &quot;Equivalence notions on labelled transitions systems&quot; description: &quot;&quot;&quot; We give the specification of three different notions of equivalence classically defined on labelled transitions systems underlying the theories of process algebra (and particularly CCS). The fundamentals properties of these equivalence notions are proven.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/ccs/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=a13fbede8302bc09f1d6d8d79c53c378&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-ccs.8.7.0 coq.8.10.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.dev). The following dependencies couldn&#39;t be met: - coq-ccs -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ccs.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "d700004cb84c8cb4b0dc96aacb79adc3", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 255, "avg_line_length": 42.34131736526946, "alnum_prop": 0.5507000424268137, "repo_name": "coq-bench/coq-bench.github.io", "id": "1369d192cfda18bf4aa216a2d5190f6792cac2bb", "size": "7096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/extra-dev/8.10.dev/ccs/8.7.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "7ea43a0ede258e005fa8d1931d696f27", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "fb3b3c08a5594af432773953fa274a97350033cd", "size": "216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Peperomia/Peperomia pseudovariegata/Peperomia pseudovariegata sarcophylla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import { useRouter } from 'next/router' export default function Post(props) { const router = useRouter() if (typeof window === 'undefined') { if (router.query.post?.startsWith('redir')) { console.log(router) throw new Error('render should not occur for redirect') } } if (typeof window !== 'undefined' && !window.initialHref) { window.initialHref = window.location.href } if (router.isFallback) return <p>Loading...</p> return ( <> <p id="gsp">getStaticProps</p> <p id="props">{JSON.stringify(props)}</p> </> ) } export const getStaticProps = ({ params }) => { if (params.post.startsWith('redir')) { let destination = '/404' if (params.post.includes('dest-external')) { destination = 'https://example.com' } else if (params.post.includes('dest-')) { destination = params.post.split('dest-').pop().replace(/_/g, '/') } let permanent = undefined let statusCode = undefined if (params.post.includes('statusCode-')) { permanent = parseInt( params.post.split('statusCode-').pop().split('-').shift(), 10 ) } if (params.post.includes('permanent')) { permanent = true } else if (!statusCode) { permanent = false } let revalidate if (params.post.includes('revalidate-')) { revalidate = 1 } console.log('redirecting', { destination, permanent, statusCode, revalidate, }) return { redirect: { destination, permanent, statusCode, }, revalidate, } } return { props: { params, }, } } export const getStaticPaths = () => { return { paths: ['first', 'second'].map((post) => ({ params: { post } })), fallback: 'blocking', } }
{ "content_hash": "5a031c90fb0ffac84f1896f8bd206970", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 71, "avg_line_length": 21.08139534883721, "alnum_prop": 0.5659128516271373, "repo_name": "azukaru/next.js", "id": "72807960f78c37bf3faf592d5f7a9d652bf5868c", "size": "1813", "binary": false, "copies": "4", "ref": "refs/heads/canary", "path": "test/integration/gssp-redirect/pages/gsp-blog-blocking/[post].js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "579" }, { "name": "CSS", "bytes": "28169" }, { "name": "Dockerfile", "bytes": "523" }, { "name": "JavaScript", "bytes": "8479433" }, { "name": "Rust", "bytes": "218402" }, { "name": "SCSS", "bytes": "5645" }, { "name": "Sass", "bytes": "26" }, { "name": "Shell", "bytes": "5419" }, { "name": "TypeScript", "bytes": "2472830" } ], "symlink_target": "" }
from nose import * from ldns import LDNS_SECTION_QUESTION from ldns.packet import Packet from ldns.resourcerecord import resource_record_from_str RR1 = "www.google.de. 299 IN AAAA 2a00:1450:4016:803::1018" RR2 = "www.google.de. 299 IN A 173.194.44.55" class TestPacket(object): def setup(self): self.pkt = Packet() def teardown(self): self.pkt = None @with_setup(None, None) def test_new_packet(self): pkt = Packet() del pkt def test_push_rr(self): rr1 = resource_record_from_str(RR1) self.pkt.push_rr(rr1, LDNS_SECTION_QUESTION) assert(not self.pkt.is_empty())
{ "content_hash": "77704915f5d2a8469955bb2cd684c84e", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 59, "avg_line_length": 23.925925925925927, "alnum_prop": 0.6501547987616099, "repo_name": "gegenschall/cython-ldns", "id": "d8c521f139a9da97b3dd41e9b0cca2875efdcdb1", "size": "646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_packet.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "105221" } ], "symlink_target": "" }
'use strict'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } import * as React from 'react'; import { forwardRef, memo, useMemo, useState, useRef } from 'react'; import setAndForwardRef from '../../modules/setAndForwardRef'; import usePressEvents from '../../hooks/usePressEvents'; import View from '../View'; /** * Component used to build display components that should respond to whether the * component is currently pressed or not. */ function Pressable(props, forwardedRef) { var accessible = props.accessible, children = props.children, delayLongPress = props.delayLongPress, delayPressIn = props.delayPressIn, delayPressOut = props.delayPressOut, disabled = props.disabled, focusable = props.focusable, onBlur = props.onBlur, onFocus = props.onFocus, onLongPress = props.onLongPress, onPress = props.onPress, onPressMove = props.onPressMove, onPressIn = props.onPressIn, onPressOut = props.onPressOut, style = props.style, testOnly_pressed = props.testOnly_pressed, rest = _objectWithoutPropertiesLoose(props, ["accessible", "children", "delayLongPress", "delayPressIn", "delayPressOut", "disabled", "focusable", "onBlur", "onFocus", "onLongPress", "onPress", "onPressMove", "onPressIn", "onPressOut", "style", "testOnly_pressed"]); var _useForceableState = useForceableState(false), focused = _useForceableState[0], setFocused = _useForceableState[1]; var _useForceableState2 = useForceableState(testOnly_pressed === true), pressed = _useForceableState2[0], setPressed = _useForceableState2[1]; var hostRef = useRef(null); var setRef = useMemo(function () { return setAndForwardRef({ getForwardedRef: function getForwardedRef() { return forwardedRef; }, setLocalRef: function setLocalRef(hostNode) { hostRef.current = hostNode; } }); }, [forwardedRef]); var pressConfig = useMemo(function () { return { delayLongPress: delayLongPress, delayPressStart: delayPressIn, delayPressEnd: delayPressOut, disabled: disabled, onLongPress: onLongPress, onPress: onPress, onPressChange: setPressed, onPressStart: onPressIn, onPressMove: onPressMove, onPressEnd: onPressOut }; }, [delayLongPress, delayPressIn, delayPressOut, disabled, onLongPress, onPress, onPressIn, onPressMove, onPressOut, setPressed]); var pressEventHandlers = usePressEvents(hostRef, pressConfig); var accessibilityState = _objectSpread({ disabled: disabled }, props.accessibilityState); var interactionState = { focused: focused, pressed: pressed }; function createFocusHandler(callback, value) { return function (event) { if (event.nativeEvent.target === hostRef.current) { setFocused(value); if (callback != null) { callback(event); } } }; } return React.createElement(View, _extends({}, rest, pressEventHandlers, { accessibilityState: accessibilityState, accessible: accessible !== false, focusable: focusable !== false, onBlur: createFocusHandler(onBlur, false), onFocus: createFocusHandler(onFocus, true), ref: setRef, style: typeof style === 'function' ? style(interactionState) : style }), typeof children === 'function' ? children(interactionState) : children); } function useForceableState(forced) { var _useState = useState(false), pressed = _useState[0], setPressed = _useState[1]; return [pressed || forced, setPressed]; } var MemoedPressable = memo(forwardRef(Pressable)); MemoedPressable.displayName = 'Pressable'; export default MemoedPressable;
{ "content_hash": "4bcfde7060d4f6dbab80d032090868ca", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 534, "avg_line_length": 44.96666666666667, "alnum_prop": 0.6938472942920682, "repo_name": "cdnjs/cdnjs", "id": "57b56d33e37b04c7601b8ff94fb00681dd48599b", "size": "5602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/react-native-web/0.0.0-dfb716c98/exports/Pressable/index.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/** * @file src/storage/Integrity.cpp * @author Pawel Wieczorek <p.wieczorek2@samsung.com> * @version 0.1 * @brief Implementation of Cynara::Integrity */ #include <dirent.h> #include <errno.h> #include <fstream> #include <functional> #include <memory> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <config/PathConfig.h> #include <exceptions/CannotCreateFileException.h> #include <exceptions/UnexpectedErrorException.h> #include <log/log.h> #include "Integrity.h" namespace Cynara { namespace StorageConfig = PathConfig::StoragePath; bool Integrity::backupGuardExists(void) const { struct stat buffer; std::string guardFilename = m_dbPath + StorageConfig::guardFilename; int ret = stat(guardFilename.c_str(), &buffer); if (ret == 0) { return true; } else { int err = errno; if (err != ENOENT) { LOGE("'stat' function error [%d] : <%s>", err, strerror(err)); throw UnexpectedErrorException(err, strerror(err)); } return false; } } void Integrity::createBackupGuard(void) const { syncElement(m_dbPath + StorageConfig::guardFilename, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC); syncDirectory(m_dbPath); } void Integrity::syncDatabase(const Buckets &buckets, bool syncBackup) { std::string suffix = ""; if (syncBackup) { suffix += StorageConfig::backupFilenameSuffix; } for (const auto &bucketIter : buckets) { const auto &bucketId = bucketIter.first; const auto &bucketFilename = m_dbPath + StorageConfig::bucketFilenamePrefix + bucketId + suffix; syncElement(bucketFilename); } syncElement(m_dbPath + StorageConfig::indexFilename + suffix); syncElement(m_dbPath + PathConfig::StoragePath::checksumFilename + suffix); syncDirectory(m_dbPath); } void Integrity::revalidatePrimaryDatabase(const Buckets &buckets) { createPrimaryHardLinks(buckets); syncDatabase(buckets, false); deleteHardLink(m_dbPath + StorageConfig::guardFilename); syncDirectory(m_dbPath); deleteBackupHardLinks(buckets); } void Integrity::deleteNonIndexedFiles(BucketPresenceTester tester) { DIR *dirPtr = nullptr; struct dirent *direntPtr; if ((dirPtr = opendir(m_dbPath.c_str())) == nullptr) { int err = errno; LOGE("'opendir' function error [%d] : <%s>", err, strerror(err)); throw UnexpectedErrorException(err, strerror(err)); return; } std::unique_ptr<DIR, std::function<void(DIR*)>> dirStream(dirPtr, [](DIR *dir) { if (closedir(dir) < 0) { int err = errno; (void) err; LOGE("'closedir' function error [%d] : <%s>", err, strerror(err)); } }); while (errno = 0, (direntPtr = readdir(dirPtr)) != nullptr) { std::string filename = direntPtr->d_name; //ignore all special files (working dir, parent dir, index, checksums) if (isSpecialDirectory(filename) || isSpecialDatabaseEntry(filename)) { continue; } std::string bucketId; auto nameLength = filename.length(); auto prefixLength = StorageConfig::bucketFilenamePrefix.length(); //remove if it is impossible that it is a bucket file if (nameLength < prefixLength) { deleteHardLink(m_dbPath + filename); continue; } //remove if there is no bucket filename prefix //0 is returned from string::compare() if strings are equal if (0 != filename.compare(0, prefixLength, StorageConfig::bucketFilenamePrefix)) { deleteHardLink(m_dbPath + filename); continue; } //remove if bucket is not in index bucketId = filename.substr(prefixLength); if (!tester(bucketId)) { deleteHardLink(m_dbPath + filename); } } if (errno) { int err = errno; LOGE("'readdir' function error [%d] : <%s>", err, strerror(err)); throw UnexpectedErrorException(err, strerror(err)); return; } } void Integrity::syncElement(const std::string &filename, int flags, mode_t mode) { int fileFd = TEMP_FAILURE_RETRY(open(filename.c_str(), flags, mode)); if (fileFd < 0) { int err = errno; if (err != EEXIST) { LOGE("File <%s> : 'open' function error [%d] : <%s>", filename.c_str(), err, strerror(err)); throw UnexpectedErrorException(err, strerror(err)); } else { throw CannotCreateFileException(filename); } } int ret = fsync(fileFd); if (ret < 0) { int err = errno; LOGE("'fsync' function error [%d] : <%s>", err, strerror(err)); throw UnexpectedErrorException(err, strerror(err)); } ret = close(fileFd); if (ret < 0) { int err = errno; LOGE("'close' function error [%d] : <%s>", err, strerror(err)); throw UnexpectedErrorException(err, strerror(err)); } } // from: man 2 fsync // Calling fsync() does not necessarily ensure that the entry in the directory containing // the file has also reached disk. For that an explicit fsync() on a file descriptor for // the directory is also needed. void Integrity::syncDirectory(const std::string &dirname, mode_t mode) { syncElement(dirname, O_DIRECTORY, mode); } void Integrity::createPrimaryHardLinks(const Buckets &buckets) { for (const auto &bucketIter : buckets) { const auto &bucketId = bucketIter.first; const auto &bucketFilename = m_dbPath + StorageConfig::bucketFilenamePrefix + bucketId; deleteHardLink(bucketFilename); createHardLink(bucketFilename + StorageConfig::backupFilenameSuffix, bucketFilename); } const auto &indexFilename = m_dbPath + StorageConfig::indexFilename; const auto &checksumFilename = m_dbPath + PathConfig::StoragePath::checksumFilename; deleteHardLink(indexFilename); createHardLink(indexFilename + StorageConfig::backupFilenameSuffix, indexFilename); deleteHardLink(checksumFilename); createHardLink(checksumFilename + StorageConfig::backupFilenameSuffix, checksumFilename); } void Integrity::deleteBackupHardLinks(const Buckets &buckets) { for (const auto &bucketIter : buckets) { const auto &bucketId = bucketIter.first; const auto &bucketFilename = m_dbPath + StorageConfig::bucketFilenamePrefix + bucketId + StorageConfig::backupFilenameSuffix; deleteHardLink(bucketFilename); } deleteHardLink(m_dbPath + StorageConfig::indexFilename + StorageConfig::backupFilenameSuffix); deleteHardLink(m_dbPath + StorageConfig::checksumFilename + StorageConfig::backupFilenameSuffix); } void Integrity::createHardLink(const std::string &oldName, const std::string &newName) { int ret = link(oldName.c_str(), newName.c_str()); if (ret < 0) { int err = errno; throw UnexpectedErrorException(err, strerror(err)); LOGN("Trying to link to non-existent file: <%s>", oldName.c_str()); } } void Integrity::deleteHardLink(const std::string &filename) { int ret = unlink(filename.c_str()); if (ret < 0) { int err = errno; if (err != ENOENT) { LOGE("'unlink' function error [%d] : <%s>", err, strerror(err)); throw UnexpectedErrorException(err, strerror(err)); } else { LOGN("Trying to unlink non-existent file: <%s>", filename.c_str()); } } } bool Integrity::isSpecialDirectory(const std::string &filename) { return "." == filename || ".." == filename; } bool Integrity::isSpecialDatabaseEntry(const std::string &filename) { return PathConfig::StoragePath::indexFilename == filename || PathConfig::StoragePath::checksumFilename == filename; } } /* namespace Cynara */
{ "content_hash": "e88a1372b71c6d26185c3acd71d3846f", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 98, "avg_line_length": 32.577235772357724, "alnum_prop": 0.6357624157723983, "repo_name": "Samsung/cynara", "id": "f8559154945394701755916b8f115fc46d818d58", "size": "8681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/storage/Integrity.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "134845" }, { "name": "C++", "bytes": "1210562" }, { "name": "CMake", "bytes": "66530" }, { "name": "Shell", "bytes": "15675" } ], "symlink_target": "" }
/*global module, test, equal, ok, jQuery */ (function ($) { "use strict"; /* If there is no delegation support, forcibly reset the plugin between * test runs */ function resetPlugin() { if (!$.fn.on && !$.fn.delegate && !$.fn.live) { $.fn.example.boundClassNames = []; } } module("Basic usage", { setup: function () { $('#basic1').example('Test'); $('#basicform').submit(function (e) { e.preventDefault(); }); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#basic1').val(), "Test", "The example should read 'Test'."); ok($('#basic1').hasClass('example'), "The class should be 'example'."); }); test("should be cleared on focus", function () { $('#basic1').focus(); equal($('#basic1').val(), "", "The example should be cleared."); ok(!$('#basic1').hasClass('example'), "The class should no longer be 'example'."); }); test("should reappear on blur if empty", function () { $('#basic1').focus().blur(); equal($('#basic1').val(), "Test", "The example should read 'Test'."); ok($('#basic1').hasClass('example'), "The class should be 'example'."); }); test("should not be populated with an example on blur if user input is present", function () { $('#basic1').focus(); $('#basic1').val("My own value"); $('#basic1').blur(); equal($('#basic1').val(), "My own value", "The example should not be cleared."); ok(!$('#basic1').hasClass('example'), "The class should not be 'example'."); }); test("should not be populated with an example on focus if user input is present", function () { $('#basic1').focus().val("My own value").blur().focus(); equal($('#basic1').val(), "My own value", "The example should not be cleared."); ok(!$('#basic1').hasClass('example'), "The class should not be 'example'."); }); test("should be cleared on form submit", function () { $('#basicform').submit(); equal($('#basic1').val(), "", "The example should be cleared."); }); test("shouldn't clear user inputs on form submit", function () { $('#basic2').focus().val("User input"); $('#basicform').triggerHandler('submit'); equal($('#basic2').val(), "User input", "The user input should be intact."); }); module("Using custom classes", { setup: function () { $('#custom1').example("Test", {className: "notExample"}); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#custom1').val(), "Test", "The example should be set."); ok($('#custom1').hasClass('notExample'), "The class should be the specified one."); ok(!$('#custom1').hasClass('example'), "The class should not be 'example'."); }); test("should be cleared on focus", function () { $('#custom1').focus(); equal($('#custom1').val(), "", "The example should be cleared."); ok(!$('#custom1').hasClass('notExample'), "The class should not be the specified one."); }); test("should be reappear on blur", function () { $('#custom1').focus().blur(); equal($('#custom1').val(), "Test", "The example should reappear."); ok($('#custom1').hasClass('notExample'), "The class should be the specified one."); }); module("Multiple forms", { setup: function () { $('#multipleform1, #multipleform2').submit(function (e) { e.preventDefault(); }); $('#mf1').example('Test'); $('#mf2').example('Test'); }, teardown: resetPlugin }); test("should only clear examples in that form", function () { $('#multipleform1').submit(); equal($('#mf1').val(), "", "The example should be cleared."); equal($('#mf2').val(), "Test", "An example in another form should not be cleared."); }); module("Simple callback", { setup: function () { $('#callback1').example(function () { return "Callback Test"; }); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#callback1').val(), "Callback Test", "The example should read 'Callback Test'."); ok($('#callback1').hasClass('example'), "The class should be 'example'."); }); test("should be cleared on focus", function () { $('#callback1').focus(); equal($('#callback1').val(), "", "The example should be cleared."); ok(!$('#callback1').hasClass('example'), "The class should no longer be 'example'."); }); test("should reappear on blur if empty", function () { $('#callback1').focus().blur(); equal($('#callback1').val(), "Callback Test", "The example should read 'Callback Test'."); ok($('#callback1').hasClass('example'), "The class should be 'example'."); }); module("More complicated callback", { setup: function () { $('#callback2').example(function () { return $(this).attr('title'); }); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#callback2').val(), "Starting", "The example should read 'Starting'."); ok($('#callback2').hasClass('example'), "The class should be 'example'."); }); test("should be cleared on focus", function () { $('#callback2').focus(); equal($('#callback2').val(), "", "The example should be cleared."); ok(!$('#callback2').hasClass('example'), "The class should no longer be 'example'."); }); test("should reappear on blur if empty", function () { $('#callback2').focus().blur(); equal($('#callback2').val(), "Starting", "The example should read 'Starting'."); ok($('#callback2').hasClass('example'), "The class should be 'example'."); }); test("should run the callback every time instead of caching it", function () { $('#callback2').attr('title', 'Another'); $('#callback2').focus().blur(); equal($('#callback2').val(), "Another", "The example should read 'Another'."); ok($('#callback2').hasClass('example'), "The class should be 'example'."); }); module("Metadata plugin", { setup: function () { $('#m1').example(); }, teardown: resetPlugin }); test("should have an example set", function () { equal($('#m1').val(), "Something", "The example should read 'Something'."); ok($('#m1').hasClass('m1'), "The class should be 'm1'."); }); test("should be cleared on focus", function () { $('#m1').focus(); equal($('#m1').val(), "", "The example should be cleared."); ok(!$('#m1').hasClass('m1'), "The class should no longer be 'm1'."); }); test("should reappear on blur if empty", function () { $('#m1').focus().blur(); equal($('#m1').val(), "Something", "The example should read 'Something'."); ok($('#m1').hasClass('m1'), "The class should be 'm1'."); }); test("should be overridden by arguments", function () { $('#m2').example('Precedence', {className: 'o1'}); equal($('#m2').val(), "Precedence", "The example in the arguments should take precedence"); ok($('#m2').hasClass('o1'), "The class should be 'o1'."); }); module("On page load", { teardown: resetPlugin }); test("should not set an example if a value is already set", function () { $('#load1').example("Test"); equal($('#load1').val(), "Already filled in", "The example should not be set."); ok(!$('#load1').hasClass('example'), "The class should not be 'example'."); }); test("should not clear a field with a value even when using a callback", function () { $('#load2').example(function () { return "Nope"; }); equal($('#load2').val(), "Default", "The value should be the default."); ok(!$('#load2').hasClass('example'), "The class should not be 'example'."); }); module("Changing values by Javascript", { setup: function () { $('#f1').example('Example'); }, teardown: resetPlugin }); test("should set example", function () { equal($('#f1').val(), "Example", "The example should read 'Example'."); ok($('#f1').hasClass('example'), "The example class should be set."); }); test("should remove example class when changed", function () { $('#f1').val("New value"); $('#f1').change(); equal($('#f1').val(), "New value", "Value should be changed to 'New value'."); ok(!$('#f1').hasClass('example'), "The example class should no longer be set."); /* Clear the field between test runs. */ $('#f1').val(''); }); module("Clearing values when loaded from cache", { teardown: resetPlugin }); test("value should be set to default value", function () { /* Fake loading from cache by setting the example to be different to * the recorded defaultValue. */ $('#c1').val('Cached example').example('Cached example'); equal($('#c1').val(), "Filled in", "Value should have been reset to 'Filled in'."); }); test("value should be cleared and set to the example if without default", function () { $('#c2').val('Cached example').example('Cached example'); equal($('#c2').val(), 'Cached example', "Value should have been emptied."); ok($('#c2').hasClass('example'), 'The example class should be set.'); }); test("value is not touched if it doesn't match the example", function () { $('#c3').val('Some user input').example('Test'); equal($('#c3').val(), 'Some user input', 'Value should not have been modified.'); ok(!$('#c3').hasClass('example'), 'The example class should not be set.'); }); test('value is always cleared if the example is a callback', function () { $('#c4').val('Some user input').example(function () { return 'Test'; }); equal($('#c4').val(), 'Test', 'The cached value is overridden.'); ok($('#c4').hasClass('example'), 'The example class should be set.'); }); test('value is not touched if it is the default', function () { $('#c5').val('Some default').example('Test'); equal($('#c5').val(), 'Some default', 'Value should not have been modified.'); ok(!$('#c5').hasClass('example'), 'The example class should not be set.'); }); module('Custom events', { teardown: resetPlugin }); test('a specific form is cleared when calling example:resetForm on it', function () { $('#ce1, #ce2').example('Testing'); $('#custom').trigger('example:resetForm'); equal($('#ce1').val(), '', 'The value should have been cleared.'); ok(!$('#ce1').hasClass('example'), 'The example class should not be set.'); equal($('#ce2').val(), 'Testing', 'The value should not have been cleared.'); ok($('#ce2').hasClass('example'), 'The example class should be set.'); }); test('triggering example:resetForm on a field will bubble to the form', function () { $('#ce1').example('Testing'); $('#ce1').trigger('example:resetForm'); equal($('#ce1').val(), '', 'The value should have been cleared.'); ok(!$('#ce1').hasClass('example'), 'The example class should not be set.'); }); }(jQuery));
{ "content_hash": "36ff2e589dff2edf047d73e54038b016", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 99, "avg_line_length": 41.779359430604984, "alnum_prop": 0.547274275979557, "repo_name": "mudge/jquery_example", "id": "bc881493b21f22c98ac4deb594978428aff164c3", "size": "11740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/jquery.example_test.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4602" }, { "name": "HTML", "bytes": "3105" }, { "name": "JavaScript", "bytes": "66502" }, { "name": "Ruby", "bytes": "147" } ], "symlink_target": "" }
package mtr.packet; import mtr.data.EnumHelper; import mtr.data.NameColorDataBase; import mtr.data.SerializedDataBase; import mtr.data.TransportMode; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.thread.ReentrantBlockableEventLoop; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; public abstract class PacketTrainDataBase implements IPacket { protected static <T extends NameColorDataBase, U extends ReentrantBlockableEventLoop<? extends Runnable>> void updateData(Set<T> dataSet, Map<Long, T> cacheMap, U minecraft, FriendlyByteBuf packet, PacketCallback packetCallback, BiFunction<Long, TransportMode, T> createDataWithId) { final FriendlyByteBuf packetFullCopy = new FriendlyByteBuf(packet.copy()); final long id = packet.readLong(); final TransportMode transportMode = EnumHelper.valueOf(TransportMode.TRAIN, packet.readUtf(SerializedDataBase.PACKET_STRING_READ_LENGTH)); final String key = packet.readUtf(SerializedDataBase.PACKET_STRING_READ_LENGTH); final FriendlyByteBuf packetCopy = new FriendlyByteBuf(packet.copy()); minecraft.execute(() -> { final T data = cacheMap.get(id); if (data == null) { if (createDataWithId != null) { final T newData = createDataWithId.apply(id, transportMode); dataSet.add(newData); newData.update(key, packetCopy); } } else { data.update(key, packetCopy); } packetCallback.packetCallback(packetCopy, packetFullCopy); }); } protected static <T extends NameColorDataBase, U extends ReentrantBlockableEventLoop<? extends Runnable>> void deleteData(Set<T> dataSet, U minecraft, FriendlyByteBuf packet, PacketCallback packetCallback) { final FriendlyByteBuf packetFullCopy = new FriendlyByteBuf(packet.copy()); final long id = packet.readLong(); minecraft.execute(() -> { dataSet.removeIf(data -> data.id == id); packetCallback.packetCallback(null, packetFullCopy); }); } @FunctionalInterface protected interface PacketCallback { void packetCallback(FriendlyByteBuf updatePacket, FriendlyByteBuf fullPacket); } }
{ "content_hash": "c87c45946e1bc30ca6936fe2be9bd2b2", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 284, "avg_line_length": 41.86, "alnum_prop": 0.7740086000955566, "repo_name": "jonafanho/Minecraft-Transit-Railway", "id": "fb06a4decb444bcb785a27d3514c173eadb4a34d", "size": "2093", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/mtr/packet/PacketTrainDataBase.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5304" }, { "name": "HTML", "bytes": "7010" }, { "name": "Java", "bytes": "2490725" }, { "name": "JavaScript", "bytes": "79235" } ], "symlink_target": "" }
<?xml version="1.0"?> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="tests/bootstrap.php" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"> <coverage> <include> <directory suffix=".php">src</directory> </include> </coverage> <testsuites> <testsuite name="unit"> <directory>tests/unit</directory> </testsuite> <testsuite name="integration"> <directory>tests/integration</directory> </testsuite> </testsuites> </phpunit>
{ "content_hash": "7fd3bb5c5b96a2c1278ddb37431cf500", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 169, "avg_line_length": 32.5625, "alnum_prop": 0.6775431861804223, "repo_name": "felixsand/PhPsst", "id": "d6855fbe6328a17c80efa197ad0ba948ad28158b", "size": "521", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "phpunit.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "47345" } ], "symlink_target": "" }
<?php /** * PSR2_Sniffs_Namespaces_NamespaceDeclarationSniff. * * Ensures namespaces are declared correctly. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ class PSR2_Sniffs_Namespaces_NamespaceDeclarationSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array( T_NAMESPACE ); }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token in * the stack passed in $tokens. * * @return void */ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); for ($i = ( $stackPtr + 1 ); $i < ( $phpcsFile->numTokens - 1 ); $i++) { if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) { continue; } break; } // The $i var now points to the first token on the line after the // namespace declaration, which must be a blank line. $next = $phpcsFile->findNext( T_WHITESPACE, $i, $phpcsFile->numTokens, true ); if ($tokens[$next]['line'] === $tokens[$i]['line']) { $error = 'There must be one blank line after the namespace declaration'; $phpcsFile->addError( $error, $stackPtr, 'BlankLineAfter' ); } }//end process() }//end class ?>
{ "content_hash": "0769438917297f3911b682fc1e884d85", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 94, "avg_line_length": 28.391304347826086, "alnum_prop": 0.5865237366003063, "repo_name": "TheTypoMaster/SPHERE-Framework", "id": "82da6a553af1920cb995f0734b4e0ac993d73944", "size": "2352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Library/MOC-V/Core/SecureKernel/Vendor/PhpSecLib/0.3.9/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/PSR2/Sniffs/Namespaces/NamespaceDeclarationSniff.php", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ApacheConf", "bytes": "2630" }, { "name": "Batchfile", "bytes": "7341" }, { "name": "CSS", "bytes": "1047983" }, { "name": "HTML", "bytes": "6258719" }, { "name": "JavaScript", "bytes": "15888113" }, { "name": "Makefile", "bytes": "6774" }, { "name": "PHP", "bytes": "9320934" }, { "name": "PowerShell", "bytes": "149" }, { "name": "Python", "bytes": "22027" }, { "name": "Ruby", "bytes": "2399" }, { "name": "Shell", "bytes": "6738" }, { "name": "Smarty", "bytes": "65319" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xml:lang= "en-US"> <head> <title>Concurrency Utilities Overview</title><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "//hm.baidu.com/hm.js?dd1361ca20a10cc161e72d4bc4fef6df";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();</script> <link rel="stylesheet" type="text/css" href="../../../technotes/css/guide.css" /> </head> <body> <!-- STATIC HEADER --> <!-- header start --> <div id="javaseheader"> <div id="javaseheaderlogo"> <img src="../../../images/javalogo.gif" alt="Java logo" /> </div> <div id="javaseheaderindex"> <a href= "../../../index.html">Documentation Contents</a> </div> <div class="clear"></div> </div> <!-- header end --> <h1>Concurrency Utilities<br /> Overview</h1> <!-- Body text begins here --> <p>The Java platform includes a package of <i>concurrency utilities</i>. These are classes that are designed to be used as building blocks in building concurrent classes or applications. Just as the collections framework simplified the organization and manipulation of in-memory data by providing implementations of commonly used data structures, the concurrency utilities simplify the development of concurrent classes by providing implementations of building blocks commonly used in concurrent designs. The concurrency utilities include a high-performance, flexible thread pool; a framework for asynchronous execution of tasks; a host of collection classes optimized for concurrent access; synchronization utilities such as counting semaphores; atomic variables; locks; and condition variables.</p> <p>Using the concurrency utilities, instead of developing components such as thread pools yourself, offers a number of advantages:</p> <ul> <li><strong>Reduced programming effort.</strong> It is easier to use a standard class than to develop it yourself.</li> <li><strong>Increased performance.</strong> The implementations in the concurrency utilities were developed and peer-reviewed by concurrency and performance experts; these implementations are likely to be faster and more scalable than a typical implementation, even by a skilled developer.</li> <li><strong>Increased reliability.</strong> Developing concurrent classes is difficult -- the low-level concurrency primitives provided by the Java language (<code>synchronized</code>, <code>volatile</code>, <code>wait()</code>, <code>notify()</code>, and <code>notifyAll()</code>) are difficult to use correctly, and errors using these facilities can be difficult to detect and debug. By using standardized, extensively tested concurrency building blocks, many potential sources of threading hazards such as deadlock, starvation, race conditions, or excessive context switching are eliminated. The concurrency utilities were carefully audited for deadlock, starvation, and race conditions.</li> <li><strong>Improved maintainability.</strong> Programs that use standard library classes are easier to understand and maintain than those that rely on complicated, homegrown classes.</li> <li><strong>Increased productivity.</strong> Developers are likely to already understand the standard library classes, so there is no need to learn the API and behavior of ad hoc concurrent components. Additionally, concurrent applications are simpler to debug when they are built on reliable, well-tested components.</li> </ul> <p>In short, using the concurrency utilities to implement a concurrent application can help your program be clearer, shorter, faster, more reliable, more scalable, easier to write, easier to read, and easier to maintain.</p> <p>The concurrency utilities includes:</p> <ul> <li><strong>Task scheduling framework</strong>. The <a href= "../../../api/java/util/concurrent/Executor.html"><code>Executor</code></a> interface standardizes invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Implementations are provided that enable tasks to be executed within the submitting thread, in a <a href= "../../../api/java/util/concurrent/Executors.html#newSingleThreadExecutor--"> single background thread</a> (as with events in Swing), in a newly created thread, or in a <a href= "../../../api/java/util/concurrent/Executors.html#newFixedThreadPool-int-"> thread pool</a>, and developers can create customized implementations of <a href= "../../../api/java/util/concurrent/AbstractExecutorService.html">Executor</a> that support arbitrary execution policies. The built-in implementations offer configurable policies such as queue length limits and <a href= "../../../api/java/util/concurrent/RejectedExecutionHandler.html">saturation policy</a> that can improve the stability of applications by preventing runaway resource use.</li> <li><b>Fork/join framework</b>. Based on the <tt><a href= "../../../api/java/util/concurrent/ForkJoinPool.html">ForkJoinPool</a></tt> class, this framework is an implementation of <tt>Executor</tt>. It is designed to efficiently run a large number of tasks using a pool of worker threads. A <i>work-stealing</i> technique is used to keep all the worker threads busy, to take full advantage of multiple processors.</li> <li><strong>Concurrent collections</strong>. Several new collections classes were added, including the new <a href= "../../../api/java/util/Queue.html"><code>Queue</code></a>, <a href="../../../api/java/util/concurrent/BlockingQueue.html"><code> BlockingQueue</code></a> and <a href= "../../../api/java/util/concurrent/BlockingDeque.html"><code>BlockingDeque</code></a> interfaces, and high-performance, concurrent implementations of <code>Map</code>, <code>List</code>, and <code>Queue</code>. See the <a href="../collections/">Collections Framework Guide</a> for more information.</li> <li><strong>Atomic variables</strong>. Utility classes are provided that atomically manipulate single variables (primitive types or references), providing high-performance atomic arithmetic and compare-and-set methods. The atomic variable implementations in the <a href= "../../../api/java/util/concurrent/atomic/package-summary.html#package_description"> <code>java.util.concurrent.atomic</code></a> package offer higher performance than would be available by using synchronization (on most platforms), making them useful for implementing high-performance concurrent algorithms and conveniently implementing counters and sequence number generators.</li> <li><strong>Synchronizers</strong>. General purpose synchronization classes, including <a href= "../../../api/java/util/concurrent/Semaphore.html">semaphores</a>, <a href= "../../../api/java/util/concurrent/CyclicBarrier.html">barriers</a>, <a href= "../../../api/java/util/concurrent/CountDownLatch.html">latches</a>, <a href= "../../../api/java/util/concurrent/Phaser.html">phasers</a>, and <a href= "../../../api/java/util/concurrent/Exchanger.html">exchangers</a>, facilitate coordination between threads.</li> <li><strong>Locks</strong>. While locking is built into the Java language through the <tt>synchronized</tt> keyword, there are a number of limitations to built-in monitor locks. The <a href= "../../../api/java/util/concurrent/locks/package-summary.html#package_description"> <code>java.util.concurrent.locks</code></a> package provides a high-performance lock implementation with the same memory semantics as synchronization, and it also supports specifying a timeout when attempting to acquire a lock, multiple condition variables per lock, nonnested ("hand-over-hand") holding of multiple locks, and support for interrupting threads that are waiting to acquire a lock.</li> <li><strong>Nanosecond-granularity timing</strong>. The <a href= "../../../api/java/lang/System.html#nanoTime--"><code>System.nanoTime</code></a> method enables access to a nanosecond-granularity time source for making relative time measurements and methods that accept timeouts (such as the <a href= "../../../api/java/util/concurrent/BlockingQueue.html#offer-E-long-java.util.concurrent.TimeUnit-"> <code>BlockingQueue.offer</code></a>, <a href= "../../../api/java/util/concurrent/BlockingQueue.html#poll-long-java.util.concurrent.TimeUnit-"> <code>BlockingQueue.poll</code></a>, <a href= "../../../api/java/util/concurrent/locks/Lock.html#tryLock-long-java.util.concurrent.TimeUnit-"> <code>Lock.tryLock</code></a>, <a href= "../../../api/java/util/concurrent/locks/Condition.html#await-long-java.util.concurrent.TimeUnit-"> <code>Condition.await</code></a>, and <a href= "../../../api/java/lang/Thread.html#sleep-long-int-"><code>Thread.sleep</code></a>) can take timeout values in nanoseconds. The actual precision of the <code>System.nanoTime</code> method is platform-dependent.</li> </ul> <!-- Body text ends here --> <!-- footer start --> <div id="javasefooter"> <div class="hr"> <hr /></div> <div id="javasecopyright"> <img id="oraclelogofooter" src= "../../../images/oraclelogo.gif" alt="Oracle and/or its affiliates" border="0" width="100" height="29" name= "oraclelogofooter" /> <a href="../../../legal/cpyr.html">Copyright &#169;</a> 1993, 2015, Oracle and/or its affiliates. All rights reserved.</div> <div id="javasecontactus"> <a href= "http://docs.oracle.com/javase/feedback.html">Contact Us</a> </div> </div> <!-- footer end --> <!-- STATIC FOOTER --> </body> </html>
{ "content_hash": "aa3a655640f364bf999ea03c6c6da5eb", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 293, "avg_line_length": 48.60204081632653, "alnum_prop": 0.7543564980054588, "repo_name": "piterlin/piterlin.github.io", "id": "13363084061a4d574a20674beca992e2f8432213", "size": "9526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/technotes/guides/concurrency/overview.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "479" }, { "name": "HTML", "bytes": "9480869" }, { "name": "JavaScript", "bytes": "246" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="Placement Stats" app:showAsAction="never" /> </menu>
{ "content_hash": "2876d56da6b0ff103610f136bb6b91e3", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 64, "avg_line_length": 37.22222222222222, "alnum_prop": 0.6477611940298508, "repo_name": "mkfeuhrer/TPO-MNNIT", "id": "6557c77f177bc419ba44856f513036bc73677011", "size": "335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/menu/tpo_home.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "320854" } ], "symlink_target": "" }
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_filter :verify_signed_in private def verify_signed_in redirect_to need_session_path unless current_user end def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user end
{ "content_hash": "1806a5a02f85da9a8781759831cdd790", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 73, "avg_line_length": 21.764705882352942, "alnum_prop": 0.7081081081081081, "repo_name": "jslate/shacs", "id": "0c9220a27dd3ede6330f30951686b8d9a00dd1b4", "size": "370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/application_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "177" }, { "name": "CoffeeScript", "bytes": "896" }, { "name": "JavaScript", "bytes": "94" }, { "name": "Ruby", "bytes": "27646" } ], "symlink_target": "" }
body { -webkit-justify-content: center; -moz-justify-content: center; -ms-justify-content: center; justify-content: center; } .non-narrow.zero-top-spacing { padding-top: 0 !important; } section { padding: 0 16px; margin-left: 100px; margin-right: 100px; max-width: 750px; } div.column { padding: 0 16px; max-width: 750px; } div.header { background-color: transparent; } div.header .container { -webkit-justify-content: flex-start; -moz-justify-content: flex-start; -ms-justify-content: flex-start; justify-content: flex-start; } div.header .container .logo { margin: 0; } div.header-home .container .logo { max-width: 180px; margin-left: 20px; } div.header-home .name-home { padding-top: 30px; font-size: 40px; } div.header-home nav ul a { font-size: 18px; } div.header .content { -webkit-align-items: flex-start; -moz-align-items: flex-start; -ms-align-items: flex-start; align-items: flex-start; } div.header .name { color: #333333; } div.header nav { font-size: 14px; margin-bottom: 0; } div.header nav ul { text-align: left; } div.header nav ul a { color: #666666; } div.header nav ul a:hover { color: #333333; } div.footer { background-color: transparent; } div.footer .container { flex-direction: row; } div.footer .container a { margin-left: 3px; margin-right: 3px; color: #666666; } div.footer .container a:hover { color: #333333; } div.footer .container a .icon { font-size: 18px; } div.footer .container a .icon.larger { font-size: 20px; } div.main .content .front-matter .date, div.main .content .front-matter .author, div.main .content .front-matter .tags, div.main .content .front-matter .word-count, div.main .content .front-matter .middot:before { display: initial; } div.main .container.f04 { -webkit-justify-content: flex-start; -moz-justify-content: flex-start; -ms-justify-content: flex-start; justify-content: flex-start; } div.main .container.f04 .content { -webkit-align-items: flex-start; -moz-align-items: flex-start; -ms-align-items: flex-start; align-items: flex-start; } div.main .container.f04 .content .num { margin: 0 0 10px 0; font-size: 32px; } div.main .container.f04 .content .detail { margin-bottom: 30px; } .container { padding: 0 30px; } div.header { padding-top: 60px; padding-bottom: 60px; } div.footer { padding-top: 30px; padding-bottom: 60px; } div.main { padding-top: 0; } div.main .container .content .post-item { display: flex; list-style: none; padding-left: 1.5em; } div.main .container .content .post-item .meta { display: block; } div.main.post { padding-top: 60px; padding-bottom: 60px; } div.main .content .markdown blockquote { padding-right: 5rem; padding-left: 1.25rem; } div.main .content .navigation { -webkit-flex-direction: row; -moz-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } div.main .content .navigation div { margin-top: 0em; }
{ "content_hash": "acfed8f2f703aaf3843a36cedf641e43", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 48, "avg_line_length": 18.899328859060404, "alnum_prop": 0.7201704545454546, "repo_name": "Kjir/kjir.github.io", "id": "f4b5487446aff0f7fbe5f177602cc1baa2691a0b", "size": "2816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "themes/cocoa-eh/layouts/partials/css/min600px.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "128040" }, { "name": "HTML", "bytes": "104168" }, { "name": "JavaScript", "bytes": "17814" }, { "name": "XSLT", "bytes": "3885" } ], "symlink_target": "" }
Doc.Ti=IAEA Safety Standards Series No. GSR Part 3, Radiation Protection and Safety of Radiation Sources: International Basic Safety Standards Introduction.=[G/Org-IAEA-Safety-GSR3-CmA/Sec/1_Introduction_0.md] General.=[G/Org-IAEA-Safety-GSR3-CmA/Sec/2_General_0.md] Planned.=[G/Org-IAEA-Safety-GSR3-CmA/Sec/3_Planned_0.md] Emergency.=[G/Org-IAEA-Safety-GSR3-CmA/Sec/4_Emergency_0.md] Existing.=[G/Org-IAEA-Safety-GSR3-CmA/Sec/5_Existing_0.md] Secs={Introduction.H.Sec}<li>{General.H.Sec}<li>{Planned.H.Sec}<li>{Emergency.H.Sec}<li>{Existing.H.Sec} Sec={Doc} =[G/Z/ol/Base]
{ "content_hash": "ca466501a4615c497555231c1400c2ee", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 143, "avg_line_length": 34.23529411764706, "alnum_prop": 0.7457044673539519, "repo_name": "CommonAccord/Cmacc-Org", "id": "cd668e3eed97b13158862292b549b2c62a4a8109", "size": "582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Doc/G/Org-IAEA-Safety-GSR3-CmA/0.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4996" }, { "name": "HTML", "bytes": "130299" }, { "name": "PHP", "bytes": "1463" } ], "symlink_target": "" }
package co.cask.cdap.explore.client; import co.cask.cdap.common.discovery.EndpointStrategy; import co.cask.cdap.common.discovery.RandomEndpointStrategy; import co.cask.cdap.common.http.DefaultHttpRequestConfig; import co.cask.cdap.explore.service.Explore; import co.cask.cdap.security.spi.authentication.AuthenticationContext; import co.cask.common.http.HttpRequestConfig; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.inject.Inject; import org.apache.twill.discovery.Discoverable; import org.apache.twill.discovery.DiscoveryServiceClient; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import static co.cask.cdap.common.conf.Constants.Service; /** * An Explore Client that talks to a server implementing {@link Explore} over HTTP, * and that uses discovery to find the endpoints. */ public class DiscoveryExploreClient extends AbstractExploreClient { private final Supplier<EndpointStrategy> endpointStrategySupplier; private final HttpRequestConfig httpRequestConfig; private final AuthenticationContext authenticationContext; @Inject @VisibleForTesting public DiscoveryExploreClient(final DiscoveryServiceClient discoveryClient, AuthenticationContext authenticationContext) { this.endpointStrategySupplier = Suppliers.memoize(new Supplier<EndpointStrategy>() { @Override public EndpointStrategy get() { return new RandomEndpointStrategy(discoveryClient.discover(Service.EXPLORE_HTTP_USER_SERVICE)); } }); this.httpRequestConfig = new DefaultHttpRequestConfig(); this.authenticationContext = authenticationContext; } @Override protected HttpRequestConfig getHttpRequestConfig() { return httpRequestConfig; } @Override protected InetSocketAddress getExploreServiceAddress() { Discoverable discoverable = endpointStrategySupplier.get().pick(3L, TimeUnit.SECONDS); if (discoverable != null) { return discoverable.getSocketAddress(); } throw new RuntimeException(String.format("Cannot discover service %s", Service.EXPLORE_HTTP_USER_SERVICE)); } // This class is only used internally. // It does not go through router, so it doesn't ever need an auth token, sslEnabled, or verifySSLCert. @Override protected String getAuthToken() { return null; } @Override protected boolean isSSLEnabled() { return false; } @Override protected boolean verifySSLCert() { return false; } // when run from programs, the user id will be set in the authentication context @Override protected String getUserId() { return authenticationContext.getPrincipal().getName(); } }
{ "content_hash": "7015136233694bc7e92e7bd6300a50ff", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 111, "avg_line_length": 33.023809523809526, "alnum_prop": 0.7700072098053352, "repo_name": "caskdata/cdap", "id": "4c7a11b5644bf2597a3ff5160be6c2b302bbdcd8", "size": "3371", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "cdap-explore-client/src/main/java/co/cask/cdap/explore/client/DiscoveryExploreClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "26055" }, { "name": "CSS", "bytes": "478678" }, { "name": "HTML", "bytes": "647505" }, { "name": "Java", "bytes": "19722699" }, { "name": "JavaScript", "bytes": "2362906" }, { "name": "Python", "bytes": "166065" }, { "name": "Ruby", "bytes": "3178" }, { "name": "Scala", "bytes": "173411" }, { "name": "Shell", "bytes": "225202" }, { "name": "Visual Basic", "bytes": "870" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\Core\Routing\RouteProvider. */ namespace Drupal\Core\Routing; use Drupal\Core\Cache\Cache; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Cache\CacheTagsInvalidatorInterface; use Drupal\Core\Path\CurrentPathStack; use Drupal\Core\PathProcessor\InboundPathProcessorInterface; use Drupal\Core\State\StateInterface; use Symfony\Cmf\Component\Routing\PagedRouteCollection; use Symfony\Cmf\Component\Routing\PagedRouteProviderInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\RouteCollection; use \Drupal\Core\Database\Connection; /** * A Route Provider front-end for all Drupal-stored routes. */ class RouteProvider implements PreloadableRouteProviderInterface, PagedRouteProviderInterface, EventSubscriberInterface { /** * The database connection from which to read route information. * * @var \Drupal\Core\Database\Connection */ protected $connection; /** * The name of the SQL table from which to read the routes. * * @var string */ protected $tableName; /** * The state. * * @var \Drupal\Core\State\StateInterface */ protected $state; /** * A cache of already-loaded routes, keyed by route name. * * @var \Symfony\Component\Routing\Route[] */ protected $routes = array(); /** * A cache of already-loaded serialized routes, keyed by route name. * * @var string[] */ protected $serializedRoutes = []; /** * The current path. * * @var \Drupal\Core\Path\CurrentPathStack */ protected $currentPath; /** * The cache backend. * * @var \Drupal\Core\Cache\CacheBackendInterface */ protected $cache; /** * The cache tag invalidator. * * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface */ protected $cacheTagInvalidator; /** * A path processor manager for resolving the system path. * * @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface */ protected $pathProcessor; /** * Cache ID prefix used to load routes. */ const ROUTE_LOAD_CID_PREFIX = 'route_provider.route_load:'; /** * Constructs a new PathMatcher. * * @param \Drupal\Core\Database\Connection $connection * A database connection object. * @param \Drupal\Core\State\StateInterface $state * The state. * @param \Drupal\Core\Path\CurrentPathStack $current_path * The current path. * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend * The cache backend. * @param \Drupal\Core\PathProcessor\InboundPathProcessorInterface $path_processor * The path processor. * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tag_invalidator * The cache tag invalidator. * @param string $table * (Optional) The table in the database to use for matching. Defaults to 'router' */ public function __construct(Connection $connection, StateInterface $state, CurrentPathStack $current_path, CacheBackendInterface $cache_backend, InboundPathProcessorInterface $path_processor, CacheTagsInvalidatorInterface $cache_tag_invalidator, $table = 'router') { $this->connection = $connection; $this->state = $state; $this->currentPath = $current_path; $this->cache = $cache_backend; $this->cacheTagInvalidator = $cache_tag_invalidator; $this->pathProcessor = $path_processor; $this->tableName = $table; } /** * Finds routes that may potentially match the request. * * This may return a mixed list of class instances, but all routes returned * must extend the core symfony route. The classes may also implement * RouteObjectInterface to link to a content document. * * This method may not throw an exception based on implementation specific * restrictions on the url. That case is considered a not found - returning * an empty array. Exceptions are only used to abort the whole request in * case something is seriously broken, like the storage backend being down. * * Note that implementations may not implement an optimal matching * algorithm, simply a reasonable first pass. That allows for potentially * very large route sets to be filtered down to likely candidates, which * may then be filtered in memory more completely. * * @param Request $request A request against which to match. * * @return \Symfony\Component\Routing\RouteCollection with all urls that * could potentially match $request. Empty collection if nothing can * match. */ public function getRouteCollectionForRequest(Request $request) { // Cache both the system path as well as route parameters and matching // routes. $cid = 'route:' . $request->getPathInfo() . ':' . $request->getQueryString(); if ($cached = $this->cache->get($cid)) { $this->currentPath->setPath($cached->data['path'], $request); $request->query->replace($cached->data['query']); return $cached->data['routes']; } else { // Just trim on the right side. $path = $request->getPathInfo(); $path = $path === '/' ? $path : rtrim($request->getPathInfo(), '/'); $path = $this->pathProcessor->processInbound($path, $request); $this->currentPath->setPath($path, $request); // Incoming path processors may also set query parameters. $query_parameters = $request->query->all(); $routes = $this->getRoutesByPath(rtrim($path, '/')); $cache_value = [ 'path' => $path, 'query' => $query_parameters, 'routes' => $routes, ]; $this->cache->set($cid, $cache_value, CacheBackendInterface::CACHE_PERMANENT, ['route_match']); return $routes; } } /** * Find the route using the provided route name (and parameters). * * @param string $name * The route name to fetch * * @return \Symfony\Component\Routing\Route * The found route. * * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException * Thrown if there is no route with that name in this repository. */ public function getRouteByName($name) { $routes = $this->getRoutesByNames(array($name)); if (empty($routes)) { throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name)); } return reset($routes); } /** * {@inheritdoc} */ public function preLoadRoutes($names) { if (empty($names)) { throw new \InvalidArgumentException('You must specify the route names to load'); } $routes_to_load = array_diff($names, array_keys($this->routes), array_keys($this->serializedRoutes)); if ($routes_to_load) { $cid = static::ROUTE_LOAD_CID_PREFIX . hash('sha512', serialize($routes_to_load)); if ($cache = $this->cache->get($cid)) { $routes = $cache->data; } else { $result = $this->connection->query('SELECT name, route FROM {' . $this->connection->escapeTable($this->tableName) . '} WHERE name IN ( :names[] )', array(':names[]' => $routes_to_load)); $routes = $result->fetchAllKeyed(); $this->cache->set($cid, $routes, Cache::PERMANENT, ['routes']); } $this->serializedRoutes += $routes; } } /** * {@inheritdoc} */ public function getRoutesByNames($names) { $this->preLoadRoutes($names); foreach ($names as $name) { // The specified route name might not exist or might be serialized. if (!isset($this->routes[$name]) && isset($this->serializedRoutes[$name])) { $this->routes[$name] = unserialize($this->serializedRoutes[$name]); unset($this->serializedRoutes[$name]); } } return array_intersect_key($this->routes, array_flip($names)); } /** * Returns an array of path pattern outlines that could match the path parts. * * @param array $parts * The parts of the path for which we want candidates. * * @return array * An array of outlines that could match the specified path parts. */ protected function getCandidateOutlines(array $parts) { $number_parts = count($parts); $ancestors = array(); $length = $number_parts - 1; $end = (1 << $number_parts) - 1; // The highest possible mask is a 1 bit for every part of the path. We will // check every value down from there to generate a possible outline. if ($number_parts == 1) { $masks = array(1); } elseif ($number_parts <= 3) { // Optimization - don't query the state system for short paths. This also // insulates against the state entry for masks going missing for common // user-facing paths since we generate all values without checking state. $masks = range($end, 1); } elseif ($number_parts <= 0) { // No path can match, short-circuit the process. $masks = array(); } else { // Get the actual patterns that exist out of state. $masks = (array) $this->state->get('routing.menu_masks.' . $this->tableName, array()); } // Only examine patterns that actually exist as router items (the masks). foreach ($masks as $i) { if ($i > $end) { // Only look at masks that are not longer than the path of interest. continue; } elseif ($i < (1 << $length)) { // We have exhausted the masks of a given length, so decrease the length. --$length; } $current = ''; for ($j = $length; $j >= 0; $j--) { // Check the bit on the $j offset. if ($i & (1 << $j)) { // Bit one means the original value. $current .= $parts[$length - $j]; } else { // Bit zero means means wildcard. $current .= '%'; } // Unless we are at offset 0, add a slash. if ($j) { $current .= '/'; } } $ancestors[] = '/' . $current; } return $ancestors; } /** * {@inheritdoc} */ public function getRoutesByPattern($pattern) { $path = RouteCompiler::getPatternOutline($pattern); return $this->getRoutesByPath($path); } /** * Get all routes which match a certain pattern. * * @param string $path * The route pattern to search for (contains % as placeholders). * * @return \Symfony\Component\Routing\RouteCollection * Returns a route collection of matching routes. */ protected function getRoutesByPath($path) { // Split the path up on the slashes, ignoring multiple slashes in a row // or leading or trailing slashes. $parts = preg_split('@/+@', $path, NULL, PREG_SPLIT_NO_EMPTY); $collection = new RouteCollection(); $ancestors = $this->getCandidateOutlines($parts); if (empty($ancestors)) { return $collection; } // The >= check on number_parts allows us to match routes with optional // trailing wildcard parts as long as the pattern matches, since we // dump the route pattern without those optional parts. $routes = $this->connection->query("SELECT name, route, fit FROM {" . $this->connection->escapeTable($this->tableName) . "} WHERE pattern_outline IN ( :patterns[] ) AND number_parts >= :count_parts", array( ':patterns[]' => $ancestors, ':count_parts' => count($parts), )) ->fetchAll(\PDO::FETCH_ASSOC); // We sort by fit and name in PHP to avoid a SQL filesort. usort($routes, array($this, 'routeProviderRouteCompare')); foreach ($routes as $row) { $collection->add($row['name'], unserialize($row['route'])); } return $collection; } /** * Comparison function for usort on routes. */ protected function routeProviderRouteCompare(array $a, array $b) { if ($a['fit'] == $b['fit']) { return strcmp($a['name'], $b['name']); } // Reverse sort from highest to lowest fit. PHP should cast to int, but // the explicit cast makes this sort more robust against unexpected input. return (int) $a['fit'] < (int) $b['fit'] ? 1 : -1; } /** * {@inheritdoc} */ public function getAllRoutes() { return new PagedRouteCollection($this); } /** * {@inheritdoc} */ public function reset() { $this->routes = array(); $this->serializedRoutes = array(); $this->cacheTagInvalidator->invalidateTags(['routes']); } /** * {@inheritdoc} */ static function getSubscribedEvents() { $events[RoutingEvents::FINISHED][] = array('reset'); return $events; } /** * {@inheritdoc} */ public function getRoutesPaged($offset, $length = NULL) { $select = $this->connection->select($this->tableName, 'router') ->fields('router', ['name', 'route']); if (isset($length)) { $select->range($offset, $length); } $routes = $select->execute()->fetchAllKeyed(); $result = []; foreach ($routes as $name => $route) { $result[$name] = unserialize($route); } return $result; } /** * {@inheritdoc} */ public function getRoutesCount() { return $this->connection->query("SELECT COUNT(*) FROM {" . $this->connection->escapeTable($this->tableName) . "}")->fetchField(); } }
{ "content_hash": "d97e5f6f62885853f959bceac7b96884", "timestamp": "", "source": "github", "line_count": 419, "max_line_length": 268, "avg_line_length": 31.572792362768496, "alnum_prop": 0.6402600347720916, "repo_name": "fian005/asiavia_dev", "id": "ac8188790a8cfd8d206f0ee52396e726aaaad9f2", "size": "13229", "binary": false, "copies": "37", "ref": "refs/heads/master", "path": "core/lib/Drupal/Core/Routing/RouteProvider.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "34257" }, { "name": "C++", "bytes": "50616" }, { "name": "CSS", "bytes": "419955" }, { "name": "HTML", "bytes": "488556" }, { "name": "JavaScript", "bytes": "853618" }, { "name": "PHP", "bytes": "28482046" }, { "name": "Shell", "bytes": "47922" } ], "symlink_target": "" }
//////////////////////////////////////////////////////////////////////////////// // // EXPANZ // Copyright 2008-2011 EXPANZ // All Rights Reserved. // // NOTICE: Expanz permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// #import "expanz_ui_QueryDataSource.h" #import <objc/runtime.h> @implementation expanz_ui_QueryDataSource /* ================================================= Class Methods ================================================== */ + (BOOL) resolveInstanceMethod:(SEL)sel { NSString* name = NSStringFromSelector(sel); if ([name hasPrefix:@"set"]) { IMP imp = imp_implementationWithBlock((void*) objc_unretainedPointer(^(id me, BOOL selected) { NSString* fieldName = [name substringFromIndex:3]; fieldName = [fieldName substringToIndex:[fieldName length] - 1]; NSMutableDictionary* cache = [me performSelector:@selector(cache)]; [cache setObject:[NSNumber numberWithBool:selected] forKey:fieldName]; })); class_addMethod(self, sel, imp, "v@:c"); return YES; } return NO; } /* ================================================== Initializers ================================================== */ - (id) init { self = [super init]; if (self) { _cache = [[NSMutableDictionary alloc] init]; } return self; } /* ================================================ Interface Methods =============================================== */ - (NSString*) query { __block NSMutableArray* queries = [[NSMutableArray alloc] init]; [_cache enumerateKeysAndObjectsUsingBlock:(^(NSString* key, NSNumber* value, BOOL* stop) { if ([value boolValue] == YES) { [queries addObject:key]; } })]; if ([queries count] > 1) { [NSException raise:NSInvalidArgumentException format:@"Expected QueryDataSource to have one query, but instead got: %@", queries]; } NSString* codeFormattedQuery = [queries objectAtIndex:0]; return [codeFormattedQuery stringByReplacingOccurrencesOfString:@"_" withString:@"."]; } /* ================================================================================================================== */ - (UITableViewCell*) tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { return nil; } - (NSInteger) tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section { return 0; } /* ================================================== Private Methods =============================================== */ - (NSMutableDictionary*) cache { return _cache; } @end
{ "content_hash": "e69fdbe15f312cc2e050ee61128351aa", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 120, "avg_line_length": 38.72222222222222, "alnum_prop": 0.49856527977044474, "repo_name": "expanz/expanz-iOS-SDK", "id": "b621ce0c2a1927b594e27fd68260c3d768383e86", "size": "2788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Main/UserInterface/DataRenderer/expanz_ui_QueryDataSource.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "6781" }, { "name": "Objective-C", "bytes": "752993" }, { "name": "Shell", "bytes": "638" } ], "symlink_target": "" }
package org.elasticsearch.xpack.autoscaling.capacity; import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import java.util.Objects; /** * Represents an autoscaling result from a single decider */ public class AutoscalingDeciderResult implements ToXContent, Writeable { private final AutoscalingCapacity requiredCapacity; private final Reason reason; public interface Reason extends ToXContent, NamedWriteable { String summary(); } /** * Create a new result with required capacity. * @param requiredCapacity required capacity or null if no capacity can be calculated due to insufficient information. * @param reason details/data behind the calculation */ public AutoscalingDeciderResult(AutoscalingCapacity requiredCapacity, Reason reason) { this.requiredCapacity = requiredCapacity; this.reason = reason; } public AutoscalingDeciderResult(StreamInput in) throws IOException { this.requiredCapacity = in.readOptionalWriteable(AutoscalingCapacity::new); this.reason = in.readOptionalNamedWriteable(Reason.class); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalWriteable(requiredCapacity); out.writeOptionalNamedWriteable(reason); } public AutoscalingCapacity requiredCapacity() { return requiredCapacity; } public Reason reason() { return reason; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (requiredCapacity != null) { builder.field("required_capacity", requiredCapacity); } if (reason != null) { builder.field("reason_summary", reason.summary()); builder.field("reason_details", reason); } return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AutoscalingDeciderResult that = (AutoscalingDeciderResult) o; return Objects.equals(requiredCapacity, that.requiredCapacity) && Objects.equals(reason, that.reason); } @Override public int hashCode() { return Objects.hash(requiredCapacity, reason); } }
{ "content_hash": "acb478ae54485e2e0791cb53ecf2a991", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 122, "avg_line_length": 32.1219512195122, "alnum_prop": 0.7091875474563402, "repo_name": "nknize/elasticsearch", "id": "8b35864b544fd024206f3b828b4fb19950c1e438", "size": "2875", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "x-pack/plugin/autoscaling/src/main/java/org/elasticsearch/xpack/autoscaling/capacity/AutoscalingDeciderResult.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "12298" }, { "name": "Batchfile", "bytes": "16353" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "251795" }, { "name": "HTML", "bytes": "5348" }, { "name": "Java", "bytes": "36849935" }, { "name": "Perl", "bytes": "7116" }, { "name": "Python", "bytes": "76127" }, { "name": "Shell", "bytes": "102829" } ], "symlink_target": "" }
from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative.api import DeclarativeMeta from .error import BaseValidationError, ValidationError from .attribute import validate_attribute class MetaClass(DeclarativeMeta): """ """ def __init__(cls, classname, bases, dict_): """ """ super(MetaClass, cls).__init__(classname, bases, dict_) if hasattr(cls, "__table__"): validate_attribute(cls) def _table_columns(constraint, table): return "{}__{}".format( table.name, "__".join(sorted(constraint.columns.keys())) ) metadata = MetaData(naming_convention={ "table_columns": _table_columns, "ix": "ix_%(table_columns)s", "uq": "uq_%(table_columns)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s__%(column_0_name)s__%(referred_table_name)s", "pk": "pk_%(table_name)s" }) class BaseModel(object): """ """ def __init__(self, **kwargs): """ Args: kwargs: Raises: TypeError: sqlalchemy_validation.ValidationError """ cls_ = type(self) errors = ValidationError() for column_name, value in kwargs.items(): if not hasattr(cls_, column_name): raise TypeError( "{!r} is an invalid keyword argument for {!s}".format (column_name, cls_.__name__)) try: setattr(self, column_name, value) except BaseValidationError as e: errors[(column_name,)] = e if errors: raise errors def __call__(self, **kwargs): """Sets kwargs to model's columns and returns self. Args: Returns: self Raises: TypeError: sqlalchemy_validation.ValidationError """ self.__init__(**kwargs) return self Model = declarative_base( cls=BaseModel, constructor=None, metaclass=MetaClass, metadata=metadata )
{ "content_hash": "3f2707297354866953f2ab1e9b045977", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 74, "avg_line_length": 25.5, "alnum_prop": 0.5633668101386896, "repo_name": "minimum-core/sqlalchemy-validation", "id": "b5967822753aba42f549b74f88968226b5a42d86", "size": "2091", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sqlalchemy_validation/model.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "31763" } ], "symlink_target": "" }
from applications import summarize_applications from applications import comments_by_application from users import summarize_users
{ "content_hash": "590ff519ea669be2335cb150ee443d2f", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 48, "avg_line_length": 43.666666666666664, "alnum_prop": 0.8778625954198473, "repo_name": "vesahe/solitadds-backend", "id": "c7df63da6ce8cbb4a52d6dc45b58da1674cea6c1", "size": "131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "analyze/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "11104" } ], "symlink_target": "" }
+++ Description = "PTL No More" author = "mestery" categories = ["OpenStack", "Open Source", "governance"] date = "2015-09-11T20:50:37-05:00" socialsharing = true tags = ["Open Source", "governance", "OpenStack"] title = "PTL No More" url = "" +++ I've been the OpenStack Neutron for 3 releases in a row. I started in Juno, was re-elected for Kilo, and then again for Liberty. This time, I'm [no longer running][1] to be the Neutron PTL anymore. I am really proud of what the team has accomplished while I was the PTL. I'm proud of not only the technical achievements, but also the community building and societal changes Neutron has undergone. All of this was accomplished with the help of some amazing people who likely spent as much time ensuring Neutron was a healthy place for new developers as they did fixing bugs and adding features. (Note to those who were a part of this: It was all worth it, and everyone new to Neutron thanks you for your efforts over the past one and a half years). One thing which has really crystallized for me during my time as PTL is how important it is to always treat people with respect and integrity. It's easy to sit behind a computer and forget there are actual human beings behind the bug report you're reading when it doesn't have enough information or when the gerrit review you're staring at lacks unit tests. But as Open Source developers and more importantly as human beings ourselves, we can't forget the bug report was filed by someone who is trying to help, or the code review was maybe submitted by a first time contributor. At the end of the day, we're all people who are engaging with other people. Respect and integrity are what keep the system moving smoothly. They allow the web of trust Open Source relies on to be effective. While I may be gone from the PTL role in Neutron, I plan to remain engaged in the Neutron and OpenStack communities. I'm confident the next PTL will be someone amazing, because Neutron has a deep bench of leadership and a community which will welcome a new PTL and work together to make that person effective. I look forward to what amazing things are to come for OpenStack and Neutron. [1]: http://lists.openstack.org/pipermail/openstack-dev/2015-September/074280.html
{ "content_hash": "45fb8a919dd5c3ca9d6f8b4698a4ac15", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 82, "avg_line_length": 53.73809523809524, "alnum_prop": 0.7789100575985822, "repo_name": "mestery/siliconloons", "id": "730c55490767bbee396fa95534bea53cd8f57fbd", "size": "2257", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "content/posts/2015-09-11-ptl-no-more.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "158891" }, { "name": "HTML", "bytes": "26478" }, { "name": "JavaScript", "bytes": "751856" } ], "symlink_target": "" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package paq_nomina; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.EJB; import javax.faces.event.AjaxBehaviorEvent; import org.primefaces.event.DateSelectEvent; import org.primefaces.event.SelectEvent; import paq_gestion.ejb.ServicioEmpleado; import paq_gestion.ejb.ServicioGestion; import paq_nomina.ejb.ServicioNomina; import sistema.aplicacion.Pantalla; import framework.aplicacion.TablaGenerica; import framework.componentes.AreaTexto; import framework.componentes.AutoCompletar; import framework.componentes.Boton; import framework.componentes.Calendario; import framework.componentes.Check; import framework.componentes.Confirmar; import framework.componentes.Dialogo; import framework.componentes.Division; import framework.componentes.Etiqueta; import framework.componentes.Grid; import framework.componentes.Grupo; import framework.componentes.PanelTabla; import framework.componentes.Radio; import framework.componentes.Reporte; import framework.componentes.SeleccionCalendario; import framework.componentes.SeleccionFormatoReporte; import framework.componentes.SeleccionTabla; import framework.componentes.Tabla; import framework.componentes.Tabulador; import framework.componentes.Texto; import java.util.Locale; /** * * @author psw */ public class pre_accion_personal extends Pantalla { private AutoCompletar aut_empleado = new AutoCompletar(); private Tabla tab_partida_vigente = new Tabla(); private Tabla tab_empleado_departamento = new Tabla(); private Tabla tab_deta_empleado_depar = new Tabla(); private SeleccionTabla set_encargo = new SeleccionTabla(); private String p_gen_encargo_posicion = utilitario.getVariable("p_gen_encargo_posicion"); private String p_gen_terminacion_encargo_posicion = utilitario.getVariable("p_gen_terminacion_encargo_posicion"); private String p_gen_accion_contratacion = utilitario.getVariable("p_gen_accion_contratacion"); //Reactivar private Dialogo dia_reactiva=new Dialogo(); private Texto tex_encargo=new Texto(); private Texto tex_anterior=new Texto(); private Calendario cal_fecha_encargo=new Calendario(); //configuracion de reporte private Reporte rep_reporte=new Reporte(); private SeleccionFormatoReporte sef_reporte=new SeleccionFormatoReporte(); private Map p_parametros=new HashMap(); private Dialogo dia_tipo_vinculacion=new Dialogo(); private Radio rad_tipo_vinculacion=new Radio(); private SeleccionTabla sel_tab_accion_motivo=new SeleccionTabla(); private Dialogo dia_editar_motivo=new Dialogo(); private AreaTexto are_tex_motivo=new AreaTexto(); private Dialogo dia_terminacion=new Dialogo(); private Calendario cal_terminacion=new Calendario(); private AreaTexto are_tex_observacion=new AreaTexto(); private Etiqueta eti_cargo_actual=new Etiqueta(); private Etiqueta eti_cargo_accion=new Etiqueta(); @EJB private ServicioGestion ser_gestion = (ServicioGestion) utilitario.instanciarEJB(ServicioGestion.class); @EJB private ServicioEmpleado ser_empleado = (ServicioEmpleado) utilitario.instanciarEJB(ServicioEmpleado.class); @EJB private ServicioNomina ser_nomina = (ServicioNomina) utilitario.instanciarEJB(ServicioNomina.class); private Confirmar con_guardar=new Confirmar(); private Dialogo dia_calendario=new Dialogo(); private Calendario cal_fecha_ingreso_vac=new Calendario(); private Dialogo dia_asi_vacacion=new Dialogo(); private Dialogo dia_partida_grupo_cargo=new Dialogo(); private AutoCompletar aut_part_gru_cargo=new AutoCompletar(); public pre_accion_personal() { if (utilitario.getVariable("p_gen_accion_empl_comision")==null || utilitario.getVariable("p_gen_accion_empl_comision").isEmpty()){ utilitario.agregarNotificacionInfo("No se puede abrir la pantalla","Importar parametro de sistema p_gen_accion_empl_comision"); return; } if (utilitario.getVariable("p_gen_status_stand_by")==null || utilitario.getVariable("p_gen_status_stand_by").isEmpty()){ utilitario.agregarNotificacionInfo("No se puede abrir la pantalla","Importar parametro de sistema p_gen_status_stand_by"); return; } con_guardar.setId("con_guardar"); agregarComponente(con_guardar); dia_calendario.setId("dia_calendario"); agregarComponente(dia_calendario); dia_asi_vacacion.setId("dia_asi_vacacion"); agregarComponente(dia_asi_vacacion); aut_empleado.setId("aut_empleado"); aut_empleado.setAutoCompletar("select IDE_GTEMP,DOCUMENTO_IDENTIDAD_GTEMP,APELLIDO_PATERNO_GTEMP,APELLIDO_MATERNO_GTEMP,PRIMER_NOMBRE_GTEMP,SEGUNDO_NOMBRE_GTEMP from GTH_EMPLEADO"); aut_empleado.setMetodoChange("filtrarEmpleado"); bar_botones.quitarBotonsNavegacion(); bar_botones.agregarComponente(new Etiqueta("Empleado:")); bar_botones.agregarComponente(aut_empleado); Boton bot_limpiar = new Boton(); bot_limpiar.setIcon("ui-icon-cancel"); bot_limpiar.setMetodo("limpiar"); bar_botones.agregarBoton(bot_limpiar); Boton bot_reactiva=new Boton(); bot_reactiva.setValue("Reversa de Encargo de Posición"); bot_reactiva.setMetodo("reactivar"); bot_reactiva.setIcon("ui-icon-transfer-e-w"); // bar_botones.agregarBoton(bot_reactiva); rep_reporte.setId("rep_reporte"); rep_reporte.getBot_aceptar().setMetodo("aceptarReporte"); agregarComponente(rep_reporte); sef_reporte.setId("sef_reporte"); agregarComponente(sef_reporte); bar_botones.agregarReporte(); //dialogo de tipo vinculacion List lista1 = new ArrayList(); Object fila1[] = { "0", "CONTRATO" }; Object fila2[] = { "1", "NOMBRAMIENTO" }; lista1.add(fila1); lista1.add(fila2); rad_tipo_vinculacion.setRadio(lista1); rad_tipo_vinculacion.setVertical(); Grid gri_vinculacion=new Grid(); gri_vinculacion.setColumns(4); gri_vinculacion.getChildren().add(new Etiqueta("TIPO CONTRATO")); gri_vinculacion.getChildren().add(rad_tipo_vinculacion); dia_tipo_vinculacion.setId("dia_tipo_vinculacion"); dia_tipo_vinculacion.setTitle("TIPO DE VINCULACION"); dia_tipo_vinculacion.setWidth("30%"); dia_tipo_vinculacion.setHeight("25%"); dia_tipo_vinculacion.setDynamic(false); dia_tipo_vinculacion.setDialogo(gri_vinculacion); dia_tipo_vinculacion.setDynamic(false); dia_tipo_vinculacion.getBot_aceptar().setMetodo("aceptarReporte"); agregarComponente(dia_tipo_vinculacion); //seleccion tabla de accion motivo sel_tab_accion_motivo.setId("sel_tab_accion_motivo"); //sel_tab_accion_motivo.setSeleccionTabla("SELECT ide_gemed,detalle_gemed,detalle_reporte_gemed FROM gen_motivo_empleado_depa", "ide_gemed"); sel_tab_accion_motivo.setSeleccionTabla("SELECT a.IDE_GEAME,b.DETALLE_GEAED,c.DETALLE_GEMED,c.detalle_reporte_gemed FROM GEN_ACCION_MOTIVO_EMPLEADO a " + "LEFT JOIN ( " + "SELECT IDE_GEAED,DETALLE_GEAED from GEN_ACCION_EMPLEADO_DEPA " + ")b ON b.IDE_GEAED=a.IDE_GEAED " + "LEFT JOIN ( " + "SELECT IDE_GEMED,DETALLE_GEMED,detalle_reporte_gemed FROM GEN_MOTIVO_EMPLEADO_DEPA " + ")c ON c.IDE_GEMED=a.IDE_GEMED WHERE a.IDE_GEAME IN (-1) " + "ORDER BY b.DETALLE_GEAED,c.DETALLE_GEMED", "IDE_GEAME"); sel_tab_accion_motivo.setTitle("MOTIVOS DE ACCION DE PERSONAL"); sel_tab_accion_motivo.getTab_seleccion().getColumna("detalle_gemed").setFiltro(true); sel_tab_accion_motivo.setRadio(); sel_tab_accion_motivo.setDynamic(false); sel_tab_accion_motivo.getBot_aceptar().setMetodo("aceptarReporte"); agregarComponente(sel_tab_accion_motivo); //dialogo de editar motivo are_tex_motivo.setId("are_tex_motivo"); are_tex_motivo.setValue(""); //are_tex_motivo.set Grid gri_editar_motivo=new Grid(); gri_editar_motivo.setMensajeInfo("En esta �rea puede editar el detalle de la Acción de Personal"); gri_editar_motivo.getChildren().add(are_tex_motivo); dia_editar_motivo.setId("dia_editar_motivo"); dia_editar_motivo.setTitle("EDITOR DE EL DETALLE DE ACCióN DE PERSONAL"); dia_editar_motivo.setWidth("65%"); dia_editar_motivo.setHeight("60%"); dia_editar_motivo.setDialogo(gri_editar_motivo); dia_editar_motivo.setDynamic(false); dia_editar_motivo.getBot_aceptar().setMetodo("aceptarReporte"); gri_editar_motivo.setStyle("width:" + (dia_editar_motivo.getAnchoPanel() - 5) + "px;overflow:auto;"); are_tex_motivo.setStyle("width:" + (dia_editar_motivo.getAnchoPanel() - 15) + "px;overflow:auto; height:"+ (dia_editar_motivo.getAltoPanel() - 5)+"px"); agregarComponente(dia_editar_motivo); Tabulador tab_tabulador = new Tabulador(); tab_tabulador.setId("tab_tabulador"); tab_partida_vigente.setHeader(eti_cargo_actual); tab_partida_vigente.setId("tab_partida_vigente"); tab_partida_vigente.setIdCompleto("tab_tabulador:tab_partida_vigente"); tab_partida_vigente.setTabla("GEN_EMPLEADOS_DEPARTAMENTO_PAR", "IDE_GEEDP", 1); tab_partida_vigente.getColumna("IDE_GEGRO").setCombo( "GEN_GRUPO_OCUPACIONAL", "IDE_GEGRO", "DETALLE_GEGRO", ""); tab_partida_vigente .getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO=-1)"); tab_partida_vigente.getColumna("GEN_IDE_GECAF").setCombo( "GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", ""); tab_partida_vigente.getColumna("IDE_SUCU").setCombo("SIS_SUCURSAL", "IDE_SUCU", "NOM_SUCU", ""); tab_partida_vigente.getColumna("IDE_SUCU").setVisible(true); tab_partida_vigente .getColumna("IDE_GEARE") .setCombo( "GEN_AREA", "IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU=-1)"); tab_partida_vigente.getColumna("IDE_GEARE").setMetodoChange( "cargarCargoDepartamentos"); tab_partida_vigente.getColumna("IDE_GEARE").setBuscarenCombo(false); tab_partida_vigente .getColumna("IDE_GEDEP") .setCombo( "GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU=-1 AND IDE_GEARE=-1)"); tab_partida_vigente.getColumna("IDE_GECAE").setCombo( "GEN_CATEGORIA_ESTATUS", "IDE_GECAE", "DETALLE_GECAE", ""); tab_partida_vigente.getColumna("IDE_GETIV").setCombo( "GEN_TIPO_VINCULACION", "IDE_GETIV", "DETALLE_GETIV", ""); tab_partida_vigente .getColumna("IDE_GEPGC") .setCombo( "SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP " + "from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP"); tab_partida_vigente.getColumna("IDE_GTTEM").setCombo( "GTH_TIPO_EMPLEADO", "IDE_GTTEM", "DETALLE_GTTEM", ""); tab_partida_vigente.getColumna("IDE_GTTCO").setCombo( "GTH_TIPO_CONTRATO", "IDE_GTTCO", "DETALLE_GTTCO", ""); tab_partida_vigente.getColumna("IDE_GTTSI").setCombo( "GTH_TIPO_SINDICATO", "IDE_GTTSI", "DETALLE_GTTSI", ""); tab_partida_vigente.getColumna("IDE_GTGRE").setCombo( "GTH_GRUPO_EMPLEADO", "IDE_GTGRE", "DETALLE_GTGRE", ""); tab_partida_vigente.getColumna("IDE_GTGRE").setCombo( "GTH_GRUPO_EMPLEADO", "IDE_GTGRE", "DETALLE_GTGRE", ""); tab_partida_vigente.getColumna("ACTIVO_GEEDP").setVisible(false); tab_partida_vigente.getColumna("ACUMULA_FONDOS_GEEDP").setCheck(); tab_partida_vigente.getColumna("LINEA_SUPERVICION_GEEDP").setCheck(); tab_partida_vigente.getColumna("IDE_GTEMP").setVisible(false); tab_partida_vigente.getColumna("CONTROL_ASISTENCIA_GEEDP").setCheck(); tab_partida_vigente.getColumna("CONTROL_ASISTENCIA_GEEDP").setValorDefecto("false"); List listaliquidacion = new ArrayList(); Object fila3[] = { "0", "SI" }; Object fila4[] = { "1", "NO" }; listaliquidacion.add(fila3); listaliquidacion.add(fila4); List listaejecutaliqui = new ArrayList(); Object fila5[] = { "0", "SI" }; Object fila6[] = { "1", "NO" }; listaejecutaliqui.add(fila5); listaejecutaliqui.add(fila6); tab_partida_vigente.getColumna("LIQUIDACION_GEEDP").setRadio(listaliquidacion, "0"); tab_partida_vigente.getColumna("LIQUIDACION_GEEDP").setRadioVertical(true); tab_partida_vigente.getColumna("EJECUTO_LIQUIDACION_GEEDP").setRadio(listaejecutaliqui, "0"); tab_partida_vigente.getColumna("EJECUTO_LIQUIDACION_GEEDP").setRadioVertical(true); tab_partida_vigente.setCondicion("IDE_GTEMP=-1 AND ACTIVO_GEEDP=true"); tab_partida_vigente.setMostrarcampoSucursal(true); tab_partida_vigente.setTipoFormulario(true); tab_partida_vigente.setLectura(true); tab_partida_vigente.getGrid().setColumns(4); tab_partida_vigente.setMostrarNumeroRegistros(false); tab_partida_vigente.dibujar(); PanelTabla pat_panel = new PanelTabla(); pat_panel.setPanelTabla(tab_partida_vigente); tab_tabulador.agregarTab("Estado Actual", pat_panel); tab_deta_empleado_depar.setId("tab_deta_empleado_depar"); tab_deta_empleado_depar.onSelect("seleccionarTabla1"); tab_deta_empleado_depar .setIdCompleto("tab_tabulador:tab_deta_empleado_depar"); tab_deta_empleado_depar.setTabla("GEN_DETALLE_EMPLEADO_DEPARTAME", "IDE_GEDED", 2); tab_deta_empleado_depar.getColumna("FECHA_SALIDA_GEDED").setVisible(false); tab_deta_empleado_depar.getColumna("GEN_IDE_GEDED").setVisible(false); tab_deta_empleado_depar.getColumna("IDE_GEINS").setCombo( "GEN_INSTITUCION", "IDE_GEINS", "DETALLE_GEINS", ""); tab_deta_empleado_depar.getColumna("IDE_GEINS").setAutoCompletar(); tab_deta_empleado_depar.setRecuperarLectura(true); tab_deta_empleado_depar .getColumna("IDE_GEAME") .setCombo( "SELECT a.IDE_GEAME,b.IDE_GEAED,b.DETALLE_GEAED,c.DETALLE_GEMED FROM GEN_ACCION_MOTIVO_EMPLEADO a " + "LEFT JOIN ( " + "SELECT IDE_GEAED,DETALLE_GEAED from GEN_ACCION_EMPLEADO_DEPA " + ")b ON b.IDE_GEAED=a.IDE_GEAED " + "LEFT JOIN ( " + "SELECT IDE_GEMED,DETALLE_GEMED FROM GEN_MOTIVO_EMPLEADO_DEPA " + ")c ON c.IDE_GEMED=a.IDE_GEMED " + "ORDER BY b.DETALLE_GEAED,c.DETALLE_GEMED"); tab_deta_empleado_depar.getColumna("IDE_GEAME").setAutoCompletar(); tab_deta_empleado_depar.getColumna("IDE_GEAME").setMetodoChange("cambioAccion"); tab_deta_empleado_depar.getColumna("FECHA_INGRESO_GEDED").setValorDefecto(utilitario.getFechaActual()); tab_deta_empleado_depar.getColumna("ACTIVO_GEDED").setCheck(); tab_deta_empleado_depar.getColumna("ACTIVO_GEDED").setValorDefecto("true"); tab_deta_empleado_depar.getColumna("ACTIVO_GEDED").setLectura(true); tab_deta_empleado_depar.getColumna("IDE_GTEMP").setVisible(false); tab_deta_empleado_depar.setCampoOrden("IDE_GEDED DESC"); tab_deta_empleado_depar.agregarRelacion(tab_empleado_departamento); tab_deta_empleado_depar.setCondicion("IDE_GTEMP=-1"); tab_deta_empleado_depar.getColumna("GEN_IDE_GEDED").setLectura(true); tab_deta_empleado_depar.setScrollable(true); tab_deta_empleado_depar.setScrollHeight(100); tab_deta_empleado_depar.setValidarInsertar(true); tab_deta_empleado_depar.dibujar(); PanelTabla pat_panel2 = new PanelTabla(); pat_panel2.setPanelTabla(tab_deta_empleado_depar); tab_deta_empleado_depar.setRecuperarLectura(false); tab_empleado_departamento.setHeader(eti_cargo_accion); tab_empleado_departamento.setId("tab_empleado_departamento"); tab_empleado_departamento.setIdCompleto("tab_tabulador:tab_empleado_departamento"); tab_empleado_departamento.setTabla("GEN_EMPLEADOS_DEPARTAMENTO_PAR","IDE_GEEDP", 3); tab_empleado_departamento.onSelect("seleccionaTablaEmpleadosDepartamento"); tab_empleado_departamento.getColumna("IDE_GEGRO").setCombo("GEN_GRUPO_OCUPACIONAL", "IDE_GEGRO", "DETALLE_GEGRO", ""); tab_empleado_departamento.getColumna("FECHA_GEEDP").setValorDefecto(utilitario.getFechaActual()); tab_empleado_departamento.getColumna("FECHA_GEEDP").setMetodoChange("llenarFechaFinContrato"); tab_empleado_departamento.getColumna("IDE_GEGRO").setMetodoChange("cargarCargoFuncional"); // tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL","IDE_GECAF","DETALLE_GECAF","PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO=-1)"); tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL","IDE_GECAF","DETALLE_GECAF",""); tab_empleado_departamento.getColumna("IDE_GECAF").setMetodoChange("cargarPartidaGrupoCargo"); tab_empleado_departamento.getColumna("IDE_GECAF").setBuscarenCombo(false); tab_empleado_departamento.getColumna("GEN_IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", ""); tab_empleado_departamento.getColumna("IDE_SUCU").setCombo("SIS_SUCURSAL", "IDE_SUCU", "NOM_SUCU", ""); tab_empleado_departamento.getColumna("IDE_SUCU").setVisible(true); tab_empleado_departamento.getColumna("IDE_SUCU").setMetodoChange( "cargarCargoAreas"); tab_empleado_departamento .getColumna("IDE_GEARE") .setCombo( "GEN_AREA", "IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU=-1)"); tab_empleado_departamento.getColumna("IDE_GEARE").setMetodoChange( "cargarCargoDepartamentos"); tab_empleado_departamento.getColumna("IDE_GEARE").setBuscarenCombo( false); // tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO","IDE_GEDEP","DETALLE_GEDEP","IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU=-1 AND IDE_GEARE=-1)"); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO","IDE_GEDEP","DETALLE_GEDEP",""); tab_empleado_departamento.getColumna("IDE_GEDEP").setMetodoChange( "cargarPartidaGrupoCargo"); tab_empleado_departamento.getColumna("IDE_GEDEP").setBuscarenCombo( false); tab_empleado_departamento.getColumna("IDE_GECAE").setCombo("GEN_CATEGORIA_ESTATUS", "IDE_GECAE", "DETALLE_GECAE", ""); tab_empleado_departamento.getColumna("IDE_GECAE").setLectura(true); tab_empleado_departamento.getColumna("IDE_GETIV").setCombo( "GEN_TIPO_VINCULACION", "IDE_GETIV", "DETALLE_GETIV", ""); tab_empleado_departamento.getColumna("IDE_GETIV").setBuscarenCombo( false); tab_empleado_departamento.getColumna("AJUSTE_SUELDO_GEEDP").setMetodoChange("cambioAjuste"); tab_empleado_departamento.getColumna("IDE_GEPGC").setCombo("SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP,pgc.TITULO_CARGO_GEPGC " +"from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP "); tab_empleado_departamento.getColumna("IDE_GEPGC").setLectura(true); tab_empleado_departamento.getColumna("IDE_GTTEM").setCombo( "GTH_TIPO_EMPLEADO", "IDE_GTTEM", "DETALLE_GTTEM", ""); tab_empleado_departamento.getColumna("IDE_GTTCO").setCombo( "GTH_TIPO_CONTRATO", "IDE_GTTCO", "DETALLE_GTTCO", ""); tab_empleado_departamento.getColumna("IDE_GTTSI").setCombo( "GTH_TIPO_SINDICATO", "IDE_GTTSI", "DETALLE_GTTSI", ""); tab_empleado_departamento.getColumna("IDE_GTGRE").setCombo( "GTH_GRUPO_EMPLEADO", "IDE_GTGRE", "DETALLE_GTGRE", ""); tab_empleado_departamento.getColumna("IDE_GTGRE").setCombo( "GTH_GRUPO_EMPLEADO", "IDE_GTGRE", "DETALLE_GTGRE", ""); tab_empleado_departamento.getColumna("ACTIVO_GEEDP").setCheck(); tab_empleado_departamento.getColumna("ACTIVO_GEEDP").setLectura(true); tab_empleado_departamento.getColumna("ACTIVO_GEEDP").setValorDefecto("true"); tab_empleado_departamento.getColumna("ACUMULA_FONDOS_GEEDP").setCheck(); tab_empleado_departamento.getColumna("LINEA_SUPERVICION_GEEDP") .setCheck(); tab_empleado_departamento.getColumna("IDE_GEPGC").setAutoCompletar(); tab_empleado_departamento.getColumna("IDE_GEPGC").setMetodoChange("cambioPartida"); tab_empleado_departamento.getColumna("IDE_GTEMP").setVisible(false); tab_empleado_departamento.getColumna("CONTROL_ASISTENCIA_GEEDP").setCheck(); tab_empleado_departamento.getColumna("CONTROL_ASISTENCIA_GEEDP").setValorDefecto("false"); tab_partida_vigente.getColumna("LIQUIDACION_GEEDP").setRadio(listaliquidacion, "0"); tab_partida_vigente.getColumna("LIQUIDACION_GEEDP").setRadioVertical(true); tab_partida_vigente.getColumna("EJECUTO_LIQUIDACION_GEEDP").setRadio(listaejecutaliqui, "0"); tab_partida_vigente.getColumna("EJECUTO_LIQUIDACION_GEEDP").setRadioVertical(true); tab_empleado_departamento.setMostrarcampoSucursal(true); tab_empleado_departamento.setTipoFormulario(true); tab_empleado_departamento.getGrid().setColumns(4); tab_empleado_departamento.getColumna("IDE_GTTCO").setMetodoChange("cambioTipoContrato"); tab_empleado_departamento.setRecuperarLectura(true); tab_empleado_departamento.setMostrarNumeroRegistros(false); actualizarCombosDepartamentoEmpleado(); PanelTabla pat_panel1 = new PanelTabla(); pat_panel1.setPanelTabla(tab_empleado_departamento); pat_panel1.getMenuTabla().getItem_insertar().setRendered(false); pat_panel1.getMenuTabla().getItem_eliminar().setRendered(false); pat_panel1.getMenuTabla().getItem_actualizar().setRendered(false); aut_part_gru_cargo.setId("aut_part_gru_cargo"); aut_part_gru_cargo.setAutoCompletar("SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP,pgc.TITULO_CARGO_GEPGC " +"from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP where pgc.VACANTE_GEPGC=TRUE and pgc.ACTIVO_GEPGC=TRUE "); Grid gri=new Grid(); gri.setColumns(2); gri.getChildren().add(new Etiqueta("Partida Grupo Cargo")); gri.getChildren().add(aut_part_gru_cargo); dia_partida_grupo_cargo.setId("dia_partida_grupo_cargo"); dia_partida_grupo_cargo.setWidth("30%"); dia_partida_grupo_cargo.setHeight("20%"); dia_partida_grupo_cargo.setDialogo(gri); dia_partida_grupo_cargo.setTitle("PARTIDA GRUPO CARGO"); dia_partida_grupo_cargo.getBot_aceptar().setMetodo("aceptarPartidaGrupoCargo"); dia_partida_grupo_cargo.setDynamic(true); agregarComponente(dia_partida_grupo_cargo); Boton bot_cambiar_pgc=new Boton(); bot_cambiar_pgc.setValue("Registro de Partida"); bot_cambiar_pgc.setMetodo("cambiarPartida"); bot_cambiar_pgc.setIcon("ui-icon-transfer-e-w"); bar_botones.agregarBoton(bot_cambiar_pgc); Grupo gri_grid = new Grupo(); //pat_panel2.setStyle("width:99%;height:100%;overflow: hidden;display: block;"); gri_grid.getChildren().add(pat_panel2); gri_grid.getChildren().add(pat_panel1); tab_tabulador.agregarTab("Acciones de Personal", gri_grid); Division div_division = new Division(); div_division.setId("div_division"); div_division.dividir1(tab_tabulador); agregarComponente(div_division); set_encargo.setId("set_encargo"); set_encargo.setWidth("70%"); set_encargo.setHeight("60%"); set_encargo.setTitle("ENCARGO DE PUESTO"); set_encargo.setSeleccionTabla( "select a.ide_gepgc,IDE_GEARE,a.ide_gegro,a.ide_gecaf,a.ide_sucu,a.ide_gedep,a.ide_gttem, titulo_cargo_gepgc,c.detalle_gegro as grupo_ocuapcional,detalle_gecaf as cargo,salario_encargo_gepgc from gen_partida_grupo_cargo a, gen_cargo_funcional b,gen_grupo_ocupacional c where a.ide_gecaf = b.ide_gecaf and a.ide_gegro = c.ide_gegro and encargo_gepgc=TRUE order by titulo_cargo_gepgc ", "ide_gepgc"); set_encargo.getTab_seleccion().getColumna("ide_gepgc").setVisible(false); set_encargo.getTab_seleccion().getColumna("IDE_GEARE").setVisible(false); set_encargo.getTab_seleccion().getColumna("ide_gegro").setVisible(false); set_encargo.getTab_seleccion().getColumna("ide_gecaf").setVisible(false); set_encargo.getTab_seleccion().getColumna("ide_sucu").setVisible(false); set_encargo.getTab_seleccion().getColumna("ide_gedep").setVisible(false); set_encargo.getTab_seleccion().getColumna("ide_gttem").setVisible(false); set_encargo.getBot_aceptar().setMetodo("aceptarEncargo"); set_encargo.getBot_cancelar().setMetodo("cancelarEncargo"); set_encargo.setRadio(); agregarComponente(set_encargo); dia_reactiva.setId("dia_reactiva"); dia_reactiva.setHeight("33%"); dia_reactiva.setWidth("50%"); dia_reactiva.setTitle("Reactivacion de Encargo de Posición"); Grid gri_rac=new Grid(); gri_rac.setStyle("Width:"+(dia_reactiva.getAnchoPanel()-10)+"PX;height:" + (dia_reactiva.getAltoPanel()-10) + "px;overflow: auto;display: block;"); gri_rac.setColumns(2); gri_rac.getChildren().add(new Etiqueta("Posición Encargada :")); tex_encargo.setSize(50); tex_encargo.setReadonly(true); tex_encargo.setStyle("width:99%"); gri_rac.getChildren().add(tex_encargo); gri_rac.getChildren().add(new Etiqueta("Posición Anterior :")); tex_anterior.setSize(50); tex_anterior.setReadonly(true); tex_anterior.setStyle("width:99%"); gri_rac.getChildren().add(tex_anterior); gri_rac.getChildren().add(new Etiqueta("Fecha Encargo Posición :")); gri_rac.getChildren().add(cal_fecha_encargo); dia_reactiva.getBot_aceptar().setMetodo("aceptarReactivar"); dia_reactiva.setDialogo(gri_rac); agregarComponente(dia_reactiva); //dia_terminacion dia_terminacion.setId("dia_terminacion"); dia_terminacion.setWidth("40%"); dia_terminacion.setHeight("40%"); are_tex_observacion.setId("are_tex_observacion"); are_tex_observacion.setStyle("width:300px;"); cal_terminacion.setId("cal_terminacion"); Grid gri_terminacion=new Grid(); gri_terminacion.setColumns(2); // gri_terminacion.setStyle("width:" + (dia_terminacion.getAnchoPanel() - 5) + "px;overflow:auto;"); gri_terminacion.getChildren().add(new Etiqueta("Ingrese la fecha te termino de contrato: ")); gri_terminacion.getChildren().add(cal_terminacion); gri_terminacion.getChildren().add(new Etiqueta("Ingrese Motivo de Fin de Contrato: ")); gri_terminacion.getChildren().add(are_tex_observacion); dia_terminacion.setTitle("TERMINO DE CONTRATO"); dia_terminacion.setDialogo(gri_terminacion); dia_terminacion.getBot_aceptar().setMetodo("cargarFechaTerminacion"); agregarComponente(dia_terminacion); } public Dialogo getDia_partida_grupo_cargo() { return dia_partida_grupo_cargo; } public void setDia_partida_grupo_cargo(Dialogo dia_partida_grupo_cargo) { this.dia_partida_grupo_cargo = dia_partida_grupo_cargo; } public AutoCompletar getAut_part_gru_cargo() { return aut_part_gru_cargo; } public void setAut_part_gru_cargo(AutoCompletar aut_part_gru_cargo) { this.aut_part_gru_cargo = aut_part_gru_cargo; } public void aceptarPartidaGrupoCargo(){ if (aut_part_gru_cargo.getValor()==null || aut_part_gru_cargo.getValor().isEmpty()){ utilitario.agregarMensajeInfo("No ha seleccionado ninguna partida",""); return; } TablaGenerica tab_datos= utilitario.consultar("select ide_gepgc,ide_gegro,ide_gecaf,ide_sucu,ide_gedep,ide_geare,ide_gttem from gen_partida_grupo_cargo where IDE_GEPGC ="+aut_part_gru_cargo.getValor()); if(tab_datos.isEmpty()==false){ tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+tab_datos.getValor("IDE_GEGRO")+")"); tab_empleado_departamento.getColumna("IDE_GEARE").setCombo("GEN_AREA","IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_datos.getValor("ide_sucu")+")"); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_datos.getValor("ide_sucu")+" AND IDE_GEARE="+tab_datos.getValor("IDE_GEARE")+")"); tab_empleado_departamento.modificar(tab_empleado_departamento.getFilaActual()); tab_empleado_departamento.setValor("IDE_GEPGC",aut_part_gru_cargo.getValor()); tab_empleado_departamento.setValor("IDE_GEGRO",tab_datos.getValor("IDE_GEGRO")); tab_empleado_departamento.setValor("IDE_GECAF", tab_datos.getValor("IDE_GECAF")); tab_empleado_departamento.setValor("IDE_SUCU", tab_datos.getValor("ide_sucu")); tab_empleado_departamento.setValor("IDE_GTTEM", tab_datos.getValor("IDE_GTTEM")); tab_empleado_departamento.setValor("IDE_GEDEP", tab_datos.getValor("IDE_GEDEP")); tab_empleado_departamento.setValor("IDE_GEARE",tab_datos.getValor("IDE_GEARE")); utilitario.addUpdateTabla(tab_empleado_departamento, "IDE_GEPGC,IDE_GECAF,IDE_SUCU,IDE_GTTEM,IDE_GEDEP,IDE_GEARE", "tab_tabulador:tab_empleado_departamento"); dia_partida_grupo_cargo.cerrar(); } } public void cambiarPartida(){ if (tab_deta_empleado_depar.getValor("activo_geded")==null || tab_deta_empleado_depar.getValor("activo_geded").isEmpty()){ utilitario.agregarMensajeInfo("No se puede cambiar la partida", "La accion se encuentra inactiva"); return; } if (tab_deta_empleado_depar.getValor("activo_geded").equalsIgnoreCase("false") || tab_deta_empleado_depar.getValor("activo_geded").equalsIgnoreCase("0")){ utilitario.agregarMensajeInfo("No se puede cambiar la partida", "La accion se encuentra inactiva"); return; } aut_part_gru_cargo.setAutoCompletar("SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP,pgc.TITULO_CARGO_GEPGC " +"from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP where pgc.VACANTE_GEPGC=TRUE and pgc.ACTIVO_GEPGC=TRUE "); aut_part_gru_cargo.setValor(null); dia_partida_grupo_cargo.dibujar(); } public void llenarFechaFinContrato(DateSelectEvent evt){ tab_empleado_departamento.modificar(evt); int int_dias=0; String str_fecha_ini=tab_empleado_departamento.getValor("FECHA_GEEDP"); try { int_dias=Integer.parseInt(ser_gestion.getTipoContrato(tab_empleado_departamento.getValor("IDE_GTTCO")).getValor("DIA_FINC_GTTCO")); } catch (Exception e) { // TODO: handle exception } System.out.println("fecha fin "+utilitario.getFormatoFecha(utilitario.sumarDiasFecha(utilitario.getFecha(str_fecha_ini), int_dias))); tab_empleado_departamento.setValor("FECHA_FINCTR_GEEDP", utilitario.getFormatoFecha(utilitario.sumarDiasFecha(utilitario.getFecha(str_fecha_ini), int_dias))); utilitario.addUpdateTabla(tab_empleado_departamento, "FECHA_FINCTR_GEEDP", ""); } public void llenarFechaFinContrato(AjaxBehaviorEvent evt){ tab_empleado_departamento.modificar(evt); int int_dias=0; String str_fecha_ini=tab_empleado_departamento.getValor("FECHA_GEEDP"); try { int_dias=Integer.parseInt(ser_gestion.getTipoContrato(tab_empleado_departamento.getValor("IDE_GTTCO")).getValor("DIA_FINC_GTTCO")); } catch (Exception e) { // TODO: handle exception } System.out.println("fecha fin "+utilitario.getFormatoFecha(utilitario.sumarDiasFecha(utilitario.getFecha(str_fecha_ini), int_dias))); tab_empleado_departamento.setValor("FECHA_FINCTR_GEEDP", utilitario.getFormatoFecha(utilitario.sumarDiasFecha(utilitario.getFecha(str_fecha_ini), int_dias))); utilitario.addUpdateTabla(tab_empleado_departamento, "FECHA_FINCTR_GEEDP", ""); } /** * Carga el nombre del cargo del estado actual */ private void cargarNombreCargoPartidaActual(){ if(tab_partida_vigente.isEmpty()==false){ List lis_puesto=utilitario.getConexion().consultar("select titulo_cargo_gepgc from gen_partida_grupo_cargo where ide_gepgc="+tab_partida_vigente.getValor("ide_gepgc")); if(lis_puesto.isEmpty()==false){ eti_cargo_actual.setValue(lis_puesto.get(0)); } } } /** * Carga el nombre del cargo de la partida seleccionada */ private void cargarNombreCargoPartidaSeleccionada(){ if(tab_empleado_departamento.isEmpty()==false){ List lis_puesto=utilitario.getConexion().consultar("select titulo_cargo_gepgc from gen_partida_grupo_cargo where ide_gepgc="+tab_empleado_departamento.getValor("ide_gepgc")); if(lis_puesto.isEmpty()==false){ eti_cargo_accion.setValue(lis_puesto.get(0)); } } } public void aceptarReactivar(){ String str_GEN_IDE_GEDED= tab_deta_empleado_depar.getValor("GEN_IDE_GEDED"); utilitario.getConexion().getSqlPantalla().clear(); utilitario.getConexion().agregarSql("UPDATE GEN_DETALLE_EMPLEADO_DEPARTAME set ACTIVO_GEDED=false WHERE IDE_GTEMP="+aut_empleado.getValor()); utilitario.getConexion().agregarSql("UPDATE GEN_DETALLE_EMPLEADO_DEPARTAME set ACTIVO_GEDED=true WHERE IDE_GEDED="+str_GEN_IDE_GEDED); utilitario.getConexion().agregarSql("UPDATE GEN_EMPLEADOS_DEPARTAMENTO_PAR set ACTIVO_GEEDP=false WHERE IDE_GTEMP="+aut_empleado.getValor()); utilitario.getConexion().agregarSql("UPDATE GEN_EMPLEADOS_DEPARTAMENTO_PAR set ACTIVO_GEEDP=true WHERE IDE_GEDED="+str_GEN_IDE_GEDED); if(guardarPantalla().isEmpty()){ dia_reactiva.cerrar(); tab_partida_vigente.ejecutarSql(); actualizarCombosDepartamentoActivoEmpleado(); tab_deta_empleado_depar.ejecutarSql(); seleccionarTabla1(); //utilitario.addUpdate("tab_tabulador:tab_partida_vigente"); } } private String getAccionAnterior(){ tab_deta_empleado_depar.ejecutarSql(); if(tab_deta_empleado_depar.getTotalFilas()>1){ return tab_deta_empleado_depar.getValor(1,"IDE_GEDED"); } return null; } public void cambioTipoContrato(AjaxBehaviorEvent evt){ tab_empleado_departamento.modificar(evt); if(tab_empleado_departamento.getValor("IDE_GTTCO")!=null){ TablaGenerica tab_tipocon=utilitario.consultar("SELECT * FROM GTH_TIPO_CONTRATO WHERE IDE_GTTCO="+tab_empleado_departamento.getValor("IDE_GTTCO")); if(!tab_tipocon.isEmpty()){ String str_dias=tab_tipocon.getValor("DIA_FINC_GTTCO"); String str_fecha_ini=tab_empleado_departamento.getValor("FECHA_GEEDP"); if(str_dias!=null && str_fecha_ini!=null){ int int_dias=0; try { int_dias=Integer.parseInt(str_dias); } catch (Exception e) { // TODO: handle exception } tab_empleado_departamento.setValor("FECHA_FINCTR_GEEDP", utilitario.getFormatoFecha(utilitario.sumarDiasFecha(utilitario.getFecha(str_fecha_ini), int_dias))); utilitario.addUpdateTabla(tab_empleado_departamento, "FECHA_FINCTR_GEEDP", ""); } } } } public void cambioPartida(SelectEvent evt){ tab_empleado_departamento.modificar(evt); if(tab_empleado_departamento.getValor("IDE_GEPGC")!=null){ TablaGenerica tab_datos= utilitario.consultar("select ide_gepgc,ide_gegro,ide_gecaf,ide_sucu,ide_gedep,ide_geare,ide_gttem from gen_partida_grupo_cargo where IDE_GEPGC ="+tab_empleado_departamento.getValor("IDE_GEPGC")); if(tab_datos.isEmpty()==false){ tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+tab_datos.getValor("IDE_GEGRO")+")"); tab_empleado_departamento.getColumna("IDE_GEARE").setCombo("GEN_AREA","IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_datos.getValor("ide_sucu")+")"); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_datos.getValor("ide_sucu")+" AND IDE_GEARE="+tab_datos.getValor("IDE_GEARE")+")"); tab_empleado_departamento.setValor("IDE_GEGRO",tab_datos.getValor("IDE_GEGRO")); tab_empleado_departamento.setValor("IDE_GECAF", tab_datos.getValor("IDE_GECAF")); tab_empleado_departamento.setValor("IDE_SUCU", tab_datos.getValor("ide_sucu")); tab_empleado_departamento.setValor("IDE_GTTEM", tab_datos.getValor("IDE_GTTEM")); tab_empleado_departamento.setValor("IDE_GEDEP", tab_datos.getValor("IDE_GEDEP")); tab_empleado_departamento.setValor("IDE_GEARE",tab_datos.getValor("IDE_GEARE")); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } } } public void cambioAjuste(AjaxBehaviorEvent evt){ tab_empleado_departamento.modificar(evt); try { double dou_ajuste= Double.parseDouble(tab_empleado_departamento.getValor("AJUSTE_SUELDO_GEEDP")); TablaGenerica tab_sueldo=utilitario.consultar("SELECT * FROM GEN_EMPLEADOS_DEPARTAMENTO_PAR where ACTIVO_GEEDP=true and IDE_GTEMP="+aut_empleado.getValor()); if(tab_sueldo.isEmpty()==false){ double dou_sueldo= Double.parseDouble(tab_sueldo.getValor("RMU_GEEDP")); dou_sueldo+=dou_ajuste; tab_empleado_departamento.setValor("RMU_GEEDP", utilitario.getFormatoNumero(dou_sueldo)); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } else{ utilitario.agregarMensaje("No existe una Accion Activa",""); } } catch (Exception e) { // TODO: handle exception } } public void limpiar(){ tab_partida_vigente.limpiar(); tab_deta_empleado_depar.limpiar(); aut_empleado.limpiar(); utilitario.addUpdate("tab_tabulador,aut_empleado"); } public void reactivar(){ if(tab_deta_empleado_depar.getValor("IDE_GEAME")!=null){ if(tab_deta_empleado_depar.getValor("ACTIVO_GEDED")!=null && tab_deta_empleado_depar.getValor("ACTIVO_GEDED").equals("true")){ if (tab_deta_empleado_depar.getValor("IDE_GEAME").equals(p_gen_encargo_posicion)){ //Busco los nombres de los cargos TablaGenerica tab_cargo=utilitario.consultar("select ide_gepgc,titulo_cargo_gepgc " + "from gen_partida_grupo_cargo where ide_gepgc in (select ide_gepgc from gen_empleados_departamento_par where ide_geded in("+tab_deta_empleado_depar.getValor("IDE_GEDED")+","+tab_deta_empleado_depar.getValor("GEN_IDE_GEDED")+"))"); if(tab_cargo.getTotalFilas()==2){ //Carga los nombres de los puestos tex_encargo.setValue(tab_cargo.getValor(1,"titulo_cargo_gepgc")); tex_anterior.setValue(tab_cargo.getValor(0,"titulo_cargo_gepgc")); } else{ tex_anterior.limpiar(); tex_anterior.limpiar(); } cal_fecha_encargo.setValue(utilitario.getFecha(tab_partida_vigente.getValor("FECHA_ENCARGO_GEEDP"))); dia_reactiva.dibujar(); } else{ utilitario.agregarMensajeInfo("No se puede Reactivar", "Debe seleccionar una Acción de tipo Encargo de Posicion"); } } else{ utilitario.agregarMensajeInfo("No se puede Reactivar", "La Acción debe estar activa"); } } } private void actualizarCombosDepartamentoEmpleado(String ide_sucu,String IDE_GEGRO,String IDE_GEARE){ tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+IDE_GEGRO+")"); tab_empleado_departamento.getColumna("IDE_GEARE").setCombo("GEN_AREA","IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+ide_sucu+")"); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+ide_sucu+" AND IDE_GEARE="+IDE_GEARE+")"); tab_empleado_departamento.setValor("IDE_GEGRO",IDE_GEGRO); tab_empleado_departamento.setValor("IDE_GECAF", set_encargo.getTab_seleccion().getValor("IDE_GECAF")); tab_empleado_departamento.setValor("IDE_SUCU", ide_sucu); tab_empleado_departamento.setValor("IDE_GTTEM", set_encargo.getTab_seleccion().getValor("IDE_GTTEM")); tab_empleado_departamento.setValor("IDE_GEDEP", set_encargo.getTab_seleccion().getValor("IDE_GEDEP")); tab_empleado_departamento.setValor("IDE_GEARE",IDE_GEARE); cargarNombreCargoPartidaSeleccionada(); } private void actualizarCombosDepartamentoEmpleado(){ tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+tab_empleado_departamento.getValor("IDE_GEGRO")+")"); tab_empleado_departamento.getColumna("IDE_GEARE").setCombo("GEN_AREA","IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_empleado_departamento.getValor("ide_sucu")+")"); tab_empleado_departamento.actualizarCombosFormulario(); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_empleado_departamento.getValor("IDE_SUCU")+" AND IDE_GEARE="+tab_empleado_departamento.getValor("IDE_GEARE")+")"); tab_empleado_departamento.actualizarCombosFormulario(); cargarNombreCargoPartidaSeleccionada(); } private void actualizarCombosDepartamentoEmpleadoconActual(){ tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+tab_partida_vigente.getValor("IDE_GEGRO")+")"); tab_empleado_departamento.getColumna("IDE_GEARE").setCombo("GEN_AREA","IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_partida_vigente.getValor("ide_sucu")+")"); tab_empleado_departamento.actualizarCombosFormulario(); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_partida_vigente.getValor("IDE_SUCU")+" AND IDE_GEARE="+tab_partida_vigente.getValor("IDE_GEARE")+")"); tab_empleado_departamento.actualizarCombosFormulario(); cargarNombreCargoPartidaSeleccionada(); } private void actualizarCombosDepartamentoActivoEmpleado(){ tab_partida_vigente.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+tab_partida_vigente.getValor("IDE_GEGRO")+")"); tab_partida_vigente.getColumna("IDE_GEARE").setCombo("GEN_AREA","IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_partida_vigente.getValor("ide_sucu")+")"); tab_partida_vigente.actualizarCombosFormulario(); tab_partida_vigente.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_partida_vigente.getValor("IDE_SUCU")+" AND IDE_GEARE="+tab_partida_vigente.getValor("IDE_GEARE")+")"); tab_partida_vigente.actualizarCombosFormulario(); cargarNombreCargoPartidaActual(); } public void cargarCargoFuncional(AjaxBehaviorEvent evt){ tab_empleado_departamento.modificar(evt); tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+tab_empleado_departamento.getValor("IDE_GEGRO")+")"); tab_empleado_departamento.getColumna("GEN_IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=FALSE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO where IDE_GEGRO="+tab_empleado_departamento.getValor("IDE_GEGRO")+")"); tab_empleado_departamento.getColumna("IDE_GEPGC").setCombo("SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP " + "from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP " + "where ide_gegro="+tab_empleado_departamento.getValor("IDE_GEGRO")+" " + "and IDE_GECAF="+tab_empleado_departamento.getValor("IDE_GECAF")+" " + "and IDE_SUCU="+tab_empleado_departamento.getValor("IDE_SUCU")+" " + "and ide_gedep="+tab_empleado_departamento.getValor("IDE_GEDEP")+" " + "and IDE_GEARE="+tab_empleado_departamento.getValor("IDE_GEARE")+" "); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } public void cargarCargoDepartamentos(AjaxBehaviorEvent evt){ tab_empleado_departamento.modificar(evt); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_empleado_departamento.getValor("IDE_SUCU")+" AND IDE_GEARE="+tab_empleado_departamento.getValor("IDE_GEARE")+")"); tab_empleado_departamento.getColumna("IDE_GEPGC").setCombo("SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP " + "from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP " + "where ide_gegro="+tab_empleado_departamento.getValor("IDE_GEGRO")+" " + "and IDE_GECAF="+tab_empleado_departamento.getValor("IDE_GECAF")+" " + "and IDE_SUCU="+tab_empleado_departamento.getValor("IDE_SUCU")+" " + "and ide_gedep="+tab_empleado_departamento.getValor("IDE_GEDEP")+" " + "and IDE_GEARE="+tab_empleado_departamento.getValor("IDE_GEARE")+" "); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } public void cargarCargoAreas(AjaxBehaviorEvent evt){ tab_empleado_departamento.modificar(evt); tab_empleado_departamento.getColumna("IDE_GEARE").setCombo("GEN_AREA", "IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL where IDE_SUCU="+tab_empleado_departamento.getValor("ide_sucu")+")"); tab_empleado_departamento.getColumna("IDE_GEPGC").setCombo("SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP " + "from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP " + "where ide_gegro="+tab_empleado_departamento.getValor("IDE_GEGRO")+" " + "and IDE_GECAF="+tab_empleado_departamento.getValor("IDE_GECAF")+" " + "and IDE_SUCU="+tab_empleado_departamento.getValor("IDE_SUCU")+" " + "and ide_gedep="+tab_empleado_departamento.getValor("IDE_GEDEP")+" " + "and IDE_GEARE="+tab_empleado_departamento.getValor("IDE_GEARE")+" "); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } public void cargarPartidaGrupoCargo(AjaxBehaviorEvent evt){ tab_empleado_departamento.modificar(evt); tab_empleado_departamento.getColumna("IDE_GEPGC").setCombo("SELECT IDE_GEPGC,PAP.CODIGO_PARTIDA_GEPAP,PAP.DETALLE_GEPAP " + "from GEN_PARTIDA_GRUPO_CARGO pgc " + "left join GEN_PARTIDA_PRESUPUESTARIA pap on PAP.IDE_GEPAP=PGC.IDE_GEPAP " + "where ide_gegro="+tab_empleado_departamento.getValor("IDE_GEGRO")+" " + "and IDE_GECAF="+tab_empleado_departamento.getValor("IDE_GECAF")+" " + "and IDE_SUCU="+tab_empleado_departamento.getValor("IDE_SUCU")+" " + "and ide_gedep="+tab_empleado_departamento.getValor("IDE_GEDEP")+" " + "and IDE_GEARE="+tab_empleado_departamento.getValor("IDE_GEARE")+" "); System.out.println("imprimo metodo tab_empleado_departamento "+tab_empleado_departamento.getSql()); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } private boolean isSecuencialValido(String anio,String numero){ if(numero!=null){ TablaGenerica tab_valida=utilitario.consultar("SELECT * FROM GEN_DETALLE_EMPLEADO_DEPARTAME where SECUENCIAL_GEDED="+numero+" and to_char (FECHA_INGRESO_GEDED,'YYYY') ='"+anio+"'"); if(tab_valida.isEmpty()){ return true; } } return false; } private String getMaximoSecuencial(int anio){ String str_max="1"; List lis_max=utilitario.getConexion().consultar("SELECT MAX(SECUENCIAL_GEDED) FROM GEN_DETALLE_EMPLEADO_DEPARTAME where to_char (FECHA_INGRESO_GEDED,'YYYY') ='"+anio+"'"); if(lis_max!=null){ try { str_max= String.valueOf(Integer.parseInt(lis_max.get(0).toString())+1); } catch (Exception e) { // TODO: handle exception str_max="1"; } } return str_max; } public void filtrarEmpleado(SelectEvent evt){ aut_empleado.onSelect(evt); if(aut_empleado.getValor()!=null){ tab_partida_vigente.setCondicion("IDE_GTEMP=" + aut_empleado.getValor() + " AND IDE_GEDED in (SELECT IDE_GEDED FROM GEN_DETALLE_EMPLEADO_DEPARTAME WHERE ACTIVO_GEDED=true and IDE_GTEMP=" + aut_empleado.getValor()+")"); tab_partida_vigente.ejecutarSql(); tab_deta_empleado_depar.setCondicion("IDE_GTEMP=" + aut_empleado.getValor()); tab_deta_empleado_depar.ejecutarSql(); tab_empleado_departamento.setValorForanea(tab_deta_empleado_depar.getValorSeleccionado()); tab_empleado_departamento.getColumna("IDE_GTEMP") .setValorDefecto(aut_empleado.getValor()); if(!tab_deta_empleado_depar.isEmpty()){ cargarTablaPartida(tab_deta_empleado_depar.getValor("IDE_GEAME"),false); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } tab_deta_empleado_depar.getColumna("IDE_GTEMP") .setValorDefecto(aut_empleado.getValor()); actualizarCombosDepartamentoActivoEmpleado(); System.out.println("Imprime SQL"); tab_deta_empleado_depar.imprimirSql(); } else{ tab_partida_vigente.limpiar(); tab_deta_empleado_depar.limpiar(); } utilitario.addUpdate("tab_tabulador:tab_partida_vigente,tab_tabulador:tab_empleado_departamento,tab_tabulador:tab_deta_empleado_depar"); } private void cargarTablaPartida(String IDE_GEAME,boolean boo_terminacion_subroga) { if(IDE_GEAME!=null){ TablaGenerica tab_accion = utilitario .consultar("SELECT * FROM GEN_ACCION_MOTIVO_EMPLEADO WHERE IDE_GEAME=" + IDE_GEAME); String str_campos_visibles = ""; String str_campos_importa = ""; if (!tab_accion.isEmpty()) { if (tab_accion.getValor("CAMPO_VISIBLE_GEAME") != null) { str_campos_visibles = tab_accion.getValor("CAMPO_VISIBLE_GEAME"); } if (tab_accion.getValor("CAMPO_DATO_GEAME") != null) { str_campos_importa = tab_accion.getValor("CAMPO_DATO_GEAME"); } } tab_empleado_departamento.getChildren().clear(); String[] str_cv = str_campos_visibles.split(","); for (int i = 0; i < tab_empleado_departamento.getTotalColumnas(); i++) { boolean boo_encontro = false; if (!str_campos_visibles.isEmpty()) { tab_empleado_departamento.getColumnas()[i].setVisible(true); tab_empleado_departamento.getColumnas()[i].setLectura(false); for (int j = 0; j < str_cv.length; j++) { String str_nombre = tab_empleado_departamento.getColumnas()[i] .getNombre(); String str_nombre_visual = tab_empleado_departamento .getColumnas()[i].getNombreVisual(); String str_aux=str_cv[j].trim(); if(str_aux.trim().endsWith("*") ||str_aux.trim().startsWith("*")){ //Si empieza o termina con * se considera q es de lectura str_aux=str_aux.replace("*", "").trim(); tab_empleado_departamento.getColumna(str_aux).setLectura(true); } if (str_aux.equalsIgnoreCase(str_nombre.trim()) ||str_aux.trim().equalsIgnoreCase( str_nombre_visual.trim())) { boo_encontro = true; break; } } tab_empleado_departamento.getColumnas()[i] .setVisible(boo_encontro); } else { tab_empleado_departamento.getColumnas()[i].setVisible(true); tab_empleado_departamento.getColumnas()[i].setLectura(false); } } tab_empleado_departamento.getColumna("IDE_GTEMP").setVisible(false); if (tab_deta_empleado_depar.isFilaInsertada() && boo_terminacion_subroga){ tab_empleado_departamento.getColumna("IDE_GECAF").setCombo("GEN_CARGO_FUNCIONAL", "IDE_GECAF", "DETALLE_GECAF", "PRINCIPAL_SECUNDARIO_GECAF=TRUE AND IDE_GECAF IN (SELECT IDE_GECAF FROM GEN_GRUPO_CARGO)"); tab_empleado_departamento.getColumna("IDE_GEARE").setCombo("GEN_AREA","IDE_GEARE", "DETALLE_GEARE", "IDE_GEARE IN (SELECT IDE_GEARE from GEN_DEPARTAMENTO_SUCURSAL)"); // tab_empleado_departamento.actualizarCombosFormulario(); tab_empleado_departamento.getColumna("IDE_GEDEP").setCombo("GEN_DEPARTAMENTO", "IDE_GEDEP", "DETALLE_GEDEP", "IDE_GEDEP IN (SELECT IDE_GEDEP from GEN_DEPARTAMENTO_SUCURSAL )"); // tab_empleado_departamento.actualizarCombosFormulario(); cargarNombreCargoPartidaSeleccionada(); } tab_empleado_departamento.dibujar(); if(tab_deta_empleado_depar.isFilaInsertada() && !boo_terminacion_subroga){ actualizarCombosDepartamentoEmpleadoconActual(); } else if (!boo_terminacion_subroga) { //Hace que no le permita editar la partida //tab_empleado_departamento.getFilaSeleccionada().setLectura(true); actualizarCombosDepartamentoEmpleado(); } if(tab_deta_empleado_depar.isFilaInsertada() && tab_empleado_departamento.isEmpty()){ tab_empleado_departamento.limpiar(); tab_empleado_departamento.insertar(); // Extrae valores de la partida activa str_cv = str_campos_importa.split(","); for (int i = 0; i < tab_empleado_departamento.getTotalColumnas(); i++) { String str_nombre = tab_empleado_departamento.getColumnas()[i] .getNombre(); String str_nombre_visual = tab_empleado_departamento .getColumnas()[i].getNombreVisual(); if (!str_campos_importa.isEmpty()) { for (int j = 0; j < str_cv.length; j++) { String str_aux=str_cv[j].trim(); if (str_aux.equalsIgnoreCase(str_nombre.trim()) || str_aux.equalsIgnoreCase( str_nombre_visual.trim())) { if(!str_nombre.equalsIgnoreCase("IDE_GEEDP")){ tab_empleado_departamento.setValor(str_nombre, tab_partida_vigente.getValor(str_nombre)); } break; } } } else { try { //IMporta todos los campos menos IDE_GEEDP if(!str_nombre.equalsIgnoreCase("IDE_GEEDP")){ tab_empleado_departamento.setValor(str_nombre, tab_partida_vigente.getValor(str_nombre)); } } catch (Exception e) { // TODO: handle exception } } } cargarNombreCargoPartidaSeleccionada(); TablaGenerica tab_accion_emp=utilitario.consultar("SELECT * FROM GEN_ACCION_MOTIVO_EMPLEADO WHERE IDE_GEAME="+IDE_GEAME); if (tab_accion_emp.getValor("IDE_GEAED").equalsIgnoreCase(utilitario.getVariable("p_gen_accion_empl_comision"))){ tab_empleado_departamento.setValor("ACTIVO_GEEDP","false"); tab_empleado_departamento.setValor("IDE_GECAE",utilitario.getVariable("p_gen_status_stand_by")); tab_empleado_departamento.getColumna("IDE_GECAE").setLectura(true); }else{ tab_empleado_departamento.setValor("ACTIVO_GEEDP","true"); } utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } } } public Tabla getTab_asi_vac() { return tab_asi_vac; } public void setTab_asi_vac(Tabla tab_asi_vac) { this.tab_asi_vac = tab_asi_vac; } public void dibujarDialogoAsistenciaVacacion(TablaGenerica tab_periodo_vacacion_maximo){ dia_asi_vacacion.setTitle("PERIODO DE VACACION EXISTENTE"); dia_asi_vacacion.getBot_aceptar().setMetodo("aceptarPeriodoVacacion"); Grid gri=new Grid(); List lista1 = new ArrayList(); Object fila1[] = { "0", "ACTIVAR PERIODO" }; Object fila2[] = { "1", "CREAR NUEVO PERIODO DE VACACION" }; lista1.add(fila1); lista1.add(fila2); rad_dia_asi_vacacion.setRadio(lista1); rad_dia_asi_vacacion.setVertical(); rad_dia_asi_vacacion.setValue("1"); tab_asi_vac.setId("tab_asi_vac"); tab_asi_vac.setSql(tab_periodo_vacacion_maximo.getSql()); tab_asi_vac.setCampoPrimaria("IDE_ASVAC"); tab_asi_vac.setNumeroTabla(10); tab_asi_vac.setLectura(true); tab_asi_vac.dibujar(); gri.getChildren().add(rad_dia_asi_vacacion); gri.getChildren().add(tab_asi_vac); dia_asi_vacacion.setDialogo(gri); dia_asi_vacacion.dibujar(); utilitario.addUpdate("dia_asi_vacacion"); } public void dibujarContratoTerminacionSubrogacion(){ cargarTablaPartida(tab_deta_empleado_depar.getValor("IDE_GEAME"),true); TablaGenerica tab_contrato_anterior=utilitario.consultar("SELECT * FROM GEN_EMPLEADOS_DEPARTAMENTO_PAR where IDE_GEDED in ( " + "SELECT IDE_GEDED FROM GEN_DETALLE_EMPLEADO_DEPARTAME WHERE IDE_GEDED IN ( " + "select GEN_IDE_GEDED from GEN_DETALLE_EMPLEADO_DEPARTAME " + "where IDE_GTEMP="+aut_empleado.getValor()+" and ACTIVO_GEDED=TRUE))"); System.out.println("tab con "+tab_contrato_anterior.getSql()); tab_empleado_departamento.setValor("IDE_GEPGC", tab_contrato_anterior.getValor("IDE_GEPGC")); tab_empleado_departamento.setValor("IDE_GEGRO", tab_contrato_anterior.getValor("IDE_GEGRO")); tab_empleado_departamento.setValor("IDE_GECAF", tab_contrato_anterior.getValor("IDE_GECAF")); tab_empleado_departamento.setValor("IDE_GEDEP", tab_contrato_anterior.getValor("IDE_GEDEP")); tab_empleado_departamento.setValor("IDE_SUCU", tab_contrato_anterior.getValor("IDE_SUCU")); tab_empleado_departamento.setValor("IDE_GEARE", tab_contrato_anterior.getValor("IDE_GEARE")); tab_empleado_departamento.setValor("IDE_GTTEM", tab_contrato_anterior.getValor("IDE_GTTEM")); tab_empleado_departamento.setValor("IDE_GTTSI", tab_contrato_anterior.getValor("IDE_GTTSI")); tab_empleado_departamento.setValor("IDE_GTTCO", tab_contrato_anterior.getValor("IDE_GTTCO")); tab_empleado_departamento.setValor("IDE_GTGRE", tab_contrato_anterior.getValor("IDE_GTGRE")); tab_empleado_departamento.setValor("IDE_GETIV", tab_contrato_anterior.getValor("IDE_GETIV")); tab_empleado_departamento.setValor("IDE_GECAE", tab_contrato_anterior.getValor("IDE_GECAE")); tab_empleado_departamento.setValor("FECHA_GEEDP", tab_contrato_anterior.getValor("FECHA_GEEDP")); } private Radio rad_dia_asi_vacacion=new Radio(); private Tabla tab_asi_vac=new Tabla(); public void cambioAccion(SelectEvent evt) { tab_deta_empleado_depar.modificar(evt); if (p_gen_encargo_posicion==null || p_gen_encargo_posicion.isEmpty()){ utilitario.agregarMensajeInfo("No se puede realizar la accion de personal", "Importar el paramtero de sistema p_gen_encargo_posicion"); return; } if (p_gen_accion_contratacion==null || p_gen_accion_contratacion.isEmpty()){ utilitario.agregarMensajeInfo("No se puede realizar la accion de personal", "Importar el paramtero de sistema p_gen_accion_contratacion"); return; } if (p_gen_terminacion_encargo_posicion==null || p_gen_terminacion_encargo_posicion.isEmpty()){ utilitario.agregarMensajeInfo("No se puede realizar la accion de personal", "Importar el paramtero de sistema p_gen_terminacion_encargo_posicion"); return; } if (tab_deta_empleado_depar.getValor("IDE_GEAME") != null) { // cargarTablaPartida(tab_deta_empleado_depar.getValor("IDE_GEAME")); if (tab_deta_empleado_depar.getValor("IDE_GEAME").equals(p_gen_terminacion_encargo_posicion)) { dibujarContratoTerminacionSubrogacion(); return; }else if (tab_deta_empleado_depar.getValor("IDE_GEAME").equals(p_gen_encargo_posicion)) { // ENCARGO POSICION set_encargo.getBot_aceptar().setMetodo("aceptarEncargo"); set_encargo.getBot_cancelar().setMetodo("cancelarEncargo"); set_encargo.dibujar(); utilitario.addUpdate("set_encargo"); return; }else if (tab_deta_empleado_depar.getValorArreglo("IDE_GEAME",1).equals(p_gen_accion_contratacion)){ // PARA INGRESO O ACTUALIZACION DE PERIODO DE VACACION SOLO CUANDO ES UNA CONTRATACION //comentado porque no controlam os asistencia /* utilitario.getConexion().getSqlPantalla().clear(); TablaGenerica tab_periodo_vacacion_maximo=ser_asistencia.getAsiVacacionMaximoPeriodo(aut_empleado.getValor()); if (tab_periodo_vacacion_maximo.getTotalFilas()>0){ String activo_asvac=tab_periodo_vacacion_maximo.getValor("ACTIVO_ASVAC"); if (activo_asvac!=null && !activo_asvac.isEmpty() && (activo_asvac.equalsIgnoreCase("1") || activo_asvac.equalsIgnoreCase("true"))){ utilitario.agregarMensaje("Ya existe un periodo de vacacion activo", "Se usara el periodo activo"); }else{ dibujarDialogoAsistenciaVacacion(tab_periodo_vacacion_maximo); return; } }else{ str_fecha_ingreso_asvac=ser_empleado.getEmpleado(aut_empleado.getValor()).getValor("FECHA_INGRESO_GTEMP"); dia_calendario.setTitle("Seleccione Fecha de Ingreso de Periodo de Vacacion"); dia_calendario.setWidth("35%"); dia_calendario.setHeight("20%"); cal_fecha_ingreso_vac.setValue(utilitario.getFecha(str_fecha_ingreso_asvac)); Grid gri=new Grid(); gri.setColumns(2); gri.getChildren().add(new Etiqueta("Fecha Ingreso: ")); gri.getChildren().add(cal_fecha_ingreso_vac); dia_calendario.setDialogo(gri); dia_calendario.getBot_aceptar().setMetodo("aceptarCrearPeriodoVacacion"); dia_calendario.dibujar(); utilitario.addUpdate("dia_calendario"); } */ }else { // PARA FINIQUITOS List lis_finiquito=new ArrayList(); lis_finiquito=utilitario.getConexion().consultar("SELECT finiquito_contrato_geaed FROM gen_accion_empleado_depa where ide_geaed in (select ide_geaed from gen_accion_motivo_empleado where ide_geame="+tab_deta_empleado_depar.getValor("IDE_GEAME")+")"); if(lis_finiquito.get(0)!=null && !lis_finiquito.get(0).toString().isEmpty()){ if(lis_finiquito.get(0).toString().equals("true")){ cal_terminacion.setValue(null); are_tex_observacion.setValue(null); dia_terminacion.getBot_aceptar().setMetodo("cargarFechaTerminacion"); dia_terminacion.dibujar(); utilitario.addUpdate("dia_terminacion"); return; } } } // aqui cambie cargarTablaPartida(tab_deta_empleado_depar.getValor("IDE_GEAME"),false); } } public Dialogo getDia_asi_vacacion() { return dia_asi_vacacion; } public void setDia_asi_vacacion(Dialogo dia_asi_vacacion) { this.dia_asi_vacacion = dia_asi_vacacion; } public void aceptarCrearPeriodoVacacion(){ if (cal_fecha_ingreso_vac.getValue()==null || cal_fecha_ingreso_vac.getValue().toString().isEmpty()){ utilitario.agregarMensajeInfo("Debe seleccionar una fecha de ingreso de periodo de vacacion", ""); return; } System.out.println("date "+cal_fecha_ingreso_vac.getDate()+" value "+cal_fecha_ingreso_vac.getValue()); System.out.println("formato fecha "+utilitario.getFormatoFecha(cal_fecha_ingreso_vac.getValue())); System.out.println("str fecha_ingreso "+str_fecha_ingreso_asvac); if (!utilitario.isFechaValida(utilitario.getFormatoFecha(cal_fecha_ingreso_vac.getValue()))){ utilitario.agregarMensajeInfo("Fecha invalida", ""); return; } if (str_fecha_ingreso_asvac==null || str_fecha_ingreso_asvac.isEmpty()){ utilitario.agregarMensajeInfo("no se puede continuar ", "No existe fecha de ingreso en la ficha del empleado"); return ; } //if (utilitario.isFechaMenor(utilitario.getFecha(utilitario.getFormatoFecha(cal_fecha_ingreso_vac.getValue())), utilitario.getFecha(str_fecha_ingreso_asvac))){ // utilitario.agregarMensajeInfo("La fecha de ingreso de periodo no puede ser menor que la fecha de ingreso ", str_fecha_ingreso_asvac); // return ; //} /* comentado por la u salesiana ser_asistencia.crearPeriodoVacacion(aut_empleado.getValor(), utilitario.getFormatoFecha(cal_fecha_ingreso_vac.getValue())); dia_calendario.cerrar(); */ dia_asi_vacacion.cerrar(); } String str_fecha_ingreso_asvac=""; public void aceptarPeriodoVacacion(){ System.out.println("radio "+rad_dia_asi_vacacion.getValue()); if (rad_dia_asi_vacacion.getValue().equals("1")){ str_fecha_ingreso_asvac=tab_asi_vac.getValor("FECHA_INGRESO_ASVAC"); dia_calendario.setTitle("Seleccione Fecha de Ingreso de Periodo de Vacacion"); dia_calendario.setWidth("35%"); dia_calendario.setHeight("20%"); cal_fecha_ingreso_vac.setValue(utilitario.getFecha(str_fecha_ingreso_asvac)); Grid gri=new Grid(); gri.setColumns(2); gri.getChildren().add(new Etiqueta("Fecha Ingreso: ")); gri.getChildren().add(cal_fecha_ingreso_vac); dia_calendario.setDialogo(gri); dia_calendario.getBot_aceptar().setMetodo("aceptarCrearPeriodoVacacion"); dia_calendario.dibujar(); utilitario.addUpdate("dia_calendario"); } if (rad_dia_asi_vacacion.getValue().equals("0")){ // if (ser_asistencia.activarPeriodoVacacion(tab_asi_vac.getValor("IDE_ASVAC"))){ // utilitario.agregarMensaje("El periodo "+tab_asi_vac.getValor("IDE_ASVAC")+" se activo correctamente", ""); /* comentado por u salesiana utilitario.getConexion().agregarSqlPantalla(ser_asistencia.getSqlActivarPeriodoVacacion(tab_asi_vac.getValor("IDE_ASVAC"))); */ dia_asi_vacacion.cerrar(); return; // } } } public void cargarFechaTerminacion(){ if(cal_terminacion.getValue()!=null && !cal_terminacion.getValue().toString().isEmpty()){ cargarTablaPartida(tab_deta_empleado_depar.getValor("IDE_GEAME"),false); tab_empleado_departamento.setValor("FECHA_LIQUIDACION_GEEDP", utilitario.getFormatoFecha(utilitario.getFecha(utilitario.getFormatoFecha(cal_terminacion.getValue())))); tab_empleado_departamento.setValor("LIQUIDACION_GEEDP", "1"); tab_empleado_departamento.setValor("ACTIVO_GEEDP","false"); tab_empleado_departamento.getColumna("LIQUIDACION_GEEDP").setLectura(true); tab_empleado_departamento.setValor("IDE_GECAE","1"); tab_empleado_departamento.getColumna("IDE_GECAE").setLectura(true); tab_empleado_departamento.setValor("OBSERVACION_GEEDP", are_tex_observacion.getValue().toString()); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); dia_terminacion.cerrar(); }else{ utilitario.agregarMensajeInfo("No se puede continuar", "Debe ingresar la fecha"); } } public void aceptarEncargo() { if (set_encargo.getValorSeleccionado() != null) { if(tab_partida_vigente.getValor("IDE_GEDED")!=null){ // aqui cambie cargarTablaPartida(tab_deta_empleado_depar.getValor("IDE_GEAME"),false); // tab_empleado_departamento.setValor("ide_gepgc", set_encargo.getValorSeleccionado()); set_encargo.getTab_seleccion().setFilaActual(set_encargo.getValorSeleccionado()); //CARGO LOS DATOS DEL PUSTO ENCARGADO tab_deta_empleado_depar.setValor("GEN_IDE_GEDED", tab_partida_vigente.getValor("IDE_GEDED")); actualizarCombosDepartamentoEmpleado(set_encargo.getTab_seleccion().getValor("ide_sucu"), set_encargo.getTab_seleccion().getValor("IDE_GEGRO"), set_encargo.getTab_seleccion().getValor("IDE_GEARE")); tab_empleado_departamento.setValor("FECHA_ENCARGO_GEEDP", utilitario.getFechaActual()); tab_empleado_departamento.setValor("SUELDO_SUBROGA_GEEDP", set_encargo.getTab_seleccion().getValor("salario_encargo_gepgc")); double dou_ajuste=0; try { //Calcula el ajueste de dou_ajuste=(Double.parseDouble(tab_empleado_departamento.getValor("SUELDO_SUBROGA_GEEDP")))-(Double.parseDouble(tab_empleado_departamento.getValor("RMU_GEEDP"))); } catch (Exception e) { // TODO: handle exception } if(dou_ajuste<0){ dou_ajuste=0; } tab_empleado_departamento.setValor("AJUSTE_SUELDO_GEEDP", utilitario.getFormatoNumero(dou_ajuste)); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); set_encargo.cerrar(); } else{ utilitario.agregarMensajeError("No se puede Completar la Acción", "El empleado seleccionado no tiene una Acción activa"); } } } public Confirmar getCon_guardar() { return con_guardar; } public void setCon_guardar(Confirmar con_guardar) { this.con_guardar = con_guardar; } public Dialogo getDia_calendario() { return dia_calendario; } public void setDia_calendario(Dialogo dia_calendario) { this.dia_calendario = dia_calendario; } public void cancelarEncargo() { set_encargo.cerrar(); tab_empleado_departamento.limpiar(); utilitario.addUpdate("tab_tabulador:tab_empleado_departamento"); } @Override public void insertar() { if(aut_empleado.getValor()!=null){ tab_deta_empleado_depar.insertar(); eti_cargo_accion.setValue(""); tab_deta_empleado_depar.setValor("SECUENCIAL_GEDED", getMaximoSecuencial(utilitario.getAnio(utilitario.getFechaActual()))); if(!tab_partida_vigente.isEmpty()){ //Guardo la partida Anterior tab_deta_empleado_depar.setValor("GEN_IDE_GEDED", tab_partida_vigente.getValor("IDE_GEDED")); } }else{ utilitario.agregarMensajeInfo("No se puede Insertar", "Debe seleccionar un Empleado"); } } @Override public void guardar() { if(aut_empleado.getValor()==null){ utilitario.agregarMensajeInfo("No se puede guardar", "Debe seleccionar un empleado"); return; } //if (tab_deta_empleado_depar.getValor("FECHA_INGRESO_GEDED")==null || tab_deta_empleado_depar.getValor("FECHA_INGRESO_GEDED").isEmpty()){ // utilitario.agregarMensajeInfo("No se puede guardar", "La fecha de ingreso de la accion no puede ser nula o vacia"); // return; // } // if (tab_deta_empleado_depar.getTotalFilas()>1){ // String ide_geedp_activo=utilitario.consultar("select * from GEN_EMPLEADOS_DEPARTAMENTO_PAR where ide_geded in ( select ide_geded from GEN_DETALLE_EMPLEADO_DEPARTAME where IDE_GTEMP="+aut_empleado.getValor()+" and ACTIVO_GEDED=TRUE )").getValor("ide_geedp"); // String fecha_accion=tab_deta_empleado_depar.getValor("FECHA_INGRESO_GEDED"); // String str_valida_accion=ser_nomina.validarAccionPersonalPermitida(ide_geedp_activo,fecha_accion); // System.out.println("str_valida "+str_valida_accion); // if (str_valida_accion.startsWith("No")){ // utilitario.agregarNotificacionInfo("No se puede guardar", str_valida_accion); // return; //} // } if (tab_deta_empleado_depar.getTotalFilas()>1){ /*aqui se valida la fecha de contrato con acciones de personal anteriores*/ TablaGenerica tab_fecha=utilitario.consultar("select ide_gtemp,max (FECHA_INGRESO_GEDED) as fecha_ingreso_accion " + "from GEN_DETALLE_EMPLEADO_DEPARTAME where ide_gtemp="+aut_empleado.getValor()+" group by ide_gtemp"); //if(tab_fecha.getTotalFilas()>0){ // if(tab_fecha.getValor("fecha_ingreso_accion")!=null && !tab_fecha.getValor("fecha_ingreso_accion").isEmpty() ){ // if(tab_deta_empleado_depar.getValor("FECHA_INGRESO_GEDED")!=null && !tab_deta_empleado_depar.getValor("FECHA_INGRESO_GEDED").isEmpty()){ // if(utilitario.isFechaMayor(utilitario.getFecha(tab_fecha.getValor("fecha_ingreso_accion")), utilitario.getFecha(tab_deta_empleado_depar.getValor("FECHA_INGRESO_GEDED")))){ // utilitario.agregarNotificacionInfo("No se puede Guardar", "La fecha de ingreso de accion no puede ser menor que la ultima fecha de ingreso de accion "+tab_fecha.getValor("fecha_ingreso_accion")); // return; // } // } // } } //} if(tab_deta_empleado_depar.isFilaInsertada()){ if(!isSecuencialValido(tab_deta_empleado_depar.getValor("FECHA_INGRESO_GEDED"), tab_deta_empleado_depar.getValor("SECUENCIAL_GEDED"))){ return; } } if(tab_empleado_departamento.getValor("fecha_finctr_geedp")!=null && !tab_empleado_departamento.getValor("fecha_finctr_geedp").isEmpty()){ if(tab_empleado_departamento.getValor("fecha_geedp")!=null && !tab_empleado_departamento.getValor("fecha_geedp").isEmpty()){ if (utilitario.isFechaMenor(utilitario.getFecha(tab_empleado_departamento.getValor("fecha_finctr_geedp")), utilitario.getFecha(tab_empleado_departamento.getValor("fecha_geedp")))){ utilitario.agregarMensajeInfo("No se puede guardar", "La fecha fin de contrato no puede ser menor que la fecha contrato"); return; } } } if(tab_empleado_departamento.getValor("fecha_encargo_fin_geedp")!=null && !tab_empleado_departamento.getValor("fecha_encargo_fin_geedp").isEmpty()){ if(tab_empleado_departamento.getValor("fecha_geedp")!=null && !tab_empleado_departamento.getValor("fecha_geedp").isEmpty()){ if (utilitario.isFechaMenor(utilitario.getFecha(tab_empleado_departamento.getValor("fecha_encargo_fin_geedp")), utilitario.getFecha(tab_empleado_departamento.getValor("fecha_geedp")))){ utilitario.agregarMensajeInfo("No se puede guardar", "La fecha encargo fin de contrato no puede ser menor que la fecha contrato"); return; } } } if(tab_empleado_departamento.getValor("fecha_encargo_geedp")!=null && !tab_empleado_departamento.getValor("fecha_encargo_geedp").isEmpty()){ if(tab_empleado_departamento.getValor("fecha_geedp")!=null && !tab_empleado_departamento.getValor("fecha_geedp").isEmpty()){ if (utilitario.isFechaMenor(utilitario.getFecha(tab_empleado_departamento.getValor("fecha_encargo_geedp")), utilitario.getFecha(tab_empleado_departamento.getValor("fecha_geedp")))){ utilitario.agregarMensajeInfo("No se puede guardar", "La fecha encargo inicio no puede ser menor que la fecha contrato"); return; } } } if(tab_empleado_departamento.getValor("fecha_encargo_geedp")!=null && !tab_empleado_departamento.getValor("fecha_encargo_geedp").isEmpty()){ if(tab_empleado_departamento.getValor("fecha_encargo_fin_geedp")!=null && !tab_empleado_departamento.getValor("fecha_encargo_fin_geedp").isEmpty()){ if (utilitario.isFechaMayor(utilitario.getFecha(tab_empleado_departamento.getValor("fecha_encargo_geedp")), utilitario.getFecha(tab_empleado_departamento.getValor("fecha_encargo_fin_geedp")))){ utilitario.agregarMensajeInfo("No se puede guardar", "La fecha de encargo inicial no puede ser mayor que la fecha encargo fin"); return; } } } if(tab_empleado_departamento.getValor("fecha_ajuste_geedp")!=null && !tab_empleado_departamento.getValor("fecha_ajuste_geedp").isEmpty()){ if(tab_empleado_departamento.getValor("fecha_geedp")!=null && !tab_empleado_departamento.getValor("fecha_geedp").isEmpty()){ if (utilitario.isFechaMenor(utilitario.getFecha(tab_empleado_departamento.getValor("fecha_ajuste_geedp")), utilitario.getFecha(tab_empleado_departamento.getValor("fecha_geedp")))){ utilitario.agregarMensajeInfo("No se puede guardar", "La fecha ajuste de contrato no puede ser menor que la fecha contrato"); return; } } } /*aqui se valida la fecha de contrato con acciones de personal anteriores*/ TablaGenerica tab_fecha=utilitario.consultar("select ide_gtemp,max (fecha_geedp) as fecha_contrato from gen_empleados_departamento_par where ide_gtemp="+aut_empleado.getValor()+" group by ide_gtemp"); if (tab_deta_empleado_depar.getTotalFilas()>1){ System.out.println("valor"+aut_empleado.getValor()); if(tab_fecha.getTotalFilas()>0){ if(tab_fecha.getValor("fecha_contrato")!=null && !tab_fecha.getValor("fecha_contrato").isEmpty() ){ if(tab_empleado_departamento.getValor("fecha_geedp")!=null && !tab_empleado_departamento.getValor("fecha_geedp").isEmpty()){ if(utilitario.isFechaMayor(utilitario.getFecha(tab_fecha.getValor("fecha_contrato")), utilitario.getFecha(tab_empleado_departamento.getValor("fecha_geedp")))){ utilitario.agregarMensajeInfo("No se puede Guardar", "La fecha de contrato actual no puede ser menor que la fecha de contrato del anterior accion de personal"); return; } } } } } TablaGenerica tab_pv=utilitario.consultar("select * from ("+tab_partida_vigente.getSql()+")a order by a.IDE_GEDED desc "); String ide_geded_ultimo=tab_pv.getValor("IDE_GEDED"); try { if (Long.parseLong(tab_empleado_departamento.getValor("IDE_GEDED"))<Long.parseLong(ide_geded_ultimo)){ utilitario.agregarMensajeInfo("no se puede guardar", "la accion seleccionada no se encuentra vigente"); return; } } catch (Exception e) { // TODO: handle exception } if(tab_empleado_departamento.isFilaInsertada()){ //Desactiva todas las partidas y solo deja activa la nueva utilitario.getConexion().agregarSql("UPDATE GEN_DETALLE_EMPLEADO_DEPARTAME set ACTIVO_GEDED=false WHERE IDE_GTEMP="+aut_empleado.getValor()); utilitario.getConexion().agregarSql("UPDATE GEN_EMPLEADOS_DEPARTAMENTO_PAR set ACTIVO_GEEDP=false WHERE IDE_GTEMP="+aut_empleado.getValor()); } String str_ide_gepgc_ant=ser_gestion.getPartidaGrupoEmpleado(tab_empleado_departamento.getValorSeleccionado()).getValor("IDE_GEPGC"); boolean boo_cambio_partida=ser_gestion.isCambioPartida(tab_empleado_departamento.getValorSeleccionado(), tab_empleado_departamento.getValor("IDE_GEPGC")); String str_gepgc_vacante=ser_gestion.getPartidaGrupo(tab_empleado_departamento.getValor("IDE_GEPGC")).getValor("VACANTE_GEPGC"); guardarAccion(); } public void guardarAccion(){ if(tab_deta_empleado_depar.guardar()){ if(tab_empleado_departamento.guardar()){ utilitario.getConexion().agregarSqlPantalla("update GEN_PARTIDA_GRUPO_CARGO set VACANTE_GEPGC=FALSE where IDE_GEPGC="+tab_empleado_departamento.getValor("IDE_GEPGC")); if(guardarPantalla().isEmpty()){ if(ser_gestion.validarAccionFiniquito(tab_deta_empleado_depar.getValor(tab_deta_empleado_depar.getFilaActual(), "IDE_GEAME"))){ if(ser_gestion.inactivarEmpleado(tab_empleado_departamento.getValorSeleccionado())){ /* comentado por u salesiana ser_asistencia.desactivarPeriodoVacacion(ser_asistencia.getAsiVacacionActiva(aut_empleado.getValor()).getValor("IDE_ASVAC"),tab_empleado_departamento.getValor("FECHA_LIQUIDACION_GEEDP")); */ utilitario.agregarMensajeInfo("Se guardo correctamente", "Terminación del contrato"); } } //Para que ponga el visto en activo String str_anterior=tab_deta_empleado_depar.getValorSeleccionado(); tab_deta_empleado_depar.ejecutarSql(); tab_deta_empleado_depar.setFilasSeleccionados(str_anterior); seleccionarTabla1(); tab_partida_vigente.ejecutarSql(); actualizarCombosDepartamentoActivoEmpleado(); } } } } @Override public void actualizar() { // TODO Auto-generated method stub super.actualizar(); if (tab_empleado_departamento.isFocus()){ actualizarCombosDepartamentoEmpleado(); } } @Override public void eliminar() { if(tab_deta_empleado_depar.isFilaInsertada()){ utilitario.getConexion().getSqlPantalla().clear(); tab_empleado_departamento.eliminar(); tab_deta_empleado_depar.eliminar(); cargarNombreCargoPartidaSeleccionada(); } else{ if(tab_deta_empleado_depar.getValor("ACTIVO_GEDED")!=null && tab_deta_empleado_depar.getValor("ACTIVO_GEDED").equalsIgnoreCase("true")){ if (utilitario.consultar("select * from NRH_DETALLE_ROL where IDE_GEEDP="+tab_empleado_departamento.getValor("ide_geedp")).getTotalFilas()>0){ utilitario.agregarNotificacionInfo("No se puede eliminar el registro", "La accion tiene otros registros generados"); return; } String str_anerior=getAccionAnterior(); if(str_anerior!=null){ if (utilitario.consultar("select * from NRH_ANTICIPO where IDE_GEEDP="+tab_empleado_departamento.getValorSeleccionado()).getTotalFilas()>0){ utilitario.agregarMensajeInfo("No se puede eliminar","El colaborador tiene registros generados"); return; } utilitario.getConexion().agregarSqlPantalla("DELETE FROM GEN_EMPLEADOS_DEPARTAMENTO_PAR WHERE IDE_GEEDP="+tab_empleado_departamento.getValorSeleccionado()); utilitario.getConexion().agregarSqlPantalla("DELETE FROM GEN_DETALLE_EMPLEADO_DEPARTAME WHERE IDE_GEDED="+tab_deta_empleado_depar.getValorSeleccionado()); utilitario.getConexion().agregarSql("UPDATE GEN_DETALLE_EMPLEADO_DEPARTAME set ACTIVO_GEDED=true WHERE IDE_GEDED="+str_anerior); utilitario.getConexion().agregarSql("UPDATE GEN_EMPLEADOS_DEPARTAMENTO_PAR set ACTIVO_GEEDP=true WHERE IDE_GEDED="+str_anerior); if(guardarPantalla().isEmpty()){ tab_deta_empleado_depar.ejecutarSql(); seleccionarTabla1(); tab_partida_vigente.ejecutarSql(); actualizarCombosDepartamentoActivoEmpleado(); System.out.println("eliminar ide_gedep : "+tab_empleado_departamento.getValorSeleccionado()); ser_gestion.activarEmpleado(tab_empleado_departamento.getValorSeleccionado()); } } else{ if(tab_deta_empleado_depar.getTotalFilas()==1){ //Si solo tiene una partida creada intenta eliminar utilitario.getConexion().agregarSqlPantalla("DELETE FROM GEN_EMPLEADOS_DEPARTAMENTO_PAR WHERE IDE_GEEDP="+tab_empleado_departamento.getValorSeleccionado()); utilitario.getConexion().agregarSqlPantalla("DELETE FROM GEN_DETALLE_EMPLEADO_DEPARTAME WHERE IDE_GEDED="+tab_deta_empleado_depar.getValorSeleccionado()); if(guardarPantalla().isEmpty()){ tab_deta_empleado_depar.ejecutarSql(); tab_partida_vigente.ejecutarSql(); } } else{ utilitario.agregarMensajeInfo("No se puede Eliminar", "No se puede eliminar no se encontraron Acciones Anteriores"); } } } else{ utilitario.agregarMensajeInfo("No se puede Eliminar", "Solo puede Eliminar una partida Activa"); } } } public void seleccionarTabla1(SelectEvent evt){ if(tab_deta_empleado_depar.isFilaInsertada()){ return; } tab_deta_empleado_depar.seleccionarFila(evt); seleccionarTabla1(); } public void seleccionarTabla1(AjaxBehaviorEvent evt){ if(tab_deta_empleado_depar.isFilaInsertada()){ return; } tab_deta_empleado_depar.seleccionarFila(evt); seleccionarTabla1(); } private void seleccionarTabla1(){ tab_empleado_departamento.ejecutarValorForanea(tab_deta_empleado_depar.getValorSeleccionado()); if(!tab_deta_empleado_depar.isEmpty()){ cargarTablaPartida(tab_deta_empleado_depar.getValor("IDE_GEAME"),false); } } public Tabla getTab_partida_vigente() { return tab_partida_vigente; } public void setTab_partida_vigente(Tabla tab_partida_vigente) { this.tab_partida_vigente = tab_partida_vigente; } public Tabla getTab_empleado_departamento() { return tab_empleado_departamento; } public void setTab_empleado_departamento(Tabla tab_empleado_departamento) { this.tab_empleado_departamento = tab_empleado_departamento; } public Tabla getTab_deta_empleado_depar() { return tab_deta_empleado_depar; } public void setTab_deta_empleado_depar(Tabla tab_deta_empleado_depar) { this.tab_deta_empleado_depar = tab_deta_empleado_depar; } public SeleccionTabla getSet_encargo() { return set_encargo; } public void setSet_encargo(SeleccionTabla set_encargo) { this.set_encargo = set_encargo; } public AutoCompletar getAut_empleado() { return aut_empleado; } public void setAut_empleado(AutoCompletar aut_empleado) { this.aut_empleado = aut_empleado; } public Dialogo getDia_reactiva() { return dia_reactiva; } public void setDia_reactiva(Dialogo dia_reactiva) { this.dia_reactiva = dia_reactiva; } public Reporte getRep_reporte() { return rep_reporte; } public void setRep_reporte(Reporte rep_reporte) { this.rep_reporte = rep_reporte; } public SeleccionFormatoReporte getSef_reporte() { return sef_reporte; } public void setSef_reporte(SeleccionFormatoReporte sef_reporte) { this.sef_reporte = sef_reporte; } public Dialogo getDia_tipo_vinculacion() { return dia_tipo_vinculacion; } public void setDia_tipo_vinculacion(Dialogo dia_tipo_vinculacion) { this.dia_tipo_vinculacion = dia_tipo_vinculacion; } public SeleccionTabla getSel_tab_accion_motivo() { return sel_tab_accion_motivo; } public void setSel_tab_accion_motivo(SeleccionTabla sel_tab_accion_motivo) { this.sel_tab_accion_motivo = sel_tab_accion_motivo; } public Dialogo getDia_editar_motivo() { return dia_editar_motivo; } public void setDia_editar_motivo(Dialogo dia_editar_motivo) { this.dia_editar_motivo = dia_editar_motivo; } public Dialogo getDia_terminacion() { return dia_terminacion; } public void setDia_terminacion(Dialogo dia_terminacion) { this.dia_terminacion = dia_terminacion; } @Override public void abrirListaReportes() { // TODO Auto-generated method stub rep_reporte.dibujar(); } @Override public void aceptarReporte() { Locale locale=new Locale("es","ES"); // TODO Auto-generated method stub if(rep_reporte.getReporteSelecionado().equals("Acción de Personal")){ if(tab_deta_empleado_depar.getTotalFilas()>0){ if(rep_reporte.isVisible()){ p_parametros=new HashMap(); rep_reporte.cerrar(); rad_tipo_vinculacion.setValue(null); dia_tipo_vinculacion.dibujar(); } else if(dia_tipo_vinculacion.isVisible()){ if(rad_tipo_vinculacion.getValue()!=null && !rad_tipo_vinculacion.getValue().toString().isEmpty()){ p_parametros.put("p_tipo_vinculacion",rad_tipo_vinculacion.getValue()); System.out.println("parametro p_tipo_vinculacion... "+rad_tipo_vinculacion.getValue()); String motivo=""; motivo=tab_deta_empleado_depar.getValorSeleccionado(); System.out.println("variable motivo... "+motivo); if(motivo.isEmpty()){ motivo="-1"; } System.out.println("valor de tipo vinculacion: "+rad_tipo_vinculacion.getValue()); sel_tab_accion_motivo.getTab_seleccion().setSql("SELECT a.IDE_GEAME,b.DETALLE_GEAED,c.DETALLE_GEMED,c.detalle_reporte_gemed FROM GEN_ACCION_MOTIVO_EMPLEADO a " + "LEFT JOIN ( " + "SELECT IDE_GEAED,DETALLE_GEAED from GEN_ACCION_EMPLEADO_DEPA " + ")b ON b.IDE_GEAED=a.IDE_GEAED " + "LEFT JOIN ( " + "SELECT IDE_GEMED,DETALLE_GEMED,detalle_reporte_gemed FROM GEN_MOTIVO_EMPLEADO_DEPA " + ")c ON c.IDE_GEMED=a.IDE_GEMED WHERE a.IDE_GEAME IN (select ide_geame from gen_detalle_empleado_departame where ide_geded= "+motivo+") " + "ORDER BY b.DETALLE_GEAED,c.DETALLE_GEMED"); sel_tab_accion_motivo.getTab_seleccion().getColumna("detalle_gemed").setFiltro(true); sel_tab_accion_motivo.getTab_seleccion().ejecutarSql(); sel_tab_accion_motivo.getTab_seleccion().setFilaActual(tab_deta_empleado_depar.getValor("IDE_GEAME")); sel_tab_accion_motivo.getBot_aceptar().setMetodo("aceptarReporte"); dia_tipo_vinculacion.cerrar(); tab_deta_empleado_depar.getStringColumna("IDE_GEAME"); System.out.println("VALOR DED LA COMUNA IDE_GEAME: "+tab_deta_empleado_depar.getStringColumna("IDE_GEAME")); System.out.println("sql sel_tab_accion_motivo... "+sel_tab_accion_motivo.getTab_seleccion().getSql()); sel_tab_accion_motivo.dibujar(); }else{ utilitario.agregarMensajeInfo("No se puede generar el reporte de accion de personal", "Seleccione una opción"); } } else if(sel_tab_accion_motivo.isVisible()){ if(sel_tab_accion_motivo.getValorSeleccionado()!=null && !sel_tab_accion_motivo.getValorSeleccionado().toString().isEmpty()){ p_parametros.put("p_detalle_accion",sel_tab_accion_motivo.getValorSeleccionado()); System.out.println("PARAMETRO p_detalle_accion... "+sel_tab_accion_motivo.getValorSeleccionado()); String a=sel_tab_accion_motivo.getTab_seleccion().getFilaSeleccionada().getCampos()[sel_tab_accion_motivo.getTab_seleccion().getNumeroColumna("detalle_reporte_gemed")]+""; System.out.println("valord de...sel_tab_accion_motivo... a: "+a); are_tex_motivo.setValue(a); System.out.println("valor de tex area de edicion: "+are_tex_motivo.getValue()); sel_tab_accion_motivo.cerrar(); dia_editar_motivo.dibujar(); }else{ utilitario.agregarMensajeInfo("No se puede generar el reporte de accion de personal", "Seleccione una opción de motivo"); } } else if(dia_editar_motivo.isVisible()){ p_parametros.put("p_detalle_accion",are_tex_motivo.getValue()); System.out.println("PArametro p_detalle_accion... "+are_tex_motivo.getValue()); p_parametros.put("ide_geded",Long.parseLong(tab_deta_empleado_depar.getValor("ide_geded"))); //System.out.println("PArametro ide_geded... "+Long.parseLong(tab_deta_empleado_depar.getValor("ide_geded"))); sef_reporte.setSeleccionFormatoReporte(p_parametros, rep_reporte.getPath()); p_parametros.put("p_gerencia_general",utilitario.getVariable("p_gerencia_general_ap")); //System.out.println("PArametro p_gerencia_general... "+utilitario.getVariable("p_gerencia_general_ap")); p_parametros.put("p_gerencia_administrativa",utilitario.getVariable("p_gerencia_administrativa_ap")); //System.out.println("PArametro p_gerencia_administrativa... "+utilitario.getVariable("p_gerencia_administrativa_ap")); p_parametros.put("p_cargo_gerencia_general",utilitario.getVariable("p_cargo_gerencia_general_ap")); //System.out.println("PArametro p_cargo_gerencia_general... "+utilitario.getVariable("p_cargo_gerencia_general_ap")); p_parametros.put("p_cargo_gerencia_administrativa",utilitario.getVariable("p_cargo_gerencia_administrativa_ap")); //System.out.println("PArametro p_cargo_gerencia_administrativa... "+utilitario.getVariable("p_cargo_gerencia_administrativa_ap")); p_parametros.put("REPORT_LOCALE", locale); dia_editar_motivo.cerrar(); sef_reporte.dibujar(); System.out.println("valor de detalle de accion: "+are_tex_motivo.getValue()); System.out.println("valor de ide_geded: "+Long.parseLong(tab_deta_empleado_depar.getValor("ide_geded"))); } }else{ utilitario.agregarMensajeInfo("No se puede continuar", "No ha seleccionado ningun registro en la cabecera de la acción de personal"); } } } }
{ "content_hash": "be14bcfbe700b518af9316ebc8da70eb", "timestamp": "", "source": "github", "line_count": 1949, "max_line_length": 388, "avg_line_length": 46.87634684453566, "alnum_prop": 0.7121122567369366, "repo_name": "diego10j/produquimic", "id": "d10fa53d80f85751fcfd4e02fb901d99671bcf0b", "size": "91380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "produquimic/produquimic-war/src/java/paq_nomina/pre_accion_personal.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "190882" }, { "name": "HTML", "bytes": "48654" }, { "name": "Java", "bytes": "6513805" }, { "name": "JavaScript", "bytes": "119861" }, { "name": "PHP", "bytes": "833289" }, { "name": "PLSQL", "bytes": "14640" } ], "symlink_target": "" }
using System; using NUnit.Framework; using Punku; [TestFixture] [Category ("Validate")] public class Validate_OrganizationNumberSweden { [Test] public void IsAkiteBolag01 () { Assert.AreEqual (OrganizationNumberSweden.IsAktieBolag ("5566848635"), true); } [Test] public void IsAkiteBolag02 () { Assert.AreEqual (OrganizationNumberSweden.IsAktieBolag ("8112189876"), false); } [Test] public void IsValid01 () { Assert.AreEqual (OrganizationNumberSweden.IsValid ("8112189876"), true); } [Test] public void IsValid02 () { Assert.AreEqual (OrganizationNumberSweden.IsValid ("811218-9876"), true); } [Test] public void IsValid03 () { Assert.AreEqual (OrganizationNumberSweden.IsValid ("19811218-9876"), true); } [Test] public void IsValid04 () { Assert.AreEqual (OrganizationNumberSweden.IsValid ("198112189876"), true); } [Test] public void IsValid05 () { Assert.AreEqual (OrganizationNumberSweden.IsValid ("5566848635"), true); } }
{ "content_hash": "1d0e848888a534bbeaa48d814ffa98f6", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 80, "avg_line_length": 19.58, "alnum_prop": 0.7242083758937692, "repo_name": "martinlindhe/Punku", "id": "8879dcfb809d59ed77e7683e62a5500751f6f79d", "size": "981", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PunkuTests/Validate/OrganizationNumberSweden.cs", "mode": "33261", "license": "mit", "language": [ { "name": "C#", "bytes": "4312022" } ], "symlink_target": "" }
#region Using Statements using System; using System.Text; using Microsoft.Xna.Framework.Content; #endregion namespace RolePlayingGameData { /// <summary> /// A range of character statistics values. /// </summary> /// <remarks>Typically used for constrained random modifiers.</remarks> #if WINDOWS [Serializable] #endif public class StatisticsRange { [ContentSerializer(Optional = true)] public Int32Range HealthPointsRange; [ContentSerializer(Optional = true)] public Int32Range MagicPointsRange; [ContentSerializer(Optional = true)] public Int32Range PhysicalOffenseRange; [ContentSerializer(Optional = true)] public Int32Range PhysicalDefenseRange; [ContentSerializer(Optional = true)] public Int32Range MagicalOffenseRange; [ContentSerializer(Optional = true)] public Int32Range MagicalDefenseRange; #region Value Generation /// <summary> /// Generate a random value between the minimum and maximum, inclusively. /// </summary> /// <param name="random">The Random object used to generate the value.</param> public StatisticsValue GenerateValue(Random random) { // check the parameters Random usedRandom = random; if (usedRandom == null) { usedRandom = new Random(); } // generate the new value StatisticsValue outputValue = new StatisticsValue(); outputValue.HealthPoints = HealthPointsRange.GenerateValue(usedRandom); outputValue.MagicPoints = MagicPointsRange.GenerateValue(usedRandom); outputValue.PhysicalOffense = PhysicalOffenseRange.GenerateValue(usedRandom); outputValue.PhysicalDefense = PhysicalDefenseRange.GenerateValue(usedRandom); outputValue.MagicalOffense = MagicalOffenseRange.GenerateValue(usedRandom); outputValue.MagicalDefense = MagicalDefenseRange.GenerateValue(usedRandom); return outputValue; } #endregion #region String Output /// <summary> /// Builds a string that describes this object. /// </summary> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("HP:"); sb.Append(HealthPointsRange.ToString()); sb.Append("; MP:"); sb.Append(MagicPointsRange.ToString()); sb.Append("; PO:"); sb.Append(PhysicalOffenseRange.ToString()); sb.Append("; PD:"); sb.Append(PhysicalDefenseRange.ToString()); sb.Append("; MO:"); sb.Append(MagicalOffenseRange.ToString()); sb.Append("; MD:"); sb.Append(MagicalDefenseRange.ToString()); return sb.ToString(); } /// <summary> /// Builds a string that describes a modifier, where non-zero stats are skipped. /// </summary> public string GetModifierString() { StringBuilder sb = new StringBuilder(); bool firstStatistic = true; // add the health points value, if any if ((HealthPointsRange.Minimum != 0) || (HealthPointsRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("HP:"); sb.Append(HealthPointsRange.ToString()); } // add the magic points value, if any if ((MagicPointsRange.Minimum != 0) || (MagicPointsRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("MP:"); sb.Append(MagicPointsRange.ToString()); } // add the physical offense value, if any if ((PhysicalOffenseRange.Minimum != 0) || (PhysicalOffenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("PO:"); sb.Append(PhysicalOffenseRange.ToString()); } // add the physical defense value, if any if ((PhysicalDefenseRange.Minimum != 0) || (PhysicalDefenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("PD:"); sb.Append(PhysicalDefenseRange.ToString()); } // add the magical offense value, if any if ((MagicalOffenseRange.Minimum != 0) || (MagicalOffenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("MO:"); sb.Append(MagicalOffenseRange.ToString()); } // add the magical defense value, if any if ((MagicalDefenseRange.Minimum != 0) || (MagicalDefenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("MD:"); sb.Append(MagicalDefenseRange.ToString()); } return sb.ToString(); } #endregion #region Operator: StatisticsRange + StatisticsValue /// <summary> /// Add one value to another, piecewise, and return the result. /// </summary> public static StatisticsRange Add(StatisticsRange value1, StatisticsValue value2) { StatisticsRange outputRange = new StatisticsRange(); outputRange.HealthPointsRange = value1.HealthPointsRange + value2.HealthPoints; outputRange.MagicPointsRange = value1.MagicPointsRange + value2.MagicPoints; outputRange.PhysicalOffenseRange = value1.PhysicalOffenseRange + value2.PhysicalOffense; outputRange.PhysicalDefenseRange = value1.PhysicalDefenseRange + value2.PhysicalDefense; outputRange.MagicalOffenseRange = value1.MagicalOffenseRange + value2.MagicalOffense; outputRange.MagicalDefenseRange = value1.MagicalDefenseRange + value2.MagicalDefense; return outputRange; } /// <summary> /// Add one value to another, piecewise, and return the result. /// </summary> public static StatisticsRange operator +(StatisticsRange value1, StatisticsValue value2) { return Add(value1, value2); } #endregion #region Content Type Reader /// <summary> /// Reads a StatisticsRange object from the content pipeline. /// </summary> public class StatisticsRangeReader : ContentTypeReader<StatisticsRange> { protected override StatisticsRange Read(ContentReader input, StatisticsRange existingInstance) { StatisticsRange output = new StatisticsRange(); output.HealthPointsRange = input.ReadObject<Int32Range>(); output.MagicPointsRange = input.ReadObject<Int32Range>(); output.PhysicalOffenseRange = input.ReadObject<Int32Range>(); output.PhysicalDefenseRange = input.ReadObject<Int32Range>(); output.MagicalOffenseRange = input.ReadObject<Int32Range>(); output.MagicalDefenseRange = input.ReadObject<Int32Range>(); return output; } } #endregion } }
{ "content_hash": "4c1ad6a9dd2ec057d2f91e95f6e52ae0", "timestamp": "", "source": "github", "line_count": 276, "max_line_length": 89, "avg_line_length": 32.039855072463766, "alnum_prop": 0.5085378265294583, "repo_name": "vnen/xna-rpg-godot", "id": "71c2e32eb58d70f0a6b7c25978661d04ddb910ad", "size": "9174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "original/RolePlayingGameData/Data/StatisticsRange.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1092440" }, { "name": "GDScript", "bytes": "79347" }, { "name": "Shell", "bytes": "3615" } ], "symlink_target": "" }
<DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/> <title>Kamal Traders - TORAN-623</title> <!-- CSS --> <link href="/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/> <link href="/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/> <link href="/css/anime.css" type="text/css" rel="stylesheet" media="screen,projection"/> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class = "container"> <div class = "mar20 brand-logo"> <a style = "cursor:pointer;font-size:24px;" href = "http://kamaltraders.in"> <img src='images/kamal_traders.png' style="height:60px;"> </a> </div> <nav> <ul class = blue-text text-darken-4> <li><a style="color:#909090;" class = "bold" href = "index.html">Home</a></li> <li><a style="color:#909090;" class = "" href = "category_30.html">Torans</a></li> <li><a style="color:#909090;" class = "" href = "category_31.html">Bouquet</a></li> <li><a style="color:#909090;" class = "" href = "category_32.html">Flower Gate</a></li> <li><a style="color:#909090;" class = "" href = "categories.html">All Categories</a></li> </ul> </nav> <div class="row container"> <hr> <div class="large-5 columns"> <img src="images/mains/234/original/623--TORAN.jpg?1352909261" style="min-height:200px;"> </div> <div class="large-5 columns"> <h4>TORAN-623</h4> <p>Decoration Ball / Decorations Garlands. Torans / Garlands and Decoration for Weddings, Shop Openings, Anniversaries, Annual functions at School Colleges. Avail from best colour combinations only we provide adding Uniqueness to your functions. Decorations for T.V. Serial Sets and Production houses and best part - One Time Investment. Quality Material at reasonable rates. Order Now.</p> <div class="panel"> <h5 id="price">Price : Rs. 1000.00</h5> <a href="tel:9999999999" class="small button" id="callmebutton">Call Me</a> </div> </div> </div> </div> <footer style = "width:100%;background-color:#f3f7f3" class="white-text page-footer"> <div class="container"> <div class="row"> <div class="col l4 s12"> <ul> <li><a style="color:#909090;" class = "" href="index.html">Home</a></li> <li><a style="color:#909090;" class = "" href="products.html">Products</a></li> <li><a style="color:#909090;" class = "" href="categories.html">Categories</a></li> </ul> </div> <div class="col l4 s12"> <ul> <li><a style="color:#909090;" class = "" href="aboutus.html">About Us</a></li> <li><a style="color:#909090;" class = "" href="contact.html">Contact Us</a></li> <li><a style="color:#909090;" class = "" href="terms.html">Terms & Conditions</a></li> </ul> </div> </div> </div> <div class="footer-copyright"> <div class="container" style="color:#17a2a2;"> © 2015 Copyright Kamal Traders </div> </div> </footer> <scripts--> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="js/materialize.js"></script> <script src="js/init.js"></script> <script src="js/main.js"></script> <script type = "text/javascript"> $(document).ready(function(){ $('.slider').slider({full_width: true}); $('select').material_select(); if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { } else { $('#callmebutton').attr('href', '#'); $("#callmebutton").on( "click", function() { $('#callmebutton').replaceWith('<p class="small button" id="callmebutton">Call Me on 9987760244</p>'); }); } }); $(function () { $('#emailLink').on('click', function (event) { event.preventDefault(); var email1 = 'aaron@kodeplay.com'; var subject = 'New Order Placed'; name = $('#name').val(); email = $('#email').val(); phone = $('#phone').val(); textarea1 = encodeURIComponent($('#textarea1').val()); //textarea1 = textarea1.replace('\n', '%0D%0A'); body_content = 'Name : ' + name + '%0D%0A'; body_content += 'Email : ' + email + '%0D%0A'; body_content += 'Phone : ' + phone + '%0D%0A'; body_content += 'Message : ' + textarea1 + '%0D%0A'; var emailBody = body_content; //var emailBody = 'Some blah%0D%0ASome blah'; window.location = 'mailto:' + email1 + '?subject=' + subject + '&body=' + emailBody; }); }); </script> </body> </html>
{ "content_hash": "39b2b0d913d8c082c1656e09d0e3fca2", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 113, "avg_line_length": 36.940298507462686, "alnum_prop": 0.5789898989898989, "repo_name": "kamaltraders/kamal-traders", "id": "e8b1cf9562e5fe6ec174218076e75e25f265e175", "size": "4951", "binary": false, "copies": "2", "ref": "refs/heads/gh-pages", "path": "product_234.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "622489" }, { "name": "HTML", "bytes": "7063324" }, { "name": "JavaScript", "bytes": "523962" }, { "name": "PHP", "bytes": "4856" } ], "symlink_target": "" }
package org.opensaml.samlext.saml2mdui.impl; import org.opensaml.common.impl.AbstractSAMLObjectBuilder; import org.opensaml.samlext.saml2mdui.UIInfo; /** * Builder of {@link org.opensaml.samlext.saml2mdui.UIInfo}. */ public class UIInfoBuilder extends AbstractSAMLObjectBuilder<UIInfo> { /** * Constructor. */ public UIInfoBuilder() { } /** {@inheritDoc} */ public UIInfo buildObject() { return buildObject(UIInfo.MDUI_NS, UIInfo.DEFAULT_ELEMENT_LOCAL_NAME, UIInfo.MDUI_PREFIX); } /** {@inheritDoc} */ public UIInfo buildObject(String namespaceURI, String localName, String namespacePrefix) { return new UIInfoImpl(namespaceURI, localName, namespacePrefix); } }
{ "content_hash": "cb5de01f7ce4801f17b42108bcf9fa7f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 98, "avg_line_length": 25.275862068965516, "alnum_prop": 0.703956343792633, "repo_name": "Safewhere/kombit-service-java", "id": "a524179cd32fb658927ca5fcae909253d9c8ca49", "size": "1577", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "OpenSaml/src/org/opensaml/samlext/saml2mdui/impl/UIInfoBuilder.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "73985" }, { "name": "Java", "bytes": "5965174" } ], "symlink_target": "" }
from indico.modules.files.controllers import RHDeleteFile, RHFileDownload, RHFileInfo from indico.web.flask.wrappers import IndicoBlueprint _bp = IndicoBlueprint('files', __name__) _bp.add_url_rule('/files/<uuid:uuid>', 'file_info', RHFileInfo) _bp.add_url_rule('/files/<uuid:uuid>/download', 'download_file', RHFileDownload) _bp.add_url_rule('/files/<uuid:uuid>', 'delete_file', RHDeleteFile, methods=('DELETE',))
{ "content_hash": "fbb12471a635363f00e8898d0faa797f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 88, "avg_line_length": 46.44444444444444, "alnum_prop": 0.7416267942583732, "repo_name": "indico/indico", "id": "b4956ba8eee9ac92d2584802a22d40ea664c856d", "size": "632", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "indico/modules/files/blueprint.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33289" }, { "name": "HTML", "bytes": "1420471" }, { "name": "JavaScript", "bytes": "2362355" }, { "name": "Mako", "bytes": "1527" }, { "name": "Python", "bytes": "5550085" }, { "name": "SCSS", "bytes": "486043" }, { "name": "Shell", "bytes": "3877" }, { "name": "TeX", "bytes": "23435" }, { "name": "XSLT", "bytes": "1504" } ], "symlink_target": "" }
package me.walkersneps.snepsbotx.gui; import me.walkersneps.snepsbotx.SnepsBotX; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JoinIRCChannelGUI extends JFrame{ private JPanel rootPanel; private JTextField channelToJoinTextField; private JButton joinBUTTON; private JLabel channelToJoinLABEL; JoinIRCChannelGUI () { super("Join a Channel"); setContentPane(rootPanel); joinBUTTON.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String channel = channelToJoinTextField.getText(); SnepsBotX.join(channel); } }); pack(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } } //end of class
{ "content_hash": "c04f5d4ad48b28eecac23932a1013a70", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 66, "avg_line_length": 18.34, "alnum_prop": 0.6564885496183206, "repo_name": "Walkersneps/SnepsBotX", "id": "6d30f52e0ef18ef177ca9bec7e041491611c03ee", "size": "917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/me/walkersneps/snepsbotx/gui/JoinIRCChannelGUI.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "53405" } ], "symlink_target": "" }
package com.google.code.mojo.license.document; import com.google.code.mojo.license.header.Header; import com.google.code.mojo.license.util.FileUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import static org.testng.Assert.*; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ public final class DocumentTest { Header header; @BeforeClass public void setup() throws MalformedURLException { Map<String, String> props = new HashMap<String, String>(); props.put("year", "2008"); header = new Header(new File("src/test/resources/test-header1.txt").toURI().toURL(), props); } @Test public void test_create() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); assertEquals(doc.getFile().getName(), "doc1.txt"); assertFalse(doc.isNotSupported()); } @Test public void test_unsupported() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc1.txt"), DocumentType.UNKNOWN.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); assertEquals(doc.getFile().getName(), "doc1.txt"); assertTrue(doc.isNotSupported()); } @Test public void test_hasHeader() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); assertFalse(doc.hasHeader(header, true)); } @Test public void test_isHeader() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); assertFalse(doc.is(header)); doc = new Document( new File("src/test/resources/test-header1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); assertTrue(doc.is(header)); } @Test public void test_remove_header1() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc1.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertEquals(doc.getContent(), FileUtils.read(new File("src/test/resources/doc/doc1.txt"), System.getProperty("file.encoding"))); } @Test public void test_remove_header2() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc2.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertEquals(doc.getContent(), "some data\r\n"); } @Test public void test_remove_header3() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc3.txt"), DocumentType.TXT.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertEquals(doc.getContent(), "some data\r\nand other data\r\n"); } @Test public void test_remove_header_xml_1() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc4.xml"), DocumentType.XML.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertEquals(doc.getContent(), "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<web-app/>\r\n"); } @Test public void test_remove_header_xml_2() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc5.xml"), DocumentType.XML.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertEquals(doc.getContent(), "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<web-app/>\r\n"); } @Test public void test_remove_header_xml_3() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc6.xml"), DocumentType.XML.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertEquals(doc.getContent(), "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<web-app/>\r\n"); } @Test public void test_remove_header_xml_4() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc8.xml"), DocumentType.XML.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertTrue(doc.getContent().contains("no key word")); } @Test public void test_remove_header_xml_5() throws Exception { Document doc = new Document( new File("src/test/resources/doc/doc9.xml"), DocumentType.XML.getDefaultHeaderType().getDefinition(), System.getProperty("file.encoding"), new String[]{"copyright"}); doc.parseHeader(); doc.removeHeader(); assertEquals(doc.getContent(), "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + "<web-app>\r\n" + "\r\n" + "</web-app>\r\n"); } }
{ "content_hash": "f4ebbe2d2009e4cf0f587328170bd28d", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 114, "avg_line_length": 40.37125748502994, "alnum_prop": 0.5909225749035895, "repo_name": "neo4j/license-maven-plugin", "id": "7a17a5ec7afa37ad2630915434b3bec0c1d53d22", "size": "7394", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/google/code/mojo/license/document/DocumentTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "13092" }, { "name": "ActionScript", "bytes": "894" }, { "name": "Ada", "bytes": "1738" }, { "name": "Assembly", "bytes": "650" }, { "name": "C#", "bytes": "163" }, { "name": "CSS", "bytes": "29" }, { "name": "ColdFusion", "bytes": "131" }, { "name": "Erlang", "bytes": "2720" }, { "name": "Java", "bytes": "169588" }, { "name": "JavaScript", "bytes": "534" }, { "name": "Lua", "bytes": "2290" }, { "name": "PHP", "bytes": "538" }, { "name": "Pascal", "bytes": "798" }, { "name": "Ruby", "bytes": "288" }, { "name": "Shell", "bytes": "1296" }, { "name": "XQuery", "bytes": "13683" }, { "name": "XSLT", "bytes": "1088" } ], "symlink_target": "" }
package com.sjl.dsl4xml.support.convert; import com.sjl.dsl4xml.TypeSafeConverter; public class NumberFloatConverter implements TypeSafeConverter<Number,Float> { @Override public boolean canConvertFrom(Class<?> aClass) { return Number.class.isAssignableFrom(aClass); } @Override public boolean canConvertTo(Class<?> aClass) { return aClass.isAssignableFrom(Float.class) || // object wrapper aClass.isAssignableFrom(Float.TYPE); // primitive } @Override public Float convert(Number aFrom) { if (aFrom == null) return null; if (aFrom instanceof Float) return (Float) aFrom; return aFrom.floatValue(); } }
{ "content_hash": "7d16bca6cc5a49bfe63d626ea25647b1", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 78, "avg_line_length": 24.6, "alnum_prop": 0.6449864498644986, "repo_name": "steveliles/dsl4xml", "id": "dc3dfc7cf1cfeb5435a88639bddd57c69bfcb1f8", "size": "738", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "support/src/main/java/com/sjl/dsl4xml/support/convert/NumberFloatConverter.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "235673" } ], "symlink_target": "" }
<?php namespace Carnage\Cqrs\Event\Listener; use Carnage\Cqrs\MessageHandler\AbstractMethodNameMessageHandler; /** * Class AbstractEventListener * @package Carnage\Cqrs\Event\Listener * @deprecated */ abstract class AbstractEventListener extends AbstractMethodNameMessageHandler { }
{ "content_hash": "d003fdc8169aea6542b4a3ab7431849c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 77, "avg_line_length": 20.642857142857142, "alnum_prop": 0.8166089965397924, "repo_name": "carnage/cqrs", "id": "3e0eef48ef19f669f541c7c31fe7f7dcced47c5b", "size": "289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Event/Listener/AbstractEventListener.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "53484" } ], "symlink_target": "" }
.PHONY: clean-pyc clean-build docs help: @echo "clean-build - remove build artifacts" @echo "clean-pyc - remove Python file artifacts" @echo "lint - check style with flake8" @echo "test - run tests quickly with the default Python" @echo "coverage - check code coverage quickly with the default Python" @echo "docs - generate Sphinx HTML documentation, including API docs" @echo "release - package and upload a release" @echo "sdist - package" clean: clean-build clean-pyc clean-build: rm -fr build/ rm -fr dist/ rm -fr *.egg-info clean-pyc: find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + lint: flake8 alarm_client test: py.test tests coverage: coverage run --source populus coverage report -m coverage html open htmlcov/index.html docs: $(MAKE) -C docs clean $(MAKE) -C docs html open docs/_build/html/index.html release: clean python setup.py sdist bdist_wheel upload sdist: clean python setup.py sdist bdist_wheel ls -l dist
{ "content_hash": "fb3102ebf68c70dbf902ba386d0e0da7", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 71, "avg_line_length": 21.851063829787233, "alnum_prop": 0.6991236611489776, "repo_name": "pipermerriam/ethereum-alarm-clock", "id": "acf03fa1567d7d178dfee680d00947b453782c6e", "size": "1027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1027" }, { "name": "Python", "bytes": "195643" }, { "name": "Shell", "bytes": "599" } ], "symlink_target": "" }
package ru.job4j.collectionsFramework; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.TreeSet; import java.util.LinkedList; import java.util.UUID; /** * Class for testing speed collections. * * @author Ayuzyak * @since 31.03.2017 * @version 1.0 */ class TimeListCheck { /** * Add long. * * @param collection the collection * @param line the line * @param amount the amount * @return the long */ public long add(Collection<String> collection, String line, int amount) { long startTimer = System.nanoTime(); for (int i = 0; i < amount; i++) { collection.add(line); } long stopTimer = System.nanoTime(); return stopTimer - startTimer; } /** * Delete long. * * @param collection the collection * @param amount the amount * @return the long */ public long delete(Collection<String> collection, int amount) { Iterator<String> iter = collection.iterator(); long startTimer = System.nanoTime(); for (int i = 0; i < amount; i++) { if (iter.hasNext()) { iter.next(); iter.remove(); } } long stopTimer = System.nanoTime(); return stopTimer - startTimer; } } /** * The type Start list check. */ public class StartListCheck { /** * The entry point of application. * * @param args the input arguments */ public static void main(String[] args) { TimeListCheck timeListCheck = new TimeListCheck(); ArrayList<String> arrayList = new ArrayList<>(); LinkedList<String> linkedList = new LinkedList<>(); TreeSet<String> treeSet = new TreeSet<>(); long addArrayList = 0; long addLinkedList = 0; long addTreeSet = 0; String testString; for (int j = 0; j < 10000; j++) { UUID uuid = UUID.randomUUID(); testString = uuid.toString(); addArrayList += timeListCheck.add(arrayList, testString, 100); addLinkedList += timeListCheck.add(linkedList, testString, 100); addTreeSet += timeListCheck.add(treeSet, testString, 100); } System.out.println("Add ArrayList: \t\t" + addArrayList); System.out.println("Add LinkedList: \t" + addLinkedList); System.out.println("Add TreeSet: \t\t" + addTreeSet); System.out.println(); System.out.println("Remove ArrayList: \t\t" + timeListCheck.delete(arrayList, 1000)); System.out.println("Remove LinkedList: \t\t" + timeListCheck.delete(linkedList, 1000)); System.out.println("Remove TreeSet: \t\t" + timeListCheck.delete(treeSet, 1000)); } }
{ "content_hash": "c2d83fcdc74b4318935b77eb11146c17", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 95, "avg_line_length": 27.58823529411765, "alnum_prop": 0.5934612651030562, "repo_name": "YuzyakAV/ayuzyak", "id": "9023c01985ed091c57052d6849c694c3d554da31", "size": "2814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_005_Collections_Lite/src/main/java/ru/job4j/collectionsFramework/StartListCheck.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "43" }, { "name": "Java", "bytes": "620517" }, { "name": "JavaScript", "bytes": "4078" }, { "name": "TSQL", "bytes": "5477" }, { "name": "XSLT", "bytes": "444" } ], "symlink_target": "" }
@echo off rem Copyright 2016 windocker authors. All rights reserved. rem Use of this source code is governed by Apache License 2.0 rem that can be found in the LICENSE file. rem -------------------------------------------------------------------- rem This script has to be run in each command prompt that Docker rem commands to be executed. Please make sure init_host.cmd has already rem been executed either in this command prompt or in another. rem Otherwise, Docker commands will not work correctly. rem -------------------------------------------------------------------- call conf.cmd echo [windocker] Configuration file(conf.cmd) has been loaded. rem Requests from Docker client in Windows to Docker daemon in B2D VM rem should not pass through proxy. '--no-proxy' causes IP of B2D VM rem to be added to the end of NO_PROXY variable. for /f "tokens=*" %%i in ('docker-machine env --no-proxy default') do %%i echo [windocker] Environment variables have been set: echo [windocker] HTTP_PROXY : %HTTP_PROXY% echo [windocker] HTTPS_PROXY : %HTTPS_PROXY% echo [windocker] NO_PROXY : %NO_PROXY% echo [windocker] DOCKER_HOST : %DOCKER_HOST% echo [windocker] DOCKER_MACHINE_NAME: %DOCKER_MACHINE_NAME% echo [windocker] DOCKER_TLS_VERIFY : %DOCKER_TLS_VERIFY% echo [windocker] DOCKER_CERT_PATH : %DOCKER_CERT_PATH% echo. echo [windocker] Command prompt has been initialized. echo [windocker] Try 'docker run hello-world'.
{ "content_hash": "5e63f2b079f4be03017a6d202fdc2fc5", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 73, "avg_line_length": 48.61290322580645, "alnum_prop": 0.6529528865295289, "repo_name": "kumlali/windocker", "id": "290a446af99d6325fc8205386cff8191da8fa5a2", "size": "1507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "windocker/init_client.cmd", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4385" }, { "name": "Shell", "bytes": "2167" } ], "symlink_target": "" }
var express = require('express'); var router = express.Router(); var title = { title: 'Quiz @danielearning' }; var quizController = require('../controllers/quiz_controller'); var commentController = require('../controllers/comment_controller'); var sessionController = require('../controllers/session_controller'); var statisticsController = require('../controllers/statistics_controller'); /* GET home page. */ router.get('/', function(req, res) { res.render('index', title); }); router.param('quizId', quizController.load); // autoload :quizId router.param('commentId', commentController.load); // autoload :commentId router.get('/quizes', quizController.index); router.get('/quizes/:quizId(\\d+)', quizController.show); router.get('/quizes/:quizId(\\d+)/answer', quizController.answer); router.get('/quizes/new', sessionController.loginRequired, quizController.new); router.post('/quizes/create', sessionController.loginRequired, quizController.create); router.get('/quizes/:quizId(\\d+)/edit', sessionController.loginRequired, quizController.edit); router.put('/quizes/:quizId(\\d+)', sessionController.loginRequired, quizController.update); router.delete('/quizes/:quizId(\\d+)', sessionController.loginRequired, quizController.destroy); router.get ('/quizes/:quizId(\\d+)/comments/new', commentController.new); router.post('/quizes/:quizId(\\d+)/comments/create', commentController.create); router.put ('/comments/:commentId(\\d+)/publish', commentController.publish); router.get ('/login', sessionController.new); router.post ('/login', sessionController.create); router.delete('/login', sessionController.destroy); router.get('/author', function(req, res) { res.render('author', title); }); router.get('/statistics', statisticsController.retrieve); module.exports = router;
{ "content_hash": "057df6d2bd6ae8253c84bab14ea7a780", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 100, "avg_line_length": 41.8, "alnum_prop": 0.7102604997341839, "repo_name": "danielearning/quizz", "id": "269c23af60a0a7105c93c438c1def80fe5e35a8b", "size": "1881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "quiz/routes/index.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1104" }, { "name": "JavaScript", "bytes": "16152" } ], "symlink_target": "" }
dojo.provide("dojox.lang.tests.main"); try{ // functional block dojo.require("dojox.lang.tests.listcomp"); dojo.require("dojox.lang.tests.lambda"); dojo.require("dojox.lang.tests.fold"); dojo.require("dojox.lang.tests.curry"); dojo.require("dojox.lang.tests.misc"); dojo.require("dojox.lang.tests.array"); dojo.require("dojox.lang.tests.object"); dojo.require("dojox.lang.tests.mix"); dojo.require("dojox.lang.tests.recomb"); dojo.require("dojox.lang.tests.observable"); }catch(e){ doh.debug(e); }
{ "content_hash": "53b2e1deabb9834616162ebe7e290012", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 45, "avg_line_length": 30.11764705882353, "alnum_prop": 0.720703125, "repo_name": "weierophinney/pastebin", "id": "50fd59f30093df17e55ecb82bc14683f85165625", "size": "514", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/js-src/dojox/lang/tests/main.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "21319" }, { "name": "JavaScript", "bytes": "6252462" }, { "name": "PHP", "bytes": "371342" }, { "name": "Shell", "bytes": "473" } ], "symlink_target": "" }
package com.allen.oauth.utils; import java.security.MessageDigest; public class MD5Util { private static String byteArrayToHexString(byte b[]) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) resultSb.append(byteToHexString(b[i])); return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) n += 256; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } public static String MD5Encode(String origin, String charsetname) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); if (charsetname == null || "".equals(charsetname)) resultString = byteArrayToHexString(md.digest(resultString.getBytes())); else resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname))); } catch (Exception exception) { } return resultString; } private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; }
{ "content_hash": "66e7f7104b9bc69b717ec61b89e5b43b", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 114, "avg_line_length": 28.307692307692307, "alnum_prop": 0.6594202898550725, "repo_name": "allenfancy/Spring_OAuth", "id": "22021085d173964c9d66dd118f10ef16e3c9a488", "size": "1104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/allen/oauth/utils/MD5Util.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1998" }, { "name": "Java", "bytes": "51519" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SLC_Classview_CSharp.Assessment { public class Utility { public static string FormatAssessmentIdentificationCode(string identificationSystem, string ID) { return string.Format("'assessmentIdentificationCode': [{'identificationSystem': {0}, 'ID': {1}}]", identificationSystem, ID); } /*create assessement * "Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=assessmentTitle, fieldValue=, expectedTypes=[STRING]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=assessmentIdentificationCode, fieldValue=, expectedTypes=[LIST]]", * "assessmentTitle": "Homework 1", "assessmentIdentificationCode": [{"identificationSystem": "Test Contractor", "ID": "Homework 1"}] * */ public static string CreateAssessment(string endPoint, string token, string param) { //var param = string.Format("{'assessmentTitle': {0}, 'assessmentIdentificationCode': [{'identificationSystem': {1}, 'ID': {2}}]", assessmentTitle, identificationSystem, ID); var result = Global.Utility.PostData(endPoint, token, param); return result; } /*update assessment * "Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=assessmentTitle, fieldValue=, expectedTypes=[STRING]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=assessmentIdentificationCode, fieldValue=, expectedTypes=[LIST]] * ValidationError [type=ENUMERATION_MISMATCH, fieldName=academicSubject, fieldValue=AP Cal, expectedTypes=[Agriculture, Food, and Natural Resources, * Architecture and Construction, Business and Marketing, Communication and Audio/Visual Technology, Composite, Computer and Information Sciences, * Critical Reading, ELA, Engineering and Technology, English, English Language and Literature, Fine and Performing Arts, Foreign Language and Literature, * Health Care Sciences, Hospitality and Tourism, Human Services, Life and Physical Sciences, Manufacturing, Mathematics, Military Science, Miscellaneous, * Other, Physical, Health, and Safety Education, Public, Protective, and Government Service, Reading, Religious Education and Theology, Science, * Social Sciences and History, Social Studies, Transportation, Distribution and Logistics, Writing]]", * {"assessmentTitle": "Homework 1", "assessmentIdentificationCode": [{"identificationSystem": "Test Contractor", "ID": "Homework 1"}], "assessmentItem": [{ "identificationCode": "AssessmentItem-1", "correctResponse": "False", "maxRawScore": 5, "itemCategory": "True-False" }]} * */ public static void UpdateAssessment(string endPoint, string token, string param) { } /* update assessment item * Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=identificationCode, fieldValue=, expectedTypes=[STRING]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=itemCategory, fieldValue=, expectedTypes=[TOKEN]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=maxRawScore, fieldValue=, expectedTypes=[INTEGER]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=correctResponse, fieldValue=, expectedTypes=[STRING]]", * */ public static void UpdateAssessmentItem() { } /*add sectionAssessmentAssociation * "Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=sectionId, fieldValue=, expectedTypes=[REFERENCE]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=assessmentId, fieldValue=, expectedTypes=[REFERENCE]] * ValidationError [type=UNKNOWN_FIELD, fieldName=assessment, fieldValue={}, expectedTypes=[]]", * */ public static void AddSectionAssessmentAssociation() { } /* UpdateStudent * "Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=studentUniqueStateId, fieldValue=, expectedTypes=[STRING]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=name, fieldValue=, expectedTypes=[COMPLEX]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=sex, fieldValue=, expectedTypes=[TOKEN]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=birthData, fieldValue=, expectedTypes=[COMPLEX]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=firstName, fieldValue=, expectedTypes=[STRING]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=lastSurname, fieldValue=, expectedTypes=[STRING]]", * "Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=studentUniqueStateId, fieldValue=, expectedTypes=[STRING]] * {"name": {"firstName": "Karrie", "lastSurname": "Sollars"}, "sex": "Female", "birthData": {"birthDate": "1999-03-12"}, "studentUniqueStateId": "800000021"} */ public static void UpdateStudent() { } /*CreateStudentAssessment: https://api.sandbox.slcedu.org/api/rest/v1/studentAssessments * "Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=administrationDate, fieldValue=, expectedTypes=[DATE]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=studentId, fieldValue=, expectedTypes=[REFERENCE]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=assessmentId, fieldValue=, expectedTypes=[REFERENCE]]", * */ public static void CreateStudentAssessment() { } /*update studentAssessmentAssociation * * "Validation failed: ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=administrationDate, fieldValue=, expectedTypes=[DATE]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=studentId, fieldValue=, expectedTypes=[REFERENCE]] * ValidationError [type=REQUIRED_FIELD_MISSING, fieldName=assessmentId, fieldValue=, expectedTypes=[REFERENCE]]", * */ public static void UpdateStudentAssessmentAssociation(string studentAssessmentId, string studentId, string assessmentId, string administrationDate, string score, string token) { var param = string.Format("{{\"studentId\": \"{0}\", \"assessmentId\": \"{1}\", \"administrationDate\": \"{2}\", \"scoreResults\": [{{\"assessmentReportingMethod\": \"Other\", \"result\": \"{3}\"}}]}}", studentId, assessmentId, administrationDate, score); var api = string.Format("https://api.sandbox.slcedu.org/api/rest/v1/studentAssessments/{0}", studentAssessmentId); Global.Utility.PutData(api, token, param); } } }
{ "content_hash": "fbff193c735b73a597af5f2651b61707", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 267, "avg_line_length": 69.71717171717172, "alnum_prop": 0.6961750217328311, "repo_name": "mikeng13/slcCampNYC_teamMnM_web", "id": "7a8980011f8ba6af15d112e02a7d8addf0a72170", "size": "6904", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assessment/Utility.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
void Stencil2DPartitionChunks::fire(void){ LOAD_FRAME(Stencil2DPartition); double *Initial = FRAME(Initial); //matrix pointer initial Matrix[M][N] const uint64_t n_rows = FRAME(nRows); // matrix M row const uint64_t n_cols = FRAME(nCols); // Matrix N column double *New = FRAME(New); uint64_t nTpRows = n_rows-2; uint64_t nChunks=nTpRows/g_nSU; for(size_t i=0; i<g_nSU; ++i){ uint64_t pos = nChunks*i*n_cols; uint64_t nTpRowsFinal = ((i==(g_nSU-1))? (nTpRows%g_nSU):0) + nChunks; INVOKE(Stencil2DRowDecomposition,i,Initial+pos,nTpRowsFinal+2,n_cols,New+pos, &FRAME(swapMatrix)); } EXIT_TP(); } void Stencil2DPartitionSwap::fire(void){ LOAD_FRAME(Stencil2DPartition); uint64_t timestep = FRAME(timeStep); double *src = FRAME(Initial); //matrix pointer initial Matrix[M][N] const uint64_t InitialM = FRAME(nRows); // matrix M row const uint64_t InitialN = FRAME(nCols); // Matrix N column double *dst = FRAME(New); timestep --; typedef double (*Array2D)[InitialN]; Array2D DST = (Array2D) dst, SRC = (Array2D) src; SWAP_PTR(&DST,&SRC); if (timestep == 0) SIGNAL(signalUP); else if (timestep !=0){ // INVOKE(Stencil2D,NewMatrix,InitialM,InitialN,InitialMatrix,timestep,&Runtime::finalSignal); INVOKE(Stencil2DPartition,src,InitialM,InitialN,dst,timestep,&Runtime::finalSignal); } EXIT_TP(); }
{ "content_hash": "c60146ba819ee27d1743e7b46ed2e904", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 101, "avg_line_length": 29.17391304347826, "alnum_prop": 0.7019374068554396, "repo_name": "szuckerm/DARTS", "id": "3d249c5afd2814eaf5ae542d3faffa63412054ab", "size": "1472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/Stencil2D_Naive_Tps/Stencil2DPartition.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "20935" }, { "name": "C++", "bytes": "1062486" }, { "name": "CMake", "bytes": "83862" }, { "name": "Shell", "bytes": "55500" } ], "symlink_target": "" }
import React, { PropTypes } from 'react' import { Label } from 'semantic-ui-react' class Tag extends React.Component { render () { return ( <Label as='a' color={this.props.category.colour} tag >{this.props.value}</Label> ) } } Tag.propTypes = { category: PropTypes.shape({ colour: PropTypes.string.isRequired }).isRequired, value: PropTypes.string.isRequired } export default Tag
{ "content_hash": "7ed716497f534ee3f6d629001942be0b", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 42, "avg_line_length": 19.17391304347826, "alnum_prop": 0.6326530612244898, "repo_name": "amandahogan/eda-job-list", "id": "a985c68bf51027ea5b339fa06d124ed885e7b3ef", "size": "441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/Tag/Tag.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "65" }, { "name": "HTML", "bytes": "398" }, { "name": "JavaScript", "bytes": "24288" } ], "symlink_target": "" }
{% extends "includes/base.html" %} {% block content %} <center><h2 class="alt title_color">Enter your Twitter username below to get started.</h2></center> {% include "includes/_form.html" %} {% include "faves/_view_counts.html" %} {% endblock %}
{ "content_hash": "75ecb56ad4fc46d61eff4d8456e85aa0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 99, "avg_line_length": 19.46153846153846, "alnum_prop": 0.6600790513833992, "repo_name": "poeks/twitterbelle", "id": "cf5ba478748981655eedc3ea934bcb35d9722662", "size": "253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/faves/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "5451" }, { "name": "Python", "bytes": "350587" } ], "symlink_target": "" }
/* * INCLUDES DATA FROM PANGO: * https://developer.gnome.org/pango/stable/pango-Scripts-and-Languages.html */ #pragma once #include "hb.h" #include "unicode/uscript.h" #include <vector> #include <map> #include <set> #include <string> #ifndef DEFAULT_LANGUAGES #define DEFAULT_LANGUAGES "en:zh-cn" #endif class LanguageHelper { public: LanguageHelper(); /* * EXPECTS A LIST LANGUAGES SEPARATED BY COLONS */ void setDefaultLanguages(const std::string &languages); /* * DETERMINES THE SCRIPTS USED TO WRITE @lang * * QUOTING PANGO: * Most languages use only one script for writing, but there are * some that use two (Latin and Cyrillic for example), and a few * use three (Japanese for example). */ const std::vector<hb_script_t>& getScriptsForLang(const std::string &lang) const; /* * DETERMINES IF @script MAY BE USED TO WRITE @lang */ bool includesScript(const std::string &lang, hb_script_t script) const; /* * RETURNS THE RESOLVED LANGUAGE IF @script MAY BE USED TO WRITE ONE OF THE "DEFAULT LANGUAGES" */ std::string getDefaultLanguage(hb_script_t script) const; /* * QUOTING PANGO: * * Given a script, finds a language tag that is reasonably * representative of that script. This will usually be the * most widely spoken or used language written in that script: * for instance, the sample language for %HB_SCRIPT_CYRILLIC * is <literal>ru</literal> (Russian), the sample language * for %HB_SCRIPT_ARABIC is <literal>ar</literal>. * * For some * scripts, no sample language will be returned because there * is no language that is sufficiently representative. The best * example of this is %HB_SCRIPT_HAN, where various different * variants of written Chinese, Japanese, and Korean all use * significantly different sets of Han characters and forms * of shared characters. No sample language can be provided * for many historical scripts as well. */ std::string getSampleLanguage(hb_script_t script) const; /* * TRYING TO DETECT A LANGUAGE FOR @script BY ASKING 3 QUESTIONS: * * 1. CAN @script BE USED TO WRITE @langHint? * 2. CAN @script BE USED TO WRITE ONE OF THE "DEFAULT LANGUAGES"? * 3. IS THERE A PREDOMINANT LANGUAGE THAT IS LIKELY FOR @script? */ std::string detectLanguage(hb_script_t script, const std::string &langHint = "") const; static hb_script_t hbScriptFromICU(UScriptCode script) { if (script == USCRIPT_INVALID_CODE) { return HB_SCRIPT_INVALID; } return hb_script_from_string(uscript_getShortName(script), -1); } inline std::string detectLanguage(UScriptCode script, const std::string &langHint = "") const { return detectLanguage(hbScriptFromICU(script), langHint); } protected: std::map<std::string, std::vector<hb_script_t>> scriptMap; std::map<hb_script_t, std::string> sampleLanguageMap; std::set<std::string> defaultLanguageSet; };
{ "content_hash": "3d9d2ebaeac0739f04d484f65a1496c6", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 99, "avg_line_length": 30.88235294117647, "alnum_prop": 0.6596825396825396, "repo_name": "arielm/Unicode", "id": "d6c0b678c95546fb88488ee42a37357dd20452e2", "size": "3423", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Projects/ScriptDetector/src/LanguageHelper.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "3305258" }, { "name": "C++", "bytes": "5837282" }, { "name": "Hack", "bytes": "42081" }, { "name": "Java", "bytes": "2382" }, { "name": "Makefile", "bytes": "17820" }, { "name": "Objective-C", "bytes": "9626" }, { "name": "Objective-C++", "bytes": "4074" }, { "name": "Shell", "bytes": "3176" } ], "symlink_target": "" }
declare function plural(n: number): number; declare const _default: (string | number | (string[] | undefined)[] | number[] | (string | undefined)[] | typeof plural | { 'GEL': (string | undefined)[]; 'MDL': string[]; 'RON': (string | undefined)[]; 'RUB': string[]; 'RUR': string[]; 'THB': string[]; 'TMT': string[]; 'TWD': string[]; 'UAH': string[]; 'XXX': string[]; } | undefined)[]; export default _default;
{ "content_hash": "3997a05927e5cb4c3ce3a1d7b4730666", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 123, "avg_line_length": 28.1875, "alnum_prop": 0.5543237250554324, "repo_name": "Leo-g/Flask-Scaffold", "id": "5c8dfe84d0552670427c5c29c0e3233bba895bb6", "size": "653", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "app/templates/static/node_modules/@angular/common/locales/ru-MD.d.ts", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "15274" }, { "name": "HTML", "bytes": "14505" }, { "name": "JavaScript", "bytes": "49098" }, { "name": "Nginx", "bytes": "1545" }, { "name": "Python", "bytes": "62750" }, { "name": "Shell", "bytes": "21" } ], "symlink_target": "" }
package com.iluwatar; /** * * Mediator encapsulates how a set of objects (PartyMember) interact. Instead of * referring to each other directly they use a mediator (Party) interface. * */ public class App { public static void main(String[] args) { // create party and members Party party = new PartyImpl(); Hobbit hobbit = new Hobbit(); Wizard wizard = new Wizard(); Rogue rogue = new Rogue(); Hunter hunter = new Hunter(); // add party members party.addMember(hobbit); party.addMember(wizard); party.addMember(rogue); party.addMember(hunter); // perform actions -> the other party members // are notified by the party hobbit.act(Action.ENEMY); wizard.act(Action.TALE); rogue.act(Action.GOLD); hunter.act(Action.HUNT); } }
{ "content_hash": "5f9e1c915183c31a74583a24fdbcd4b8", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 80, "avg_line_length": 23.393939393939394, "alnum_prop": 0.6904145077720207, "repo_name": "JonathanJohannsen/ObserverTest", "id": "92905b29d6a5863aa012091e80bf014961821eeb", "size": "772", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "observer/src/main/java/com/iluwatar/mediator/src/main/java/com/iluwatar/App.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "11283" } ], "symlink_target": "" }
import { StatementSyntax, ValueReference } from 'glimmer-runtime'; import { AttributeBindingReference, RootReference, applyClassNameBinding } from '../utils/references'; import EmptyObject from 'ember-metal/empty_object'; export class CurlyComponentSyntax extends StatementSyntax { constructor({ args, definition, templates }) { super(); this.args = args; this.definition = definition; this.templates = templates; this.shadow = null; } compile(builder) { builder.component.static(this); } } function attrsToProps(keys, attrs) { let merged = new EmptyObject(); merged.attrs = merged; for (let i = 0, l = keys.length; i < l; i++) { let name = keys[i]; let value = attrs[name]; // Do we have to support passing both class /and/ classNames...? if (name === 'class') { name = 'classNames'; } merged[name] = value; } return merged; } class CurlyComponentManager { create(definition, args, dynamicScope) { let parentView = dynamicScope.view; let klass = definition.ComponentClass; let attrs = args.named.value(); let props = attrsToProps(args.named.keys, attrs); let component = klass.create(props); dynamicScope.view = component; parentView.appendChild(component); // component.trigger('didInitAttrs', { attrs }); // component.trigger('didReceiveAttrs', { newAttrs: attrs }); // component.trigger('willInsertElement'); // component.trigger('willRender'); return component; } getSelf(component) { return new RootReference(component); } didCreateElement(component, element, operations) { component.element = element; let { attributeBindings, classNames, classNameBindings } = component; if (attributeBindings) { attributeBindings.forEach(binding => { AttributeBindingReference.apply(component, binding, operations); }); } if (classNames) { classNames.forEach(name => { operations.addAttribute('class', new ValueReference(name)); }); } if (classNameBindings) { classNameBindings.forEach(binding => { applyClassNameBinding(component, binding, operations); }); } component._transitionTo('hasElement'); } didCreate(component) { // component.trigger('didInsertElement'); // component.trigger('didRender'); component._transitionTo('inDOM'); } update(component, args, dynamicScope) { let attrs = args.named.value(); let props = attrsToProps(args.named.keys, attrs); // let oldAttrs = component.attrs; // let newAttrs = attrs; component.setProperties(props); // component.trigger('didUpdateAttrs', { oldAttrs, newAttrs }); // component.trigger('didReceiveAttrs', { oldAttrs, newAttrs }); // component.trigger('willUpdate'); // component.trigger('willRender'); } didUpdate(component) { // component.trigger('didUpdate'); // component.trigger('didRender'); } getDestructor(component) { return component; } } const MANAGER = new CurlyComponentManager(); import { ComponentDefinition } from 'glimmer-runtime'; import Component from '../ember-views/component'; function tagName(vm) { let { tagName } = vm.dynamicScope().view; if (tagName === '') { throw new Error('Not implemented: fragments (`tagName: ""`)'); } return new ValueReference(tagName || 'div'); } function elementId(vm) { let component = vm.dynamicScope().view; return new ValueReference(component.elementId); } export class CurlyComponentDefinition extends ComponentDefinition { constructor(name, ComponentClass, template) { super(name, MANAGER, ComponentClass || Component); this.template = template; } compile(builder) { builder.wrapLayout(this.template.asLayout()); builder.tag.dynamic(tagName); builder.attrs.dynamic('id', elementId); builder.attrs.static('class', 'ember-view'); } }
{ "content_hash": "7c9e0b649a9be9fc4649a2f08779dc76", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 102, "avg_line_length": 25.640522875816995, "alnum_prop": 0.6724445577364262, "repo_name": "topaxi/ember.js", "id": "ea3cf4229ab9f9089f5ddea2b6953921725726ea", "size": "3923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/ember-glimmer/lib/components/curly-component.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7608" }, { "name": "JavaScript", "bytes": "3439482" }, { "name": "Ruby", "bytes": "6190" }, { "name": "Shell", "bytes": "2524" } ], "symlink_target": "" }
package com.aserdyuchenko; import com.aserdyuchenko.MaxLenght; import com.aserdyuchenko.Point; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Тест для класса MaxLenght. * 1. whenAllPointsInOnePointThenAreaZero() * Невозможно построить треугольник, так как все точки находятся в одной точке и площадь равна нулю. * * 2. whenPointsLieOnLineThenAreaZero() * Невозможно построить треугольник, так как все точки на одной линии и площадь равна нулю. * * 3. whenDistanceBCisMax() * Максимальная сторона BC * * 4. whenDistanceACisMax() * Максимальная сторона AC * * 5. whenDistanceABisMax() * МАксимальная сторона AB * * @author Anton Serdyuchenko * @since 02.09.2016 * @version 1.0 */ public class MaxLenghtTest { /** * @param NUMBERONE - NUMBERONE. */ public static final int NUMBERONE = 4; /** * @param NUMBERTWO - NUMBERTWO. */ public static final int NUMBERTWO = 5; /** * whenAllPointsInOnePointThenAreaZero(). */ @Test public void whenAllPointsInOnePointThenAreaZero() { Point a = new Point(0, 0); Point b = new Point(0, 0); Point c = new Point(0, 0); MaxLenght maxLenght = new MaxLenght(a, b, c); String result = maxLenght.max(); assertThat(result, is("Невозможно построить треугольник!")); } /** * whenPointsLieOnLineThenAreaZero(). */ @Test public void whenPointsLieOnLineThenAreaZero() { Point a = new Point(0, 0); Point b = new Point(2, 0); Point c = new Point(NUMBERONE, 0); MaxLenght maxLenght = new MaxLenght(a, b, c); String maximum = maxLenght.max(); assertThat(maximum, is("Невозможно построить треугольник!")); } /** * whenDistanceBCisMax(). */ @Test public void whenDistanceBCisMax() { Point a = new Point(0, 0); Point b = new Point(2, 0); Point c = new Point(0, NUMBERTWO); MaxLenght maxLenght = new MaxLenght(a, b, c); String maximum = maxLenght.max(); assertThat(maximum, is("Distance BC is maximum")); } /** * whenDistanceACisMax(). */ @Test public void whenDistanceACisMax() { Point a = new Point(0, 0); Point b = new Point(2, 0); Point c = new Point(2, NUMBERTWO); MaxLenght maxLenght = new MaxLenght(a, b, c); String maximum = maxLenght.max(); assertThat(maximum, is("Distance AC is maximum")); } /** * whenDistanceABisMax(). */ @Test public void whenDistanceABisMax() { Point a = new Point(0, 0); Point b = new Point(NUMBERTWO, 0); Point c = new Point(0, 2); MaxLenght maxLenght = new MaxLenght(a, b, c); String maximum = maxLenght.max(); assertThat(maximum, is("Distance AB is maximum")); } }
{ "content_hash": "c8bfe7ba80e2fd8d6f5dccfc01a31813", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 100, "avg_line_length": 28.13, "alnum_prop": 0.6384642730181301, "repo_name": "anton415/java-courses", "id": "031ca7bcc5bc457fd385648fca17def221b0cb33", "size": "3097", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Intern/Part_1_Syntax/src/test/java/com/aserdyuchenko/MaxLenghtTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "146176" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/marcusberner/sandal.png?branch=master)](https://travis-ci.org/marcusberner/sandal) [![browser support](https://ci.testling.com/marcusberner/sandal.png)](https://ci.testling.com/marcusberner/sandal) [![NPM](https://nodei.co/npm/sandal.png?downloads=true)](https://nodei.co/npm/sandal/) Sandal is a javascript dependency injection container. A sandal container can be used to register and resolve components. It will resolve dependencies and inject them. ## Installation Download source from [GitHub](https://github.com/marcusberner/sandal) or install using npm or bower: ### Node package manager $ npm install sandal ### Bower $ bower install sandal ## API ### Create a container #### Node.js ```js var Sandal = require('sandal'); var sandal = new Sandal(); ``` #### Browser ```js var sandal = new Sandal(); ``` ### Register components #### sandal.object(name, obj, [groups]) * `name` (string) The name that will be used to resolve the component. "sandal" and "done" are reserved names. * `obj` (any type) The object that will be provided when resolving. * `groups` (Array of strings) Will add the object to the provided groups. "sandal" and "done" are reserved names. ##### Example ```js sandal.object('myObject', 'any object', ['myGroup', 'myOtherGroup']); ``` #### sandal.service(name, [dependencies], ctor, [transient], [groups]) * `name` (string) The name that will be used to resolve the component. "sandal" and "done" are reserved names. * `dependencies` (Array of strings) If provided the names in the array will be resolved and injected into the ctor. Otherwise the names of the ctor arguments will be used. * `ctor` (function) The service constructor. When resolving, the ctor will be called with the new operator and the result will be provided. * `transient` (boolean) If true the ctor will be called every time the service is resolved, resulting an a new object. Default behavior is singleton where the ctor is only called the first time and the resulting object is provided every time. * `groups` (Array of strings) Will add the service to the provided groups. "sandal" and "done" are reserved names. If the constructor requires asynchronous tasks to be completed before the resulting object is ready to use, a done callback named `done` can be taken as a constructor argument. This will inject a callback that has to be called before the service is resolved. The done callback accepts an error. If an error is provided, that will result in an error when resolving the service or any factory or service dependent on the service. ##### Example ```js var MyService = function (dependency1) { this.doStruff = function () {}; }; MyService.prototype.doOtherStuff = function () {}; var MyAsyncService = function (x, done) { doSomeAsyncInit(function (err) { done(err); }); }; sandal.service('myService', MyService, true, ['myGroup']); sandal.service('myAsyncService', ['myService', 'done'], MyAsyncService); ``` #### sandal.factory(name, [dependencies], factory, [transient], [groups]) * `name` (string) The name that will be used to resolve the component. "sandal" and "done" are reserved names. * `dependencies` (Array of strings) If provided the names in the array will be resolved and injected into the factory. Otherwise the names of the factory arguments will be used. * `factory` (function) The factory function. When resolving, the factory will be called and the return value will be provided. If one of the dependencies has the name "done", a done callback function will be injected. In that case the provided result will be the second argument to the done callback and not the return value of the factory function. * `transient` (boolean) If true the factory will be called every time the it is resolved, resulting an a new object. Default behavior is singleton where the factory is only called the first time and the resulting object is provided every time. * `groups` (Array of strings) Will add the factory to the provided groups. "sandal" and "done" are reserved names. A factory that requires some asynchronous task to be completed should take a `done` callback just like a service. If a factory takes a done callback, the second argument of the done callback will be the resolved object instead of the return value of the factory function. ##### Example ```js var myFactory = function (dependency1) { return 'some value'; }; var myAsyncFactory = function (d1, done) { d1.doSomeAsyncInit(function (err) { done(err, 'some value'); }); }; sandal.factory('myFactory', myFactory, true, ['myGroup']); sandal.factory('myAsyncFactory', ['dependency1', 'done'], myAsyncFactory); ``` ### Resolving components #### sandal.resolve([names], callback) * `names` (string or Array of strings) If provided, the name/names will be resolved and injected into the callback. The first argument to the callback function will always be any error from resolving. If not provided the names of the callback arguments will be used. The names must match the names used for services, factories, objects or groups. Resolving a group will provide an object containing all components in the group. The component will be contained within a property with the same name as the registered name. * `callback` (function) The dependencies will be resolved and injected to the callback function. ##### Example ```js sandal.resolve(function (err, myObject, myService, myFactory, myGroup) { }); sandal.resolve('myObject', function (err, o) { }); sandal.resolve(['myObject', 'myService', 'myFactory', 'myGroup'], function (err, o, s, f, t) { }); ``` #### sandal.resolveAsFactory(factory, [dependencies], callback) * `factory` (function) The factory function to resolve. The factory will not be added to the container but resolved as if it was added and then resolved. * `dependencies` (Array of strings) If provided, the name/names will be resolved and injected into the factory. * `callback` (function) The resolved factory will be passed to the callback as the second argument. It failing the error will be passed as a first argument. ##### Example ```js sandal.object('myObject', { some: 'data' }); sandal.resolveAsFactory(function (myObject) { // Return output or pass to done() if available }, function (err, output) { // output will be result of factory }); ``` #### sandal.resolveAsService(service, [dependencies], callback) * `service` (function) The service constructor. The service will not be added to the container but resolved as if it was added and then resolved. * `dependencies` (Array of strings) If provided, the name/names will be resolved and injected into the service constructor. * `callback` (function) The resolved service will be passed to the callback as the second argument. It failing the error will be passed as a first argument. ##### Example ```js sandal.object('myObject', { some: 'data' }); sandal.resolveAsService(function (myObject) { // Constructor code }, function (err, output) { // output will be the constructed object }); ``` ### Removing components Registering a component with an already registered name will throw an error. To replace a component it must be removed before registering the new component. #### sandal.remove(names) * `names` (string or Array of strings) Name/names of objects, factories, services or groups to remove. Removing a group will remove the group but not the components in the group. ##### Example ```js sandal.remove('myObject'); sandal.remove(['myObject', 'myService', 'myFactory', 'myGroup']); ``` #### sandal.clear() Removes all registered components. #### Example ```js sandal.clear(); ``` ### Checking component To check if a component has been registered, use the `.has(name)` function. #### sandal.has(name) * `name` (string) Name of object, factory, service or group to look for. ##### Example ```js sandal.object('myObject', { some: 'data' }); sandal.has('myObject'); // Returns true sandal.has('yourObject'); // Returns false sandal.has('sandal'); // Returns true since the container is always available ``` ### Extending Both a container and the contstructor can be extended. ##### Example ```js Sandal.extend(function (constructor, isConstructor) { // isConstructor = true constructor.prototype.someNewFunction = function () {}; }); var sandal = new Sandal(); sandal.extend(function (container, isConstructor) { // isConstructor = false container.someOtherNewFunction = function () {}; }); ``` Expected behaviour is that, extending the constructor applies to all created containers and extending a container only applies to that container. The same extension can be compatible with both extending the constructor and a container. The same container behaviour is exprected in both cases. It's recommended to throw an error if the extension is not applicable to the constructor or container base on the `isConstructor` argument, indicating that it was used in a non supported way. ### Chaining All sandal operations can be chained. ##### Example ```js sandal.factory('myFactory', MyFactory).resolve(function (err, myFactory) {}); ```
{ "content_hash": "bbb242046f68c142775017e5196182b9", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 520, "avg_line_length": 34.609022556390975, "alnum_prop": 0.7334347164892462, "repo_name": "marcusberner/sandal", "id": "afae8ca85d5da8296fbb6e6b360a2a187479735f", "size": "9216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "53380" } ], "symlink_target": "" }
extern "Java" { namespace javax { namespace swing { namespace plaf { namespace synth { class ColorType; } } } } } class javax::swing::plaf::synth::ColorType : public ::java::lang::Object { public: // actually protected ColorType(::java::lang::String *); public: virtual jint getID(); virtual ::java::lang::String * toString(); static ::javax::swing::plaf::synth::ColorType * FOREGROUND; static ::javax::swing::plaf::synth::ColorType * BACKGROUND; static ::javax::swing::plaf::synth::ColorType * TEXT_FOREGROUND; static ::javax::swing::plaf::synth::ColorType * TEXT_BACKGROUND; static ::javax::swing::plaf::synth::ColorType * FOCUS; static jint MAX_COUNT; private: static jint count; jint __attribute__((aligned(__alignof__( ::java::lang::Object)))) id; ::java::lang::String * description; public: static ::java::lang::Class class$; }; #endif // __javax_swing_plaf_synth_ColorType__
{ "content_hash": "d9aa5a4b839bf65a0b580520f26c4619", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 72, "avg_line_length": 24.575, "alnum_prop": 0.6337741607324516, "repo_name": "the-linix-project/linix-kernel-source", "id": "99a238cf3025b8d26a4bd84d76914a590c216c65", "size": "1188", "binary": false, "copies": "160", "ref": "refs/heads/master", "path": "gccsrc/gcc-4.7.2/libjava/javax/swing/plaf/synth/ColorType.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ada", "bytes": "38139979" }, { "name": "Assembly", "bytes": "3723477" }, { "name": "Awk", "bytes": "83739" }, { "name": "C", "bytes": "103607293" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "38577421" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "32588" }, { "name": "Emacs Lisp", "bytes": "13451" }, { "name": "FORTRAN", "bytes": "4294984" }, { "name": "GAP", "bytes": "13089" }, { "name": "Go", "bytes": "11277335" }, { "name": "Haskell", "bytes": "2415" }, { "name": "Java", "bytes": "45298678" }, { "name": "JavaScript", "bytes": "6265" }, { "name": "Matlab", "bytes": "56" }, { "name": "OCaml", "bytes": "148372" }, { "name": "Objective-C", "bytes": "995127" }, { "name": "Objective-C++", "bytes": "436045" }, { "name": "PHP", "bytes": "12361" }, { "name": "Pascal", "bytes": "40318" }, { "name": "Perl", "bytes": "358808" }, { "name": "Python", "bytes": "60178" }, { "name": "SAS", "bytes": "1711" }, { "name": "Scilab", "bytes": "258457" }, { "name": "Shell", "bytes": "2610907" }, { "name": "Tcl", "bytes": "17983" }, { "name": "TeX", "bytes": "1455571" }, { "name": "XSLT", "bytes": "156419" } ], "symlink_target": "" }
package br.unicamp.ic.sed.mobilemedia.mobilephonemgr.warningexceptionshandler_mobilephonemgr.impl; import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.mobilephonecontroller.spec.req.IExceptionsHandlerCtr; import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.prov.IManager; class IExceptionsHandlerAdapter implements IExceptionsHandlerCtr{ public void handle(Exception exception) { //System.out.println("IExceptionsHandlerAdapter.handle()"); br.unicamp.ic.sed.mobilemedia.mobilephonemgr.warningexceptionhandler.spec.prov.IExceptionsHandlerCtr handler; IManager mgr = ComponentFactory.createInstance(); handler = (br.unicamp.ic.sed.mobilemedia.mobilephonemgr.warningexceptionhandler.spec.prov.IExceptionsHandlerCtr)mgr.getRequiredInterface("IExceptionsHandlerCtr"); handler.handle(exception); } }
{ "content_hash": "b80f25c184ba094b636024c66da0db4e", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 164, "avg_line_length": 44.31578947368421, "alnum_prop": 0.8171021377672208, "repo_name": "leotizzei/MobileMedia-Cosmos-v1", "id": "8a7aac1baafde45020461ea322f7596e453bcce0", "size": "842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/br/unicamp/ic/sed/mobilemedia/mobilephonemgr/warningexceptionshandler_mobilephonemgr/impl/IExceptionsHandlerAdapter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "181120" }, { "name": "Shell", "bytes": "241" } ], "symlink_target": "" }
package org.weakref.jmx; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; public class CustomFlattenAnnotationObject extends FlattenObject { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Flatten public @interface CustomFlatten { String description() default ""; } @Override @CustomFlatten public SimpleObject getSimpleObject() { return super.getSimpleObject(); } }
{ "content_hash": "ef65957f1fc610e95fa04c4dc44bbd30", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 64, "avg_line_length": 22.36, "alnum_prop": 0.7334525939177102, "repo_name": "martint/jmxutils", "id": "e39faa9959cbe13476953efb5424feacfb9f9021", "size": "1167", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/weakref/jmx/CustomFlattenAnnotationObject.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "196407" } ], "symlink_target": "" }
@interface Sha256Wrapper : NSObject - (nullable instancetype)init; - (int)updateWithData:(nonnull NSData *)data; - (int)updateWithString:(nonnull NSString *)string; - (nullable NSData *)finish; @end
{ "content_hash": "b689ce818645ab7cbf80618226b53617", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 51, "avg_line_length": 22.333333333333332, "alnum_prop": 0.7512437810945274, "repo_name": "spark/photon-tinker-ios", "id": "b05a92a9aaf1da1654da40ac824c4fb6bdc19e01", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mbedTLSWrapper/mbedTLSWrapper/Sha256Wrapper.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "668" }, { "name": "Objective-C", "bytes": "97954" }, { "name": "Ruby", "bytes": "441" }, { "name": "Swift", "bytes": "173616" } ], "symlink_target": "" }
<?php abstract class Shineisp_Api_Controller_Action extends Shineisp_Controller_Common { public function init(){ $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); } /** * Accept the request of the clients * * @param string $classname */ public function soap( $classname ){ if(empty($classname)){ return false; } list($app, $module, $class) = explode("_", $classname); // initialize server and set URI $optionsoap = array( 'location' => "http://" . $_SERVER['HTTP_HOST'] . "/".strtolower($class).".wsld", 'uri' => 'urn:'.$classname); $server = new Zend_Soap_Server(null, $optionsoap); // set SOAP service class $server->setClass ( $classname ); // Bind already initialized object to Soap Server $server->setObject(new $classname()); $server->setReturnResponse(false); // register exceptions for generating SOAP faults $server->registerFaultException ( array ('Shineisp_Api_Exceptions' ) ); // handle request $server->handle (); } /** * Show the WSDL file of a specific class * * @param string $classname */ public function wsdl( $classname ) { //You can add Zend_Auth code here if you do not want //everybody can access the WSDL file. if(empty($classname)){ return false; } list($app, $module, $class) = explode("_", $classname); // initilizing zend autodiscover object. $wsdl = new Zend_Soap_AutoDiscover (); // register SOAP service class $wsdl->setClass ( $classname ); // set a SOAP action URI. here, SOAP action is 'soap' as defined above. $wsdl->setUri ( "http://" . $_SERVER['HTTP_HOST'] . "/" . strtolower($class).".soap" ); // handle request $wsdl->handle (); } }
{ "content_hash": "b525c9e84566c88389e6b17b8f3ce53c", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 113, "avg_line_length": 29.714285714285715, "alnum_prop": 0.5389423076923077, "repo_name": "shinesoftware/shineisp", "id": "aab08e44f88980f193f986b22e6ca517728525e0", "size": "2080", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "library/Shineisp/Api/Controller/Action.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "2032" }, { "name": "Batchfile", "bytes": "2294" }, { "name": "CSS", "bytes": "39083" }, { "name": "HTML", "bytes": "984155" }, { "name": "JavaScript", "bytes": "556737" }, { "name": "PHP", "bytes": "31409543" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Shell", "bytes": "1409" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>paramcoq: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.2 / paramcoq - 1.0.9</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> paramcoq <small> 1.0.9 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-03-01 03:55:52 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-03-01 03:55:52 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.2 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.0 Official release 4.09.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;abhishek.anand.iitg@gmail.com&quot; homepage: &quot;https://github.com/aa755/paramcoq&quot; dev-repo: &quot;git+https://github.com/aa755/paramcoq&quot; authors: [&quot;Chantal Keller&quot; &quot;Marc Lasson&quot;] bug-reports: &quot;https://github.com/aa755/paramcoq/issues&quot; license: &quot;MIT&quot; build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Param&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] synopsis: &quot;Keller, Chantal, and Marc Lasson. “Parametricity in an Impredicative Sort.” Computer Science Logic, September 27, 2012. https://doi.org/10.4230/LIPIcs.CSL.2012.399&quot; description: &quot;Originally implemented by the above authors.&quot; flags: light-uninstall url { src: &quot;https://github.com/aa755/paramcoq/archive/v1.0.9.tar.gz&quot; checksum: &quot;md5=7c46df48ebf0bda825ebf369dc960445&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-paramcoq.1.0.9 coq.8.10.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.2). The following dependencies couldn&#39;t be met: - coq-paramcoq -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-paramcoq.1.0.9</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "dd78d86f7112a82a94ca0b2aceaa3207", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 185, "avg_line_length": 40.57831325301205, "alnum_prop": 0.5369655581947743, "repo_name": "coq-bench/coq-bench.github.io", "id": "f915d8200b79a4ba415d58e2f9d10e630382ec8a", "size": "6742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.0-2.0.5/released/8.10.2/paramcoq/1.0.9.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<resources> <string name="app_name">Metaball</string> </resources>
{ "content_hash": "d8ea665f27ddd27856945cd481daa131", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 45, "avg_line_length": 23.666666666666668, "alnum_prop": 0.6901408450704225, "repo_name": "dgmltn/Android-Metaball", "id": "3a7fd38fae31a7afb3ebad9f74ec691fa1b3cd69", "size": "71", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "demo/src/main/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "15340" }, { "name": "Kotlin", "bytes": "2318" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="description" content="<#name#> demo"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"> <title><#name#> demo</title> <link rel="shortcut icon" href="images/avatar.png" type="image/x-icon" /> <link rel="stylesheet" href="stylesheet/base.css"/> <link rel="stylesheet" href="stylesheet/<#name#>.css"/> </head> <body> <div id="content"> </div> </body> <script src="javascript/<#name#>.js"></script> </html>
{ "content_hash": "bed94c402ad143f1ea97a6fe8c0d9e0e", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 108, "avg_line_length": 31.941176470588236, "alnum_prop": 0.6556169429097606, "repo_name": "xudafeng/generator-demo", "id": "02d7d2ae350fc0084b84666e4e6432dfd5005c02", "size": "543", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "template/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2311" }, { "name": "HTML", "bytes": "543" }, { "name": "JavaScript", "bytes": "2071" } ], "symlink_target": "" }
<?php use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Log; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Facades\Response; use Noherczeg\RestExt\Exceptions\ErrorMessageException; use Noherczeg\RestExt\Exceptions\NotFoundException; use Noherczeg\RestExt\Exceptions\PermissionException; /* |-------------------------------------------------------------------------- | Error Logging |-------------------------------------------------------------------------- | | We log any errors in our App. | */ App::error(function(Exception $exception, $code) { Log::error($exception); }); /* |-------------------------------------------------------------------------- | HTTP Exceptions |-------------------------------------------------------------------------- | | HTTP Exceptions are translated to proper REST Responses. | | TODO Content should be loaded with the Localization tool | */ App::error(function(Symfony\Component\HttpKernel\Exception\HttpException $e, $code) { $headers = $e->getHeaders(); $content = ["content" => null, "links" => [ ["rel" => "self", "href" => URL::full()], ]]; switch ($code) { case 401: $content['content'] = 'Invalid API key'; $headers['WWW-Authenticate'] = 'Basic realm="' . Config::get('restext::realm') . '"'; break; case 403: $content['content'] = 'Access denied'; break; case 404: $content['content'] = 'Requested Resource not found'; break; case 406: $content['content'] = 'Given Content-Type not acceptable'; break; default: $content['content'] = 'An unknown error occured'; } return Response::json($e->getMessage() ?: $content, $code, $headers); }); /* |-------------------------------------------------------------------------- | Application Error Messages |-------------------------------------------------------------------------- | | Error Messages set ususaly when a user error occures. | */ App::error(function(ErrorMessageException $e) { return Response::json([ 'reason' => $e->getMessages()->all(), 'links' => [['rel' => 'self', 'href' => URL::full()]] ], 400); }); /* |-------------------------------------------------------------------------- | 404 Error |-------------------------------------------------------------------------- | | */ App::error(function(NotFoundException $e) { return Response::json([ 'reason' => $e->getMessage() ?: 'Requested page not found', 'links' => [['rel' => 'self', 'href' => URL::full()]] ], 404); }); /* |-------------------------------------------------------------------------- | Permission Error |-------------------------------------------------------------------------- | | Unauthorized errors are handled here. | */ App::error(function(PermissionException $e) { return Response::json([ 'reason' => $e->getMessage() ?: 'Access denied', 'links' => [['rel' => 'self', 'href' => URL::full()]] ], 403); }); /* |-------------------------------------------------------------------------- | Repository Error |-------------------------------------------------------------------------- | | Sent when an Entity couldn't be found in the Repositories. | */ App::error(function(ModelNotFoundException $e) { return Response::json([ 'reason' => 'Requested Resource not found', 'links' => [['rel' => 'self', 'href' => URL::full()]] ], 404); }); /* |-------------------------------------------------------------------------- | Database Error |-------------------------------------------------------------------------- | | Redis doesn't respond to Requests | */ App::error(function(\Predis\Connection\ConnectionException $e) { return Response::json([ 'reason' => 'The Cache server is not responding', 'links' => [['rel' => 'self', 'href' => URL::full()]] ], 500); }); /* |-------------------------------------------------------------------------- | Database Error |-------------------------------------------------------------------------- | | The Relational Database doesn't respond to Requests. | */ App::error(function(\Doctrine\DBAL\ConnectionException $e) { return Response::json([ 'reason' => 'The Database server is not responding', 'links' => [['rel' => 'self', 'href' => URL::full()]] ], 500); });
{ "content_hash": "aae5397115b33ebce87ee365dfb03d69", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 97, "avg_line_length": 27.07185628742515, "alnum_prop": 0.4366290643662906, "repo_name": "noherczeg/RestExt", "id": "6d4920afe6221c0373ec10b688c01e3d9b3694e6", "size": "4521", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extra/errors.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "72058" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <div id="content-wrapper"> <div id="main-content"> <?php if(is_array($response)){ print_r($response); } if(isset($response) && ! is_array($response)){ echo '<br/> Encrypted Data: '.$response; } if(isset($result)){ if(is_array($result)) echo '<br/> Decrypted Data: '.print_r($result); else echo '<br/> Decrypted Data: '.$result; } if(isset($returnparam)){ //echo '<br/> Return Param: '.print_r($returnparam); } ?> </div> </div>
{ "content_hash": "edf430bd0cd718603b484ef331d0512e", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 72, "avg_line_length": 26.379310344827587, "alnum_prop": 0.4222222222222222, "repo_name": "bicpu/gps-beta", "id": "00ddd28e2ce097e215f72dcf8a391623c64556ee", "size": "765", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "application/views/payment/test.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "158040" }, { "name": "HTML", "bytes": "153765" }, { "name": "JavaScript", "bytes": "3179936" }, { "name": "PHP", "bytes": "5626720" } ], "symlink_target": "" }
package testutil
{ "content_hash": "4fe89efcaa13773c0efca7134fec1ab8", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 16, "avg_line_length": 17, "alnum_prop": 0.8823529411764706, "repo_name": "luci/luci-go", "id": "ed7b54ba18073a7ba828befe2ab6fdd3f6798f77", "size": "685", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "cipd/appengine/impl/testutil/doc.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25460" }, { "name": "Go", "bytes": "10674259" }, { "name": "HTML", "bytes": "658081" }, { "name": "JavaScript", "bytes": "18433" }, { "name": "Makefile", "bytes": "2862" }, { "name": "Python", "bytes": "49205" }, { "name": "Shell", "bytes": "20986" }, { "name": "TypeScript", "bytes": "110221" } ], "symlink_target": "" }
audioCaptureDuration="30s" # Where to save the volume adjustments volumeDB="$HOME/can-you-hear-me/volume.csv" # Which output device to choose (change if it doesn't work) outputDevice="auto" # End configuration outputDevices="$(pacmd list-sinks | grep -e 'name:' -e 'index' -e 'Speakers' | grep 'name')" numberOfOutputDevices=$(echo "$outputDevices" | wc -l) # Check if volume database exists; if not create it with a csv header if [ ! -f "$volumeDB" ]; then echo "Date,Avg Output" >> "$volumeDB" fi # try to find a suitable output device if [ "$outputDevice" == "auto" ]; then if (( numberOfOutputDevices > 1 )); then echo "Warning: You have the following output devices: $outputDevices . I'll select the first one by default, but you should change it in the configuration settings." outputDevices=$(echo "$outputDevices" | head -n 1) elif (( numberOfOutputDevices == 0 )); then echo "Error: I can't find any output devices." exit fi fi # get the average output volume outputVolumeFormatted=$(parec -d $(echo "$outputDevices" | # get the name of it cut -d '<' -f 2 | cut -d '>' -f 1).monitor | # format the name so it works with lame (timeout $audioCaptureDuration lame -r -V0 -) | # record for X seconds to stdout ffmpeg -i pipe:0 -af "volumedetect" -f null /dev/null 2>&1 | # pipe audio to ffmpeg, get mean volume in dB grep "mean_volume" | rev | cut -d " " -f 1-2 | rev) # extract dB from output; save to file # get the output volume, and round it so that bash can use it outputVolumeDb=$(echo "$outputVolumeFormatted" | cut -d " " -f 1 | awk '{print int($1+0.5)}') if ((outputVolumeDb < -65 )); then echo "Warning: I didn't detect any sound. Make sure that your output device is correctly selected." fi date=$(date) # write results to file echo "$date,$outputVolumeFormatted" >> "$volumeDB" # Credits # http://unix.stackexchange.com/questions/89571/how-to-get-volume-level-from-the-command-line # http://superuser.com/questions/323119/how-can-i-normalize-audio-using-ffmpeg # http://askubuntu.com/questions/229352/how-to-record-output-to-speakers # http://stackoverflow.com/questions/2395284/round-a-divided-number-in-bash
{ "content_hash": "3afb335c2d4510f603a90cbed1339b13", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 167, "avg_line_length": 39.892857142857146, "alnum_prop": 0.6866606982990152, "repo_name": "Decagon/can-you-hear-me", "id": "1277705ace0d2ca587022fbc2b92eb99ee980a8d", "size": "2358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "can-you-hear-me.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "2358" } ], "symlink_target": "" }
import argparse from models.dense_net import DenseNet from data_providers.utils import get_data_provider_by_name train_params_cifar = { 'batch_size': 64, 'n_epochs': 300, 'initial_learning_rate': 0.1, 'reduce_lr_epoch_1': 150, # epochs * 0.5 'reduce_lr_epoch_2': 225, # epochs * 0.75 'validation_set': True, 'validation_split': None, # None or float 'shuffle': 'every_epoch', # None, once_prior_train, every_epoch 'normalization': 'by_chanels', # None, divide_256, divide_255, by_chanels } train_params_svhn = { 'batch_size': 64, 'n_epochs': 40, 'initial_learning_rate': 0.1, 'reduce_lr_epoch_1': 20, 'reduce_lr_epoch_2': 30, 'validation_set': True, 'validation_split': None, # you may set it 6000 as in the paper 'shuffle': True, # shuffle dataset every epoch or not 'normalization': 'divide_255', } def get_train_params_by_name(name): if name in ['C10', 'C10+', 'C100', 'C100+']: return train_params_cifar if name == 'SVHN': return train_params_svhn if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--train', action='store_true', help='Train the model') parser.add_argument( '--test', action='store_true', help='Test model for required dataset if pretrained model exists.' 'If provided together with `--train` flag testing will be' 'performed right after training.') parser.add_argument( '--model_type', '-m', type=str, choices=['DenseNet', 'DenseNet-BC'], default='DenseNet', help='What type of model to use') parser.add_argument( '--growth_rate', '-k', type=int, choices=[12, 24, 40], default=12, help='Grows rate for every layer, ' 'choices were restricted to used in paper') parser.add_argument( '--depth', '-d', type=int, choices=[40, 100, 190, 250], default=40, help='Depth of whole network, restricted to paper choices') parser.add_argument( '--dataset', '-ds', type=str, choices=['C10', 'C10+', 'C100', 'C100+', 'SVHN'], default='C10', help='What dataset should be used') parser.add_argument( '--total_blocks', '-tb', type=int, default=3, metavar='', help='Total blocks of layers stack (default: %(default)s)') parser.add_argument( '--keep_prob', '-kp', type=float, metavar='', help="Keep probability for dropout.") parser.add_argument( '--weight_decay', '-wd', type=float, default=1e-4, metavar='', help='Weight decay for optimizer (default: %(default)s)') parser.add_argument( '--nesterov_momentum', '-nm', type=float, default=0.9, metavar='', help='Nesterov momentum (default: %(default)s)') parser.add_argument( '--reduction', '-red', type=float, default=0.5, metavar='', help='reduction Theta at transition layer for DenseNets-BC models') parser.add_argument( '--logs', dest='should_save_logs', action='store_true', help='Write tensorflow logs') parser.add_argument( '--no-logs', dest='should_save_logs', action='store_false', help='Do not write tensorflow logs') parser.set_defaults(should_save_logs=True) parser.add_argument( '--saves', dest='should_save_model', action='store_true', help='Save model during training') parser.add_argument( '--no-saves', dest='should_save_model', action='store_false', help='Do not save model during training') parser.set_defaults(should_save_model=True) parser.add_argument( '--renew-logs', dest='renew_logs', action='store_true', help='Erase previous logs for model if exists.') parser.add_argument( '--not-renew-logs', dest='renew_logs', action='store_false', help='Do not erase previous logs for model if exists.') parser.add_argument( '--num_inter_threads', '-inter', type=int, default=1, metavar='', help='number of inter threads for inference / test') parser.add_argument( '--num_intra_threads', '-intra', type=int, default=128, metavar='', help='number of intra threads for inference / test') parser.set_defaults(renew_logs=True) args = parser.parse_args() if not args.keep_prob: if args.dataset in ['C10', 'C100', 'SVHN']: args.keep_prob = 0.8 else: args.keep_prob = 1.0 if args.model_type == 'DenseNet': args.bc_mode = False args.reduction = 1.0 elif args.model_type == 'DenseNet-BC': args.bc_mode = True model_params = vars(args) if not args.train and not args.test: print("You should train or test your network. Please check params.") exit() # some default params dataset/architecture related train_params = get_train_params_by_name(args.dataset) print("Params:") for k, v in model_params.items(): print("\t%s: %s" % (k, v)) print("Train params:") for k, v in train_params.items(): print("\t%s: %s" % (k, v)) print("Prepare training data...") data_provider = get_data_provider_by_name(args.dataset, train_params) print("Initialize the model..") model = DenseNet(data_provider=data_provider, **model_params) if args.train: print("Data provider train images: ", data_provider.train.num_examples) model.train_all_epochs(train_params) if args.test: if not args.train: model.load_model() print("Data provider test images: ", data_provider.test.num_examples) print("Testing...") loss, accuracy = model.test(data_provider.test, batch_size=200) print("mean cross_entropy: %f, mean accuracy: %f" % (loss, accuracy))
{ "content_hash": "3602bb184d70bd15fe934cf54fa957c4", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 79, "avg_line_length": 37.493589743589745, "alnum_prop": 0.6060865105146179, "repo_name": "ikhlestov/vision_networks", "id": "46a107d0ae75d01ad21ea1ad479227d2bcb899c8", "size": "5849", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "run_dense_net.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "48855" } ], "symlink_target": "" }
sudo -v sudo apt-get install -y default-jre sudo apt-get install -y default-jdk
{ "content_hash": "a029314fa55a3618eefa16d84d93fe2d", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 35, "avg_line_length": 27, "alnum_prop": 0.7530864197530864, "repo_name": "idf/bootstraping", "id": "7d1f4b3df767f8ca17c61c0f54d9cb839d020791", "size": "81", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ubuntu_java.sh", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Shell", "bytes": "8210" } ], "symlink_target": "" }
* Kubernetes 1.8+ ## Chart Details This chart will do the following: * Optionally deploy PostgreSQL, MongoDB * Deploy RabbitMQ (optionally as an HA cluster) * Deploy JFrog Xray micro-services ## Requirements - A running Kubernetes cluster - Dynamic storage provisioning enabled - Default StorageClass set to allow services using the default StorageClass for persistent storage - A running Artifactory - [Kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) installed and setup to use the cluster - [Helm](https://helm.sh/) installed and setup to use the cluster (helm init) ## Deploy JFrog Xray ```bash # cd to directory that includes untar version of helm charts helm install -n xray --set replicaCount=2,rabbitmq-ha.replicaCount=2,common.masterKey=${MASTER_KEY} incubator/xray # Passing the imagePullSecrets to authenticate with Bintray and download E+ docker images. helm upgrade xray --set replicaCount=3,rabbitmq-ha.replicaCount=3,common.masterKey=${MASTER_KEY} incubator/xray ``` ### Deploy Xray Deploy the Xray tools and services ```bash # Get required dependency charts $ helm dependency update incubator/xray # Deploy Xray $ helm install -n xray incubator/xray ``` ## Status See the status of your deployed **helm** releases ```bash $ helm status xray ``` ## Upgrade To upgrade an existing Xray, you still use **helm** ```bash # Update existing deployed version to 2.1.0 $ helm upgrade --set common.xrayVersion=2.1.0 incubator/xray ``` ## Remove Removing a **helm** release is done with ```bash # Remove the Xray services and data tools $ helm delete --purge xray # Remove the data disks $ kubectl delete pvc -l release=xray ``` ### Create a unique Master Key JFrog Xray requires a unique master key to be used by all micro-services in the same cluster. By default the chart has one set in values.yaml (`common.masterKey`). **This key is for demo purpose and should not be used in a production environment!** You should generate a unique one and pass it to the template at install/upgrade time. ```bash # Create a key $ export MASTER_KEY=$(openssl rand -hex 32) $ echo ${MASTER_KEY} # Pass the created master key to helm $ helm install --set common.masterKey=${MASTER_KEY} -n xray incubator/xray ``` **NOTE:** Make sure to pass the same master key with `--set common.masterKey=${MASTER_KEY}` on all future calls to `helm install` and `helm upgrade`! ## Special deployments This is a list of special use cases for non-standard deployments ### High Availability For **high availability** of Xray, just need to set the replica count per pod be equal or higher than **2**. Recommended is **3**. > It is highly recommended to also set **RabbitMQ** to run as an HA cluster. ```bash # Start Xray with 3 replicas per service and 3 replicas for RabbitMQ $ helm install -n xray --set replicaCount=3,rabbitmq-ha.replicaCount=3 incubator/xray ``` ### External Databases There is an option to use external database services (MongoDB or PostgreSQL) for your Xray. #### MongoDB To use an external **MongoDB**, You need to set Xray **MongoDB** connection URL. For this, pass the parameter: `global.mongoUrl=${XRAY_MONGODB_CONN_URL}`. **IMPORTANT:** Make sure the DB is already created before deploying Xray services ```bash # Passing a custom MongoDB to Xray # Example # MongoDB host: custom-mongodb.local # MongoDB port: 27017 # MongoDB user: xray # MongoDB password: password1_X $ export XRAY_MONGODB_CONN_URL='mongodb://${MONGODB_USER}:${MONGODB_PASSWORD}@custom-mongodb.local:27017/?authSource=${MONGODB_DATABSE}&authMechanism=SCRAM-SHA-1' $ helm install -n xray --set global.mongoUrl=${XRAY_MONGODB_CONN_URL} incubator/xray ``` #### PostgreSQL To use an external **PostgreSQL**, You need to disable the use of the bundled **PostgreSQL** and set a custom **PostgreSQL** connection URL. For this, pass the parameters: `postgresql.enabled=false` and `global.postgresqlUrl=${XRAY_POSTGRESQL_CONN_URL}`. **IMPORTANT:** Make sure the DB is already created before deploying Xray services ```bash # Passing a custom PostgreSQL to Xray # Example # PostgreSQL host: custom-postgresql.local # PostgreSQL port: 5432 # PostgreSQL user: xray # PostgreSQL password: password2_X $ export XRAY_POSTGRESQL_CONN_URL='postgres://${POSTGRESQL_USER}:${POSTGRESQL_PASSWORD}@custom-postgresql.local:5432/${POSTGRESQL_DATABASE}?sslmode=disable' $ helm install -n xray --set postgresql.enabled=false,global.postgresqlUrl=${XRAY_POSTGRESQL_CONN_URL} incubator/xray ``` ## Configuration The following table lists the configurable parameters of the artifactory chart and their default values. | Parameter | Description | Default | |------------------------------|--------------------------------------------------|------------------------------------| | `imagePullSecrets` | Docker registry pull secret | | | `imagePullPolicy` | Container pull policy | `IfNotPresent` | | `initContainerImage` | Init container image | `alpine:3.6` | | `replicaCount` | Replica count for Xray services | `1` | | `postgresql.enabled` | Use enclosed PostgreSQL as database | `true` | | `postgresql.postgresDatabase` | PostgreSQL database name | `xraydb` | | `postgresql.postgresUser` | PostgreSQL database user | `xray` | | `postgresql.postgresPassword` | PostgreSQL database password | ` ` | | `postgresql.persistence.enabled` | PostgreSQL use persistent storage | `true` | | `postgresql.persistence.size` | PostgreSQL persistent storage size | `50Gi` | | `postgresql.persistence.existingClaim` | PostgreSQL use existing persistent storage | ` ` | | `postgresql.service.port` | PostgreSQL database port | `5432` | | `postgresql.resources.requests.memory` | PostgreSQL initial memory request | | | `postgresql.resources.requests.cpu` | PostgreSQL initial cpu request | | | `postgresql.resources.limits.memory` | PostgreSQL memory limit | | | `postgresql.resources.limits.cpu` | PostgreSQL cpu limit | | | `mongodb.enabled` | Enable Mongodb | `true` | | `mongodb.image.tag` | Mongodb docker image tag | `3.6.3` | | `mongodb.image.pullPolicy` | Mongodb Container pull policy | `IfNotPresent` | | `mongodb.persistence.enabled` | Mongodb persistence volume enabled | `true` | | `mongodb.persistence.existingClaim` | Use an existing PVC to persist data | `nil` | | `mongodb.persistence.storageClass` | Storage class of backing PVC | `generic` | | `mongodb.persistence.size` | Mongodb persistence volume size | `50Gi` | | `mongodb.livenessProbe.initialDelaySeconds` | Mongodb delay before liveness probe is initiated | ` ` | | `mongodb.readinessProbe.initialDelaySeconds`| Mongodb delay before readiness probe is initiated | ` ` | | `mongodb.mongodbExtraFlags` | MongoDB additional command line flags | `["--wiredTigerCacheSizeGB=1"]`| | `mongodb.mongodbDatabase` | Mongodb Database for Xray | `xray` | | `mongodb.mongodbRootPassword` | Mongodb Database Password for root user | ` ` | | `mongodb.mongodbUsername` | Mongodb Database Xray User | `admin` | | `mongodb.mongodbPassword` | Mongodb Database Password for Xray User | ` ` | | `rabbitmq-ha.replicaCount` | RabbitMQ Number of replica | `1` | | `rabbitmq-ha.rabbitmqUsername` | RabbitMQ application username | `guest` | | `rabbitmq-ha.rabbitmqPassword` | RabbitMQ application password | ` ` | | `rabbitmq-ha.customConfigMap` | RabbitMQ Use a custom ConfigMap | `true` | | `rabbitmq-ha.rabbitmqErlangCookie` | RabbitMQ Erlang cookie | `XRAYRABBITMQCLUSTER`| | `rabbitmq-ha.rabbitmqMemoryHighWatermark` | RabbitMQ Memory high watermark | `500MB` | | `rabbitmq-ha.persistentVolume.enabled` | If `true`, persistent volume claims are created | `true` | | `rabbitmq-ha.persistentVolume.size` | RabbitMQ Persistent volume size | `20Gi` | | `rabbitmq-ha.rbac.create` | If true, create & use RBAC resources | `false` | | `common.xrayVersion` | Xray image tag | `2.1.0` | | `common.xrayConfigPath` | Xray config path | `/var/opt/jfrog/xray/data` | | `common.xrayUserId` | Xray User Id | `1035` | | `common.xrayGroupId` | Xray Group Id | `1035` | | `common.stdOutEnabled` | Xray enable standard output | `true` | | `common.masterKey` | Xray Master Key Can be generated with `openssl rand -hex 32` | `FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF` | | `global.mongoUrl` | Xray external MongoDB URL | ` ` | | `global.postgresqlUrl` | Xray external PostgresSQL URL | ` ` | | `analysis.name` | Xray Analysis name | `xray-analysis` | | `analysis.image` | Xray Analysis container image | `docker.bintray.io/jfrog/xray-analysis` | | `analysis.internalPort` | Xray Analysis internal port | `7000` | | `analysis.externalPort` | Xray Analysis external port | `7000` | | `analysis.service.type` | Xray Analysis service type | `ClusterIP` | | `analysis.storage.sizeLimit` | Xray Analysis storage size limit | `10Gi` | | `analysis.resources` | Xray Analysis resources | `{}` | | `indexer.name` | Xray Indexer name | `xray-indexer` | | `indexer.image` | Xray Indexer container image | `docker.bintray.io/jfrog/xray-indexer` | | `indexer.internalPort` | Xray Indexer internal port | `7002` | | `indexer.externalPort` | Xray Indexer external port | `7002` | | `indexer.service.type` | Xray Indexer service type | `ClusterIP` | | `indexer.storage.sizeLimit` | Xray Indexer storage size limit | `10Gi` | | `indexer.resources` | Xray Indexer resources | `{}` | | `persist.name` | Xray Persist name | `xray-persist` | | `persist.image` | Xray Persist container image | `docker.bintray.io/jfrog/xray-persist` | | `persist.internalPort` | Xray Persist internal port | `7003` | | `persist.externalPort` | Xray Persist external port | `7003` | | `persist.service.type` | Xray Persist service type | `ClusterIP` | | `persist.storage.sizeLimit` | Xray Persist storage size limit | `10Gi` | | `persist.resources` | Xray Persist resources | `{}` | | `server.name` | Xray server name | `xray-server` | | `server.image` | Xray server container image | `docker.bintray.io/jfrog/xray-server` | | `server.internalPort` | Xray server internal port | `8000` | | `server.externalPort` | Xray server external port | `80` | | `server.service.name` | Xray server service name | `xray` | | `server.service.type` | Xray server service type | `LoadBalancer` | | `server.storage.sizeLimit` | Xray server storage size limit | `10Gi` | | `server.resources` | Xray server resources | `{}` | Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. ## Useful links - https://www.jfrog.com/confluence/display/XRAY/Xray+High+Availability - https://www.jfrog.com/confluence/display/EP/Getting+Started - https://www.jfrog.com/confluence/
{ "content_hash": "dcd20a56e1e29dd1f35bb7dbca78938b", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 163, "avg_line_length": 66.45622119815668, "alnum_prop": 0.5340822411760627, "repo_name": "caiwenhao/charts", "id": "ce9525cb3fbee8a524079a37d4b2cc0c2f69d973", "size": "14489", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "incubator/xray/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3406" }, { "name": "Go", "bytes": "8523" }, { "name": "Makefile", "bytes": "1692" }, { "name": "Python", "bytes": "2218" }, { "name": "Shell", "bytes": "52546" }, { "name": "Smarty", "bytes": "355537" } ], "symlink_target": "" }
const should = require('should'); const sinon = require('sinon'); const configUtils = require('../../../../utils/configUtils'); const imageTransform = require('@tryghost/image-transform'); const logging = require('../../../../../core/shared/logging'); const normalize = require('../../../../../core/server/web/api/middleware/normalize-image'); describe('normalize', function () { let res; let req; beforeEach(function () { req = { file: { name: 'test', path: '/test/path', ext: '.jpg' } }; sinon.stub(imageTransform, 'resizeFromPath'); sinon.stub(logging, 'error'); }); afterEach(function () { sinon.restore(); configUtils.restore(); }); it('should do manipulation by default', function (done) { imageTransform.resizeFromPath.resolves(); normalize(req, res, function () { imageTransform.resizeFromPath.calledOnce.should.be.true(); done(); }); }); it('should add files array to request object with original and resized files', function (done) { imageTransform.resizeFromPath.resolves(); normalize(req, res, function () { req.files.length.should.be.equal(2); done(); }); }); it('should not do manipulation without resize flag set', function (done) { configUtils.set({ imageOptimization: { resize: false } }); normalize(req, res, function () { imageTransform.resizeFromPath.called.should.be.false(); done(); }); }); it('should not create files array when resizing fails', function (done) { imageTransform.resizeFromPath.rejects(); normalize(req, res, () => { logging.error.calledOnce.should.be.true(); req.file.should.not.be.equal(undefined); should.not.exist(req.files); done(); }); }); ['.gif', '.svg', '.svgz'].forEach(function (extension) { it(`should skip resizing when file extension is ${extension}`, function (done) { req.file.ext = extension; normalize(req, res, function () { req.file.should.not.be.equal(undefined); should.not.exist(req.files); done(); }); }); }); });
{ "content_hash": "78c703d392ae283f5755d0afdf828158", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 100, "avg_line_length": 29.73170731707317, "alnum_prop": 0.5373256767842494, "repo_name": "bitjson/Ghost", "id": "a467aaa733c84f997bb952587bd1cd9012679192", "size": "2438", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/unit/web/api/middleware/normalize-image_spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "106334" }, { "name": "HTML", "bytes": "97186" }, { "name": "Handlebars", "bytes": "77516" }, { "name": "JavaScript", "bytes": "2085284" }, { "name": "XSLT", "bytes": "7177" } ], "symlink_target": "" }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * CreateImageResponseType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.amazon.ec2; /** * CreateImageResponseType bean class */ public class CreateImageResponseType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = CreateImageResponseType Namespace URI = http://ec2.amazonaws.com/doc/2010-11-15/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2010-11-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for RequestId */ protected java.lang.String localRequestId ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getRequestId(){ return localRequestId; } /** * Auto generated setter method * @param param RequestId */ public void setRequestId(java.lang.String param){ this.localRequestId=param; } /** * field for ImageId */ protected java.lang.String localImageId ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getImageId(){ return localImageId; } /** * Auto generated setter method * @param param ImageId */ public void setImageId(java.lang.String param){ this.localImageId=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { CreateImageResponseType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2010-11-15/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":CreateImageResponseType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "CreateImageResponseType", xmlWriter); } } namespace = "http://ec2.amazonaws.com/doc/2010-11-15/"; if (! namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); xmlWriter.writeStartElement(prefix,"requestId", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace,"requestId"); } } else { xmlWriter.writeStartElement("requestId"); } if (localRequestId==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!"); }else{ xmlWriter.writeCharacters(localRequestId); } xmlWriter.writeEndElement(); namespace = "http://ec2.amazonaws.com/doc/2010-11-15/"; if (! namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); xmlWriter.writeStartElement(prefix,"imageId", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace,"imageId"); } } else { xmlWriter.writeStartElement("imageId"); } if (localImageId==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("imageId cannot be null!!"); }else{ xmlWriter.writeCharacters(localImageId); } xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/", "requestId")); if (localRequestId != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localRequestId)); } else { throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!"); } elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/", "imageId")); if (localImageId != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localImageId)); } else { throw new org.apache.axis2.databinding.ADBException("imageId cannot be null!!"); } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static CreateImageResponseType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ CreateImageResponseType object = new CreateImageResponseType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"CreateImageResponseType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (CreateImageResponseType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","requestId").equals(reader.getName())){ java.lang.String content = reader.getElementText(); object.setRequestId( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","imageId").equals(reader.getName())){ java.lang.String content = reader.getElementText(); object.setImageId( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
{ "content_hash": "b444179d808605ecabd88fb2138f8829", "timestamp": "", "source": "github", "line_count": 591, "max_line_length": 179, "avg_line_length": 45.51945854483925, "alnum_prop": 0.45134190766485766, "repo_name": "argv0/cloudstack", "id": "dbcaca07008e6d6e2d1e441afbb9a812cb3bc9ed", "size": "26902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "awsapi/src/com/amazon/ec2/CreateImageResponseType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "52484672" }, { "name": "JavaScript", "bytes": "1913801" }, { "name": "Perl", "bytes": "824212" }, { "name": "Python", "bytes": "2076246" }, { "name": "Ruby", "bytes": "2166" }, { "name": "Shell", "bytes": "445096" } ], "symlink_target": "" }
package org.apache.camel.component.nagios; import java.util.HashMap; import java.util.Map; import com.googlecode.jsendnsca.Level; import com.googlecode.jsendnsca.MessagePayload; import com.googlecode.jsendnsca.NagiosPassiveCheckSender; import com.googlecode.jsendnsca.PassiveCheckSender; import org.apache.camel.BindToRegistry; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class NagiosTest extends CamelTestSupport { @Mock @BindToRegistry("mySender") protected static PassiveCheckSender nagiosPassiveCheckSender; protected boolean canRun; @BeforeClass public static void setSender() { nagiosPassiveCheckSender = Mockito.mock(NagiosPassiveCheckSender.class); } @Before @Override public void setUp() throws Exception { canRun = true; super.setUp(); } @Test public void testSendToNagios() throws Exception { if (!canRun) { return; } MessagePayload expectedPayload = new MessagePayload("localhost", Level.OK, context.getName(), "Hello Nagios"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.allMessages().body().isInstanceOf(String.class); mock.expectedBodiesReceived("Hello Nagios"); template.sendBody("direct:start", "Hello Nagios"); assertMockEndpointsSatisfied(); verify(nagiosPassiveCheckSender, times(1)).send(expectedPayload); } @Test public void testSendTwoToNagios() throws Exception { if (!canRun) { return; } MessagePayload expectedPayload1 = new MessagePayload("localhost", Level.OK, context.getName(), "Hello Nagios"); MessagePayload expectedPayload2 = new MessagePayload("localhost", Level.OK, context.getName(), "Bye Nagios"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(2); mock.allMessages().body().isInstanceOf(String.class); mock.expectedBodiesReceived("Hello Nagios", "Bye Nagios"); template.sendBody("direct:start", "Hello Nagios"); template.sendBody("direct:start", "Bye Nagios"); assertMockEndpointsSatisfied(); verify(nagiosPassiveCheckSender).send(expectedPayload1); verify(nagiosPassiveCheckSender).send(expectedPayload2); } @Test public void testSendToNagiosWarn() throws Exception { if (!canRun) { return; } MessagePayload expectedPayload1 = new MessagePayload("localhost", Level.WARNING, context.getName(), "Hello Nagios"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedBodiesReceived("Hello Nagios"); template.sendBodyAndHeader("direct:start", "Hello Nagios", NagiosConstants.LEVEL, Level.WARNING); assertMockEndpointsSatisfied(); verify(nagiosPassiveCheckSender).send(expectedPayload1); } @Test public void testSendToNagiosWarnAsText() throws Exception { if (!canRun) { return; } MessagePayload expectedPayload1 = new MessagePayload("localhost", Level.WARNING, context.getName(), "Hello Nagios"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedBodiesReceived("Hello Nagios"); template.sendBodyAndHeader("direct:start", "Hello Nagios", NagiosConstants.LEVEL, "WARNING"); assertMockEndpointsSatisfied(); verify(nagiosPassiveCheckSender).send(expectedPayload1); } @Test public void testSendToNagiosMultiHeaders() throws Exception { if (!canRun) { return; } MessagePayload expectedPayload1 = new MessagePayload("myHost", Level.CRITICAL, "myService", "Hello Nagios"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedBodiesReceived("Hello Nagios"); Map<String, Object> headers = new HashMap<>(); headers.put(NagiosConstants.LEVEL, "CRITICAL"); headers.put(NagiosConstants.HOST_NAME, "myHost"); headers.put(NagiosConstants.SERVICE_NAME, "myService"); template.sendBodyAndHeaders("direct:start", "Hello Nagios", headers); assertMockEndpointsSatisfied(); verify(nagiosPassiveCheckSender).send(expectedPayload1); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .to("nagios:127.0.0.1:25664?password=secret&sender=#mySender") .to("mock:result"); } }; } }
{ "content_hash": "41ca97beea0ebaf7ff9a4f25b20f1644", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 125, "avg_line_length": 33.33766233766234, "alnum_prop": 0.6782236073237242, "repo_name": "zregvart/camel", "id": "c7302bd4b193663cf3b022431c7c47a62d82e359", "size": "5936", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "components/camel-nagios/src/test/java/org/apache/camel/component/nagios/NagiosTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6521" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "20938" }, { "name": "HTML", "bytes": "914791" }, { "name": "Java", "bytes": "90321137" }, { "name": "JavaScript", "bytes": "101298" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Shell", "bytes": "11165" }, { "name": "TSQL", "bytes": "28835" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "280849" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Jcb_Ckgl { public partial class Jcb_Ckgl_Add { } }
{ "content_hash": "eca1bf27e3457689c13c59afdff41907", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 81, "avg_line_length": 30.266666666666666, "alnum_prop": 0.3832599118942731, "repo_name": "SpiderLoveFish/ZJCRM", "id": "a83c374e508d69dc9a66d84e37d3e5e63535d79a", "size": "456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CRM/CRM/KcGl/Jcb_Ckgl_Add.aspx.designer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "5243496" }, { "name": "Batchfile", "bytes": "331" }, { "name": "C#", "bytes": "4627298" }, { "name": "CSS", "bytes": "999250" }, { "name": "HTML", "bytes": "609995" }, { "name": "JavaScript", "bytes": "6918765" } ], "symlink_target": "" }
package com.fluent.pgm.mixtures; import com.fluent.collections.FList; import com.fluent.collections.FListMultiMap; import com.fluent.collections.FMap; import com.fluent.core.*; import com.fluent.math.*; import com.google.common.util.concurrent.AtomicDouble; import org.slf4j.Logger; import java.io.IOException; import java.nio.file.Paths; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import static com.fluent.collections.Lists.parse; import static com.fluent.core.oo.*; import static com.fluent.pgm.mixtures.Common.SEED_1; import static com.fluent.pgm.mixtures.Estimation.Estimation; import static com.fluent.pgm.mixtures.Generation.Generation; import static com.fluent.pgm.mixtures.IO.IO; import static com.fluent.pgm.mixtures.Inference.Inference; import static com.fluent.pgm.mixtures.Initialisation.Initialisation; import static com.fluent.pgm.mixtures.Initialisation.Options; import static com.fluent.pgm.mixtures.Optimisation.Optimisation; import static com.fluent.pgm.mixtures.Token.MISSING; import static com.fluent.util.WriteLines.Write_Lines; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Math.log10; import static java.lang.Runtime.getRuntime; import static java.lang.String.format; import static java.util.concurrent.Executors.newFixedThreadPool; import static org.slf4j.LoggerFactory.getLogger; public class Easy { public static final Easy Easy = new Easy(); private static final Logger log = getLogger(Easy.getClass()); // Initialisation init; Estimation estimate; Optimisation optimise; IO io; Inference infer; Generation generate; Easy(IO io, Inference infer, Initialisation init, Estimation estimate, Optimisation optimise, Generation generate) { this.io = io; this.infer = infer; this.init = init; this.estimate = estimate; this.optimise = optimise; this.generate = generate; } Easy() { this(IO, Inference, Initialisation, Estimation, Optimisation, Generation); } public MoMC character_mixture_from_untagged(String data_file, String model_file) throws Exception { return mixture_from(data_file, Sequence::from_chars, model_file); } public MoMC mixture_from(String data_file, F1<String, Sequence> pipeline, String model_file, Options options) throws Exception { FList<Sequence> data = io.data_from(data_file, pipeline); ExecutorService executor = newFixedThreadPool(thread_count()); OP1<MoMC> em = model -> estimate.reestimate(model , data.split(thread_count()), executor); F3<MoMC, OP1<MoMC>, Condition<MoMC>, MoMC> optimised = optimise::optimise; MoMC model = optimised.and_then(estimate::smooth) .of(init.initialise_with(data, options), em, stopping_criterion(data, 99.99, 10)); executor.shutdown(); io.to_json(model, Paths.get(model_file)); return model; } public MoMC mixture_from(String data_file, F1<String, Sequence> pipeline, String model_file) throws Exception { return mixture_from(data_file,pipeline,model_file,Options.DEFAULT); } public String complete_characters(String datum, String model_file) throws IOException { FList<Token> tokens = parse(datum, "").apply(chunk -> chunk.equals("¬") ? MISSING : Token.from(chunk)) .minus(Token.from("")); return infer.complete(Sequence.from(tokens), io.model_from(Paths.get(model_file))).toString(); } public FList<Sequence> untagged_data_from(String model_file, String data_file, int N) throws IOException { FList<Sequence> data = generate.generate_untagged(N, io.model_from(Paths.get(model_file)), SEED_1); Write_Lines.to(Paths.get(data_file), data); return data; } public MoMC character_mixture_from_tagged(String data_directory, String output_file) throws Exception { MoMC model = estimate.estimate(io.tagged_char_data_from(data_directory)); io.to_json(model, Paths.get(output_file)); return model; } public String tag_characters(String untagged, String model_file) throws IOException { final Sequence sequence = Sequence.from_chars(untagged); final MoMC model = io.model_from(Paths.get(model_file)); return infer.joint(sequence, model).max_as((tag, posterior) -> posterior).$1; } public FMap<String, P> fuzzy_tag_characters(String untagged, String model_file) throws IOException { final Sequence sequence = Sequence.from_chars(untagged); final MoMC model = io.model_from(Paths.get(model_file)); return infer.posterior_density(sequence, model); } public FList<oo<Sequence, String>> tagged_data_from(String model_file, String data_directory, int N) throws IOException { FList<oo<Sequence, String>> data = generate.generate_tagged(N, io.model_from(Paths.get(model_file)), SEED_1); FListMultiMap<String, Sequence> tag_to_sequences = data.groupBy(sequence_with_tag -> sequence_with_tag.$2) .apply((tag, sequences_with_tags) -> oo(tag, sequences_with_tags.apply(sequence_with_tag -> sequence_with_tag.$1))); Write_Lines.to(Paths.get(data_directory), tag_to_sequences); return data; } static int thread_count() { return getRuntime().availableProcessors(); } Condition<MoMC> stopping_criterion(FList<Sequence> data, double percent_convergence, int min_improvement_iterations) { AtomicDouble old_loglikelihood = new AtomicDouble(NEGATIVE_INFINITY); AtomicInteger iteration = new AtomicInteger(); AtomicInteger improvement_iterations = new AtomicInteger(); double log_percent_convergence = log10(percent_convergence); return model -> { double loglikelihood = infer.likelihood(model, data).asLog(); log.info(format("em iteration [%04d] log-likelihood [%15.8f]", iteration.getAndIncrement(), loglikelihood)); boolean improved = (2 + old_loglikelihood.getAndSet(loglikelihood) - loglikelihood) > log_percent_convergence; improvement_iterations.getAndAdd(improved ? 1 : -improvement_iterations.get()); return improvement_iterations.get() >= min_improvement_iterations; }; } }
{ "content_hash": "8cff9eacd31716953e330535b0b7b954", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 117, "avg_line_length": 37.022222222222226, "alnum_prop": 0.6733193277310925, "repo_name": "JoseLlarena/Mixtures-Of-Markov-Chains", "id": "7e781dc1a05340bd362a07c14094abf655c08afd", "size": "6665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/fluent/pgm/mixtures/Easy.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "64856" } ], "symlink_target": "" }
jQuery(document).ready(function($){ //Put Your Custom Jquery or Javascript Code Here });
{ "content_hash": "3adaeef69f6a24a0681eb098fb7fc37a", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 49, "avg_line_length": 23.5, "alnum_prop": 0.7021276595744681, "repo_name": "senerudev/odox", "id": "87a3c668a0250f18bdf11a83080ebd8b91d79137", "size": "118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "custom/custom.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "268266" }, { "name": "JavaScript", "bytes": "1029023" }, { "name": "PHP", "bytes": "154494" }, { "name": "Shell", "bytes": "17" } ], "symlink_target": "" }
using System.IO; namespace TestFluentAssembly.TwoInterfaces { public interface IInterface1 { IInterface2 Iface2 { get; } } public interface IInterface2 { } }
{ "content_hash": "7405c263ceabf1426684f4411a4c3fe4", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 42, "avg_line_length": 13.857142857142858, "alnum_prop": 0.6443298969072165, "repo_name": "reinforced/Reinforced.Typings", "id": "0fcad4ec5539ac7622a90f314e6c4b056c391ff3", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TestFluentAssembly/TwoInterfaces.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "703383" }, { "name": "PowerShell", "bytes": "319" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "f6cf137dc1b2dfe9e8a246dda2199fb9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "1977e481d367557a915519217f34ba63f469bfc0", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Bryophyta/Bryopsida/Hypnales/Plagiotheciaceae/Pseudotaxiphyllum/Pseudotaxiphyllum falcifolium/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import 'core-js'; /** * Determines if the provided object is a navigation command. * A navigation command is anything with a navigate method. * * @param obj The object to check. */ export function isNavigationCommand(obj: any): boolean { return obj && typeof obj.navigate === 'function'; } /** * Used during the activation lifecycle to cause a redirect. */ export class Redirect { constructor(url: string, options: any = {}) { this.url = url; this.options = Object.assign({ trigger: true, replace: true }, options); this.shouldContinueProcessing = false; } /** * Called by the activation system to set the child router. * * @param router The router. */ setRouter(router: Router): void { this.router = router; } /** * Called by the navigation pipeline to navigate. * * @param appRouter The router to be redirected. */ navigate(appRouter: Router): void { let navigatingRouter = this.options.useAppRouter ? appRouter : (this.router || appRouter); navigatingRouter.navigate(this.url, this.options); } }
{ "content_hash": "f7df88e083bff6a85e2775ad8495c99b", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 94, "avg_line_length": 25.878048780487806, "alnum_prop": 0.6842601319509897, "repo_name": "milunka/router", "id": "f20fe1556f9df9005d545ae545a46b5678020a0b", "size": "1061", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/navigation-commands.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "366466" } ], "symlink_target": "" }
module AWS class SNS # A module shared between {Topic} and {Subscription}. Provides methods # for getting and setting the delivery policy and for getting the # effective delivery policy. module HasDeliveryPolicy # @return [nil,Hash] Returns the delivery policy. def delivery_policy parse_delivery_policy(delivery_policy_json) end # @return [Hash] Returns the effective delivery policy. def effective_delivery_policy parse_delivery_policy(effective_delivery_policy_json) end # @param [nil,Hash,String<JSON>] policy A delivery policy. You can # pass a JSON string, A policy hash or nil. def delivery_policy= policy policy_json = case policy when nil then '' when String then policy else policy.to_json end update_delivery_policy(policy_json) end # @return [nil,String] Returns the delivery policy JSON string. def delivery_policy_json raise NotImplementedError end # @return [String] Returns the effective delivery policy JSON string. def effective_delivery_policy_json raise NotImplementedError end protected def parse_delivery_policy policy_json policy_json.nil? ? nil : JSON.parse(policy_json) end protected def update_delivery_policy policy_json raise NotImplementedError end end end end
{ "content_hash": "77cdfbedba74f367b616abc936bde98e", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 75, "avg_line_length": 26.509090909090908, "alnum_prop": 0.6550068587105624, "repo_name": "wearelung/portoalegrecc", "id": "4fe38b4c2ecddb6a94a2dcc32a11efe1d8a48a65", "size": "2029", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/cache/ruby/1.8/gems/aws-sdk-1.3.4/lib/aws/sns/has_delivery_policy.rb", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "48011" }, { "name": "CSS", "bytes": "252438" }, { "name": "JavaScript", "bytes": "3519478" }, { "name": "PHP", "bytes": "52609" }, { "name": "Ruby", "bytes": "125149" }, { "name": "Shell", "bytes": "848" } ], "symlink_target": "" }
<!-- version alpha 0.5.1 --> <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="favicon.png" type="image/png" sizes="64x64"> <title>Sab-BOT-age</title> <link href='https://fonts.googleapis.com/css?family=Muli' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/jquery.stellar/0.6.2/jquery.stellar.min.js"></script> <script src="//cdn.rawgit.com/namuol/cheet.js/master/cheet.min.js" type="text/javascript"></script> <script src="jQueryRotate.js"></script> <!-- <script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.14.2/TweenMax.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script> --> <script> $(function(){ $.stellar({ horizontalScrolling: false, verticalOffset: 40 }); }); </script> <script> cheet('↑ ↑ ↓ ↓ ← → ← → b a', function () { document.body.style.fontFamily = "Comic Sans MS"; alert('What have you done?!'); }); </script> <link href="css/Style.css" rel="stylesheet" type="text/css"> <!-- jquery include --> <script> $(function(){ $("#includedHeader").load("header.html"); }); </script> <script> $(function(){ $("#includedFooter").load("footer.html"); }); </script> </head> <body> <!-- Feedback form link <div class="feedback" id="fd"><p id="ft">Please fill out this feedback form: <a id="fl" href="http://goo.gl/forms/ZjkhSWaanaQNhhH32">http://goo.gl/forms/ZjkhSWaanaQNhhH32</a>. It would be a huge help.</p><strong id="fx" onclick="$('#ft').css({'display': 'none'});$('#fl').css({'display': 'none'});$('#fx').css({'display': 'none'});$('#fd').css({'display': 'none'})">X</strong></div> <!-- remove before releasing --> <div class="container"> <section class="parallax" id="home_parallax1" data-stellar-background-ratio=".5" height="40%"> <!-- jquery include --> <div id="includedHeader"></div> <script> $(document).ready(function() { $(window).scroll(function () { console.log($(window).scrollTop()) if ($(window).scrollTop() > 0) { $('#nav_bar').addClass('navbar-fixed'); $('list_border').addClass('nav-spacer'); } if ($(window).scrollTop() < 1) { $('#nav_bar').removeClass('navbar-fixed'); } }); }); var ts1; ts1=0; </script> <h1 class="overlay_text" id="main_page_title">Downingtown Area Robotics</h1> <a class="overlay_description" href="socialmedia.html"> <!--<img class="social-media-img" src="images/Social Media/Social Media.png" onmouseover="this.src='images/Social Media/Social Media Under ph.png'" onmouseout="this.src='images/Social Media/Social Media.png'"> <div class="social-media-links"><p>placeholder</p></div> <p align="center"><a target="_blank" href="https://www.instagram.com/frc1640/"><img src="images/Social Media/Instagram.png" height=50></a> <a target="_blank" href="https://twitter.com/FRC1640"><img src="images/Social Media/Twitter.png" height=50></a> <a target="_blank" href="https://www.facebook.com/firstteam1640/"><img src="images/Social Media/Facebook.png" height=50></a> <a target="_blank" href="https://www.youtube.com/user/FRC1640"><img src="images/Social Media/YouTube.png" height=50></a></p> <p><img src="images/Social Media/YT_Light.png" height="50"></p> --> Check out Sab-BOT-age on social media</a><noscript class="overlay_description" id="noscript"><h1>This website will not work properly without javascript!</h1></noscript> </section> <section class="section" id="about"> <div class="spoiler-button" onclick="document.getElementById('slider1').style.maxheight=2500;if(ts1<1){$('#spoiler1').rotate({animateTo:90}); ts1=1;}else{$('#spoiler1').rotate({animateTo:0}); ts1=0;}"><hr><img src="images/arrow.png" height=60px id="spoiler1" align="left" style="margin-right:15px; margin-top:20px;"><h1 class="title_text" align="center">About</h1><hr></div> <div class="slider" id="slider1"> <p class="section_text" align="center">Now that competition season is over, FRC and FTC are currently on off-season schedules. This allows time to focus on things such as projects, learning, and outreach.</p> <p class="section_text" align="center">FRC Team 1640 had a good 2015-2016 season. With DEWBOT XII, the team ended up 3rd seed and finalist at Seneca as well as 3rd seed and champion at Westtown, the first FRC event 1640 has co-hosted with team 1391 Metal Moose. The team made it to eliminations at both MAR and the FIRST World Championship. Throughout the season, 1640 earned three engineering awards.</p> <p class="section_text" align="center">FTC Team 7314 had a phenomenal 2015-2016 season, winning the South Central PA Qualifying Tournament. This meant the team made it past qualifiers for the first time. Team 7314 was also champion at the PA Championship. The team did well in the East Super-Regional Championship Tournament. 7314 went on to do well as the only PA FTC team at the FIRST World Championship. The team also received two engineering awards during the season and were finalists at the Eastern Pennsylvania Qualifying tournament.</p> <p class="section_text" align="center"><strong>Contact us at <a href="mailto:FRC1640@gmail.com" target="_top" class="text_standout">FRC1640@gmail.com</a> - FRC 1640 is currently meeting Wednesday evenings 6:00-9:00pm; FTC 7314 is meeting Mondays 6:30-8:30pm; all at the CCIU TCHS Brandywine Campus, 443 Boot Road, Downingtown PA.</strong></p> <p class="section_text" align="center"><strong><a href="team1640.com" target="_top" class="text_standout">Find more information on the team wiki!</a></strong></p> </div> <article class="sponsors"> <hr><h1>Sponsors</h1><hr> <img src="images/sponsors/Boeing.svg" alt="Boeing" class="cards"/> <img src="images/sponsors/Comcast.png" alt="Comcast" class="cards"/> <img src="images/sponsors/CCIU.jpg" alt="Chester County Intermediate Unit" class="cards"/> <img src="images/sponsors/Herr's.jpg" alt="Herr's Foods" class="cards"/> <img src="images/sponsors/ASME.jpg" alt="American Society of Mechanical Engineers" class="cards"/> <br><strong>Ira Binder - Attorney at Law</strong><br><strong>The Featherman Family</strong> <hr> <h1>In Kind Donations</h1> <hr> <img src="images/sponsors/CMD.jpg" alt="Custom Machine and Design" class="cards"/> <img src="images/sponsors/SolidWorks.png" alt="Solidworks" class="cards"/> </article> </section> <!-- FRC --> <section class="parallax" data-stellar-background-ratio=".5" id="home_parallax2"> <h2 class="overlay_text">FRC 1640</h2> </section> <section class="section" id="about"> <p class="section_text" align="justify">FRC Team 1640 was founded with 12 students in 2005 by Downingtown East High School physics teacher Paul Sabatino. Prior to joining the Downingtown East faculty, Mr. Sabatino mentored FRC Team 104 in the West Chester School District.</p> <p class="section_text" align="justify">The team's name is Sab-BOT-age, in honor of Paul Sabatino's vital contributions.</p> <p class="section_text" align="justify">The FRC 1640 team now encompasses thirty five students from throughout Chester County and more than a dozen mentors. While the organization has expanded its scope to include a FIRST Tech Challenge team and hosts two FIRST LEGO League events annually, FRC 1640 remains solidly the core of Downingtown Area Robotic (DAR).</p> </section> <!-- FTC --> <section class="parallax" data-stellar-background-ratio=".5" id="home_parallax3"> <h2 class="overlay_text">FTC 7314</h2> </section> <section class="section" id="about"> <p class="section_text" align="justify">Before the 2013 Block Party season, FTC Team 7314 Sab-BOT-age was founded to give 7th and 8th graders an opportunity to participate in FIRST and robotics.</p> <p class="section_text" align="justify">FTC has quickly expanded in many areas including outreach, team size, performance, and more! This past season saw almost 15 students make it to the FIRST World Championship in St. Louis, Missouri. 7314 was the only Pennsylvania team to do so! FTC has joined and helped FRC 1640 in a number of outreach events including demos, scrimmages, and the Sab-BOT-age hosted FLL events.</p> </section> <!-- jquery include --> <div id="includedFooter"></div> </div> </body> </html>
{ "content_hash": "1cb017b4cba352c95884359dd749182e", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 552, "avg_line_length": 61.04195804195804, "alnum_prop": 0.683927139420323, "repo_name": "TrevorBoyce/trevorboyce.github.io", "id": "648d9dbfda7233823fa44538b8687c200ce46fcc", "size": "8745", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codetest.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5902" }, { "name": "HTML", "bytes": "28957" } ], "symlink_target": "" }
@interface VideoPlayer : NSObject { NSString *videoURL; } @property (nonatomic, retain) NSString *videoURL; - (void)play; @end
{ "content_hash": "926ed2140e8d80d6678817c5cc2391ab", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 49, "avg_line_length": 14.555555555555555, "alnum_prop": 0.7175572519083969, "repo_name": "soraxdesign/SoundCity", "id": "544955021a41ba75470461d07b38dedac96cf9df", "size": "296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classes/VideoPlayer.h", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "8463" }, { "name": "Objective-C", "bytes": "223846" }, { "name": "Shell", "bytes": "463" }, { "name": "TeX", "bytes": "403595" } ], "symlink_target": "" }
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.CSharp.Data.Processing.FilteringAndValidation { public class AutofilterNonBlank { //Source directory static string sourceDir = RunExamples.Get_SourceDirectory(); //Output directory static string outputDir = RunExamples.Get_OutputDirectory(); public static void Main() { // ExStart:1 // Instantiating a Workbook object // Opening the Excel file through the file stream Workbook workbook = new Workbook(sourceDir + "sampleNonBlank.xlsx"); // Accessing the first worksheet in the Excel file Worksheet worksheet = workbook.Worksheets[0]; // Call MatchNonBlanks function to apply the filter worksheet.AutoFilter.MatchNonBlanks(0); // Call refresh function to update the worksheet worksheet.AutoFilter.Refresh(); // Saving the modified Excel file workbook.Save(outputDir + "outSampleNonBlank.xlsx"); // ExEnd:1 Console.WriteLine("AutofilterNonBlank executed successfully."); } } }
{ "content_hash": "f34664c9e9f0a5e70694521861a4a768", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 80, "avg_line_length": 30.846153846153847, "alnum_prop": 0.6350789692435578, "repo_name": "aspose-cells/Aspose.Cells-for-.NET", "id": "2cd23ce9fc8bb1d123bcad94e9aa44cd3351b567", "size": "1203", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Examples/CSharp/Data/Processing/FilteringAndValidation/AutofilterNonBlank.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "476598" }, { "name": "C#", "bytes": "1503796" }, { "name": "CSS", "bytes": "44647" }, { "name": "HTML", "bytes": "133439" }, { "name": "JavaScript", "bytes": "375700" }, { "name": "PHP", "bytes": "16554" } ], "symlink_target": "" }
This document describes the two methods to configure TLS on the Vault servers for a Vault cluster. ## Using the default TLS assets If the TLS assets for a cluster are not specified using the custom resource (CR) specification field, `spec.TLS`, the operator creates a default CA and uses it to generate self-signed certificates for the Vault servers in the cluster. These default TLS assets are stored in the following secrets: * `<vault-cluster-name>-default-vault-client-tls`: This secret contains the `vault-client-ca.crt` file, which is the CA certificate used to sign the Vault server certificate. This CA can be used by the Vault clients to authenticate the certificate presented by the Vault server. * `<vault-cluster-name>-default-vault-server-tls`: This secret contains the `server.crt` and `server.key` files. These are the TLS certificate and key used to configure TLS on the Vault servers. For example, create a Vault cluster with no TLS secrets specified using the following specification: ```yaml apiVersion: "vault.security.coreos.com/v1alpha1" kind: "VaultService" metadata: name: example spec: nodes: 1 ``` The following default secrets are generated for the above Vault cluster: ``` $ kubectl get secrets NAME TYPE DATA AGE example-default-vault-client-tls Opaque 1 1m example-default-vault-server-tls Opaque 2 1m ``` ## Using custom TLS assets Users may pass in custom TLS assets while creating a cluster. Specify the client and server secrets in the following CR specification fields: * `spec.TLS.static.clientSecret`: This secret contains the `vault-client-ca.crt` file, which is the CA certificate used to sign the Vault server certificate. This CA can be used by the Vault clients to authenticate the certificate presented by the Vault server. * `spec.TLS.static.serverSecret`: This secret contains the `server.crt` and `server.key` files. These are the TLS certificate and key for the Vault server. The `server.crt` certificate allows the following wildcard domains: - `localhost` - `*.<namespace>.pod` - `<vault-cluster-name>.<namespace>.svc` The final CR specification is given below: ```yaml apiVersion: "vault.security.coreos.com/v1alpha1" kind: "VaultService" metadata: name: <vault-cluster-name> spec: nodes: 1 TLS: static: serverSecret: <server-secret-name> clientSecret: <client-secret-name> ``` ## Generating TLS assets Use the [hack/tls-gen.sh][hack-tls] script to generate the necessary TLS assets and bundle them into required secrets. ### Prerequisites * `kubectl` installed * [cfssl][cfssl] tools installed * [jq][jq] tool installed ### Using tls-gen script Run the following command by providing the environment variable values as necessary: ```bash $ KUBE_NS=<namespace> SERVER_SECRET=<server-secret-name> CLIENT_SECRET=<client-secret-name> hack/tls-gen.sh ``` Successful execution generates the required secrets in the desired namespace. For example: ```bash $ KUBE_NS=default SERVER_SECRET=vault-server-tls CLIENT_SECRET=vault-client-tls hack/tls-gen.sh $ kubectl -n default get secrets NAME TYPE DATA AGE vault-client-tls Opaque 1 1m vault-server-tls Opaque 2 1m ``` [cfssl]: https://github.com/cloudflare/cfssl#installation [jq]: https://stedolan.github.io/jq/download/ [hack-tls]: ../../hack/tls-gen.sh
{ "content_hash": "064bab98422cdb149d0334430d74b97e", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 278, "avg_line_length": 38.946236559139784, "alnum_prop": 0.6971286581998896, "repo_name": "coreos/vault-operator", "id": "7f5b3f63376575e4f17e1b322b1234720e40a031", "size": "3650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/user/tls_setup.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "188978" }, { "name": "HCL", "bytes": "91" }, { "name": "Shell", "bytes": "22528" } ], "symlink_target": "" }
package org.snaker.engine.parser.impl; import org.snaker.engine.model.NodeModel; import org.snaker.engine.model.StartModel; import org.snaker.engine.parser.AbstractNodeParser; import org.springframework.stereotype.Service; /** * 开始节点解析类 * @author yuqs * @since 1.0 */ public class StartParser extends AbstractNodeParser { /** * 产生StartModel模型对象 */ protected NodeModel newModel() { return new StartModel(); } }
{ "content_hash": "7a6794e5aafc4ce4cf21fe921c6aea8a", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 53, "avg_line_length": 20.285714285714285, "alnum_prop": 0.7535211267605634, "repo_name": "gtison/kf", "id": "0002e2d13d29e7abf0fb631314b1a49a6471d69f", "size": "1056", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/snaker/engine/parser/impl/StartParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "163878" }, { "name": "HTML", "bytes": "885584" }, { "name": "Java", "bytes": "1857106" }, { "name": "JavaScript", "bytes": "2120915" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8"> <title>hashCode</title> <link href="../../../../../images/logo-icon.svg" rel="icon" type="image/svg"><script>var pathToRoot = "../../../../../";</script> <script>const storage = localStorage.getItem("dokka-dark-mode") if (storage == null) { const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches if (osDarkSchemePreferred === true) { document.getElementsByTagName("html")[0].classList.add("theme-dark") } } else { const savedDarkMode = JSON.parse(storage) if(savedDarkMode === true) { document.getElementsByTagName("html")[0].classList.add("theme-dark") } } </script> <script type="text/javascript" src="../../../../../scripts/sourceset_dependencies.js" async></script> <link href="../../../../../styles/style.css" rel="Stylesheet"> <link href="../../../../../styles/jetbrains-mono.css" rel="Stylesheet"> <link href="../../../../../styles/main.css" rel="Stylesheet"> <link href="../../../../../styles/prism.css" rel="Stylesheet"> <link href="../../../../../styles/logo-styles.css" rel="Stylesheet"> <script type="text/javascript" src="../../../../../scripts/clipboard.js" async></script> <script type="text/javascript" src="../../../../../scripts/navigation-loader.js" async></script> <script type="text/javascript" src="../../../../../scripts/platform-content-handler.js" async></script> <script type="text/javascript" src="../../../../../scripts/main.js" defer></script> <script type="text/javascript" src="../../../../../scripts/prism.js" async></script> <script type="text/javascript" src="../../../../../scripts/symbol-parameters-wrapper_deferred.js" defer></script></head> <body> <div class="navigation-wrapper" id="navigation-wrapper"> <div id="leftToggler"><span class="icon-toggler"></span></div> <div class="library-name"> <a href="../../../../../index.html"> <span>stripe-android</span> </a> </div> <div> </div> <div class="pull-right d-flex"> <button id="theme-toggle-button"><span id="theme-toggle"></span></button> <div id="searchBar"></div> </div> </div> <div id="container"> <div id="leftColumn"> <div id="sideMenu"></div> </div> <div id="main"> <div class="main-content" id="content" pageids="payments-core::com.stripe.android.model/StripeIntent.NextActionData.BlikAuthorize/hashCode/#/PointingToDeclaration//-1622557690"> <div class="breadcrumbs"><a href="../../../../index.html">payments-core</a><span class="delimiter">/</span><a href="../../../index.html">com.stripe.android.model</a><span class="delimiter">/</span><a href="../../index.html">StripeIntent</a><span class="delimiter">/</span><a href="../index.html">NextActionData</a><span class="delimiter">/</span><a href="index.html">BlikAuthorize</a><span class="delimiter">/</span><span class="current">hashCode</span></div> <div class="cover "> <h1 class="cover"><span>hash</span><wbr><span><span>Code</span></span></h1> </div> <div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-dependent-content" data-active="" data-togglable=":payments-core:dokkaHtmlPartial/release"><div class="symbol monospace"><span class="token keyword">open </span><span class="token keyword">override </span><span class="token keyword">fun </span><a href="hash-code.html"><span class="token function">hashCode</span></a><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html">Int</a></div></div></div> </div> <div class="footer"> <span class="go-to-top-icon"><a href="#content" id="go-to-top-link"></a></span><span>© 2022 Copyright</span><span class="pull-right"><span>Generated by </span><a href="https://github.com/Kotlin/dokka"><span>dokka</span><span class="padded-icon"></span></a></span> </div> </div> </div> </body></html>
{ "content_hash": "7139177a827bc4ecd3ec6b76f152f853", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 644, "avg_line_length": 65.95238095238095, "alnum_prop": 0.6406738868832732, "repo_name": "stripe/stripe-android", "id": "d6adfcdbee9fca6d8617b579b5a1d7512cd793bd", "size": "4156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/payments-core/com.stripe.android.model/-stripe-intent/-next-action-data/-blik-authorize/hash-code.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "67407" }, { "name": "Kotlin", "bytes": "7720826" }, { "name": "Python", "bytes": "13146" }, { "name": "Ruby", "bytes": "5171" }, { "name": "Shell", "bytes": "18256" } ], "symlink_target": "" }
layout: post author: sunzn date: 2015-12-8 12:47 title: Android Touch事件分发和消费机制讲解 category: Android tag: [android,development,touch,animation] --- 本文转载自[网页](http://www.cnblogs.com/sunzn/archive/2013/05/10/3064129.html) ![Android Touch](/public/img/android/android_touch.jpeg)
{ "content_hash": "2a019540eb9594e590d19188cba45c2a", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 71, "avg_line_length": 25.181818181818183, "alnum_prop": 0.7689530685920578, "repo_name": "ericsonyc/ericsonyc.github.io", "id": "0d7bcb086515c760beeec318ee6d906b3a272f8b", "size": "317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/Android/2015-12-8-Android Touch事件分发和消费机制.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "37166" }, { "name": "HTML", "bytes": "30522" }, { "name": "JavaScript", "bytes": "610" } ], "symlink_target": "" }
import argparse import sys import string import signal signal.signal( signal.SIGPIPE, signal.SIG_DFL ) base = '/work/scripts/' def list(s): try: return s.split(',') except: raise argparse.ArgumentTypeError("Must be a comma separated list of characters") def replace( index, oldValue, newValue ): valueList = [] for i in oldValue: valueList.append(i) valueList[index] = newValue s = "".join(valueList) return s def toList( string ): list = [] for i in string: list.append(i) return list def parseArgs(): parser = argparse.ArgumentParser(description='Print a sequence of numbers with a custom range.', add_help=False, formatter_class=argparse.RawTextHelpFormatter) info = parser.add_argument_group('Program Info') info.add_argument('-h', '--help', action='help', help='show this help message and exit') info.add_argument('-v', '--version', action='version', version='1.0.0') required = parser.add_argument_group('Required arguments') optional = parser.add_argument_group('Optional arguments') optional.add_argument('first', nargs='?', default=False, help='first number in sequence') optional.add_argument('last', nargs='?', default=False, help='last number in sequence') optional.add_argument('-r', '--range', metavar='LIST', type=list, default='0,1,2,3,4,5,6,7,8,9', help='comma separated list you wish to sequence.') optional.add_argument('-s', '--separator', metavar='STRING', default='\n', help='use STRING to separate numbers (default:\\n)') a = parser.parse_args() print ("first "+ a.first) print ("last "+ a.last) print ("range ") print (a.range) if not a.first == False and not a.last == False: pass elif a.last == False and not a.first == False: a.last = a.first a.first = a.range[0] for x in range(0,len(a.last)-1): a.first += a.range[0] else: a.first = a.range[0] a.last = a.range[len(a.range)-1] + a.range[len(a.range)-1] + a.range[len(a.range)-1] + a.range[len(a.range)-1] for x in range(0,len(a.last)-1): a.first += a.range[0] return a def iterate( args ): iterations = [] while not args.first == args.last: iterations.append(args.first) for i in reversed(range(0,len(args.last))): charAt = toList(args.first)[i] x = args.range.index(charAt) x += 1 x = x % len(args.range) args.first = replace(i,args.first,args.range[x]) if not (x == 0): break iterations.append(args.last) print (args.separator.join(iterations)) if __name__ == "__main__": args = parseArgs() iterate(args)
{ "content_hash": "da40510e90e8366185b70d74f5a2c148", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 160, "avg_line_length": 31.1125, "alnum_prop": 0.6749698674166332, "repo_name": "tannermares/custom-sequence", "id": "0bbdae6ee8bec413035093b248db5453ee8fbcce", "size": "2534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cseq.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2534" } ], "symlink_target": "" }
package com.movilizer.connector.persistence.listeners; import com.movilitas.movilizer.v15.MovilizerGenericDataContainer; import com.movilitas.movilizer.v15.MovilizerGenericDataContainerEntry; import com.movilitas.movilizer.v15.MovilizerGenericUploadDataContainer; import com.movilitas.movilizer.v15.MovilizerUploadDataContainer; import com.movilizer.connector.persistence.entities.DatacontainerFromMovilizerQueue; import com.movilizer.connector.persistence.entities.listeners.DatacontainerFromMovilizerQueueSerializerListener; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /** * Tests for the FST serialization engine * * @author Jesús de Mula Cano <jesus.demula@movilizer.com> * @version 0.1-SNAPSHOT, 2017.07.27 * @since 0.1 */ public class SerializationTest { private DatacontainerFromMovilizerQueueSerializerListener compressorListener; @Before public void before() throws Exception { compressorListener = new DatacontainerFromMovilizerQueueSerializerListener(); } @After public void after() { } @Test public void testSimpleSerialization() throws Exception { MovilizerGenericDataContainerEntry entry = new MovilizerGenericDataContainerEntry(); entry.setName("testName"); entry.setValstr("testValue"); MovilizerGenericDataContainer genericDataContainer = new MovilizerGenericDataContainer(); genericDataContainer.getEntry().add(entry); MovilizerGenericUploadDataContainer genericUploadDataContainer = new MovilizerGenericUploadDataContainer(); genericUploadDataContainer.setData(genericDataContainer); MovilizerUploadDataContainer datacontainer = new MovilizerUploadDataContainer(); datacontainer.setContainer(genericUploadDataContainer); DatacontainerFromMovilizerQueue queueEntry = new DatacontainerFromMovilizerQueue(); queueEntry.setDatacontainer(datacontainer); assertThat(queueEntry.getSerializedDatacontainer(), is(nullValue())); compressorListener.setSerializedFieldsBeforeInsert(queueEntry); queueEntry.setDatacontainer(null); assertThat(queueEntry.getSerializedDatacontainer(), is(not(nullValue()))); assertThat(queueEntry.getDatacontainer(), is(nullValue())); compressorListener.setDeserializedFieldsAfterSelect(queueEntry); assertThat(queueEntry.getDatacontainer(), is(not(nullValue()))); assertThat(queueEntry.getDatacontainer().getContainer().getData().getEntry().size(), not(is(0))); assertThat(queueEntry.getDatacontainer().getContainer().getData().getEntry().get(0).getName(), is("testName")); assertThat(queueEntry.getDatacontainer().getContainer().getData().getEntry().get(0).getValstr(), is("testValue")); } }
{ "content_hash": "edaa737ff4cebc3f9940db7deea7b59a", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 122, "avg_line_length": 44.38461538461539, "alnum_prop": 0.7733102253032929, "repo_name": "Movilizer/movilizer-spring-connector", "id": "966b7c691e271499b36dd379a0a7444167b2506d", "size": "2886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/movilizer/connector/persistence/listeners/SerializationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "323880" } ], "symlink_target": "" }