text
stringlengths
2
1.04M
meta
dict
class Shift < ActiveRecord::Base belongs_to :user end
{ "content_hash": "fd23275cf1d423cfe4086554a641534e", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 32, "avg_line_length": 14.25, "alnum_prop": 0.7368421052631579, "repo_name": "abeaclark/easychat_backend", "id": "ebb7b773436aadc887ad4108716a9bdde5e10c2f", "size": "57", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/shift.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11095" }, { "name": "CoffeeScript", "bytes": "422" }, { "name": "HTML", "bytes": "22559" }, { "name": "JavaScript", "bytes": "1076" }, { "name": "Ruby", "bytes": "30525" } ], "symlink_target": "" }
require 'rails_helper' module ReportingPeriod describe QuarterToDate do let!(:apr_1) { Date.new(2003, 4, 1) } let!(:jun_30) { Date.new(2003, 6, 30) } context '#initialize' do it 'works on first day of quarter' do Timecop.freeze(apr_1) do quarter_to_date = described_class.new expect(quarter_to_date.period_start.to_date).to eq apr_1 expect(quarter_to_date.period_end.to_date).to eq apr_1 end end it 'works on last day of quarter' do date = jun_30 + 23.hours Timecop.freeze(date) do quarter_to_date = described_class.new expect(quarter_to_date.period_start.to_date).to eq apr_1 expect(quarter_to_date.period_end.to_date).to eq jun_30 end end end end end
{ "content_hash": "15e621e3830c0f6d77a92ec7f3dbef6f", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 66, "avg_line_length": 26.866666666666667, "alnum_prop": 0.6029776674937966, "repo_name": "ministryofjustice/correspondence_tool_staff", "id": "d5e2980df75d432e75cca3f3a090138d229db79f", "size": "806", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/models/reporting_period/quarter_to_date_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "383" }, { "name": "Dockerfile", "bytes": "1559" }, { "name": "HTML", "bytes": "83918" }, { "name": "JavaScript", "bytes": "50629" }, { "name": "Procfile", "bytes": "174" }, { "name": "Python", "bytes": "5159" }, { "name": "Ruby", "bytes": "4621757" }, { "name": "SCSS", "bytes": "38011" }, { "name": "Shell", "bytes": "11912" }, { "name": "Slim", "bytes": "253831" } ], "symlink_target": "" }
CREATE TABLE kagaribi_player ( id varchar(100) collate utf8_unicode_ci default NULL, name varchar(10), PRIMARY KEY (id) ) ENGINE=InnoDB; CREATE TABLE kagaribi_ranking ( player_id varchar(100) collate utf8_unicode_ci default NULL, score int default NULL, time datetime default '0000-00-00 00:00:00', PRIMARY KEY (player_id, time), FOREIGN KEY (player_id) REFERENCES kagaribi_player (id) ) ENGINE=InnoDB;
{ "content_hash": "a6b49870d53cae65712ad0225d635340", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 61, "avg_line_length": 27.666666666666668, "alnum_prop": 0.7469879518072289, "repo_name": "setchi/kagaribi", "id": "99251e1accea62206eecb8f220ff5e5e1cfbbf8a", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Server/db/schema.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1723" }, { "name": "C#", "bytes": "1455742" }, { "name": "PHP", "bytes": "104013" } ], "symlink_target": "" }
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN #include <memory> POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END namespace pomdog::gui { class PopupMenu final : public Widget , public std::enable_shared_from_this<PopupMenu> { public: explicit PopupMenu(const std::shared_ptr<UIEventDispatcher>& dispatcher); bool IsEnabled() const; void SetEnabled(bool isEnabled); bool IsHovered() const; bool IsFocused() const; void AddItem(const std::string& text); void ClearItems(); std::string GetItem(int index) const; int GetItemCount() const noexcept; int GetCurrentIndex() const noexcept; void SetCurrentIndex(int index); void SetFontWeight(FontWeight fontWeight); std::string GetText() const; void SetTextAlignment(TextAlignment textAlign); void SetHorizontalAlignment(HorizontalAlignment horizontalAlignment) noexcept; void SetVerticalAlignment(VerticalAlignment verticalAlignment) noexcept; HorizontalAlignment GetHorizontalAlignment() const noexcept override; VerticalAlignment GetVerticalAlignment() const noexcept override; void OnEnter() override; void OnFocusIn() override; void OnFocusOut() override; void OnPointerEntered(const PointerPoint& pointerPoint) override; void OnPointerExited(const PointerPoint& pointerPoint) override; void OnPointerPressed(const PointerPoint& pointerPoint) override; void OnPointerReleased(const PointerPoint& pointerPoint) override; void Draw(DrawingContext& drawingContext) override; Signal<void(int index)> CurrentIndexChanged; private: struct PopupMenuItem final { std::string text; }; std::vector<PopupMenuItem> items; int currentIndex = 0; ConnectionList connections; ScopedConnection focusConn; std::shared_ptr<ContextMenu> contextMenu; FontWeight fontWeight; TextAlignment textAlignment; HorizontalAlignment horizontalAlignment; VerticalAlignment verticalAlignment; bool isEnabled; bool isHovered; bool isPressed; bool isFocused; }; } // namespace pomdog::gui
{ "content_hash": "32bc7237b0099a3130679e3d193ac104", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 82, "avg_line_length": 25.951219512195124, "alnum_prop": 0.7462406015037594, "repo_name": "mogemimi/pomdog", "id": "1c8b0726cc71e0467806de3bdbd1946e0ac4ac01", "size": "2572", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pomdog/experimental/gui/popup_menu.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "72882" }, { "name": "C++", "bytes": "2914606" }, { "name": "CMake", "bytes": "102285" }, { "name": "GLSL", "bytes": "22531" }, { "name": "Go", "bytes": "34903" }, { "name": "HLSL", "bytes": "25928" }, { "name": "Metal", "bytes": "28519" }, { "name": "Objective-C", "bytes": "29461" }, { "name": "Objective-C++", "bytes": "181399" } ], "symlink_target": "" }
using System.Web.Http; using ServiceBridge.UnitTests.WebApp.Components; namespace ServiceBridge.UnitTests.WebApp { public class LifetimeController: ApiController { public string Get(string container) { Helper.InitializeServiceContainer(container); ServiceContainer.Current.Register<LifetimeTarget>(ServiceLifetime.PerRequest); return "Success"; } public string Get(int value) { var target = ServiceContainer.GetInstance<LifetimeTarget>(); target.Value = value.ToString(); var target2 = ServiceContainer.GetInstance<LifetimeTarget>(); return target2?.Value; } public string Get() { var target = ServiceContainer.GetInstance<LifetimeTarget>(); return target?.Value; } } }
{ "content_hash": "768234d9f1854cfee0a1793c3521ff41", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 90, "avg_line_length": 29.9, "alnum_prop": 0.6042363433667781, "repo_name": "edwardmeng/wheatech.ServiceModel", "id": "c57e8f227391e29bb579be3784342614e3714da8", "size": "899", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/ServiceBridge.UnitTests.WebApp/WebApi/LifetimeController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "703" }, { "name": "Batchfile", "bytes": "3071" }, { "name": "C#", "bytes": "390178" } ], "symlink_target": "" }
package com.arrggh.eve.api.sde.model.tournaments; import com.arrggh.eve.api.sde.model.BasicModelObjectValidation; public class TournamentPointsTest extends BasicModelObjectValidation<TournamentPoints> { protected Class<TournamentPoints> getClassUnderTest() { return TournamentPoints.class; } protected TournamentPoints getInstanceUnderTest() { return new TournamentPoints.TournamentPointsBuilder().build(); } }
{ "content_hash": "7132d91b5a540a8b53ad81fbd02a17ba", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 88, "avg_line_length": 30.785714285714285, "alnum_prop": 0.8074245939675174, "repo_name": "WanderingMonk/eve-industrial", "id": "2d4d0849a6800ce4a954588f825699de00f9a9fd", "size": "431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "eve-api-sde/src/test/java/com/arrggh/eve/api/sde/model/tournaments/TournamentPointsTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "173767" } ], "symlink_target": "" }
%Make and save the boxplot figures for each parameter threshold=BOXT; cd .. cd .. %Loop through parameters for parcol=1:size(pars,2) %Grab the raw parameter values partemp=pars(:,parcol); %make a place to store the results parvals=[]; %loop through all metrics for a given parameter for i=1:a %grab criteria output crittemp=crit(:,i); %make a vector of param values and criteria tempdata=[partemp,crittemp]; %sort by criteria in ASCENDING ORDER %NOTE - first values = lowest crit = best fits! tempdata=sortrows(tempdata,2); %grab only the top __% of the data tempdata=tempdata(1:floor(threshold/100*size(tempdata,1)),:); %store parameters in a place to make a boxplot parvals=[parvals,tempdata(:,1)]; end %Make the boxplot figure(1) clf set(gcf,'color','w','position',[0 0 900 900]) %make the list of labels for the metrics that were input lablist={ones(size(cstr))}; for k=1:a ltemp=cstr(k,:); ltemp=ltemp(isspace(ltemp)==0); lablist(k)={ltemp}; end btemp = boxplot(parvals,'labels',lablist,'labelorientation',... 'inline','plotstyle','compact','orientation','horizontal',... 'symbol','.k'); h2 = findobj(gca,'Tag','Outliers'); set(h2(:,:),'markeredgecolor',[0.5 0.5 0.5]); h3 = findobj(gca,'Tag','MedianOuter'); set(h3(:,:),'markeredgecolor','k'); h4 = findobj(gca,'Tag','MedianInner'); set(h4(:,:),'visible','off'); for junk=1:33 set(btemp(1,junk),'color','k') set(btemp(2,junk),'color',[0 0 0]) end %make a vector of parameter name w/o any spaces storeloc=pstr(parcol,:); storeloc=storeloc(isspace(storeloc)==0); xlabel(storeloc) %Make a boxplot folder if ones doesn't exist if exist('Output_files/Boxplots')==0 mkdir('Output_files/Boxplots') end %Save the figure print(figure(1),'-depsc',['Output_files/Boxplots/',storeloc,'_boxplot.eps']) end close all
{ "content_hash": "bbefea1f9a4da9f4e4e510d4d6b4484f", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 88, "avg_line_length": 28.894736842105264, "alnum_prop": 0.4586520947176685, "repo_name": "WardHydroLab/OTIS-MCAT", "id": "9a28737e74507c92f0c3deae6b1702a559a37fe8", "size": "2745", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/OTIS-MCAT_TEST/makeboxplots.m", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "273776" } ], "symlink_target": "" }
package org.springframework.boot.actuate.autoconfigure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.actuate.autoconfigure.EndpointMvcIntegrationTests.Application; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMappingCustomizer; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration; import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration; import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for MVC {@link Endpoint}s. * * @author Dave Syer */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) @IntegrationTest("server.port=0") @WebAppConfiguration @DirtiesContext public class EndpointMvcIntegrationTests { @Value("${local.server.port}") private int port; @Autowired private TestInterceptor interceptor; @Test public void envEndpointHidden() throws InterruptedException { String body = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/env/user.dir", String.class); assertThat(body).isNotNull().contains("spring-boot-actuator"); assertThat(this.interceptor.invoked()).isTrue(); } @Test public void healthEndpointNotHidden() throws InterruptedException { String body = new TestRestTemplate() .getForObject("http://localhost:" + this.port + "/health", String.class); assertThat(body).isNotNull().contains("status"); assertThat(this.interceptor.invoked()).isTrue(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ EmbeddedServletContainerAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } @Configuration @MinimalWebConfiguration @Import({ ManagementServerPropertiesAutoConfiguration.class, JacksonAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class }) @RestController protected static class Application { @RequestMapping("/{name}/{env}/{bar}") public Map<String, Object> master(@PathVariable String name, @PathVariable String env, @PathVariable String label) { return Collections.singletonMap("foo", (Object) "bar"); } @RequestMapping("/{name}/{env}") public Map<String, Object> master(@PathVariable String name, @PathVariable String env) { return Collections.singletonMap("foo", (Object) "bar"); } @Autowired(required = false) private final List<HttpMessageConverter<?>> converters = Collections.emptyList(); @Bean @ConditionalOnMissingBean public HttpMessageConverters messageConverters() { return new HttpMessageConverters(this.converters); } @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { return new EndpointHandlerMappingCustomizer() { @Override public void customize(EndpointHandlerMapping mapping) { mapping.setInterceptors(new Object[] { interceptor() }); } }; } @Bean protected TestInterceptor interceptor() { return new TestInterceptor(); } } protected static class TestInterceptor extends HandlerInterceptorAdapter { private final CountDownLatch latch = new CountDownLatch(1); @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { this.latch.countDown(); } public boolean invoked() throws InterruptedException { return this.latch.await(30, TimeUnit.SECONDS); } } }
{ "content_hash": "84dff4de62201b6c3ecb6b1fa8ef81f3", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 94, "avg_line_length": 35.95151515151515, "alnum_prop": 0.8137221847606204, "repo_name": "neo4j-contrib/spring-boot", "id": "cbd38d637f959d74f339faa38dd73a9403e3cca1", "size": "6552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6954" }, { "name": "CSS", "bytes": "5769" }, { "name": "FreeMarker", "bytes": "2116" }, { "name": "Groovy", "bytes": "41115" }, { "name": "HTML", "bytes": "69819" }, { "name": "Java", "bytes": "7992035" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "Ruby", "bytes": "1305" }, { "name": "SQLPL", "bytes": "20085" }, { "name": "Shell", "bytes": "20373" }, { "name": "Smarty", "bytes": "3276" }, { "name": "XSLT", "bytes": "33894" } ], "symlink_target": "" }
#ifndef itkThinPlateSplineKernelTransform_h #define itkThinPlateSplineKernelTransform_h #include "itkKernelTransform.h" namespace itk { /** \class ThinPlateSplineKernelTransform * This class defines the thin plate spline (TPS) transformation. * It is implemented in as straightforward a manner as possible from * the IEEE TMI paper by Davis, Khotanzad, Flamig, and Harms, * Vol. 16 No. 3 June 1997 * * \ingroup ITKTransform */ template<typename TParametersValueType, unsigned int NDimensions = 3> // Number of dimensions class ThinPlateSplineKernelTransform: public KernelTransform<TParametersValueType, NDimensions> { public: /** Standard class typedefs. */ typedef ThinPlateSplineKernelTransform Self; typedef KernelTransform<TParametersValueType, NDimensions> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** New macro for creation of through a Smart Pointer */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(ThinPlateSplineKernelTransform, KernelTransform); /** Scalar type. */ typedef typename Superclass::ScalarType ScalarType; /** Parameters type. */ typedef typename Superclass::ParametersType ParametersType; typedef typename Superclass::FixedParametersType FixedParametersType; /** Jacobian Type */ typedef typename Superclass::JacobianType JacobianType; /** Dimension of the domain space. */ itkStaticConstMacro(SpaceDimension, unsigned int, Superclass::SpaceDimension); /** These (rather redundant) typedefs are needed because typedefs are not inherited */ typedef typename Superclass::InputPointType InputPointType; typedef typename Superclass::OutputPointType OutputPointType; typedef typename Superclass::InputVectorType InputVectorType; typedef typename Superclass::OutputVectorType OutputVectorType; typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType; typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType; typedef typename Superclass::PointsIterator PointsIterator; protected: ThinPlateSplineKernelTransform() {} virtual ~ThinPlateSplineKernelTransform() {} /** These (rather redundant) typedefs are needed because typedefs are not inherited. */ typedef typename Superclass::GMatrixType GMatrixType; /** Compute G(x) * For the thin plate spline, this is: * G(x) = r(x)*I * \f$ G(x) = r(x)*I \f$ * where * r(x) = Euclidean norm = sqrt[x1^2 + x2^2 + x3^2] * \f[ r(x) = \sqrt{ x_1^2 + x_2^2 + x_3^2 } \f] * I = identity matrix. */ virtual void ComputeG(const InputVectorType & landmarkVector, GMatrixType & gmatrix) const ITK_OVERRIDE; /** Compute the contribution of the landmarks weighted by the kernel funcion to the global deformation of the space */ virtual void ComputeDeformationContribution(const InputPointType & inputPoint, OutputPointType & result) const ITK_OVERRIDE; private: ThinPlateSplineKernelTransform(const Self &) ITK_DELETE_FUNCTION; void operator=(const Self &) ITK_DELETE_FUNCTION; }; } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkThinPlateSplineKernelTransform.hxx" #endif #endif // itkThinPlateSplineKernelTransform_h
{ "content_hash": "1ae65eb1f737c136d0c998f6da8e499e", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 106, "avg_line_length": 38.233333333333334, "alnum_prop": 0.7271142109851787, "repo_name": "CIBC-Internal/itk", "id": "e9cacc83f578605e6035a167bcc4e87b867804fd", "size": "4216", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Modules/Core/Transform/include/itkThinPlateSplineKernelTransform.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "306" }, { "name": "C", "bytes": "30093589" }, { "name": "C++", "bytes": "46793708" }, { "name": "CMake", "bytes": "2111149" }, { "name": "CSS", "bytes": "24960" }, { "name": "DIGITAL Command Language", "bytes": "709" }, { "name": "Fortran", "bytes": "2260380" }, { "name": "HTML", "bytes": "208088" }, { "name": "Io", "bytes": "1833" }, { "name": "Java", "bytes": "28598" }, { "name": "Lex", "bytes": "6877" }, { "name": "Makefile", "bytes": "212859" }, { "name": "Objective-C", "bytes": "49279" }, { "name": "Objective-C++", "bytes": "6591" }, { "name": "OpenEdge ABL", "bytes": "85244" }, { "name": "Perl", "bytes": "18552" }, { "name": "Python", "bytes": "886554" }, { "name": "Ruby", "bytes": "296" }, { "name": "Shell", "bytes": "122388" }, { "name": "Tcl", "bytes": "74786" }, { "name": "WebAssembly", "bytes": "4056" }, { "name": "XSLT", "bytes": "195448" }, { "name": "Yacc", "bytes": "20428" } ], "symlink_target": "" }
require_relative 'untappd_helper' # # The +DistinctBeers+ object acts as a helper class for pulling and managing # user information from the Untappd service. # class BeerHelper include UntappdHelper BEER_SEARCH_METHOD = "user/beers/" # # This method will return a limited list of the user's distinct beers. # # username: User to query # offset: The numeric offset that you want results to start at # limit: The number of results to return (max of 50) # def pullDistinctBeers(username, offset, limit=50) params = [ "offset=#{offset.to_s}", "limit=#{limit.to_s}" ] return GET(username, BEER_SEARCH_METHOD, params)["response"] end # # This method will return a complete list of the user's distinct beers. # # username: User to query # def pullAllDistinctBeers(username, dbm) offset = 0 loop do response = pullDistinctBeers(username, offset) offset += response["beers"]["count"] break if response["beers"]["count"] == 0 dbm.insertUntappdBlob(response) end end end
{ "content_hash": "31e3cb88bb98843e969dc1e5ef019f25", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 77, "avg_line_length": 28.175, "alnum_prop": 0.6379769299023957, "repo_name": "Jtfinlay/BrewClub", "id": "fb8cc066319ed6a3bc72f1f53a5b7de0acc1c19c", "size": "1240", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/beer_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "18646" } ], "symlink_target": "" }
<?php namespace fur\bright\utils; /** * This class does some arbitrary work to prevent some basic vulnerabilities * in PHP and / or libraries. * Call this in every class, or include library/Bright/Bright.php * @author ids * */ class Security { public static function init() { if(function_exists('libxml_disable_entity_loader')) libxml_disable_entity_loader(true); } }
{ "content_hash": "6aa02ee3868735b44d6887f3b3ea46a5", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 76, "avg_line_length": 22.529411764705884, "alnum_prop": 0.7180156657963447, "repo_name": "rsids/bright_api", "id": "d729e0c505a387b173f0369833e4f78acac3a9f1", "size": "383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/utils/Security.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2831" }, { "name": "PHP", "bytes": "657709" } ], "symlink_target": "" }
"""Recursive imports""" import inspect_recursive # Importing self, should get ignored class Foo: """A class""" from . import first # Importing a module twice, only one of them should be picked from . import second as b from . import second as a def foo() -> b.Bar: """Function that returns Foo""" def bar() -> a.Bar: """Function that also returns Foo"""
{ "content_hash": "4a752ea26226648eec00a208313becfd", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 61, "avg_line_length": 20.666666666666668, "alnum_prop": 0.6720430107526881, "repo_name": "mosra/m.css", "id": "a512bbb20e499c76b493812aef42cce57275e8fb", "size": "372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/test_python/inspect_recursive/inspect_recursive/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "29" }, { "name": "CSS", "bytes": "139738" }, { "name": "HTML", "bytes": "39793" }, { "name": "Python", "bytes": "340270" }, { "name": "Shell", "bytes": "461" } ], "symlink_target": "" }
#ifndef NET_IF_H #define NET_IF_H /* * Send uip_len bytes from uip_buf to the network interface selected by the * configNETWORK_INTERFACE_TO_USE constant (defined in FreeRTOSConfig.h). */ void vNetifTx( void ); /* * Receive bytes from the network interface selected by the * configNETWORK_INTERFACE_TO_USE constant (defined in FreeRTOSConfig.h). The * bytes are placed in uip_buf. The number of bytes copied into uip_buf is * returned. */ unsigned portBASE_TYPE uxNetifRx( void ); /* * Prepare a packet capture session. This will print out all the network * interfaces available, and the one actually used is set by the * configNETWORK_INTERFACE_TO_USE constant that is defined in * FreeRTOSConfig.h. */ portBASE_TYPE xNetifInit( void ); #endif /* NET_IF_H */
{ "content_hash": "a44786e0af5cfd4836ba16c3b7c9bc4f", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 78, "avg_line_length": 29.14814814814815, "alnum_prop": 0.7293519695044473, "repo_name": "kasperdokter/Reo", "id": "9ff42473a873a1d1bd0211176d0bba94fc9580c8", "size": "4613", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "FreeRTOSv9.0.0/FreeRTOS/Demo/Common/ethernet/lwip-1.4.0/ports/win32/WinPCap/netif.h", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "11728" }, { "name": "Batchfile", "bytes": "1854" }, { "name": "C", "bytes": "49627" }, { "name": "HTML", "bytes": "5672" }, { "name": "Java", "bytes": "874850" }, { "name": "Shell", "bytes": "1539" } ], "symlink_target": "" }
package com.liying.ipgw.model; /** * ======================================================= * 作者:liying - liruoer2008@yeah.net * 日期:2015/12/06 12:45 * 版本:1.0 * 描述:用户帐户实体类 * 备注: * ======================================================= */ public class AccountInfo { private String userName = null; private String psw = null; private String range = "2"; public static final String USERNAME = "userName"; public static final String PSW = "psw"; public static final String RANGE = "range"; /** * AccountInfo的构造方法 * @param userName 用户名 * @param psw 密码 * @param range 访问范围:1 国际 2 国内 */ public AccountInfo(String userName, String psw, String range) { super(); this.userName = userName; this.psw = psw; this.range = range; } /** * 无参构造方法 */ public AccountInfo() { } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } public String getRange() { return range; } public void setRange(String range) { this.range = range; } }
{ "content_hash": "056afdaf809a587989b40a918666a0a3", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 64, "avg_line_length": 21.06779661016949, "alnum_prop": 0.5470635559131134, "repo_name": "liying2008/neu-ipgw", "id": "36d501f333bdbce88af6b5c7fb79efb22a8eb2b5", "size": "1337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/liying/ipgw/model/AccountInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "344" }, { "name": "CMake", "bytes": "316" }, { "name": "Java", "bytes": "448279" } ], "symlink_target": "" }
<?php /** * Return the full URL of the current page. * * @return string The URL * @todo Combine / replace with current_page_url(). full_url() is based on the * request only while current_page_url() uses the configured site url. * @deprecated 1.9 Use current_page_url() */ function full_url() { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use current_page_url()', 1.9); $request = _elgg_services()->request; $url = $request->getSchemeAndHttpHost(); // This is here to prevent XSS in poorly written browsers used by 80% of the population. // svn commit [5813]: https://github.com/Elgg/Elgg/commit/0c947e80f512cb0a482b1864fd0a6965c8a0cd4a // @todo encoding like this should occur when inserting into web page, not here $quotes = array('\'', '"'); $encoded = array('%27', '%22'); return $url . str_replace($quotes, $encoded, $request->getRequestUri()); } /** * Sets the URL handler for a particular entity type and subtype * * @param string $entity_type The entity type * @param string $entity_subtype The entity subtype * @param string $function_name The function to register * * @return bool Depending on success * @see get_entity_url() * @see ElggEntity::getURL() * @since 1.8.0 * @deprecated 1.9.0 Use the plugin hook in ElggEntity::getURL() */ function elgg_register_entity_url_handler($entity_type, $entity_subtype, $function_name) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use the plugin hook in ElggEntity::getURL()', 1.9); global $CONFIG; if (!is_callable($function_name, true)) { return false; } if (!isset($CONFIG->entity_url_handler)) { $CONFIG->entity_url_handler = array(); } if (!isset($CONFIG->entity_url_handler[$entity_type])) { $CONFIG->entity_url_handler[$entity_type] = array(); } $CONFIG->entity_url_handler[$entity_type][$entity_subtype] = $function_name; return true; } /** * Sets the URL handler for a particular relationship type * * @param string $relationship_type The relationship type. * @param string $function_name The function to register * * @return bool Depending on success * @deprecated 1.9 Use the plugin hook in ElggRelationship::getURL() */ function elgg_register_relationship_url_handler($relationship_type, $function_name) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use the plugin hook in getURL()', 1.9); global $CONFIG; if (!is_callable($function_name, true)) { return false; } if (!isset($CONFIG->relationship_url_handler)) { $CONFIG->relationship_url_handler = array(); } $CONFIG->relationship_url_handler[$relationship_type] = $function_name; return true; } /** * Get the url for a given relationship. * * @param int $id Relationship ID * * @return string * @deprecated 1.9 Use ElggRelationship::getURL() */ function get_relationship_url($id) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggRelationship::getURL()', 1.9); global $CONFIG; $id = (int)$id; if ($relationship = get_relationship($id)) { $view = elgg_get_viewtype(); $guid = $relationship->guid_one; $type = $relationship->relationship; $url = ""; $function = ""; if (isset($CONFIG->relationship_url_handler[$type])) { $function = $CONFIG->relationship_url_handler[$type]; } if (isset($CONFIG->relationship_url_handler['all'])) { $function = $CONFIG->relationship_url_handler['all']; } if (is_callable($function)) { $url = call_user_func($function, $relationship); } if ($url == "") { $nameid = $relationship->id; $url = elgg_get_site_url() . "export/$view/$guid/relationship/$nameid/"; } return $url; } return false; } /** * Sets the URL handler for a particular extender type and name. * It is recommended that you do not call this directly, instead use * one of the wrapper functions such as elgg_register_annotation_url_handler(). * * @param string $extender_type Extender type ('annotation', 'metadata') * @param string $extender_name The name of the extender * @param string $function_name The function to register * * @return bool * @deprecated 1.9 Use plugin hook in ElggExtender::getURL() */ function elgg_register_extender_url_handler($extender_type, $extender_name, $function_name) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use the plugin hook in getURL()', 1.9, 2); global $CONFIG; if (!is_callable($function_name, true)) { return false; } if (!isset($CONFIG->extender_url_handler)) { $CONFIG->extender_url_handler = array(); } if (!isset($CONFIG->extender_url_handler[$extender_type])) { $CONFIG->extender_url_handler[$extender_type] = array(); } $CONFIG->extender_url_handler[$extender_type][$extender_name] = $function_name; return true; } /** * Get the URL of a given elgg extender. * Used by get_annotation_url and get_metadata_url. * * @param ElggExtender $extender An extender object * * @return string * @deprecated 1.9 Use method getURL() */ function get_extender_url(ElggExtender $extender) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggExtender::getURL()', 1.9); global $CONFIG; $view = elgg_get_viewtype(); $guid = $extender->entity_guid; $type = $extender->type; $url = ""; $function = ""; if (isset($CONFIG->extender_url_handler[$type][$extender->name])) { $function = $CONFIG->extender_url_handler[$type][$extender->name]; } if (isset($CONFIG->extender_url_handler[$type]['all'])) { $function = $CONFIG->extender_url_handler[$type]['all']; } if (isset($CONFIG->extender_url_handler['all']['all'])) { $function = $CONFIG->extender_url_handler['all']['all']; } if (is_callable($function)) { $url = call_user_func($function, $extender); } if ($url == "") { $nameid = $extender->id; if ($type == 'volatile') { $nameid = $extender->name; } $url = "export/$view/$guid/$type/$nameid/"; } return elgg_normalize_url($url); } /** * Get the URL for this annotation. * * @param int $id Annotation id * * @return string|bool False on failure * @deprecated 1.9 Use method getURL() on annotation object */ function get_annotation_url($id) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggAnnotation::getURL()', 1.9); $id = (int)$id; if ($extender = elgg_get_annotation_from_id($id)) { return get_extender_url($extender); } return false; } /** * Register a metadata url handler. * * @param string $extender_name The name, default 'all'. * @param string $function The function name. * * @return bool * @deprecated 1.9 Use the plugin hook in ElggExtender::getURL() */ function elgg_register_metadata_url_handler($extender_name, $function) { // deprecation notice comes from elgg_register_extender_url_handler() return elgg_register_extender_url_handler('metadata', $extender_name, $function); } /** * Register an annotation url handler. * * @param string $extender_name The name, default 'all'. * @param string $function_name The function. * * @return string * @deprecated 1.9 Use the plugin hook in ElggExtender::getURL() */ function elgg_register_annotation_url_handler($extender_name = "all", $function_name) { // deprecation notice comes from elgg_register_extender_url_handler() return elgg_register_extender_url_handler('annotation', $extender_name, $function_name); } /** * Return a list of this group's members. * * @param int $group_guid The ID of the container/group. * @param int $limit The limit * @param int $offset The offset * @param int $site_guid The site * @param bool $count Return the users (false) or the count of them (true) * * @return mixed * @deprecated 1.9 Use ElggGroup::getMembers() */ function get_group_members($group_guid, $limit = 10, $offset = 0, $site_guid = 0, $count = false) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggGroup::getMembers()', 1.9); // in 1.7 0 means "not set." rewrite to make sense. if (!$site_guid) { $site_guid = ELGG_ENTITIES_ANY_VALUE; } return elgg_get_entities_from_relationship(array( 'relationship' => 'member', 'relationship_guid' => $group_guid, 'inverse_relationship' => true, 'type' => 'user', 'limit' => $limit, 'offset' => $offset, 'count' => $count, 'site_guid' => $site_guid )); } /** * Add an object to the given group. * * @param int $group_guid The group to add the object to. * @param int $object_guid The guid of the elgg object (must be ElggObject or a child thereof) * * @return bool * @throws InvalidClassException * @deprecated 1.9 Use ElggGroup::addObjectToGroup() */ function add_object_to_group($group_guid, $object_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggGroup::addObjectToGroup()', 1.9); $group_guid = (int)$group_guid; $object_guid = (int)$object_guid; $group = get_entity($group_guid); $object = get_entity($object_guid); if ((!$group) || (!$object)) { return false; } if (!($group instanceof ElggGroup)) { $msg = "GUID:" . $group_guid . " is not a valid " . 'ElggGroup'; throw new InvalidClassException($msg); } if (!($object instanceof ElggObject)) { $msg = "GUID:" . $object_guid . " is not a valid " . 'ElggObject'; throw new InvalidClassException($msg); } $object->container_guid = $group_guid; return $object->save(); } /** * Remove an object from the given group. * * @param int $group_guid The group to remove the object from * @param int $object_guid The object to remove * * @return bool * @throws InvalidClassException * @deprecated 1.9 Use ElggGroup::removeObjectFromGroup() */ function remove_object_from_group($group_guid, $object_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggGroup::removeObjectFromGroup()', 1.9); $group_guid = (int)$group_guid; $object_guid = (int)$object_guid; $group = get_entity($group_guid); $object = get_entity($object_guid); if ((!$group) || (!$object)) { return false; } if (!($group instanceof ElggGroup)) { $msg = "GUID:" . $group_guid . " is not a valid " . 'ElggGroup'; throw new InvalidClassException($msg); } if (!($object instanceof ElggObject)) { $msg = "GUID:" . $object_guid . " is not a valid " . 'ElggObject'; throw new InvalidClassException($msg); } $object->container_guid = $object->owner_guid; return $object->save(); } /** * Return whether a given user is a member of the group or not. * * @param int $group_guid The group ID * @param int $user_guid The user guid * * @return bool * @deprecated 1.9 Use Use ElggGroup::isMember() */ function is_group_member($group_guid, $user_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggGroup::isMember()', 1.9); $object = check_entity_relationship($user_guid, 'member', $group_guid); if ($object) { return true; } else { return false; } } /** * Return all groups a user is a member of. * * @param int $user_guid GUID of user * * @return array|false * @deprecated 1.9 Use ElggUser::getGroups() */ function get_users_membership($user_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggUser::getGroups()', 1.9); $options = array( 'type' => 'group', 'relationship' => 'member', 'relationship_guid' => $user_guid, 'inverse_relationship' => false, 'limit' => false, ); return elgg_get_entities_from_relationship($options); } /** * Determines whether or not a user is another user's friend. * * @param int $user_guid The GUID of the user * @param int $friend_guid The GUID of the friend * * @return bool * @deprecated 1.9 Use ElggUser::isFriendsOf() or ElggUser::isFriendsWith() */ function user_is_friend($user_guid, $friend_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggUser::isFriendsOf() or ElggUser::isFriendsWith()', 1.9); return check_entity_relationship($user_guid, "friend", $friend_guid) !== false; } /** * Obtains a given user's friends * * @param int $user_guid The user's GUID * @param string $subtype The subtype of users, if any * @param int $limit Number of results to return (default 10) * @param int $offset Indexing offset, if any * * @return ElggUser[]|false Either an array of ElggUsers or false, depending on success * @deprecated 1.9 Use ElggUser::getFriends() */ function get_user_friends($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE, $limit = 10, $offset = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggUser::getFriends()', 1.9); return elgg_get_entities_from_relationship(array( 'relationship' => 'friend', 'relationship_guid' => $user_guid, 'type' => 'user', 'subtype' => $subtype, 'limit' => $limit, 'offset' => $offset )); } /** * Obtains the people who have made a given user a friend * * @param int $user_guid The user's GUID * @param string $subtype The subtype of users, if any * @param int $limit Number of results to return (default 10) * @param int $offset Indexing offset, if any * * @return ElggUser[]|false Either an array of ElggUsers or false, depending on success * @deprecated 1.9 Use ElggUser::getFriendsOf() */ function get_user_friends_of($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE, $limit = 10, $offset = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggUser::getFriendsOf()', 1.9); return elgg_get_entities_from_relationship(array( 'relationship' => 'friend', 'relationship_guid' => $user_guid, 'inverse_relationship' => true, 'type' => 'user', 'subtype' => $subtype, 'limit' => $limit, 'offset' => $offset )); } /** * Adds a user to another user's friends list. * * @param int $user_guid The GUID of the friending user * @param int $friend_guid The GUID of the user to friend * * @return bool Depending on success * @deprecated 1.9 Use ElggUser::addFriend() */ function user_add_friend($user_guid, $friend_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggUser::addFriend()', 1.9); $user_guid = (int) $user_guid; $friend_guid = (int) $friend_guid; if ($user_guid == $friend_guid) { return false; } if (!$friend = get_entity($friend_guid)) { return false; } if (!$user = get_entity($user_guid)) { return false; } if ((!($user instanceof ElggUser)) || (!($friend instanceof ElggUser))) { return false; } return add_entity_relationship($user_guid, "friend", $friend_guid); } /** * Removes a user from another user's friends list. * * @param int $user_guid The GUID of the friending user * @param int $friend_guid The GUID of the user on the friends list * * @return bool Depending on success * @deprecated 1.9 Use ElggUser::removeFriend() */ function user_remove_friend($user_guid, $friend_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggUser::removeFriend()', 1.9); $user_guid = (int) $user_guid; $friend_guid = (int) $friend_guid; // perform cleanup for access lists. $collections = get_user_access_collections($user_guid); if ($collections) { foreach ($collections as $collection) { remove_user_from_access_collection($friend_guid, $collection->id); } } return remove_entity_relationship($user_guid, "friend", $friend_guid); } /** * Add a user to a site. * * @param int $site_guid Site guid * @param int $user_guid User guid * * @return bool * @deprecated 1.9 Use ElggSite::addEntity() */ function add_site_user($site_guid, $user_guid) { elgg_deprecated_notice('add_site_user() is deprecated. Use ElggEntity::addEntity()', 1.9); $site_guid = (int)$site_guid; $user_guid = (int)$user_guid; return add_entity_relationship($user_guid, "member_of_site", $site_guid); } /** * Remove a user from a site. * * @param int $site_guid Site GUID * @param int $user_guid User GUID * * @return bool * @deprecated 1.9 Use ElggSite::removeEntity() */ function remove_site_user($site_guid, $user_guid) { elgg_deprecated_notice('remove_site_user() is deprecated. Use ElggEntity::removeEntity()', 1.9); $site_guid = (int)$site_guid; $user_guid = (int)$user_guid; return remove_entity_relationship($user_guid, "member_of_site", $site_guid); } /** * Add an object to a site. * * @param int $site_guid Site GUID * @param int $object_guid Object GUID * * @return mixed * @deprecated 1.9 Use ElggSite::addEntity() */ function add_site_object($site_guid, $object_guid) { elgg_deprecated_notice('add_site_object() is deprecated. Use ElggEntity::addEntity()', 1.9); $site_guid = (int)$site_guid; $object_guid = (int)$object_guid; return add_entity_relationship($object_guid, "member_of_site", $site_guid); } /** * Remove an object from a site. * * @param int $site_guid Site GUID * @param int $object_guid Object GUID * * @return bool * @deprecated 1.9 Use ElggSite::removeEntity() */ function remove_site_object($site_guid, $object_guid) { elgg_deprecated_notice('remove_site_object() is deprecated. Use ElggEntity::removeEntity()', 1.9); $site_guid = (int)$site_guid; $object_guid = (int)$object_guid; return remove_entity_relationship($object_guid, "member_of_site", $site_guid); } /** * Get the objects belonging to a site. * * @param int $site_guid Site GUID * @param string $subtype Subtype * @param int $limit Limit * @param int $offset Offset * * @return mixed * @deprecated 1.9 Use ElggSite::getEntities() */ function get_site_objects($site_guid, $subtype = "", $limit = 10, $offset = 0) { elgg_deprecated_notice('get_site_objects() is deprecated. Use ElggSite::getEntities()', 1.9); $site_guid = (int)$site_guid; $limit = (int)$limit; $offset = (int)$offset; return elgg_get_entities_from_relationship(array( 'relationship' => 'member_of_site', 'relationship_guid' => $site_guid, 'inverse_relationship' => true, 'type' => 'object', 'subtype' => $subtype, 'limit' => $limit, 'offset' => $offset )); } /** * Get the sites this object is part of * * @param int $object_guid The object's GUID * @param int $limit Number of results to return * @param int $offset Any indexing offset * * @return array On success, an array of ElggSites * @deprecated 1.9 Use ElggEntity::getSites() */ function get_object_sites($object_guid, $limit = 10, $offset = 0) { elgg_deprecated_notice('get_object_sites() is deprecated. Use ElggEntity::getSites()', 1.9); $object_guid = (int)$object_guid; $limit = (int)$limit; $offset = (int)$offset; return elgg_get_entities_from_relationship(array( 'relationship' => 'member_of_site', 'relationship_guid' => $object_guid, 'type' => 'site', 'limit' => $limit, 'offset' => $offset, )); } /** * Get the sites this user is part of * * @param int $user_guid The user's GUID * @param int $limit Number of results to return * @param int $offset Any indexing offset * * @return ElggSite[]|false On success, an array of ElggSites * @deprecated 1.9 Use ElggEntity::getSites() */ function get_user_sites($user_guid, $limit = 10, $offset = 0) { elgg_deprecated_notice('get_user_sites() is deprecated. Use ElggEntity::getSites()', 1.9); $user_guid = (int)$user_guid; $limit = (int)$limit; $offset = (int)$offset; return elgg_get_entities_from_relationship(array( 'site_guids' => ELGG_ENTITIES_ANY_VALUE, 'relationship' => 'member_of_site', 'relationship_guid' => $user_guid, 'inverse_relationship' => false, 'type' => 'site', 'limit' => $limit, 'offset' => $offset, )); } /** * Determines whether or not the specified user can edit the specified piece of extender * * @param int $extender_id The ID of the piece of extender * @param string $type 'metadata' or 'annotation' * @param int $user_guid The GUID of the user * * @return bool * @deprecated 1.9 Use the appropriate canEdit() method on metadata or annotations */ function can_edit_extender($extender_id, $type, $user_guid = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggExtender::canEdit()', 1.9); // Since Elgg 1.0, Elgg has returned false from can_edit_extender() // if no user was logged in. This breaks the access override so we add this // special check here. if (!elgg_check_access_overrides($user_guid)) { if (!elgg_is_logged_in()) { return false; } } $user_guid = (int)$user_guid; $user = get_user($user_guid); if (!$user) { $user = elgg_get_logged_in_user_entity(); $user_guid = elgg_get_logged_in_user_guid(); } $functionname = "elgg_get_{$type}_from_id"; if (is_callable($functionname)) { $extender = call_user_func($functionname, $extender_id); } else { return false; } if (!($extender instanceof ElggExtender)) { return false; } /* @var ElggExtender $extender */ // If the owner is the specified user, great! They can edit. if ($extender->getOwnerGUID() == $user_guid) { return true; } // If the user can edit the entity this is attached to, great! They can edit. $entity = $extender->getEntity(); if ($entity->canEdit($user_guid)) { return true; } // Trigger plugin hook - note that $user may be null $params = array('entity' => $entity, 'user' => $user); return elgg_trigger_plugin_hook('permissions_check', $type, $params, false); } /** * The algorithm working out the size of font based on the number of tags. * This is quick and dirty. * * @param int $min Min size * @param int $max Max size * @param int $number_of_tags The number of tags * @param int $buckets The number of buckets * * @return int * @access private * @deprecated 1.9 */ function calculate_tag_size($min, $max, $number_of_tags, $buckets = 6) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $delta = (($max - $min) / $buckets); $thresholds = array(); for ($n = 1; $n <= $buckets; $n++) { $thresholds[$n - 1] = ($min + $n) * $delta; } // Correction if ($thresholds[$buckets - 1] > $max) { $thresholds[$buckets - 1] = $max; } $size = 0; for ($n = 0; $n < count($thresholds); $n++) { if ($number_of_tags >= $thresholds[$n]) { $size = $n; } } return $size; } /** * This function generates an array of tags with a weighting. * * @param array $tags The array of tags. * @param int $buckets The number of buckets * * @return array An associated array of tags with a weighting, this can then be mapped to a display class. * @access private * @deprecated 1.9 */ function generate_tag_cloud(array $tags, $buckets = 6) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $cloud = array(); $min = 65535; $max = 0; foreach ($tags as $tag) { $cloud[$tag]++; if ($cloud[$tag] > $max) { $max = $cloud[$tag]; } if ($cloud[$tag] < $min) { $min = $cloud[$tag]; } } foreach ($cloud as $k => $v) { $cloud[$k] = calculate_tag_size($min, $max, $v, $buckets); } return $cloud; } /** * Invalidate the metadata cache based on options passed to various *_metadata functions * * @param string $action Action performed on metadata. "delete", "disable", or "enable" * @param array $options Options passed to elgg_(delete|disable|enable)_metadata * @return void * @deprecated 1.9 */ function elgg_invalidate_metadata_cache($action, array $options) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); _elgg_invalidate_metadata_cache($action, $options); } global $METASTRINGS_DEADNAME_CACHE; $METASTRINGS_DEADNAME_CACHE = array(); /** * Return the meta string id for a given tag, or false. * * @param string $string The value to store * @param bool $case_sensitive Do we want to make the query case sensitive? * If not there may be more than one result * * @return int|array|false meta string id, array of ids or false if none found * @deprecated 1.9 Use elgg_get_metastring_id() */ function get_metastring_id($string, $case_sensitive = TRUE) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use elgg_get_metastring_id()', 1.9); global $CONFIG, $METASTRINGS_CACHE, $METASTRINGS_DEADNAME_CACHE; $string = sanitise_string($string); // caching doesn't work for case insensitive searches if ($case_sensitive) { $result = array_search($string, $METASTRINGS_CACHE, true); if ($result !== false) { return $result; } // See if we have previously looked for this and found nothing if (in_array($string, $METASTRINGS_DEADNAME_CACHE, true)) { return false; } // Experimental memcache $msfc = null; static $metastrings_memcache; if ((!$metastrings_memcache) && (is_memcache_available())) { $metastrings_memcache = new ElggMemcache('metastrings_memcache'); } if ($metastrings_memcache) { $msfc = $metastrings_memcache->load($string); } if ($msfc) { return $msfc; } } // Case sensitive if ($case_sensitive) { $query = "SELECT * from {$CONFIG->dbprefix}metastrings where string= BINARY '$string' limit 1"; } else { $query = "SELECT * from {$CONFIG->dbprefix}metastrings where string = '$string'"; } $row = FALSE; $metaStrings = get_data($query); if (is_array($metaStrings)) { if (sizeof($metaStrings) > 1) { $ids = array(); foreach ($metaStrings as $metaString) { $ids[] = $metaString->id; } return $ids; } else if (isset($metaStrings[0])) { $row = $metaStrings[0]; } } if ($row) { $METASTRINGS_CACHE[$row->id] = $row->string; // Cache it // Attempt to memcache it if memcache is available if ($metastrings_memcache) { $metastrings_memcache->save($row->string, $row->id); } return $row->id; } else { $METASTRINGS_DEADNAME_CACHE[$string] = $string; } return false; } /** * Add a metastring. * It returns the id of the metastring. If it does not exist, it will be created. * * @param string $string The value (whatever that is) to be stored * @param bool $case_sensitive Do we want to make the query case sensitive? * * @return mixed Integer tag or false. * @deprecated 1.9 Use elgg_get_metastring_id() */ function add_metastring($string, $case_sensitive = true) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use elgg_get_metastring_id()', 1.9); global $CONFIG, $METASTRINGS_CACHE, $METASTRINGS_DEADNAME_CACHE; $sanstring = sanitise_string($string); $id = get_metastring_id($string, $case_sensitive); if ($id) { return $id; } $result = insert_data("INSERT into {$CONFIG->dbprefix}metastrings (string) values ('$sanstring')"); if ($result) { $METASTRINGS_CACHE[$result] = $string; if (isset($METASTRINGS_DEADNAME_CACHE[$string])) { unset($METASTRINGS_DEADNAME_CACHE[$string]); } } return $result; } /** * When given an ID, returns the corresponding metastring * * @param int $id Metastring ID * * @return string Metastring * @deprecated 1.9 */ function get_metastring($id) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated.', 1.9); global $CONFIG, $METASTRINGS_CACHE; $id = (int) $id; if (isset($METASTRINGS_CACHE[$id])) { return $METASTRINGS_CACHE[$id]; } $row = get_data_row("SELECT * from {$CONFIG->dbprefix}metastrings where id='$id' limit 1"); if ($row) { $METASTRINGS_CACHE[$id] = $row->string; return $row->string; } return false; } /** * Obtains a list of objects owned by a user's friends * * @param int $user_guid The GUID of the user to get the friends of * @param string $subtype Optionally, the subtype of objects * @param int $limit The number of results to return (default 10) * @param int $offset Indexing offset, if any * @param int $timelower The earliest time the entity can have been created. Default: all * @param int $timeupper The latest time the entity can have been created. Default: all * * @return ElggObject[]|false An array of ElggObjects or false, depending on success * @deprecated 1.9 Use elgg_get_entities_from_relationship() */ function get_user_friends_objects($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE, $limit = 10, $offset = 0, $timelower = 0, $timeupper = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use elgg_get_entities_from_relationship()', 1.9); return elgg_get_entities_from_relationship(array( 'type' => 'object', 'subtype' => $subtype, 'limit' => $limit, 'offset' => $offset, 'created_time_lower' => $timelower, 'created_time_upper' => $timeupper, 'relationship' => 'friend', 'relationship_guid' => $user_guid, 'relationship_join_on' => 'container_guid', )); } /** * Counts the number of objects owned by a user's friends * * @param int $user_guid The GUID of the user to get the friends of * @param string $subtype Optionally, the subtype of objects * @param int $timelower The earliest time the entity can have been created. Default: all * @param int $timeupper The latest time the entity can have been created. Default: all * * @return int The number of objects * @deprecated 1.9 Use elgg_get_entities_from_relationship() */ function count_user_friends_objects($user_guid, $subtype = ELGG_ENTITIES_ANY_VALUE, $timelower = 0, $timeupper = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use elgg_get_entities_from_relationship()', 1.9); return elgg_get_entities_from_relationship(array( 'type' => 'object', 'subtype' => $subtype, 'created_time_lower' => $timelower, 'created_time_upper' => $timeupper, 'relationship' => 'friend', 'relationship_guid' => $user_guid, 'relationship_join_on' => 'container_guid', 'count' => true, )); } /** * Displays a list of a user's friends' objects of a particular subtype, with navigation. * * @see elgg_view_entity_list * * @param int $user_guid The GUID of the user * @param string $subtype The object subtype * @param int $limit The number of entities to display on a page * @param bool $full_view Whether or not to display the full view (default: true) * @param bool $listtypetoggle Whether or not to allow you to flip to gallery mode (default: true) * @param bool $pagination Whether to display pagination (default: true) * @param int $timelower The earliest time the entity can have been created. Default: all * @param int $timeupper The latest time the entity can have been created. Default: all * * @return string * @deprecated 1.9 Use elgg_list_entities_from_relationship() */ function list_user_friends_objects($user_guid, $subtype = "", $limit = 10, $full_view = true, $listtypetoggle = true, $pagination = true, $timelower = 0, $timeupper = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use elgg_list_entities_from_relationship()', 1.9); return elgg_list_entities_from_relationship(array( 'type' => 'object', 'subtype' => $subtype, 'limit' => $limit, 'created_time_lower' => $timelower, 'created_time_upper' => $timeupper, 'full_view' => $full_view, 'list_type_toggle' => $listtypetoggle, 'pagination' => $pagination, 'relationship' => 'friend', 'relationship_guid' => $user_guid, 'relationship_join_on' => 'container_guid', )); } /** * Encode a location into a latitude and longitude, caching the result. * * Works by triggering the 'geocode' 'location' plugin * hook, and requires a geocoding plugin to be installed. * * @param string $location The location, e.g. "London", or "24 Foobar Street, Gotham City" * @return string|false * @deprecated 1.9.0 See geolocation plugin on github */ function elgg_geocode_location($location) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. See geolocation plugin on github', 1.9); global $CONFIG; if (is_array($location)) { return false; } $location = sanitise_string($location); // Look for cached version $query = "SELECT * from {$CONFIG->dbprefix}geocode_cache WHERE location='$location'"; $cached_location = get_data_row($query); if ($cached_location) { return array('lat' => $cached_location->lat, 'long' => $cached_location->long); } // Trigger geocode event if not cached $return = false; $return = elgg_trigger_plugin_hook('geocode', 'location', array('location' => $location), $return); // If returned, cache and return value if (($return) && (is_array($return))) { $lat = (float)$return['lat']; $long = (float)$return['long']; // Put into cache at the end of the page since we don't really care that much $query = "INSERT DELAYED INTO {$CONFIG->dbprefix}geocode_cache " . " (location, lat, `long`) VALUES ('$location', '{$lat}', '{$long}')" . " ON DUPLICATE KEY UPDATE lat='{$lat}', `long`='{$long}'"; execute_delayed_write_query($query); } return $return; } /** * Return entities within a given geographic area. * * Also accepts all options available to elgg_get_entities(). * * @see elgg_get_entities * * @param array $options Array in format: * * latitude => FLOAT Latitude of the location * * longitude => FLOAT Longitude of the location * * distance => FLOAT/ARR ( * latitude => float, * longitude => float, * ) * The distance in degrees that determines the search box. A * single float will result in a square in degrees. * @warning The Earth is round. * * @see ElggEntity::setLatLong() * * @return mixed If count, int. If not count, array. false on errors. * @since 1.8.0 * @deprecated 1.9.0 See geolocation plugin on github */ function elgg_get_entities_from_location(array $options = array()) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. See geolocation plugin on github', 1.9); global $CONFIG; if (!isset($options['latitude']) || !isset($options['longitude']) || !isset($options['distance'])) { return false; } if (!is_array($options['distance'])) { $lat_distance = (float)$options['distance']; $long_distance = (float)$options['distance']; } else { $lat_distance = (float)$options['distance']['latitude']; $long_distance = (float)$options['distance']['longitude']; } $lat = (float)$options['latitude']; $long = (float)$options['longitude']; $lat_min = $lat - $lat_distance; $lat_max = $lat + $lat_distance; $long_min = $long - $long_distance; $long_max = $long + $long_distance; $wheres = array(); $wheres[] = "lat_name.string='geo:lat'"; $wheres[] = "lat_value.string >= $lat_min"; $wheres[] = "lat_value.string <= $lat_max"; $wheres[] = "lon_name.string='geo:long'"; $wheres[] = "lon_value.string >= $long_min"; $wheres[] = "lon_value.string <= $long_max"; $joins = array(); $joins[] = "JOIN {$CONFIG->dbprefix}metadata lat on e.guid=lat.entity_guid"; $joins[] = "JOIN {$CONFIG->dbprefix}metastrings lat_name on lat.name_id=lat_name.id"; $joins[] = "JOIN {$CONFIG->dbprefix}metastrings lat_value on lat.value_id=lat_value.id"; $joins[] = "JOIN {$CONFIG->dbprefix}metadata lon on e.guid=lon.entity_guid"; $joins[] = "JOIN {$CONFIG->dbprefix}metastrings lon_name on lon.name_id=lon_name.id"; $joins[] = "JOIN {$CONFIG->dbprefix}metastrings lon_value on lon.value_id=lon_value.id"; // merge wheres to pass to get_entities() if (isset($options['wheres']) && !is_array($options['wheres'])) { $options['wheres'] = array($options['wheres']); } elseif (!isset($options['wheres'])) { $options['wheres'] = array(); } $options['wheres'] = array_merge($options['wheres'], $wheres); // merge joins to pass to get_entities() if (isset($options['joins']) && !is_array($options['joins'])) { $options['joins'] = array($options['joins']); } elseif (!isset($options['joins'])) { $options['joins'] = array(); } $options['joins'] = array_merge($options['joins'], $joins); return elgg_get_entities_from_relationship($options); } /** * Returns a viewable list of entities from location * * @param array $options Options array * * @see elgg_list_entities() * @see elgg_get_entities_from_location() * * @return string The viewable list of entities * @since 1.8.0 * @deprecated 1.9.0 See geolocation plugin on github */ function elgg_list_entities_from_location(array $options = array()) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. See geolocation plugin on github', 1.9); return elgg_list_entities($options, 'elgg_get_entities_from_location'); } // Some distances in degrees (approximate) // @todo huh? see warning on elgg_get_entities_from_location() // @deprecated 1.9.0 define("MILE", 0.01515); define("KILOMETER", 0.00932); /** * Get the current Elgg version information * * @param bool $humanreadable Whether to return a human readable version (default: false) * * @return string|false Depending on success * @deprecated 1.9 Use elgg_get_version() */ function get_version($humanreadable = false) { elgg_deprecated_notice('get_version() has been deprecated by elgg_get_version()', 1.9); return elgg_get_version($humanreadable); } /** * Sanitise a string for database use, but with the option of escaping extra characters. * * @param string $string The string to sanitise * @param string $extra_escapeable Extra characters to escape with '\\' * * @return string The escaped string * @deprecated 1.9 */ function sanitise_string_special($string, $extra_escapeable = '') { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated.', 1.9); $string = sanitise_string($string); for ($n = 0; $n < strlen($extra_escapeable); $n++) { $string = str_replace($extra_escapeable[$n], "\\" . $extra_escapeable[$n], $string); } return $string; } /** * Establish database connections * * If the configuration has been set up for multiple read/write databases, set those * links up separately; otherwise just create the one database link. * * @return void * @access private * @deprecated 1.9 */ function setup_db_connections() { elgg_deprecated_notice(__FUNCTION__ . ' is a private function and should not be used.', 1.9); _elgg_services()->db->setupConnections(); } /** * Returns (if required, also creates) a database link resource. * * Database link resources are stored in the {@link $dblink} global. These * resources are created by {@link setup_db_connections()}, which is called if * no links exist. * * @param string $dblinktype The type of link we want: "read", "write" or "readwrite". * * @return resource Database link * @access private * @deprecated 1.9 */ function get_db_link($dblinktype) { elgg_deprecated_notice(__FUNCTION__ . ' is a private function and should not be used.', 1.9); return _elgg_services()->db->getLink($dblinktype); } /** * Optimize a table. * * Executes an OPTIMIZE TABLE query on $table. Useful after large DB changes. * * @param string $table The name of the table to optimise * * @return bool * @access private * @deprecated 1.9 */ function optimize_table($table) { elgg_deprecated_notice(__FUNCTION__ . ' is a private function and should not be used.', 1.9); $table = sanitise_string($table); return _elgg_services()->db->updateData("OPTIMIZE TABLE $table"); } /** * Return tables matching the database prefix {@link $CONFIG->dbprefix}% in the currently * selected database. * * @return array|false List of tables or false on failure * @static array $tables Tables found matching the database prefix * @access private * @deprecated 1.9 */ function get_db_tables() { elgg_deprecated_notice(__FUNCTION__ . ' is a private function and should not be used.', 1.9); static $tables; if (isset($tables)) { return $tables; } $table_prefix = elgg_get_config('dbprefix'); $result = get_data("SHOW TABLES LIKE '$table_prefix%'"); $tables = array(); if (is_array($result) && !empty($result)) { foreach ($result as $row) { $row = (array) $row; if (is_array($row) && !empty($row)) { foreach ($row as $element) { $tables[] = $element; } } } } return $tables; } /** * Get the last database error for a particular database link * * @param resource $dblink The DB link * * @return string Database error message * @access private * @deprecated 1.9 */ function get_db_error($dblink) { elgg_deprecated_notice(__FUNCTION__ . ' is a private function and should not be used.', 1.9); return mysql_error($dblink); } /** * Queue a query for execution upon shutdown. * * You can specify a handler function if you care about the result. This function will accept * the raw result from {@link mysql_query()}. * * @param string $query The query to execute * @param resource $dblink The database link to use or the link type (read | write) * @param string $handler A callback function to pass the results array to * * @return boolean Whether successful. * @deprecated 1.9 Use execute_delayed_write_query() or execute_delayed_read_query() */ function execute_delayed_query($query, $dblink, $handler = "") { elgg_deprecated_notice("execute_delayed_query() has been deprecated", 1.9); return _elgg_services()->db->registerDelayedQuery($query, $dblink, $handler); } /** * Return a timestamp for the start of a given day (defaults today). * * @param int $day Day * @param int $month Month * @param int $year Year * * @return int * @access private * @deprecated 1.9 */ function get_day_start($day = null, $month = null, $year = null) { elgg_deprecated_notice('get_day_start() has been deprecated', 1.9); return mktime(0, 0, 0, $month, $day, $year); } /** * Return a timestamp for the end of a given day (defaults today). * * @param int $day Day * @param int $month Month * @param int $year Year * * @return int * @access private * @deprecated 1.9 */ function get_day_end($day = null, $month = null, $year = null) { elgg_deprecated_notice('get_day_end() has been deprecated', 1.9); return mktime(23, 59, 59, $month, $day, $year); } /** * Return the notable entities for a given time period. * * @todo this function also accepts an array(type => subtypes) for 3rd arg. Should we document this? * * @param int $start_time The start time as a unix timestamp. * @param int $end_time The end time as a unix timestamp. * @param string $type The type of entity (eg "user", "object" etc) * @param string $subtype The arbitrary subtype of the entity * @param int $owner_guid The GUID of the owning user * @param string $order_by The field to order by; by default, time_created desc * @param int $limit The number of entities to return; 10 by default * @param int $offset The indexing offset, 0 by default * @param boolean $count Set to true to get a count instead of entities. Defaults to false. * @param int $site_guid Site to get entities for. Default 0 = current site. -1 = any. * @param mixed $container_guid Container or containers to get entities from (default: any). * * @return array|false * @access private * @deprecated 1.9 */ function get_notable_entities($start_time, $end_time, $type = "", $subtype = "", $owner_guid = 0, $order_by = "asc", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) { elgg_deprecated_notice('get_notable_entities() has been deprecated', 1.9); global $CONFIG; if ($subtype === false || $subtype === null || $subtype === 0) { return false; } $start_time = (int)$start_time; $end_time = (int)$end_time; $order_by = sanitise_string($order_by); $limit = (int)$limit; $offset = (int)$offset; $site_guid = (int) $site_guid; if ($site_guid == 0) { $site_guid = $CONFIG->site_guid; } $where = array(); if (is_array($type)) { $tempwhere = ""; if (sizeof($type)) { foreach ($type as $typekey => $subtypearray) { foreach ($subtypearray as $subtypeval) { $typekey = sanitise_string($typekey); if (!empty($subtypeval)) { $subtypeval = (int) get_subtype_id($typekey, $subtypeval); } else { $subtypeval = 0; } if (!empty($tempwhere)) { $tempwhere .= " or "; } $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; } } } if (!empty($tempwhere)) { $where[] = "({$tempwhere})"; } } else { $type = sanitise_string($type); $subtype = get_subtype_id($type, $subtype); if ($type != "") { $where[] = "e.type='$type'"; } if ($subtype !== "") { $where[] = "e.subtype=$subtype"; } } if ($owner_guid != "") { if (!is_array($owner_guid)) { $owner_array = array($owner_guid); $owner_guid = (int) $owner_guid; $where[] = "e.owner_guid = '$owner_guid'"; } else if (sizeof($owner_guid) > 0) { $owner_array = array_map('sanitise_int', $owner_guid); // Cast every element to the owner_guid array to int $owner_guid = implode(",", $owner_guid); $where[] = "e.owner_guid in ({$owner_guid})"; } if (is_null($container_guid)) { $container_guid = $owner_array; } } if ($site_guid > 0) { $where[] = "e.site_guid = {$site_guid}"; } if (!is_null($container_guid)) { if (is_array($container_guid)) { foreach ($container_guid as $key => $val) { $container_guid[$key] = (int) $val; } $where[] = "e.container_guid in (" . implode(",", $container_guid) . ")"; } else { $container_guid = (int) $container_guid; $where[] = "e.container_guid = {$container_guid}"; } } // Add the calendar stuff $cal_join = " JOIN {$CONFIG->dbprefix}metadata cal_start on e.guid=cal_start.entity_guid JOIN {$CONFIG->dbprefix}metastrings cal_start_name on cal_start.name_id=cal_start_name.id JOIN {$CONFIG->dbprefix}metastrings cal_start_value on cal_start.value_id=cal_start_value.id JOIN {$CONFIG->dbprefix}metadata cal_end on e.guid=cal_end.entity_guid JOIN {$CONFIG->dbprefix}metastrings cal_end_name on cal_end.name_id=cal_end_name.id JOIN {$CONFIG->dbprefix}metastrings cal_end_value on cal_end.value_id=cal_end_value.id "; $where[] = "cal_start_name.string='calendar_start'"; $where[] = "cal_start_value.string>=$start_time"; $where[] = "cal_end_name.string='calendar_end'"; $where[] = "cal_end_value.string <= $end_time"; if (!$count) { $query = "SELECT e.* from {$CONFIG->dbprefix}entities e $cal_join where "; } else { $query = "SELECT count(e.guid) as total from {$CONFIG->dbprefix}entities e $cal_join where "; } foreach ($where as $w) { $query .= " $w and "; } $query .= _elgg_get_access_where_sql(); if (!$count) { $query .= " order by n.calendar_start $order_by"; // Add order and limit if ($limit) { $query .= " limit $offset, $limit"; } $dt = get_data($query, "entity_row_to_elggstar"); return $dt; } else { $total = get_data_row($query); return $total->total; } } /** * Return the notable entities for a given time period based on an item of metadata. * * @param int $start_time The start time as a unix timestamp. * @param int $end_time The end time as a unix timestamp. * @param mixed $meta_name Metadata name * @param mixed $meta_value Metadata value * @param string $entity_type The type of entity to look for, eg 'site' or 'object' * @param string $entity_subtype The subtype of the entity. * @param int $owner_guid Owner GUID * @param int $limit Limit * @param int $offset Offset * @param string $order_by Optional ordering. * @param int $site_guid Site to get entities for. Default 0 = current site. -1 = any. * @param bool $count If true, returns count instead of entities. (Default: false) * * @return int|array A list of entities, or a count if $count is set to true * @access private * @deprecated 1.9 */ function get_notable_entities_from_metadata($start_time, $end_time, $meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) { elgg_deprecated_notice('get_notable_entities_from_metadata() has been deprecated', 1.9); global $CONFIG; $meta_n = get_metastring_id($meta_name); $meta_v = get_metastring_id($meta_value); $start_time = (int)$start_time; $end_time = (int)$end_time; $entity_type = sanitise_string($entity_type); $entity_subtype = get_subtype_id($entity_type, $entity_subtype); $limit = (int)$limit; $offset = (int)$offset; if ($order_by == "") { $order_by = "e.time_created desc"; } $order_by = sanitise_string($order_by); $site_guid = (int) $site_guid; if ((is_array($owner_guid) && (count($owner_guid)))) { foreach ($owner_guid as $key => $guid) { $owner_guid[$key] = (int) $guid; } } else { $owner_guid = (int) $owner_guid; } if ($site_guid == 0) { $site_guid = $CONFIG->site_guid; } //$access = get_access_list(); $where = array(); if ($entity_type != "") { $where[] = "e.type='$entity_type'"; } if ($entity_subtype) { $where[] = "e.subtype=$entity_subtype"; } if ($meta_name != "") { $where[] = "m.name_id='$meta_n'"; } if ($meta_value != "") { $where[] = "m.value_id='$meta_v'"; } if ($site_guid > 0) { $where[] = "e.site_guid = {$site_guid}"; } if (is_array($owner_guid)) { $where[] = "e.container_guid in (" . implode(",", $owner_guid) . ")"; } else if ($owner_guid > 0) { $where[] = "e.container_guid = {$owner_guid}"; } // Add the calendar stuff $cal_join = " JOIN {$CONFIG->dbprefix}metadata cal_start on e.guid=cal_start.entity_guid JOIN {$CONFIG->dbprefix}metastrings cal_start_name on cal_start.name_id=cal_start_name.id JOIN {$CONFIG->dbprefix}metastrings cal_start_value on cal_start.value_id=cal_start_value.id JOIN {$CONFIG->dbprefix}metadata cal_end on e.guid=cal_end.entity_guid JOIN {$CONFIG->dbprefix}metastrings cal_end_name on cal_end.name_id=cal_end_name.id JOIN {$CONFIG->dbprefix}metastrings cal_end_value on cal_end.value_id=cal_end_value.id "; $where[] = "cal_start_name.string='calendar_start'"; $where[] = "cal_start_value.string>=$start_time"; $where[] = "cal_end_name.string='calendar_end'"; $where[] = "cal_end_value.string <= $end_time"; if (!$count) { $query = "SELECT distinct e.* "; } else { $query = "SELECT count(distinct e.guid) as total "; } $query .= "from {$CONFIG->dbprefix}entities e" . " JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid $cal_join where"; foreach ($where as $w) { $query .= " $w and "; } // Add access controls $query .= _elgg_get_access_where_sql(array('table_alias' => 'e')); $query .= ' and ' . _elgg_get_access_where_sql(array('table_alias' => "m")); if (!$count) { // Add order and limit $query .= " order by $order_by limit $offset, $limit"; return get_data($query, "entity_row_to_elggstar"); } else { if ($row = get_data_row($query)) { return $row->total; } } return false; } /** * Return the notable entities for a given time period based on their relationship. * * @param int $start_time The start time as a unix timestamp. * @param int $end_time The end time as a unix timestamp. * @param string $relationship The relationship eg "friends_of" * @param int $relationship_guid The guid of the entity to use query * @param bool $inverse_relationship Reverse the normal function of the query to say * "give me all entities for whom $relationship_guid is a * $relationship of" * @param string $type Entity type * @param string $subtype Entity subtype * @param int $owner_guid Owner GUID * @param string $order_by Optional Order by * @param int $limit Limit * @param int $offset Offset * @param boolean $count If true returns a count of entities (default false) * @param int $site_guid Site to get entities for. Default 0 = current site. -1 = any * * @return array|int|false An array of entities, or the number of entities, or false on failure * @access private * @deprecated 1.9 */ function get_noteable_entities_from_relationship($start_time, $end_time, $relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0) { elgg_deprecated_notice('get_noteable_entities_from_relationship() has been deprecated', 1.9); global $CONFIG; $start_time = (int)$start_time; $end_time = (int)$end_time; $relationship = sanitise_string($relationship); $relationship_guid = (int)$relationship_guid; $inverse_relationship = (bool)$inverse_relationship; $type = sanitise_string($type); $subtype = get_subtype_id($type, $subtype); $owner_guid = (int)$owner_guid; if ($order_by == "") { $order_by = "time_created desc"; } $order_by = sanitise_string($order_by); $limit = (int)$limit; $offset = (int)$offset; $site_guid = (int) $site_guid; if ($site_guid == 0) { $site_guid = $CONFIG->site_guid; } //$access = get_access_list(); $where = array(); if ($relationship != "") { $where[] = "r.relationship='$relationship'"; } if ($relationship_guid) { $where[] = $inverse_relationship ? "r.guid_two='$relationship_guid'" : "r.guid_one='$relationship_guid'"; } if ($type != "") { $where[] = "e.type='$type'"; } if ($subtype) { $where[] = "e.subtype=$subtype"; } if ($owner_guid != "") { $where[] = "e.container_guid='$owner_guid'"; } if ($site_guid > 0) { $where[] = "e.site_guid = {$site_guid}"; } // Add the calendar stuff $cal_join = " JOIN {$CONFIG->dbprefix}metadata cal_start on e.guid=cal_start.entity_guid JOIN {$CONFIG->dbprefix}metastrings cal_start_name on cal_start.name_id=cal_start_name.id JOIN {$CONFIG->dbprefix}metastrings cal_start_value on cal_start.value_id=cal_start_value.id JOIN {$CONFIG->dbprefix}metadata cal_end on e.guid=cal_end.entity_guid JOIN {$CONFIG->dbprefix}metastrings cal_end_name on cal_end.name_id=cal_end_name.id JOIN {$CONFIG->dbprefix}metastrings cal_end_value on cal_end.value_id=cal_end_value.id "; $where[] = "cal_start_name.string='calendar_start'"; $where[] = "cal_start_value.string>=$start_time"; $where[] = "cal_end_name.string='calendar_end'"; $where[] = "cal_end_value.string <= $end_time"; // Select what we're joining based on the options $joinon = "e.guid = r.guid_one"; if (!$inverse_relationship) { $joinon = "e.guid = r.guid_two"; } if ($count) { $query = "SELECT count(distinct e.guid) as total "; } else { $query = "SELECT distinct e.* "; } $query .= " from {$CONFIG->dbprefix}entity_relationships r" . " JOIN {$CONFIG->dbprefix}entities e on $joinon $cal_join where "; foreach ($where as $w) { $query .= " $w and "; } // Add access controls $query .= _elgg_get_access_where_sql(); if (!$count) { $query .= " order by $order_by limit $offset, $limit"; // Add order and limit return get_data($query, "entity_row_to_elggstar"); } else { if ($count = get_data_row($query)) { return $count->total; } } return false; } /** * Get all entities for today. * * @param string $type The type of entity (eg "user", "object" etc) * @param string $subtype The arbitrary subtype of the entity * @param int $owner_guid The GUID of the owning user * @param string $order_by The field to order by; by default, time_created desc * @param int $limit The number of entities to return; 10 by default * @param int $offset The indexing offset, 0 by default * @param boolean $count If true returns a count of entities (default false) * @param int $site_guid Site to get entities for. Default 0 = current site. -1 = any * @param mixed $container_guid Container(s) to get entities from (default: any). * * @return array|false * @access private * @deprecated 1.9 */ function get_todays_entities($type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) { elgg_deprecated_notice('get_todays_entities() has been deprecated', 1.9); $day_start = get_day_start(); $day_end = get_day_end(); return get_notable_entities($day_start, $day_end, $type, $subtype, $owner_guid, $order_by, $limit, $offset, $count, $site_guid, $container_guid); } /** * Get entities for today from metadata. * * @param mixed $meta_name Metadata name * @param mixed $meta_value Metadata value * @param string $entity_type The type of entity to look for, eg 'site' or 'object' * @param string $entity_subtype The subtype of the entity. * @param int $owner_guid Owner GUID * @param int $limit Limit * @param int $offset Offset * @param string $order_by Optional ordering. * @param int $site_guid Site to get entities for. Default 0 = current site. -1 = any. * @param bool $count If true, returns count instead of entities. (Default: false) * * @return int|array A list of entities, or a count if $count is set to true * @access private * @deprecated 1.9 */ function get_todays_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) { elgg_deprecated_notice('get_todays_entities_from_metadata() has been deprecated', 1.9); $day_start = get_day_start(); $day_end = get_day_end(); return get_notable_entities_from_metadata($day_start, $day_end, $meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, $order_by, $site_guid, $count); } /** * Get entities for today from a relationship * * @param string $relationship The relationship eg "friends_of" * @param int $relationship_guid The guid of the entity to use query * @param bool $inverse_relationship Reverse the normal function of the query to say * "give me all entities for whom $relationship_guid is a * $relationship of" * @param string $type Entity type * @param string $subtype Entity subtype * @param int $owner_guid Owner GUID * @param string $order_by Optional Order by * @param int $limit Limit * @param int $offset Offset * @param boolean $count If true returns a count of entities (default false) * @param int $site_guid Site to get entities for. Default 0 = current site. -1 = any * * @return array|int|false An array of entities, or the number of entities, or false on failure * @access private * @deprecated 1.9 */ function get_todays_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0) { elgg_deprecated_notice('get_todays_entities_from_relationship() has been deprecated', 1.9); $day_start = get_day_start(); $day_end = get_day_end(); return get_notable_entities_from_relationship($day_start, $day_end, $relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, $order_by, $limit, $offset, $count, $site_guid); } /** * Returns a viewable list of entities for a given time period. * * @see elgg_view_entity_list * * @param int $start_time The start time as a unix timestamp. * @param int $end_time The end time as a unix timestamp. * @param string $type The type of entity (eg "user", "object" etc) * @param string $subtype The arbitrary subtype of the entity * @param int $owner_guid The GUID of the owning user * @param int $limit The number of entities to return; 10 by default * @param boolean $fullview Whether or not to display the full view (default: true) * @param boolean $listtypetoggle Whether or not to allow gallery view * @param boolean $navigation Display pagination? Default: true * * @return string A viewable list of entities * @access private * @deprecated 1.9 */ function list_notable_entities($start_time, $end_time, $type= "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $listtypetoggle = false, $navigation = true) { elgg_deprecated_notice('list_notable_entities() has been deprecated', 1.9); $offset = (int) get_input('offset'); $count = get_notable_entities($start_time, $end_time, $type, $subtype, $owner_guid, "", $limit, $offset, true); $entities = get_notable_entities($start_time, $end_time, $type, $subtype, $owner_guid, "", $limit, $offset); return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $listtypetoggle, $navigation); } /** * Return a list of today's entities. * * @see list_notable_entities * * @param string $type The type of entity (eg "user", "object" etc) * @param string $subtype The arbitrary subtype of the entity * @param int $owner_guid The GUID of the owning user * @param int $limit The number of entities to return; 10 by default * @param boolean $fullview Whether or not to display the full view (default: true) * @param boolean $listtypetoggle Whether or not to allow gallery view * @param boolean $navigation Display pagination? Default: true * * @return string A viewable list of entities * @access private * @deprecated 1.9 */ function list_todays_entities($type= "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $listtypetoggle = false, $navigation = true) { elgg_deprecated_notice('list_todays_entities() has been deprecated', 1.9); $day_start = get_day_start(); $day_end = get_day_end(); return list_notable_entities($day_start, $day_end, $type, $subtype, $owner_guid, $limit, $fullview, $listtypetoggle, $navigation); } /** * Regenerates the simple cache. * * Not required any longer since cached files are created on demand. * * @warning This does not invalidate the cache, but actively rebuilds it. * * @param string $viewtype Optional viewtype to regenerate. Defaults to all valid viewtypes. * * @return void * @since 1.8.0 * @deprecated 1.9 Use elgg_invalidate_simplecache() */ function elgg_regenerate_simplecache($viewtype = NULL) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_invalidate_simplecache()', 1.9); elgg_invalidate_simplecache(); } /** * @access private * @deprecated 1.9 Use elgg_get_system_cache() */ function elgg_get_filepath_cache() { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_get_system_cache()', 1.9); return elgg_get_system_cache(); } /** * @access private * @deprecated 1.9 Use elgg_reset_system_cache() */ function elgg_filepath_cache_reset() { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_reset_system_cache()', 1.9); elgg_reset_system_cache(); } /** * @access private * @deprecated 1.9 Use elgg_save_system_cache() */ function elgg_filepath_cache_save($type, $data) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_save_system_cache()', 1.9); return elgg_save_system_cache($type, $data); } /** * @access private * @deprecated 1.9 Use elgg_load_system_cache() */ function elgg_filepath_cache_load($type) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_load_system_cache()', 1.9); return elgg_load_system_cache($type); } /** * @access private * @deprecated 1.9 Use elgg_enable_system_cache() */ function elgg_enable_filepath_cache() { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_enable_system_cache()', 1.9); elgg_enable_system_cache(); } /** * @access private * @deprecated 1.9 Use elgg_disable_system_cache() */ function elgg_disable_filepath_cache() { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_disable_system_cache()', 1.9); elgg_disable_system_cache(); } /** * Unregisters an entity type and subtype as a public-facing type. * * @warning With a blank subtype, it unregisters that entity type including * all subtypes. This must be called after all subtypes have been registered. * * @param string $type The type of entity (object, site, user, group) * @param string $subtype The subtype to register (may be blank) * * @return true|false Depending on success * @deprecated 1.9 Use {@link elgg_unregister_entity_type()} */ function unregister_entity_type($type, $subtype) { elgg_deprecated_notice("unregister_entity_type() was deprecated by elgg_unregister_entity_type()", 1.9); return elgg_unregister_entity_type($type, $subtype); } /** * Function to determine if the object trying to attach to other, has already done so * * @param int $guid_one This is the target object * @param int $guid_two This is the object trying to attach to $guid_one * * @return bool * @access private * @deprecated 1.9 Use check_entity_relationship() */ function already_attached($guid_one, $guid_two) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); if ($attached = check_entity_relationship($guid_one, "attached", $guid_two)) { return true; } else { return false; } } /** * Function to get all objects attached to a particular object * * @param int $guid Entity GUID * @param string $type The type of object to return e.g. 'file', 'friend_of' etc * * @return an array of objects * @access private * @deprecated 1.9 Use elgg_get_entities_from_relationship() */ function get_attachments($guid, $type = "") { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $options = array( 'relationship' => 'attached', 'relationship_guid' => $guid, 'inverse_relationship' => false, 'types' => $type, 'subtypes' => '', 'owner_guid' => 0, 'order_by' => 'time_created desc', 'limit' => 10, 'offset' => 0, 'count' => false, 'site_guid' => 0 ); $attached = elgg_get_entities_from_relationship($options); return $attached; } /** * Function to remove a particular attachment between two objects * * @param int $guid_one This is the target object * @param int $guid_two This is the object to remove from $guid_one * * @return void * @access private * @deprecated 1.9 Use remove_entity_relationship() */ function remove_attachment($guid_one, $guid_two) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); if (already_attached($guid_one, $guid_two)) { remove_entity_relationship($guid_one, "attached", $guid_two); } } /** * Function to start the process of attaching one object to another * * @param int $guid_one This is the target object * @param int $guid_two This is the object trying to attach to $guid_one * * @return true|void * @access private * @deprecated 1.9 Use add_entity_relationship() */ function make_attachment($guid_one, $guid_two) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); if (!(already_attached($guid_one, $guid_two))) { if (add_entity_relationship($guid_one, "attached", $guid_two)) { return true; } } } /** * Returns the URL for an entity. * * @param int $entity_guid The GUID of the entity * * @return string The URL of the entity * @deprecated 1.9 Use ElggEntity::getURL() */ function get_entity_url($entity_guid) { elgg_deprecated_notice('get_entity_url has been deprecated in favor of ElggEntity::getURL', '1.9'); if ($entity = get_entity($entity_guid)) { return $entity->getURL(); } return false; } /** * Delete an entity. * * Removes an entity and its metadata, annotations, relationships, river entries, * and private data. * * Optionally can remove entities contained and owned by $guid. * * @warning If deleting recursively, this bypasses ownership of items contained by * the entity. That means that if the container_guid = $guid, the item will be deleted * regardless of who owns it. * * @param int $guid The guid of the entity to delete * @param bool $recursive If true (default) then all entities which are * owned or contained by $guid will also be deleted. * * @return bool * @access private * @deprecated 1.9 Use ElggEntity::delete() instead. */ function delete_entity($guid, $recursive = true) { elgg_deprecated_notice('delete_entity has been deprecated in favor of ElggEntity::delete', '1.9'); $guid = (int)$guid; if ($entity = get_entity($guid)) { return $entity->delete($recursive); } return false; } /** * Enable an entity. * * @warning In order to enable an entity using ElggEntity::enable(), * you must first use {@link access_show_hidden_entities()}. * * @param int $guid GUID of entity to enable * @param bool $recursive Recursively enable all entities disabled with the entity? * * @return bool * @deprecated 1.9 Use elgg_enable_entity() */ function enable_entity($guid, $recursive = true) { elgg_deprecated_notice('enable_entity has been deprecated in favor of elgg_enable_entity', '1.9'); $guid = (int)$guid; // Override access only visible entities $old_access_status = access_get_show_hidden_status(); access_show_hidden_entities(true); $result = false; if ($entity = get_entity($guid)) { $result = $entity->enable($recursive); } access_show_hidden_entities($old_access_status); return $result; } /** * Returns if $user_guid can edit the metadata on $entity_guid. * * @tip Can be overridden by by registering for the permissions_check:metadata * plugin hook. * * @warning If a $user_guid isn't specified, the currently logged in user is used. * * @param int $entity_guid The GUID of the entity * @param int $user_guid The GUID of the user * @param ElggMetadata $metadata The metadata to specifically check (if any; default null) * * @return bool Whether the user can edit metadata on the entity. * @deprecated 1.9 Use ElggEntity::canEditMetadata */ function can_edit_entity_metadata($entity_guid, $user_guid = 0, $metadata = null) { elgg_deprecated_notice('can_edit_entity_metadata has been deprecated in favor of ElggEntity::canEditMetadata', '1.9'); if ($entity = get_entity($entity_guid)) { return $entity->canEditMetadata($metadata, $user_guid); } else { return false; } } /** * Disable an entity. * * Disabled entities do not show up in list or elgg_get_entities() * calls, but still exist in the database. * * Entities are disabled by setting disabled = yes in the * entities table. * * You can ignore the disabled field by using {@link access_show_hidden_entities()}. * * @param int $guid The guid * @param string $reason Optional reason * @param bool $recursive Recursively disable all entities owned or contained by $guid? * * @return bool * @see access_show_hidden_entities() * @access private * @deprecated 1.9 Use ElggEntity::disable instead. */ function disable_entity($guid, $reason = "", $recursive = true) { elgg_deprecated_notice('disable_entity was deprecated in favor of ElggEntity::disable', '1.9'); if ($entity = get_entity($guid)) { return $entity->disable($reason, $recursive); } return false; } /** * Returns if $user_guid is able to edit $entity_guid. * * @tip Can be overridden by registering for the permissions_check plugin hook. * * @warning If a $user_guid is not passed it will default to the logged in user. * * @param int $entity_guid The GUID of the entity * @param int $user_guid The GUID of the user * * @return bool * @deprecated 1.9 Use ElggEntity::canEdit instead */ function can_edit_entity($entity_guid, $user_guid = 0) { elgg_deprecated_notice('can_edit_entity was deprecated in favor of ElggEntity::canEdit', '1.9'); if ($entity = get_entity($entity_guid)) { return $entity->canEdit($user_guid); } return false; } /** * Join a user to a group. * * @param int $group_guid The group GUID. * @param int $user_guid The user GUID. * * @return bool * @deprecated 1.9 Use ElggGroup::join instead. */ function join_group($group_guid, $user_guid) { elgg_deprecated_notice('join_group was deprecated in favor of ElggGroup::join', '1.9'); $group = get_entity($group_guid); $user = get_entity($user_guid); if ($group instanceof ElggGroup && $user instanceof ElggUser) { return $group->join($user); } return false; } /** * Remove a user from a group. * * @param int $group_guid The group. * @param int $user_guid The user. * * @return bool Whether the user was removed from the group. * @deprecated 1.9 Use ElggGroup::leave() */ function leave_group($group_guid, $user_guid) { elgg_deprecated_notice('leave_group was deprecated in favor of ElggGroup::leave', '1.9'); $group = get_entity($group_guid); $user = get_entity($user_guid); if ($group instanceof ElggGroup && $user instanceof ElggUser) { return $group->leave($user); } return false; } /** * Create paragraphs from text with line spacing * * @param string $string The string * @return string * @deprecated 1.9 Use elgg_autop instead **/ function autop($string) { elgg_deprecated_notice('autop has been deprecated in favor of elgg_autop', '1.9'); return elgg_autop($string); } /** * Register a function as a web service method * * @deprecated 1.9 Enable the web services plugin and use elgg_ws_expose_function(). */ function expose_function($method, $function, array $parameters = NULL, $description = "", $call_method = "GET", $require_api_auth = false, $require_user_auth = false) { elgg_deprecated_notice("expose_function() deprecated for the function elgg_ws_expose_function() in web_services plugin", 1.9); if (!elgg_admin_notice_exists("elgg:ws:1.9")) { elgg_add_admin_notice("elgg:ws:1.9", "The web services are now a plugin in Elgg 1.9. You must enable this plugin and update your web services to use elgg_ws_expose_function()."); } if (function_exists("elgg_ws_expose_function")) { return elgg_ws_expose_function($method, $function, $parameters, $description, $call_method, $require_api_auth, $require_user_auth); } } /** * Unregister a web services method * * @param string $method The api name that was exposed * @return void * @deprecated 1.9 Enable the web services plugin and use elgg_ws_unexpose_function(). */ function unexpose_function($method) { elgg_deprecated_notice("unexpose_function() deprecated for the function elgg_ws_unexpose_function() in web_services plugin", 1.9); if (function_exists("elgg_ws_unexpose_function")) { return elgg_ws_unexpose_function($method); } } /** * Registers a web services handler * * @param string $handler Web services type * @param string $function Your function name * @return bool Depending on success * @deprecated 1.9 Enable the web services plugin and use elgg_ws_register_service_handler(). */ function register_service_handler($handler, $function) { elgg_deprecated_notice("register_service_handler() deprecated for the function elgg_ws_register_service_handler() in web_services plugin", 1.9); if (function_exists("elgg_ws_register_service_handler")) { return elgg_ws_register_service_handler($handler, $function); } } /** * Remove a web service * To replace a web service handler, register the desired handler over the old on * with register_service_handler(). * * @param string $handler web services type * @return void * @deprecated 1.9 Enable the web services plugin and use elgg_ws_unregister_service_handler(). */ function unregister_service_handler($handler) { elgg_deprecated_notice("unregister_service_handler() deprecated for the function elgg_ws_unregister_service_handler() in web_services plugin", 1.9); if (function_exists("elgg_ws_unregister_service_handler")) { return elgg_ws_unregister_service_handler($handler); } } /** * Create or update the entities table for a given site. * Call create_entity first. * * @param int $guid Site GUID * @param string $name Site name * @param string $description Site Description * @param string $url URL of the site * * @return bool * @access private * @deprecated 1.9 Use ElggSite constructor */ function create_site_entity($guid, $name, $description, $url) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggSite constructor', 1.9); global $CONFIG; $guid = (int)$guid; $name = sanitise_string($name); $description = sanitise_string($description); $url = sanitise_string($url); $row = get_entity_as_row($guid); if ($row) { // Exists and you have access to it $query = "SELECT guid from {$CONFIG->dbprefix}sites_entity where guid = {$guid}"; if ($exists = get_data_row($query)) { $query = "UPDATE {$CONFIG->dbprefix}sites_entity set name='$name', description='$description', url='$url' where guid=$guid"; $result = update_data($query); if ($result != false) { // Update succeeded, continue $entity = get_entity($guid); if (elgg_trigger_event('update', $entity->type, $entity)) { return $guid; } else { $entity->delete(); //delete_entity($guid); } } } else { // Update failed, attempt an insert. $query = "INSERT into {$CONFIG->dbprefix}sites_entity (guid, name, description, url) values ($guid, '$name', '$description', '$url')"; $result = insert_data($query); if ($result !== false) { $entity = get_entity($guid); if (elgg_trigger_event('create', $entity->type, $entity)) { return $guid; } else { $entity->delete(); //delete_entity($guid); } } } } return false; } /** * Create or update the entities table for a given group. * Call create_entity first. * * @param int $guid GUID * @param string $name Name * @param string $description Description * * @return bool * @access private * @deprecated 1.9 Use ElggGroup constructor */ function create_group_entity($guid, $name, $description) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggGroup constructor', 1.9); global $CONFIG; $guid = (int)$guid; $name = sanitise_string($name); $description = sanitise_string($description); $row = get_entity_as_row($guid); if ($row) { // Exists and you have access to it $exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}groups_entity WHERE guid = {$guid}"); if ($exists) { $query = "UPDATE {$CONFIG->dbprefix}groups_entity set" . " name='$name', description='$description' where guid=$guid"; $result = update_data($query); if ($result != false) { // Update succeeded, continue $entity = get_entity($guid); if (elgg_trigger_event('update', $entity->type, $entity)) { return $guid; } else { $entity->delete(); } } } else { // Update failed, attempt an insert. $query = "INSERT into {$CONFIG->dbprefix}groups_entity" . " (guid, name, description) values ($guid, '$name', '$description')"; $result = insert_data($query); if ($result !== false) { $entity = get_entity($guid); if (elgg_trigger_event('create', $entity->type, $entity)) { return $guid; } else { $entity->delete(); } } } } return false; } /** * Create or update the entities table for a given user. * Call create_entity first. * * @param int $guid The user's GUID * @param string $name The user's display name * @param string $username The username * @param string $password The password * @param string $salt A salt for the password * @param string $email The user's email address * @param string $language The user's default language * @param string $code A code * * @return bool * @access private * @deprecated 1.9 Use ElggUser constructor */ function create_user_entity($guid, $name, $username, $password, $salt, $email, $language, $code) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggUser constructor', 1.9); global $CONFIG; $guid = (int)$guid; $name = sanitise_string($name); $username = sanitise_string($username); $password = sanitise_string($password); $salt = sanitise_string($salt); $email = sanitise_string($email); $language = sanitise_string($language); $row = get_entity_as_row($guid); if ($row) { // Exists and you have access to it $query = "SELECT guid from {$CONFIG->dbprefix}users_entity where guid = {$guid}"; if ($exists = get_data_row($query)) { $query = "UPDATE {$CONFIG->dbprefix}users_entity SET name='$name', username='$username', password='$password', salt='$salt', email='$email', language='$language' WHERE guid = $guid"; $result = update_data($query); if ($result != false) { // Update succeeded, continue $entity = get_entity($guid); if (elgg_trigger_event('update', $entity->type, $entity)) { return $guid; } else { $entity->delete(); } } } else { // Exists query failed, attempt an insert. $query = "INSERT into {$CONFIG->dbprefix}users_entity (guid, name, username, password, salt, email, language) values ($guid, '$name', '$username', '$password', '$salt', '$email', '$language')"; $result = insert_data($query); if ($result !== false) { $entity = get_entity($guid); if (elgg_trigger_event('create', $entity->type, $entity)) { return $guid; } else { $entity->delete(); } } } } return false; } /** * Create or update the extras table for a given object. * Call create_entity first. * * @param int $guid The guid of the entity you're creating (as obtained by create_entity) * @param string $title The title of the object * @param string $description The object's description * * @return bool * @access private * @deprecated 1.9 Use ElggObject constructor */ function create_object_entity($guid, $title, $description) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggObject constructor', 1.9); global $CONFIG; $guid = (int)$guid; $title = sanitise_string($title); $description = sanitise_string($description); $row = get_entity_as_row($guid); if ($row) { // Core entities row exists and we have access to it $query = "SELECT guid from {$CONFIG->dbprefix}objects_entity where guid = {$guid}"; if ($exists = get_data_row($query)) { $query = "UPDATE {$CONFIG->dbprefix}objects_entity set title='$title', description='$description' where guid=$guid"; $result = update_data($query); if ($result != false) { // Update succeeded, continue $entity = get_entity($guid); elgg_trigger_event('update', $entity->type, $entity); return $guid; } } else { // Update failed, attempt an insert. $query = "INSERT into {$CONFIG->dbprefix}objects_entity (guid, title, description) values ($guid, '$title','$description')"; $result = insert_data($query); if ($result !== false) { $entity = get_entity($guid); if (elgg_trigger_event('create', $entity->type, $entity)) { return $guid; } else { $entity->delete(); } } } } return false; } /** * Attempt to construct an ODD object out of a XmlElement or sub-elements. * * @param XmlElement $element The element(s) * * @return mixed An ODD object if the element can be handled, or false. * @access private * @deprecated 1.9 */ function ODD_factory (XmlElement $element) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $name = $element->name; $odd = false; switch ($name) { case 'entity' : $odd = new ODDEntity("", "", ""); break; case 'metadata' : $odd = new ODDMetaData("", "", "", ""); break; case 'relationship' : $odd = new ODDRelationship("", "", ""); break; } // Now populate values if ($odd) { // Attributes foreach ($element->attributes as $k => $v) { $odd->setAttribute($k, $v); } // Body $body = $element->content; $a = stripos($body, "<![CDATA"); $b = strripos($body, "]]>"); if (($body) && ($a !== false) && ($b !== false)) { $body = substr($body, $a + 8, $b - ($a + 8)); } $odd->setBody($body); } return $odd; } /** * Utility function used by import_entity_plugin_hook() to * process an ODDEntity into an unsaved ElggEntity. * * @param ODDEntity $element The OpenDD element * * @return ElggEntity the unsaved entity which should be populated by items. * @todo Remove this. * @access private * * @throws ClassException|InstallationException|ImportException * @deprecated 1.9 */ function oddentity_to_elggentity(ODDEntity $element) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $class = $element->getAttribute('class'); $subclass = $element->getAttribute('subclass'); // See if we already have imported this uuid $tmp = get_entity_from_uuid($element->getAttribute('uuid')); if (!$tmp) { // Construct new class with owner from session $classname = get_subtype_class($class, $subclass); if ($classname) { if (class_exists($classname)) { $tmp = new $classname(); if (!($tmp instanceof ElggEntity)) { $msg = $classname . " is not a " . get_class() . "."; throw new ClassException($msg); } } else { error_log("Class '" . $classname . "' was not found, missing plugin?"); } } else { switch ($class) { case 'object' : $tmp = new ElggObject(); break; case 'user' : $tmp = new ElggUser(); break; case 'group' : $tmp = new ElggGroup(); break; case 'site' : $tmp = new ElggSite(); break; default: $msg = "Type " . $class . " is not supported. This indicates an error in your installation, most likely caused by an incomplete upgrade."; throw new InstallationException($msg); } } } if ($tmp) { if (!$tmp->import($element)) { $msg = "Could not import element " . $element->getAttribute('uuid'); throw new ImportException($msg); } return $tmp; } return NULL; } /** * Import an ODD document. * * @param string $xml The XML ODD. * * @return ODDDocument * @access private * @deprecated 1.9 */ function ODD_Import($xml) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); // Parse XML to an array $elements = xml_to_object($xml); // Sanity check 1, was this actually XML? if ((!$elements) || (!$elements->children)) { return false; } // Create ODDDocument $document = new ODDDocument(); // Itterate through array of elements and construct ODD document $cnt = 0; foreach ($elements->children as $child) { $odd = ODD_factory($child); if ($odd) { $document->addElement($odd); $cnt++; } } // Check that we actually found something if ($cnt == 0) { return false; } return $document; } /** * Export an ODD Document. * * @param ODDDocument $document The Document. * * @return string * @access private * @deprecated 1.9 */ function ODD_Export(ODDDocument $document) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); return "$document"; } /** * Get a UUID from a given object. * * @param mixed $object The object either an ElggEntity, ElggRelationship or ElggExtender * * @return string|false the UUID or false * @deprecated 1.9 */ function get_uuid_from_object($object) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); if ($object instanceof ElggEntity) { return guid_to_uuid($object->guid); } else if ($object instanceof ElggExtender) { $type = $object->type; if ($type == 'volatile') { $uuid = guid_to_uuid($object->entity_guid) . $type . "/{$object->name}/"; } else { $uuid = guid_to_uuid($object->entity_guid) . $type . "/{$object->id}/"; } return $uuid; } else if ($object instanceof ElggRelationship) { return guid_to_uuid($object->guid_one) . "relationship/{$object->id}/"; } return false; } /** * Generate a UUID from a given GUID. * * @param int $guid The GUID of an object. * * @return string * @deprecated 1.9 */ function guid_to_uuid($guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); return elgg_get_site_url() . "export/opendd/$guid/"; } /** * Test to see if a given uuid is for this domain, returning true if so. * * @param string $uuid A unique ID * * @return bool * @deprecated 1.9 */ function is_uuid_this_domain($uuid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); if (strpos($uuid, elgg_get_site_url()) === 0) { return true; } return false; } /** * This function attempts to retrieve a previously imported entity via its UUID. * * @param string $uuid A unique ID * * @return ElggEntity|false * @deprecated 1.9 */ function get_entity_from_uuid($uuid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $uuid = sanitise_string($uuid); $options = array('metadata_name' => 'import_uuid', 'metadata_value' => $uuid); $entities = elgg_get_entities_from_metadata($options); if ($entities) { return $entities[0]; } return false; } /** * Tag a previously created guid with the uuid it was imported on. * * @param int $guid A GUID * @param string $uuid A Unique ID * * @return bool * @deprecated 1.9 */ function add_uuid_to_guid($guid, $uuid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $guid = (int)$guid; $uuid = sanitise_string($uuid); $result = create_metadata($guid, "import_uuid", $uuid); return (bool)$result; } $IMPORTED_DATA = array(); $IMPORTED_OBJECT_COUNTER = 0; /** * This function processes an element, passing elements to the plugin stack to see if someone will * process it. * * If nobody processes the top level element, the sub level elements are processed. * * @param ODD $odd The odd element to process * * @return bool * @access private * @deprecated 1.9 */ function _process_element(ODD $odd) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); global $IMPORTED_DATA, $IMPORTED_OBJECT_COUNTER; // See if anyone handles this element, return true if it is. $to_be_serialised = null; if ($odd) { $handled = elgg_trigger_plugin_hook("import", "all", array("element" => $odd), $to_be_serialised); // If not, then see if any of its sub elements are handled if ($handled) { // Increment validation counter $IMPORTED_OBJECT_COUNTER ++; // Return the constructed object $IMPORTED_DATA[] = $handled; return true; } } return false; } /** * Exports an entity as an array * * @param int $guid Entity GUID * * @return array * @throws ExportException * @access private * @deprecated 1.9 */ function exportAsArray($guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $guid = (int)$guid; // Trigger a hook to $to_be_serialised = elgg_trigger_plugin_hook("export", "all", array("guid" => $guid), array()); // Sanity check if ((!is_array($to_be_serialised)) || (count($to_be_serialised) == 0)) { throw new ExportException("No such entity GUID:" . $guid); } return $to_be_serialised; } /** * Export a GUID. * * This function exports a GUID and all information related to it in an XML format. * * This function makes use of the "serialise" plugin hook, which is passed an array to which plugins * should add data to be serialised to. * * @param int $guid The GUID. * * @return string XML * @see ElggEntity for an example of its usage. * @access private * @deprecated 1.9 */ function export($guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); $odd = new ODDDocument(exportAsArray($guid)); return ODD_Export($odd); } /** * Import an XML serialisation of an object. * This will make a best attempt at importing a given xml doc. * * @param string $xml XML string * * @return bool * @throws ImportException if there was a problem importing the data. * @access private * @deprecated 1.9 */ function import($xml) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated', 1.9); global $IMPORTED_DATA, $IMPORTED_OBJECT_COUNTER; $IMPORTED_DATA = array(); $IMPORTED_OBJECT_COUNTER = 0; $document = ODD_Import($xml); if (!$document) { throw new ImportException("No OpenDD elements found in import data, import failed."); } foreach ($document as $element) { _process_element($element); } if ($IMPORTED_OBJECT_COUNTER != count($IMPORTED_DATA)) { throw new ImportException("Not all elements were imported."); } return true; } /** * Register the OpenDD import action * * @return void * @access private * @deprecated 1.9 */ function _export_init() { global $CONFIG; elgg_register_action("import/opendd"); } // Register a startup event elgg_register_event_handler('init', 'system', '_export_init', 100); /** * Returns the name of views for in a directory. * * Use this to get all namespaced views under the first element. * * @param string $dir The main directory that holds the views. (mod/profile/views/) * @param string $base The root name of the view to use, without the viewtype. (profile) * * @return array * @since 1.7.0 * @todo Why isn't this used anywhere else but in elgg_view_tree()? * Seems like a useful function for autodiscovery. * @access private * @deprecated 1.9 */ function elgg_get_views($dir, $base) { $return = array(); if (file_exists($dir) && is_dir($dir)) { if ($handle = opendir($dir)) { while ($view = readdir($handle)) { if (!in_array($view, array('.', '..', '.svn', 'CVS'))) { if (is_dir($dir . '/' . $view)) { if ($val = elgg_get_views($dir . '/' . $view, $base . '/' . $view)) { $return = array_merge($return, $val); } } else { $view = str_replace('.php', '', $view); $return[] = $base . '/' . $view; } } } } } return $return; } /** * Returns all views below a partial view. * * Settings $view_root = 'profile' will show all available views under * the "profile" namespace. * * @param string $view_root The root view * @param string $viewtype Optionally specify a view type * other than the current one. * * @return array A list of view names underneath that root view * @todo This is used once in the deprecated get_activity_stream_data() function. * @access private * @deprecated 1.9 */ function elgg_view_tree($view_root, $viewtype = "") { global $CONFIG; static $treecache = array(); // Get viewtype if (!$viewtype) { $viewtype = elgg_get_viewtype(); } // A little light internal caching if (!empty($treecache[$view_root])) { return $treecache[$view_root]; } // Examine $CONFIG->views->locations if (isset($CONFIG->views->locations[$viewtype])) { foreach ($CONFIG->views->locations[$viewtype] as $view => $path) { $pos = strpos($view, $view_root); if ($pos === 0) { $treecache[$view_root][] = $view; } } } // Now examine core $location = $CONFIG->viewpath; $viewtype = elgg_get_viewtype(); $root = $location . $viewtype . '/' . $view_root; if (file_exists($root) && is_dir($root)) { $val = elgg_get_views($root, $view_root); if (!is_array($treecache[$view_root])) { $treecache[$view_root] = array(); } $treecache[$view_root] = array_merge($treecache[$view_root], $val); } return $treecache[$view_root]; } /** * Adds an item to the river. * * @param string $view The view that will handle the river item (must exist) * @param string $action_type An arbitrary string to define the action (eg 'comment', 'create') * @param int $subject_guid The GUID of the entity doing the action * @param int $object_guid The GUID of the entity being acted upon * @param int $access_id The access ID of the river item (default: same as the object) * @param int $posted The UNIX epoch timestamp of the river item (default: now) * @param int $annotation_id The annotation ID associated with this river entry * @param int $target_guid The GUID of the the object entity's container * * @return int/bool River ID or false on failure * @deprecated 1.9 Use elgg_create_river_item() */ function add_to_river($view, $action_type, $subject_guid, $object_guid, $access_id = "", $posted = 0, $annotation_id = 0, $target_guid = 0) { elgg_deprecated_notice('add_to_river was deprecated in favor of elgg_create_river_item', '1.9'); // Make sure old parameters are passed in correct format $access_id = ($access_id == '') ? null : $access_id; $posted = ($posted == 0) ? null : $posted; return elgg_create_river_item(array( 'view' => $view, 'action_type' => $action_type, 'subject_guid' => $subject_guid, 'object_guid' => $object_guid, 'target_guid' => $target_guid, 'access_id' => $access_id, 'posted' => $posted, 'annotation_id' => $annotation_id, )); } /** * This function serialises an object recursively into an XML representation. * * The function attempts to call $data->export() which expects a stdClass in return, * otherwise it will attempt to get the object variables using get_object_vars (which * will only return public variables!) * * @param mixed $data The object to serialise. * @param string $name The name? * @param int $n Level, only used for recursion. * * @return string The serialised XML output. * @deprecated 1.9 */ function serialise_object_to_xml($data, $name = "", $n = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated.', 1.9); $classname = ($name == "" ? get_class($data) : $name); $vars = method_exists($data, "export") ? get_object_vars($data->export()) : get_object_vars($data); $output = ""; if (($n == 0) || ( is_object($data) && !($data instanceof stdClass))) { $output = "<$classname>"; } foreach ($vars as $key => $value) { $output .= "<$key type=\"" . gettype($value) . "\">"; if (is_object($value)) { $output .= serialise_object_to_xml($value, $key, $n + 1); } else if (is_array($value)) { $output .= serialise_array_to_xml($value, $n + 1); } else if (gettype($value) == "boolean") { $output .= $value ? "true" : "false"; } else { $output .= htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8'); } $output .= "</$key>\n"; } if (($n == 0) || (is_object($data) && !($data instanceof stdClass))) { $output .= "</$classname>\n"; } return $output; } /** * Serialise an array. * * @param array $data The data to serialize * @param int $n Used for recursion * * @return string * @deprecated 1.9 */ function serialise_array_to_xml(array $data, $n = 0) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated.', 1.9); $output = ""; if ($n == 0) { $output = "<array>\n"; } foreach ($data as $key => $value) { $item = "array_item"; if (is_numeric($key)) { $output .= "<$item name=\"$key\" type=\"" . gettype($value) . "\">"; } else { $item = $key; $output .= "<$item type=\"" . gettype($value) . "\">"; } if (is_object($value)) { $output .= serialise_object_to_xml($value, "", $n + 1); } else if (is_array($value)) { $output .= serialise_array_to_xml($value, $n + 1); } else if (gettype($value) == "boolean") { $output .= $value ? "true" : "false"; } else { $output .= htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8'); } $output .= "</$item>\n"; } if ($n == 0) { $output .= "</array>\n"; } return $output; } /** * Parse an XML file into an object. * * @param string $xml The XML * * @return ElggXMLElement * @deprecated 1.9 Use ElggXMLElement */ function xml_to_object($xml) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by ElggXMLElement', 1.9); return new ElggXMLElement($xml); } /** * Retrieve a site and return the domain portion of its url. * * @param int $guid ElggSite GUID * * @return string * @deprecated 1.9 Use ElggSite::getDomain() */ function get_site_domain($guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated. Use ElggSite::getDomain()', 1.9); $guid = (int)$guid; $site = get_entity($guid); if ($site instanceof ElggSite) { $breakdown = parse_url($site->url); return $breakdown['host']; } return false; } /** * Register an entity type and subtype to be eligible for notifications * * @param string $entity_type The type of entity * @param string $object_subtype Its subtype * @param string $language_name Its localized notification string (eg "New blog post") * * @return void * @deprecated 1.9 Use elgg_register_notification_event(). The 3rd argument was used * as the subject line in a notification. As of Elgg 1.9, it is now set by a callback * for a plugin hook. See the documentation at the top of the notifications library * titled "Adding a New Notification Event" for more details. */ function register_notification_object($entity_type, $object_subtype, $language_name) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_register_notification_event()', 1.9); elgg_register_notification_event($entity_type, $object_subtype); _elgg_services()->notifications->setDeprecatedNotificationSubject($entity_type, $object_subtype, $language_name); } /** * Establish a 'notify' relationship between the user and a content author * * @param int $user_guid The GUID of the user who wants to follow a user's content * @param int $author_guid The GUID of the user whose content the user wants to follow * * @return bool Depending on success * @deprecated 1.9 Use elgg_add_subscription() */ function register_notification_interest($user_guid, $author_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_add_subscription()', 1.9); return add_entity_relationship($user_guid, 'notify', $author_guid); } /** * Remove a 'notify' relationship between the user and a content author * * @param int $user_guid The GUID of the user who is following a user's content * @param int $author_guid The GUID of the user whose content the user wants to unfollow * * @return bool Depending on success * @deprecated 1.9 Use elgg_remove_subscription() */ function remove_notification_interest($user_guid, $author_guid) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_remove_subscription()', 1.9); return remove_entity_relationship($user_guid, 'notify', $author_guid); } /** * Automatically triggered notification on 'create' events that looks at registered * objects and attempts to send notifications to anybody who's interested * * @see register_notification_object * * @param string $event create * @param string $object_type mixed * @param mixed $object The object created * * @return bool * @access private * @deprecated 1.9 */ function object_notifications($event, $object_type, $object) { throw new BadFunctionCallException("object_notifications is a private function and should not be called directly"); } /** * This function registers a handler for a given notification type (eg "email") * * @param string $method The method * @param string $handler The handler function, in the format * "handler(ElggEntity $from, ElggUser $to, $subject, * $message, array $params = NULL)". This function should * return false on failure, and true/a tracking message ID on success. * @param array $params An associated array of other parameters for this handler * defining some properties eg. supported msg length or rich text support. * * @return bool * @deprecated 1.9 Use elgg_register_notification_method() */ function register_notification_handler($method, $handler, $params = NULL) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_register_notification_method()', 1.9); elgg_register_notification_method($method); _elgg_services()->notifications->registerDeprecatedHandler($method, $handler); } /** * This function unregisters a handler for a given notification type (eg "email") * * @param string $method The method * * @return void * @since 1.7.1 * @deprecated 1.9 Use elgg_unregister_notification_method() */ function unregister_notification_handler($method) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by elgg_unregister_notification_method()', 1.9); elgg_unregister_notification_method($method); } /** * Import an entity. * * This function checks the passed XML doc (as array) to see if it is * a user, if so it constructs a new elgg user and returns "true" * to inform the importer that it's been handled. * * @param string $hook import * @param string $entity_type all * @param mixed $returnvalue Value from previous hook * @param mixed $params Array of params * * @return mixed * @elgg_plugin_hook_handler import all * @todo document * @access private * * @throws ImportException * @deprecated 1.9 */ function import_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) { $element = $params['element']; $tmp = null; if ($element instanceof ODDEntity) { $tmp = oddentity_to_elggentity($element); if ($tmp) { // Make sure its saved if (!$tmp->save()) { $msg = "There was a problem saving " . $element->getAttribute('uuid'); throw new ImportException($msg); } // Belts and braces if (!$tmp->guid) { throw new ImportException("New entity created but has no GUID, this should not happen."); } // We have saved, so now tag add_uuid_to_guid($tmp->guid, $element->getAttribute('uuid')); return $tmp; } } } /** * Exports all attributes of an entity. * * @warning Only exports fields in the entity and entity type tables. * * @param string $hook export * @param string $entity_type all * @param mixed $returnvalue Previous hook return value * @param array $params Parameters * * @elgg_event_handler export all * @return mixed * @access private * * @throws InvalidParameterException|InvalidClassException * @deprecated 1.9 */ function export_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) { // Sanity check values if ((!is_array($params)) && (!isset($params['guid']))) { throw new InvalidParameterException("GUID has not been specified during export, this should never happen."); } if (!is_array($returnvalue)) { throw new InvalidParameterException("Entity serialisation function passed a non-array returnvalue parameter"); } $guid = (int)$params['guid']; // Get the entity $entity = get_entity($guid); if (!($entity instanceof ElggEntity)) { $msg = "GUID:" . $guid . " is not a valid " . get_class(); throw new InvalidClassException($msg); } $export = $entity->export(); if (is_array($export)) { foreach ($export as $e) { $returnvalue[] = $e; } } else { $returnvalue[] = $export; } return $returnvalue; } /** * Exports attributes generated on the fly (volatile) about an entity. * * @param string $hook volatile * @param string $entity_type metadata * @param string $returnvalue Return value from previous hook * @param array $params The parameters, passed 'guid' and 'varname' * * @return ElggMetadata|null * @elgg_plugin_hook_handler volatile metadata * @todo investigate more. * @access private * @todo document * @deprecated 1.9 */ function volatile_data_export_plugin_hook($hook, $entity_type, $returnvalue, $params) { $guid = (int)$params['guid']; $variable_name = sanitise_string($params['varname']); if (($hook == 'volatile') && ($entity_type == 'metadata')) { if (($guid) && ($variable_name)) { switch ($variable_name) { case 'renderedentity' : elgg_set_viewtype('default'); $view = elgg_view_entity(get_entity($guid)); elgg_set_viewtype(); $tmp = new ElggMetadata(); $tmp->type = 'volatile'; $tmp->name = 'renderedentity'; $tmp->value = $view; $tmp->entity_guid = $guid; return $tmp; break; } } } } /** * Export the annotations for the specified entity * * @param string $hook 'export' * @param string $type 'all' * @param mixed $returnvalue Default return value * @param mixed $params Parameters determining what annotations to export * * @elgg_plugin_hook export all * * @return array * @throws InvalidParameterException * @access private * @deprecated 1.9 */ function export_annotation_plugin_hook($hook, $type, $returnvalue, $params) { // Sanity check values if ((!is_array($params)) && (!isset($params['guid']))) { throw new InvalidParameterException("GUID has not been specified during export, this should never happen."); } if (!is_array($returnvalue)) { throw new InvalidParameterException("Entity serialization function passed a non-array returnvalue parameter"); } $guid = (int)$params['guid']; $options = array('guid' => $guid, 'limit' => 0); if (isset($params['name'])) { $options['annotation_name'] = $params['name']; } $result = elgg_get_annotations($options); if ($result) { foreach ($result as $r) { $returnvalue[] = $r->export(); } } return $returnvalue; } /** * Handler called by trigger_plugin_hook on the "import" event. * * @param string $hook volatile * @param string $entity_type metadata * @param string $returnvalue Return value from previous hook * @param array $params The parameters * * @return null * @elgg_plugin_hook_handler volatile metadata * @todo investigate more. * @throws ImportException * @access private * @deprecated 1.9 */ function import_extender_plugin_hook($hook, $entity_type, $returnvalue, $params) { $element = $params['element']; $tmp = NULL; if ($element instanceof ODDMetaData) { /* @var ODDMetaData $element */ // Recall entity $entity_uuid = $element->getAttribute('entity_uuid'); $entity = get_entity_from_uuid($entity_uuid); if (!$entity) { throw new ImportException("Entity '" . $entity_uuid . "' could not be found."); } oddmetadata_to_elggextender($entity, $element); // Save if (!$entity->save()) { $attr_name = $element->getAttribute('name'); $msg = "There was a problem updating '" . $attr_name . "' on entity '" . $entity_uuid . "'"; throw new ImportException($msg); } return true; } } /** * Utility function used by import_extender_plugin_hook() to process * an ODDMetaData and add it to an entity. This function does not * hit ->save() on the entity (this lets you construct in memory) * * @param ElggEntity $entity The entity to add the data to. * @param ODDMetaData $element The OpenDD element * * @return bool * @access private * @deprecated 1.9 */ function oddmetadata_to_elggextender(ElggEntity $entity, ODDMetaData $element) { // Get the type of extender (metadata, type, attribute etc) $type = $element->getAttribute('type'); $attr_name = $element->getAttribute('name'); $attr_val = $element->getBody(); switch ($type) { // Ignore volatile items case 'volatile' : break; case 'annotation' : $entity->annotate($attr_name, $attr_val); break; case 'metadata' : $entity->setMetadata($attr_name, $attr_val, "", true); break; default : // Anything else assume attribute $entity->set($attr_name, $attr_val); } // Set time if appropriate $attr_time = $element->getAttribute('published'); if ($attr_time) { $entity->set('time_updated', $attr_time); } return true; } /** * Handler called by trigger_plugin_hook on the "export" event. * * @param string $hook export * @param string $entity_type all * @param mixed $returnvalue Value returned from previous hook * @param mixed $params Params * * @return array * @access private * * @throws InvalidParameterException * @deprecated 1.9 */ function export_metadata_plugin_hook($hook, $entity_type, $returnvalue, $params) { // Sanity check values if ((!is_array($params)) && (!isset($params['guid']))) { throw new InvalidParameterException("GUID has not been specified during export, this should never happen."); } if (!is_array($returnvalue)) { throw new InvalidParameterException("Entity serialisation function passed a non-array returnvalue parameter"); } $result = elgg_get_metadata(array( 'guid' => (int)$params['guid'], 'limit' => 0, )); if ($result) { /* @var ElggMetadata[] $result */ foreach ($result as $r) { $returnvalue[] = $r->export(); } } return $returnvalue; } /** * Handler called by trigger_plugin_hook on the "export" event. * * @param string $hook export * @param string $entity_type all * @param mixed $returnvalue Previous hook return value * @param array $params Parameters * * @elgg_event_handler export all * @return mixed * @throws InvalidParameterException * @access private * @deprecated 1.9 */ function export_relationship_plugin_hook($hook, $entity_type, $returnvalue, $params) { // Sanity check values if ((!is_array($params)) && (!isset($params['guid']))) { throw new InvalidParameterException("GUID has not been specified during export, this should never happen."); } if (!is_array($returnvalue)) { throw new InvalidParameterException("Entity serialisation function passed a non-array returnvalue parameter"); } $guid = (int)$params['guid']; $result = get_entity_relationships($guid); if ($result) { foreach ($result as $r) { $returnvalue[] = $r->export(); } } return $returnvalue; } /** * Handler called by trigger_plugin_hook on the "import" event. * * @param string $hook import * @param string $entity_type all * @param mixed $returnvalue Value from previous hook * @param mixed $params Array of params * * @return mixed * @access private * @deprecated 1.9 */ function import_relationship_plugin_hook($hook, $entity_type, $returnvalue, $params) { $element = $params['element']; $tmp = NULL; if ($element instanceof ODDRelationship) { $tmp = new ElggRelationship(); $tmp->import($element); return $tmp; } return $tmp; } /** Register the import hook */ elgg_register_plugin_hook_handler("import", "all", "import_entity_plugin_hook", 0); elgg_register_plugin_hook_handler("import", "all", "import_extender_plugin_hook", 2); elgg_register_plugin_hook_handler("import", "all", "import_relationship_plugin_hook", 3); /** Register the hook, ensuring entities are serialised first */ elgg_register_plugin_hook_handler("export", "all", "export_entity_plugin_hook", 0); elgg_register_plugin_hook_handler("export", "all", "export_annotation_plugin_hook", 2); elgg_register_plugin_hook_handler("export", "all", "export_metadata_plugin_hook", 2); elgg_register_plugin_hook_handler("export", "all", "export_relationship_plugin_hook", 3); /** Hook to get certain named bits of volatile data about an entity */ elgg_register_plugin_hook_handler('volatile', 'metadata', 'volatile_data_export_plugin_hook'); /** * Returns the SQL where clause for a table with access_id and enabled columns. * * This handles returning where clauses for ACCESS_FRIENDS in addition to using * get_access_list() for access collections and the standard access levels. * * Note that if this code is executed in privileged mode it will return (1=1). * * @param string $table_prefix Optional table prefix for the access code. * @param int $owner Optional user guid to get access information for. Defaults * to logged in user. * @return string * @access private * @deprecated 1.9 Use _elgg_get_access_where_sql() */ function get_access_sql_suffix($table_prefix = '', $owner = null) { elgg_deprecated_notice(__FUNCTION__ . ' is deprecated by _elgg_get_access_where_sql()', 1.9); return _elgg_get_access_where_sql(array( 'table_alias' => $table_prefix, 'user_guid' => (int)$owner, )); } /** * Get the name of the most recent plugin to be called in the * call stack (or the plugin that owns the current page, if any). * * i.e., if the last plugin was in /mod/foobar/, this would return foo_bar. * * @param boolean $mainfilename If set to true, this will instead determine the * context from the main script filename called by * the browser. Default = false. * * @return string|false Plugin name, or false if no plugin name was called * @since 1.8.0 * @access private * @deprecated 1.9 */ function elgg_get_calling_plugin_id($mainfilename = false) { elgg_deprecated_notice('elgg_get_calling_plugin_id() is deprecated', 1.9); if (!$mainfilename) { if ($backtrace = debug_backtrace()) { foreach ($backtrace as $step) { $file = $step['file']; $file = str_replace("\\", "/", $file); $file = str_replace("//", "/", $file); if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\/start\.php$/", $file, $matches)) { return $matches[1]; } } } } else { //@todo this is a hack -- plugins do not have to match their page handler names! if ($handler = get_input('handler', false)) { return $handler; } else { $file = $_SERVER["SCRIPT_NAME"]; $file = str_replace("\\", "/", $file); $file = str_replace("//", "/", $file); if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\//", $file, $matches)) { return $matches[1]; } } } return false; }
{ "content_hash": "4a40e47e1ed4aa2613821d8d7c10c351", "timestamp": "", "source": "github", "line_count": 3827, "max_line_length": 149, "avg_line_length": 30.38907760648027, "alnum_prop": 0.6560675500219263, "repo_name": "Grupo15HxH/HxH", "id": "897e4d15548156a1b823f6b410039a12ed5cda15", "size": "116299", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "elgg/engine/lib/deprecated-1.9.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8325" }, { "name": "JavaScript", "bytes": "122434" }, { "name": "PHP", "bytes": "4881416" }, { "name": "Python", "bytes": "8128" }, { "name": "Shell", "bytes": "7582" } ], "symlink_target": "" }
package pe.com.equifax.informa.web.adms.services; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import pe.com.equifax.informa.adms.beans.AdmTipoProdPerfilBean; import pe.com.equifax.informa.common.beans.ConfiguracionBean; import pe.com.equifax.informa.common.beans.MenuBean; import pe.com.equifax.informa.common.beans.ProductoBean; import pe.com.equifax.informa.common.beans.UsuarioBean; import pe.com.equifax.informa.web.utils.CommonUtils; import pe.com.equifax.informa.web.utils.Constants; import pe.com.equifax.informa.web.utils.SortProductosBean; /** * * @author mazcarate * */ public final class MenuManager { public static final String MENU_VISIBLE ="S"; private static final String CONS_PROD_ID_MASK = "?idProd={val}"; private static final String CONS_AVOID = "#"; private static final String PAGINA_X_DEFECTO = "config.htm"; private static final int CRITERIA_TIPO_PORTAL = 0; private static final int CRITERIA_TIPO_PRODUCTO = 1; private static Logger mLog = Logger.getLogger( MenuManager.class ); private MenuManager(){} private static class InformaMenuManagerHelper{ private static final MenuManager INSTANCE = new MenuManager(); } public static MenuManager getInstance(){ mLog.info( MenuManager.class.getName().concat( " singleton creado " ) ); return InformaMenuManagerHelper.INSTANCE; } /****************************MENU MANAGER V2.0*******************************************/ /** * Creacion de Menu del Sistema v2.0 con objetos TreeMap para agilizar la velocidad de búsqueda y ordenamiento * Soporte para habilitar / deshabilitar menus con sesion activa o sin ella * Soporte para mostrar/ocultar menus de forma dinamica * Soporte para ordenamiento dinamico * @param productos Lista de productos ordenada por Codigo de producto para optimizar la velocidad/iteracion de búsqueda * @throws Exception */ public List<MenuBean> doMenus( List<AdmTipoProdPerfilBean> productos ) throws Exception{ /* * Treemap con los productos agrupados por tipo de portal */ TreeMap< Integer, List<AdmTipoProdPerfilBean> > tmPortales = doGroupBy( productos , CRITERIA_TIPO_PORTAL ); List<MenuBean> lstMenus = new ArrayList<MenuBean>(); Iterator<Integer> tabIterator = tmPortales.keySet().iterator(); int portalOrden = 0; /* * Iterar sobre los elementos del portal */ while ( tabIterator.hasNext() ){ Integer gkeyPortal = (Integer) tabIterator.next(); List<AdmTipoProdPerfilBean> lstPortalProductos = tmPortales.get( gkeyPortal ); MenuBean menuPortal = new MenuBean(); menuPortal.setVisible( true ); menuPortal.setExcluirSession( true ); menuPortal.setPortal( gkeyPortal ); menuPortal.setOrden( portalOrden++ ); menuPortal.setTipo( gkeyPortal ); menuPortal.setEstado( MenuBean.ENABLED ); menuPortal.setSubmenu( new ArrayList<MenuBean>() ); lstMenus.add( menuPortal ); TreeMap<Integer,List<AdmTipoProdPerfilBean> > tmTp = doGroupBy( lstPortalProductos, CRITERIA_TIPO_PRODUCTO ); Iterator<Integer> itTipoProducto = tmTp.keySet().iterator(); List<String> temp = new ArrayList<String>(); /* * Iterar por los tipos de productos */ while( itTipoProducto.hasNext() ){ Integer gkeyTp = (Integer) itTipoProducto.next(); List<AdmTipoProdPerfilBean> lstTp = tmTp.get( gkeyTp ); MenuBean menuTp = new MenuBean(); menuTp.setLink( CONS_AVOID ); menuTp.setVisible( true ); menuTp.setExcluirSession( true ); menuTp.setPortal( gkeyPortal ); menuTp.setOrden( lstTp.get( 0 ).getTipoProductoOrden() ); menuTp.setTipo( gkeyTp ); menuTp.setEtiqueta( lstTp.get( 0 ).getTipoProducto() ); menuPortal.setEstado( MenuBean.ENABLED ); menuPortal.addSubmenu( menuTp ); /* * El portal actual hereda algunas caracteristicas del tipo producto Busqueda */ if( gkeyTp == ProductoBean.TIPO_BUSQUEDA ){ menuPortal.setEtiqueta( CommonUtils.toLowerCase( lstTp.get( 0 ).getPortalProducto() ) ); menuPortal.setLink( setUpLink( lstTp.get( 0 ) ) ); } else if( gkeyPortal == ProductoBean.TIPO_CONSUMO ){ menuPortal.setEtiqueta( CommonUtils.toLowerCase( lstTp.get( 0 ).getPortalProducto() ) ); menuPortal.setLink( setUpLink( lstTp.get( 0 ) ) ); } else{ menuPortal.setLink( PAGINA_X_DEFECTO ); menuPortal.setEtiqueta( CommonUtils.toLowerCase( lstTp.get( 0 ).getPortalProducto() ) ); } /* * Iterar por los subproductos */ for ( AdmTipoProdPerfilBean x : lstTp ){ if( !temp.contains( x.getCodProducto() ) ){ MenuBean submenu = new MenuBean(); submenu.setId( x.getCodProducto() ); menuPortal.setEstado( MenuBean.DISABLED ); submenu.setLink( setUpLink( x ) ); /* * Algunos menus deben estar siempre habilitados segun el tipo de portal y/o tipo producto */ switch ( x.getGkeyPortal() ){ /* * Los productos de Configuracion siempre deben estar habilitados */ case ProductoBean.TIPO_CONFIGURACION: submenu.setExcluirSession( true ); submenu.setEstado( MenuBean.ENABLED ); break; case ProductoBean.TIPO_CONSUMO: submenu.setExcluirSession( true ); submenu.setEstado( MenuBean.ENABLED ); break; case ProductoBean.TIPO_EMPRESA: if( x.getGkeyTipoProductoSig() == ProductoBean.TIPO_SERVICIO ){ /* * Excepcion para Ampliacion de Informacion... */ if( x.getCodProductoSig().equals( "PROD194" ) ){ submenu.setExcluirSession( false ); submenu.setEstado( MenuBean.DISABLED ); }else{ submenu.setExcluirSession( true ); submenu.setEstado( MenuBean.ENABLED ); } } else if( x.getGkeyTipoProductoSig() == ProductoBean.TIPO_BUSQUEDA ){ submenu.setExcluirSession( true ); submenu.setEstado( MenuBean.ENABLED ); } else { submenu.setExcluirSession( false ); submenu.setEstado( MenuBean.DISABLED ); } break; case ProductoBean.TIPO_PERSONA : if( x.getGkeyTipoProductoSig() == ProductoBean.TIPO_BUSQUEDA ){ submenu.setExcluirSession( true ); submenu.setEstado( MenuBean.ENABLED ); } else { if( x.getGkeyTipoProductoSig() == ProductoBean.TIPO_SERVICIO ){ submenu.setExcluirSession( true ); submenu.setEstado( MenuBean.ENABLED ); } else { submenu.setExcluirSession( false ); submenu.setEstado( MenuBean.DISABLED ); } } break; /* * Por defecto los menus deben aparecer deshabilitados * */ default: submenu.setExcluirSession( false ); submenu.setEstado( MenuBean.DISABLED ); break; } if( MENU_VISIBLE.equals( x.getFlagMenu() ) ){ submenu.setVisible( true ); }else{ submenu.setVisible( false ); } submenu.setPortal( gkeyPortal ); submenu.setOrden( x.getProductoOrden() ); submenu.setTipo( gkeyTp ); submenu.setEtiqueta( x.getNomProducto() ); menuTp.addSubmenu( submenu ); } temp.add( x.getCodProducto() ); } temp.clear(); /* * Ordenar la lista de submenus */ List<MenuBean> lst = menuTp.getSubmenu(); sortMenus( lst ); menuTp.setSubmenu( lst ); } /* * Ordenar la lista de tipo productos */ List<MenuBean> lst = menuPortal.getSubmenu(); sortMenus( lst ); menuPortal.setSubmenu( lst ); } print( lstMenus ); return lstMenus; } /** * Este metodo se llama cada vez que se obtienes los datos de nueva ficha de Personas /Personas Juridicas * asi de esta manera poder establecer que productos tiene disponible * @param map */ public void updateMenuBeans( Map<String,Integer> map ){ UsuarioBean usuario = CommonUtils.getUsuario(); List<MenuBean> lst = usuario.getLstMenus(); for ( MenuBean menuBean : lst ){ for ( MenuBean x : menuBean.getSubmenu() ){ for ( MenuBean y : x.getSubmenu() ){ /* * Obtiene el estado del producto( 0:Disabled, 1:Enabled) contenido en el Map * Si el producto es nulo significa que no es visible en el menú * Este proceso no debe afectar asu valor inicial de excluirSession */ Integer newState = map.get( y.getId() ); if( newState != null ){ y.setEstado( newState ); } if( menuBean.getTipo() == ProductoBean.TIPO_PERSONA && (y.getTipo() == ProductoBean.TIPO_REPORTE ) ){ y.setEstado( MenuBean.ENABLED ); } } } } /* * Guardar la nueva lista modificada en session */ usuario.setLstMenus( lst ); HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); curRequest.getSession().setAttribute( Constants.SESSION_USUARIO , usuario ); } /** * Hace un reset a los estados de los menus regresandolo a su configuracion inicial * establecida en la lógica del negocio */ public void doReset(){ UsuarioBean usuario = CommonUtils.getUsuario(); List<MenuBean> lst = usuario.getLstMenus(); for ( MenuBean menuBean : lst ){ for ( MenuBean x : menuBean.getSubmenu() ){ for ( MenuBean y : x.getSubmenu() ){ switch ( menuBean.getTipo() ){ /* * Conservar que todos los subproductos del Portal configuración * siempre aparezcan habilitados * */ case ProductoBean.TIPO_CONFIGURACION: y.setEstado( MenuBean.ENABLED ); break; case ProductoBean.TIPO_CONSUMO: y.setEstado( MenuBean.ENABLED ); break; default: switch ( y.getTipo() ) { case ProductoBean.TIPO_SERVICIO: /* * El Producto Ampliacion de Info debe aparecer deshabilado */ if( y.getId().equals( "PROD194" ) ){ y.setEstado( MenuBean.DISABLED ); } else { y.setEstado( MenuBean.ENABLED ); } break; case ProductoBean.TIPO_BUSQUEDA : y.setEstado( MenuBean.ENABLED ); break; default: y.setEstado( MenuBean.DISABLED ); } } } } } /* * Guardar la nueva lista modificada en session */ usuario.setLstMenus( lst ); HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); curRequest.getSession().setAttribute( Constants.SESSION_USUARIO , usuario ); } /** * Ordena la lista de menus de forma ascendente * @param lst Lista de menus */ private void sortMenus( List<MenuBean> lst ){ Collections.sort( lst , new Comparator<MenuBean>(){ public int compare( MenuBean m1, MenuBean m2 ){ return m1.getOrden() - m2.getOrden(); } }) ; } /** * * @param lstProductosXPerfil */ public List<ProductoBean> doListProducts( List<AdmTipoProdPerfilBean> lstProductosXPerfil ){ List<ProductoBean> lstProductos = new ArrayList<ProductoBean>(); List<String> temp = new ArrayList<String>(); for ( AdmTipoProdPerfilBean e : lstProductosXPerfil ){ /* * Producto */ if( !temp.contains( e.getCodProducto() ) ){ ProductoBean producto = new ProductoBean(); producto.setCodigo( e.getCodProducto() ); producto.setCodigoSGC( e.getCodProductoSGC() ); producto.setController( e.getControllerProducto().trim() ); producto.setPortal( e.getGkeyPortal() ); producto.setTitulo( e.getNomProducto() ); producto.setOrden( e.getTipoProductoOrden() ); producto.setTipo( e.getGkeyTipoProducto() ); producto.setProdSgte( "" ); List<ProductoBean> subProductos = null; if( e.getCodProducto().equals(e.getCodProductoSig() ) ){ subProductos = getSubproductos( lstProductosXPerfil,e.getCodProducto(),e.getCodProducto() ); } else{ subProductos = getSubproductos( lstProductosXPerfil,e.getCodProducto(),e.getCodProductoSig() ); } Collections.sort( subProductos, new SortProductosBean() ); producto.setSubProductos( subProductos ); lstProductos.add( producto ); } temp.add( e.getCodProducto() ); } temp.clear(); return lstProductos; } /** * * @param lstProductos * @param prodId * @param subProdId * @return */ private List<ProductoBean> getSubproductos( List<AdmTipoProdPerfilBean> lstProductos, String prodId, String subProdId ){ List<ProductoBean> subproductos = new ArrayList<ProductoBean>(); //subProdId = ( subProdId == null ) ? prodId : subProdId; //se comenta; variable no usada List<String> temp = new ArrayList<String>(); for ( AdmTipoProdPerfilBean x : lstProductos ){ if( prodId.equals( x.getCodProducto() ) ){ if( !temp.contains( x.getCodProductoSig() ) ){ ProductoBean producto = new ProductoBean(); producto.setCodigo( x.getCodProductoSig() ); producto.setCodigoSGC( x.getCodSubProductoSGC() ); producto.setController( x.getControllerProductoSig().trim() ); producto.setPortal( x.getGkeyProductoSig() ); producto.setTitulo( x.getNomProductoSig() ); List<ConfiguracionBean> configuraciones = null; if( x.getGkeyConfiguracion() == ConfiguracionBean.NO_CONFIGURABLE ){ configuraciones = getConfiguracion0( x ); } else{ if( x.getCodProducto().equals( x.getCodProductoSig() ) ){ configuraciones = getConfiguraciones( lstProductos, x.getCodProducto(), x.getCodProducto() ); } else{ configuraciones = getConfiguraciones( lstProductos, x.getCodProducto(), x.getCodProductoSig() ); } } if( !configuraciones.isEmpty() ){ /* * El producto obtiene un orden especifico en el reporte */ producto.setOrden( configuraciones.get( 0 ).getOrden() ); }else{ /* * No presenta un orden especifico al no tener configuaciones */ producto.setOrden( 1 ); } producto.setConfiguraciones( configuraciones ); subproductos.add( producto ); } temp.add( x.getCodProductoSig() ); } } temp.clear(); return subproductos; } /** * * @param lstProductos * @param prodId * @param subProdId * @return */ private List<ConfiguracionBean> getConfiguraciones( List<AdmTipoProdPerfilBean> lstProductos, String prodId, String subProdId ){ List<ConfiguracionBean> configuraciones = new ArrayList<ConfiguracionBean>(); subProdId = ( subProdId == null ) ? prodId : subProdId; for ( AdmTipoProdPerfilBean c : lstProductos ){ if( prodId.equals( c.getCodProducto() ) && subProdId.equals( c.getCodProductoSig() ) ){ ConfiguracionBean config = new ConfiguracionBean(); config.setCodigo( c.getGkeyConfiguracion() ); config.setTipo( c.getTipoConfiguracion() ); config.setValor( c.getValorConfiguracion() ); config.setNombre( c.getNomConfiguracion() ); config.setOrden( c.getOrden() ); configuraciones.add( config ); } } return configuraciones; } /** * Si el producto no es configurable , se asigna una configuracion por defecto * establecida en BD * @param bean * @return */ private List<ConfiguracionBean> getConfiguracion0( AdmTipoProdPerfilBean bean ){ List<ConfiguracionBean> configuraciones = new ArrayList<ConfiguracionBean>(); ConfiguracionBean config = new ConfiguracionBean(); config.setCodigo( bean.getGkeyConfiguracion() ); config.setTipo( bean.getTipoConfiguracion() ); config.setValor( bean.getValorConfiguracion() ); config.setNombre( bean.getNomConfiguracion() ); config.setOrden( bean.getOrden() ); configuraciones.add( config ); return configuraciones; } @SuppressWarnings("unused") private void print( List<MenuBean> lstMenus ){ for ( MenuBean x : lstMenus ) { mLog.info( "label : " + x.getEtiqueta() +","+x.getTipo()+","+x.getLink() ); if( x.getSubmenu().size() > 0 ){ for ( MenuBean m : x.getSubmenu() ) { mLog.info( "\t label : " + m.getEtiqueta()+", " +m.getTipo()+", "+m.getLink() +","+m.getOrden() ); if( m.getSubmenu().size() > 0 ){ for ( MenuBean n : m.getSubmenu() ) { mLog.info( "\t\t label : " + n.getEtiqueta()+"," +n.getTipo()+", "+n.getLink() +","+m.getOrden() ); } } } } } } /** * Retorna un nuevo link concatenando el idProd * Ejm : linkxxx.htm?idProd=123 ó linkxxx.htm?param1=val1&idProd=123 * @param link url del producto a consultar * @param idProd codigo del producto * @return */ private String setUpLink( AdmTipoProdPerfilBean adm ){ String newLink = null; String idProd = null; String link = null; /*switch ( adm.getGkeyTipoProducto() ){ case ProductoBean.TIPO_MODULO: idProd = adm.getCodProductoSig(); default: idProd = adm.getCodProducto(); break; }*/ idProd = adm.getCodProducto(); link = adm.getControllerProducto(); if( link.contains( "?" ) ){ newLink = link.trim().concat( CONS_PROD_ID_MASK.replace( "?","&" ). replace("{val}", idProd ) ); } else { newLink = link.trim().concat( CONS_PROD_ID_MASK.replace("{val}", idProd ) ); } return newLink; } /** * Agrupa objetos AdmTipoProdPerfilBean en un TreeMap mediante un criterio * @param lstProductosxPerfil Lista de productos de un perfil * @return */ private TreeMap< Integer, List<AdmTipoProdPerfilBean> > doGroupBy( List<AdmTipoProdPerfilBean> lstProductosxPerfil, int criteria ){ TreeMap< Integer, List<AdmTipoProdPerfilBean> > root = new TreeMap< Integer, List<AdmTipoProdPerfilBean> >(); int gkey = -1; for ( AdmTipoProdPerfilBean bean : lstProductosxPerfil ){ switch ( criteria ){ case CRITERIA_TIPO_PORTAL: gkey = bean.getGkeyPortal(); break; case CRITERIA_TIPO_PRODUCTO: gkey = bean.getGkeyTipoProducto(); break; case 3: gkey = bean.getGkeyProducto(); break; } /* * Si el portal aun no existe se agrega una lista vacia * para almacenar posteriormente objetos AdmTipoProdPerfilBean */ if( !root.containsKey( gkey ) ){ root.put( gkey, new ArrayList<AdmTipoProdPerfilBean>() ); } /* * Obtiene la referencia en el Treemap mediante el id del criterio y agrega un objeto * AdmTipoProdPerfilBean a su lista de productos */ root.get( gkey ).add( bean ); } return root; } /** * Obtiene un menu almacenado en sesion * @param menuId * @return */ public MenuBean getMenu( String menuId ){ List<MenuBean> lstMenus = CommonUtils.getUsuario().getLstMenus(); for( MenuBean m : lstMenus ) { if( menuId.equals( m.getId() ) ){ return m; } } return null; } /** * Clase para ordenar un Bean por una propiedad especifica de tipo Integer * @author mdp_mazcarate * * @param <T> Clase a ordenar */ class GenericIntegerSorting<T> implements Comparator<T> { String property = null; public GenericIntegerSorting( String property ) { this.property = property; } public int compare( T o1, T o2 ){ int compare = 0; try { Field f1 = o1.getClass().getField( property ); Field f2 = o2.getClass().getField( property ); if( f1!=null ){ f1.setAccessible( true ); f2.setAccessible( true ); Integer v1 = (Integer) f1.get( o1.getClass() ); Integer v2 = (Integer) f2.get( o2.getClass() ); compare = v2 - v1; } } catch ( Exception ex ) { mLog.error( ex.getMessage() ); } return compare; } } }
{ "content_hash": "d0a86a9cbf3f880e05e9b4d7bf1993b3", "timestamp": "", "source": "github", "line_count": 670, "max_line_length": 132, "avg_line_length": 31.15223880597015, "alnum_prop": 0.6277788424683787, "repo_name": "gcorreageek/equifax", "id": "faf5275048dc993c00ebc6923c5cedf87f95dfb3", "size": "20872", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ws_advanced_products_002/src/main/java/pe/com/equifax/informa/web/adms/services/MenuManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "145661" }, { "name": "HTML", "bytes": "494891" }, { "name": "Java", "bytes": "1351268" }, { "name": "JavaScript", "bytes": "973285" }, { "name": "PHP", "bytes": "25856" }, { "name": "PLSQL", "bytes": "144267" } ], "symlink_target": "" }
package com.dottydingo.hyperion.core.endpoint.status; import com.dottydingo.service.endpoint.status.EndpointStatus; import java.util.concurrent.atomic.AtomicBoolean; /** */ public class ServiceStatus extends EndpointStatus { private AtomicBoolean forceDown = new AtomicBoolean(false); private AtomicBoolean readOnly = new AtomicBoolean(false); public boolean getForceDown() { return forceDown.get(); } public void setForceDown(boolean forceDown) { this.forceDown.set(forceDown); } public boolean getReadOnly() { return readOnly.get(); } public void setReadOnly(boolean readOnly) { this.readOnly.set(readOnly); } }
{ "content_hash": "1c0d25d810adf1f91a36ce0a86d642fe", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 63, "avg_line_length": 21.515151515151516, "alnum_prop": 0.6943661971830986, "repo_name": "dottydingo/hyperion", "id": "4b1d4cea5d29dff1b42d6dc868e6c70bad1c1c3b", "size": "710", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/com/dottydingo/hyperion/core/endpoint/status/ServiceStatus.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "474817" } ], "symlink_target": "" }
package iht.models.application.debts import iht.testhelpers.CommonBuilder import org.scalatestplus.mockito.MockitoSugar import common.CommonPlaySpec class MortgageTest extends CommonPlaySpec with MockitoSugar{ "isComplete" must { "return Some(true) when Mortgage is complete" in { val mortgage = CommonBuilder.buildMortgage mortgage.isComplete shouldBe Some(true) } "return Some(true) when Mortgage has isOwned as false" in { val mortgage = CommonBuilder.buildMortgage.copy( isOwned = Some(false), value = None) mortgage.isComplete shouldBe Some(true) } "return Some(false) when one of the fields is None" in { val mortgage = CommonBuilder.buildMortgage.copy( isOwned = Some(true), value = None) mortgage.isComplete shouldBe Some(false) } "return None when value and isOwned fields are None" in { val mortgage = CommonBuilder.buildMortgage.copy(isOwned = None, value = None) mortgage.isComplete shouldBe empty } } }
{ "content_hash": "f440baea71b67c0507e398aed0cb5521", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 83, "avg_line_length": 25.925, "alnum_prop": 0.7049180327868853, "repo_name": "hmrc/iht-frontend", "id": "6eb5c5e1e9b2106b37ea16824c0b01876235f4c2", "size": "1640", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/iht/models/application/debts/MortgageTest.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Cycript", "bytes": "245093" }, { "name": "HTML", "bytes": "713728" }, { "name": "JavaScript", "bytes": "38292" }, { "name": "SCSS", "bytes": "26537" }, { "name": "Scala", "bytes": "3850086" }, { "name": "XSLT", "bytes": "241076" } ], "symlink_target": "" }
package com.paulyung.pyphoto.utils; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by yang on 2016/11/21. * paulyung@outlook.com */ public class FileHelper { /** * 删除文件 * * @param absolutePath 文件绝对路径 * @return 返回删除了的文件路径 */ public static String deleteFile(String absolutePath) { File file = new File(absolutePath); if (file.exists() && file.isFile()) file.delete(); else return null; return absolutePath; } /** * 删除多个文件 * * @param files 多个目录List * @return 返回删除了的文件路径集合 */ public static List<String> deleteFiles(List<String> files) { List<String> hadDeleteList = new ArrayList<>(); for (int i = 0; i < files.size(); ++i) { String str = deleteFile(files.get(i)); if (str != null) { hadDeleteList.add(str); } } return hadDeleteList; } /** * 删除图片,如果里面还包含目录,则不删除本目录以及里面的目录,仅删除里面的文件 * * @param path 图片目录 * @return 返回删除了的文件路径集合 */ public static List<String> deletePicture(String path) { boolean hasDir = false; List<String> hadDeleteList = new ArrayList<>(); File dir = new File(path); if (dir.exists() && dir.isDirectory()) { File[] files = dir.listFiles(); for (int i = 0; i < files.length; ++i) { if (files[i].isFile()) { String str = deleteFile(files[i].getAbsolutePath()); if (str != null) { hadDeleteList.add(str); } } else if (files[i].isDirectory()) { hasDir = true; } } if (!hasDir) dir.delete(); } return hadDeleteList; } /** * 删除多个目录的图片 * * @param dirs 目录集合 * @return 返回删除了的文件路径集合 */ public static List<String> deletePictures(List<String> dirs) { List<String> hadDeleteList = new ArrayList<>(); for (int i = 0; i < dirs.size(); ++i) { List<String> deleteFiles = deletePicture(dirs.get(i)); hadDeleteList.addAll(deleteFiles); } return hadDeleteList; } }
{ "content_hash": "e3513bf01b825d6b50865a2a15665982", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 72, "avg_line_length": 26.586206896551722, "alnum_prop": 0.5110246433203631, "repo_name": "paulyung541/photo", "id": "d0c9652e2ff1350b9f4e5cce7744d7b364ab3847", "size": "2555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/paulyung/pyphoto/utils/FileHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "189032" } ], "symlink_target": "" }
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _TCPIP_ADAPTER_H_ #define _TCPIP_ADAPTER_H_ #include <stdint.h> #include "sys/queue.h" #include "esp_wifi_types.h" #include "sdkconfig.h" #if CONFIG_TCPIP_LWIP #include "lwip/ip_addr.h" #include "dhcpserver/dhcpserver.h" typedef dhcps_lease_t tcpip_adapter_dhcps_lease_t; #ifdef __cplusplus extern "C" { #endif #define IP2STR(ipaddr) ip4_addr1_16(ipaddr), \ ip4_addr2_16(ipaddr), \ ip4_addr3_16(ipaddr), \ ip4_addr4_16(ipaddr) #define IPSTR "%d.%d.%d.%d" #define IPV62STR(ipaddr) IP6_ADDR_BLOCK1(&(ipaddr)), \ IP6_ADDR_BLOCK2(&(ipaddr)), \ IP6_ADDR_BLOCK3(&(ipaddr)), \ IP6_ADDR_BLOCK4(&(ipaddr)), \ IP6_ADDR_BLOCK5(&(ipaddr)), \ IP6_ADDR_BLOCK6(&(ipaddr)), \ IP6_ADDR_BLOCK7(&(ipaddr)), \ IP6_ADDR_BLOCK8(&(ipaddr)) #define IPV6STR "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" /** @brief IPV4 IP address information */ typedef struct { ip4_addr_t ip; /**< Interface IPV4 address */ ip4_addr_t netmask; /**< Interface IPV4 netmask */ ip4_addr_t gw; /**< Interface IPV4 gateway address */ } tcpip_adapter_ip_info_t; /** @brief IPV6 IP address information */ typedef struct { ip6_addr_t ip; /**< Interface IPV6 address */ } tcpip_adapter_ip6_info_t; /** @brief IP address info of station connected to WLAN AP * * @note See also wifi_sta_info_t (MAC layer information only) */ typedef struct { uint8_t mac[6]; /**< Station MAC address */ ip4_addr_t ip; /**< Station assigned IP address */ } tcpip_adapter_sta_info_t; /** @brief WLAN AP: Connected stations list * * Used to retrieve IP address information about connected stations. */ typedef struct { tcpip_adapter_sta_info_t sta[ESP_WIFI_MAX_CONN_NUM]; /**< Connected stations */ int num; /**< Number of connected stations */ } tcpip_adapter_sta_list_t; #endif #define ESP_ERR_TCPIP_ADAPTER_BASE 0x5000 #define ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS ESP_ERR_TCPIP_ADAPTER_BASE + 0x01 #define ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY ESP_ERR_TCPIP_ADAPTER_BASE + 0x02 #define ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED ESP_ERR_TCPIP_ADAPTER_BASE + 0x03 #define ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STARTED ESP_ERR_TCPIP_ADAPTER_BASE + 0x04 #define ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED ESP_ERR_TCPIP_ADAPTER_BASE + 0x05 #define ESP_ERR_TCPIP_ADAPTER_NO_MEM ESP_ERR_TCPIP_ADAPTER_BASE + 0x06 #define ESP_ERR_TCPIP_ADAPTER_DHCP_NOT_STOPPED ESP_ERR_TCPIP_ADAPTER_BASE + 0x07 /* @brief On-chip network interfaces */ typedef enum { TCPIP_ADAPTER_IF_STA = 0, /**< Wi-Fi STA (station) interface */ TCPIP_ADAPTER_IF_AP, /**< Wi-Fi soft-AP interface */ TCPIP_ADAPTER_IF_ETH, /**< Ethernet interface */ TCPIP_ADAPTER_IF_MAX } tcpip_adapter_if_t; /** @brief Type of DNS server */ typedef enum { TCPIP_ADAPTER_DNS_MAIN= 0, /**< DNS main server address*/ TCPIP_ADAPTER_DNS_BACKUP, /**< DNS backup server address (Wi-Fi STA and Ethernet only) */ TCPIP_ADAPTER_DNS_FALLBACK, /**< DNS fallback server address (Wi-Fi STA and Ethernet only) */ TCPIP_ADAPTER_DNS_MAX } tcpip_adapter_dns_type_t; /** @brief DNS server info */ typedef struct { ip_addr_t ip; /**< IPV4 address of DNS server */ } tcpip_adapter_dns_info_t; /** @brief Status of DHCP client or DHCP server */ typedef enum { TCPIP_ADAPTER_DHCP_INIT = 0, /**< DHCP client/server is in initial state (not yet started) */ TCPIP_ADAPTER_DHCP_STARTED, /**< DHCP client/server has been started */ TCPIP_ADAPTER_DHCP_STOPPED, /**< DHCP client/server has been stopped */ TCPIP_ADAPTER_DHCP_STATUS_MAX } tcpip_adapter_dhcp_status_t; /** @brief Mode for DHCP client or DHCP server option functions */ typedef enum{ TCPIP_ADAPTER_OP_START = 0, TCPIP_ADAPTER_OP_SET, /**< Set option */ TCPIP_ADAPTER_OP_GET, /**< Get option */ TCPIP_ADAPTER_OP_MAX } tcpip_adapter_dhcp_option_mode_t; /* Deprecated name for tcpip_adapter_dhcp_option_mode_t, to remove after ESP-IDF V4.0 */ typedef tcpip_adapter_dhcp_option_mode_t tcpip_adapter_option_mode_t; /** @brief Supported options for DHCP client or DHCP server */ typedef enum{ TCPIP_ADAPTER_DOMAIN_NAME_SERVER = 6, /**< Domain name server */ TCPIP_ADAPTER_ROUTER_SOLICITATION_ADDRESS = 32, /**< Solicitation router address */ TCPIP_ADAPTER_REQUESTED_IP_ADDRESS = 50, /**< Request specific IP address */ TCPIP_ADAPTER_IP_ADDRESS_LEASE_TIME = 51, /**< Request IP address lease time */ TCPIP_ADAPTER_IP_REQUEST_RETRY_TIME = 52, /**< Request IP address retry counter */ } tcpip_adapter_dhcp_option_id_t; /* Deprecated name for tcpip_adapter_dhcp_option_id_t, to remove after ESP-IDF V4.0 */ typedef tcpip_adapter_dhcp_option_id_t tcpip_adapter_option_id_t; /** IP event declarations */ typedef enum { IP_EVENT_STA_GOT_IP, /*!< ESP32 station got IP from connected AP */ IP_EVENT_STA_LOST_IP, /*!< ESP32 station lost IP and the IP is reset to 0 */ IP_EVENT_AP_STAIPASSIGNED, /*!< ESP32 soft-AP assign an IP to a connected station */ IP_EVENT_GOT_IP6, /*!< ESP32 station or ap or ethernet interface v6IP addr is preferred */ IP_EVENT_ETH_GOT_IP, /*!< ESP32 ethernet got IP from connected AP */ } ip_event_t; /** @brief IP event base declaration */ ESP_EVENT_DECLARE_BASE(IP_EVENT); /** Event structure for IP_EVENT_STA_GOT_IP, IP_EVENT_ETH_GOT_IP events */ typedef struct { tcpip_adapter_if_t if_index; /*!< Interface for which the event is received */ tcpip_adapter_ip_info_t ip_info; /*!< IP address, netmask, gatway IP address */ bool ip_changed; /*!< Whether the assigned IP has changed or not */ } ip_event_got_ip_t; /** Event structure for IP_EVENT_GOT_IP6 event */ typedef struct { tcpip_adapter_if_t if_index; /*!< Interface for which the event is received */ tcpip_adapter_ip6_info_t ip6_info; /*!< IPv6 address of the interface */ } ip_event_got_ip6_t; /** Event structure for IP_EVENT_AP_STAIPASSIGNED event */ typedef struct { ip4_addr_t ip; /*!< IP address which was assigned to the station */ } ip_event_ap_staipassigned_t; /** * @brief Initialize the underlying TCP/IP stack * * @note This function should be called exactly once from application code, when the application starts up. */ void tcpip_adapter_init(void); /** * @brief Cause the TCP/IP stack to start the Ethernet interface with specified MAC and IP * * @note This function should be called after the Ethernet MAC hardware is initialized. In the default configuration, application code does not need to call this function - it is called automatically by the default handler for the SYSTEM_EVENT_ETH_START event. * * @param[in] mac Set MAC address of this interface * @param[in] ip_info Set IP address of this interface * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_NO_MEM */ esp_err_t tcpip_adapter_eth_start(uint8_t *mac, tcpip_adapter_ip_info_t *ip_info); /** * @brief Cause the TCP/IP stack to start the Wi-Fi station interface with specified MAC and IP * * * @note This function should be called after the Wi-Fi Station hardware is initialized. In the default configuration, application code does not need to call this function - it is called automatically by the default handler for the SYSTEM_EVENT_STA_START event. * * @param[in] mac Set MAC address of this interface * @param[in] ip_info Set IP address of this interface * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_NO_MEM */ esp_err_t tcpip_adapter_sta_start(uint8_t *mac, tcpip_adapter_ip_info_t *ip_info); /** * @brief Cause the TCP/IP stack to start the Wi-Fi AP interface with specified MAC and IP * * @note This function should be called after the Wi-Fi AP hardware is initialized. In the default configuration, application code does not need to call this function - it is called automatically by the default handler for the SYSTEM_EVENT_AP_START event. * * DHCP server will be started automatically when this function is called. * * @param[in] mac Set MAC address of this interface * @param[in] ip_info Set IP address of this interface * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_NO_MEM */ esp_err_t tcpip_adapter_ap_start(uint8_t *mac, tcpip_adapter_ip_info_t *ip_info); /** * @brief Cause the TCP/IP stack to stop a network interface * * Causes TCP/IP stack to clean up this interface. This includes stopping the DHCP server or client, if they are started. * * @note This API is called by the default Wi-Fi and Ethernet event handlers if the underlying network driver reports that the * interface has stopped. * * @note To stop an interface from application code, call the network-specific API (esp_wifi_stop() or esp_eth_stop()). * The driver layer will then send a stop event and the event handler should call this API. * Otherwise, the driver and MAC layer will remain started. * * @param[in] tcpip_if Interface which will be stopped * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY */ esp_err_t tcpip_adapter_stop(tcpip_adapter_if_t tcpip_if); /** * @brief Cause the TCP/IP stack to bring up an interface * * @note This function is called automatically by the default event handlers for the Wi-Fi Station and Ethernet interfaces, * in response to the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events, respectively. * * @note This function is not normally used with Wi-Fi AP interface. If the AP interface is started, it is up. * * @param[in] tcpip_if Interface to bring up * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY */ esp_err_t tcpip_adapter_up(tcpip_adapter_if_t tcpip_if); /** * @brief Cause the TCP/IP stack to shutdown an interface * * @note This function is called automatically by the default event handlers for the Wi-Fi Station and Ethernet interfaces, * in response to the SYSTEM_EVENT_STA_DISCONNECTED and SYSTEM_EVENT_ETH_DISCONNECTED events, respectively. * * @note This function is not normally used with Wi-Fi AP interface. If the AP interface is stopped, it is down. * * @param[in] tcpip_if Interface to shutdown * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY */ esp_err_t tcpip_adapter_down(tcpip_adapter_if_t tcpip_if); /** * @brief Get interface's IP address information * * If the interface is up, IP information is read directly from the TCP/IP stack. * * If the interface is down, IP information is read from a copy kept in the TCP/IP adapter * library itself. * * @param[in] tcpip_if Interface to get IP information * @param[out] ip_info If successful, IP information will be returned in this argument. * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS */ esp_err_t tcpip_adapter_get_ip_info(tcpip_adapter_if_t tcpip_if, tcpip_adapter_ip_info_t *ip_info); /** * @brief Set interface's IP address information * * This function is mainly used to set a static IP on an interface. * * If the interface is up, the new IP information is set directly in the TCP/IP stack. * * The copy of IP information kept in the TCP/IP adapter library is also updated (this * copy is returned if the IP is queried while the interface is still down.) * * @note DHCP client/server must be stopped before setting new IP information. * * @note Calling this interface for the Wi-Fi STA or Ethernet interfaces may generate a * SYSTEM_EVENT_STA_GOT_IP or SYSTEM_EVENT_ETH_GOT_IP event. * * @param[in] tcpip_if Interface to set IP information * @param[in] ip_info IP information to set on the specified interface * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_TCPIP_ADAPTER_DHCP_NOT_STOPPED If DHCP server or client is still running */ esp_err_t tcpip_adapter_set_ip_info(tcpip_adapter_if_t tcpip_if, const tcpip_adapter_ip_info_t *ip_info); /** * @brief Set DNS Server information * * This function behaves differently for different interfaces: * * - For Wi-Fi Station interface and Ethernet interface, up to three types of DNS server can be set (in order of priority): * - Main DNS Server (TCPIP_ADAPTER_DNS_MAIN) * - Backup DNS Server (TCPIP_ADAPTER_DNS_BACKUP) * - Fallback DNS Server (TCPIP_ADAPTER_DNS_FALLBACK) * * If DHCP client is enabled, main and backup DNS servers will be updated automatically from the DHCP lease if the relevant DHCP options are set. Fallback DNS Server is never updated from the DHCP lease and is designed to be set via this API. * * If DHCP client is disabled, all DNS server types can be set via this API only. * * - For Wi-Fi AP interface, the Main DNS Server setting is used by the DHCP server to provide a DNS Server option to DHCP clients (Wi-Fi stations). * - The default Main DNS server is the IP of the Wi-Fi AP interface itself. * - This function can override it by setting server type TCPIP_ADAPTER_DNS_MAIN. * - Other DNS Server types are not supported for the Wi-Fi AP interface. * * @param[in] tcpip_if Interface to set DNS Server information * @param[in] type Type of DNS Server to set: TCPIP_ADAPTER_DNS_MAIN, TCPIP_ADAPTER_DNS_BACKUP, TCPIP_ADAPTER_DNS_FALLBACK * @param[in] dns DNS Server address to set * * @return * - ESP_OK on success * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS invalid params */ esp_err_t tcpip_adapter_set_dns_info(tcpip_adapter_if_t tcpip_if, tcpip_adapter_dns_type_t type, tcpip_adapter_dns_info_t *dns); /** * @brief Get DNS Server information * * Return the currently configured DNS Server address for the specified interface and Server type. * * This may be result of a previous call to tcpip_adapter_set_dns_info(). If the interface's DHCP client is enabled, * the Main or Backup DNS Server may be set by the current DHCP lease. * * @param[in] tcpip_if Interface to get DNS Server information * @param[in] type Type of DNS Server to get: TCPIP_ADAPTER_DNS_MAIN, TCPIP_ADAPTER_DNS_BACKUP, TCPIP_ADAPTER_DNS_FALLBACK * @param[out] dns DNS Server result is written here on success * * @return * - ESP_OK on success * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS invalid params */ esp_err_t tcpip_adapter_get_dns_info(tcpip_adapter_if_t tcpip_if, tcpip_adapter_dns_type_t type, tcpip_adapter_dns_info_t *dns); /** * @brief Get interface's old IP information * * Returns an "old" IP address previously stored for the interface when the valid IP changed. * * If the IP lost timer has expired (meaning the interface was down for longer than the configured interval) * then the old IP information will be zero. * * @param[in] tcpip_if Interface to get old IP information * @param[out] ip_info If successful, IP information will be returned in this argument. * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS */ esp_err_t tcpip_adapter_get_old_ip_info(tcpip_adapter_if_t tcpip_if, tcpip_adapter_ip_info_t *ip_info); /** * @brief Set interface old IP information * * This function is called from the DHCP client for the Wi-Fi STA and Ethernet interfaces, before a new IP is set. It is also called from the default handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events. * * Calling this function stores the previously configured IP, which can be used to determine if the IP changes in the future. * * If the interface is disconnected or down for too long, the "IP lost timer" will expire (after the configured interval) and set the old IP information to zero. * * @param[in] tcpip_if Interface to set old IP information * @param[in] ip_info Store the old IP information for the specified interface * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS */ esp_err_t tcpip_adapter_set_old_ip_info(tcpip_adapter_if_t tcpip_if, const tcpip_adapter_ip_info_t *ip_info); /** * @brief Create interface link-local IPv6 address * * Cause the TCP/IP stack to create a link-local IPv6 address for the specified interface. * * This function also registers a callback for the specified interface, so that if the link-local address becomes verified as the preferred address then a SYSTEM_EVENT_GOT_IP6 event will be sent. * * @param[in] tcpip_if Interface to create a link-local IPv6 address * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS */ esp_err_t tcpip_adapter_create_ip6_linklocal(tcpip_adapter_if_t tcpip_if); /** * @brief Get interface link-local IPv6 address * * If the specified interface is up and a preferred link-local IPv6 address * has been created for the interface, return a copy of it. * * @param[in] tcpip_if Interface to get link-local IPv6 address * @param[out] if_ip6 IPv6 information will be returned in this argument if successful. * * @return * - ESP_OK * - ESP_FAIL If interface is down, does not have a link-local IPv6 address, or the link-local IPv6 address is not a preferred address. */ esp_err_t tcpip_adapter_get_ip6_linklocal(tcpip_adapter_if_t tcpip_if, ip6_addr_t *if_ip6); #if 0 esp_err_t tcpip_adapter_get_mac(tcpip_adapter_if_t tcpip_if, uint8_t *mac); esp_err_t tcpip_adapter_set_mac(tcpip_adapter_if_t tcpip_if, uint8_t *mac); #endif /** * @brief Get DHCP Server status * * @param[in] tcpip_if Interface to get status of DHCP server. * @param[out] status If successful, the status of the DHCP server will be returned in this argument. * * @return * - ESP_OK */ esp_err_t tcpip_adapter_dhcps_get_status(tcpip_adapter_if_t tcpip_if, tcpip_adapter_dhcp_status_t *status); /** * @brief Set or Get DHCP server option * * @param[in] opt_op TCPIP_ADAPTER_OP_SET to set an option, TCPIP_ADAPTER_OP_GET to get an option. * @param[in] opt_id Option index to get or set, must be one of the supported enum values. * @param[inout] opt_val Pointer to the option parameter. * @param[in] opt_len Length of the option parameter. * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED * - ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STARTED */ esp_err_t tcpip_adapter_dhcps_option(tcpip_adapter_dhcp_option_mode_t opt_op, tcpip_adapter_dhcp_option_id_t opt_id, void *opt_val, uint32_t opt_len); /** * @brief Start DHCP server * * @note Currently DHCP server is only supported on the Wi-Fi AP interface. * * @param[in] tcpip_if Interface to start DHCP server. Must be TCPIP_ADAPTER_IF_AP. * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STARTED */ esp_err_t tcpip_adapter_dhcps_start(tcpip_adapter_if_t tcpip_if); /** * @brief Stop DHCP server * * @note Currently DHCP server is only supported on the Wi-Fi AP interface. * * @param[in] tcpip_if Interface to stop DHCP server. Must be TCPIP_ADAPTER_IF_AP. * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY */ esp_err_t tcpip_adapter_dhcps_stop(tcpip_adapter_if_t tcpip_if); /** * @brief Get DHCP client status * * @param[in] tcpip_if Interface to get status of DHCP client * @param[out] status If successful, the status of DHCP client will be returned in this argument. * * @return * - ESP_OK */ esp_err_t tcpip_adapter_dhcpc_get_status(tcpip_adapter_if_t tcpip_if, tcpip_adapter_dhcp_status_t *status); /** * @brief Set or Get DHCP client's option * * @note This function is not yet implemented * * @param[in] opt_op TCPIP_ADAPTER_OP_SET to set an option, TCPIP_ADAPTER_OP_GET to get an option. * @param[in] opt_id Option index to get or set, must be one of the supported enum values. * @param[inout] opt_val Pointer to the option parameter. * @param[in] opt_len Length of the option parameter. * * @return * - ESP_ERR_NOT_SUPPORTED (not implemented) */ esp_err_t tcpip_adapter_dhcpc_option(tcpip_adapter_dhcp_option_mode_t opt_op, tcpip_adapter_dhcp_option_id_t opt_id, void *opt_val, uint32_t opt_len); /** * @brief Start DHCP client * * @note DHCP Client is only supported for the Wi-Fi station and Ethernet interfaces. * * @note The default event handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events call this function. * * @param[in] tcpip_if Interface to start the DHCP client * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STARTED * - ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED */ esp_err_t tcpip_adapter_dhcpc_start(tcpip_adapter_if_t tcpip_if); /** * @brief Stop DHCP client * * @note DHCP Client is only supported for the Wi-Fi station and Ethernet interfaces. * * @note Calling tcpip_adapter_stop() or tcpip_adapter_down() will also stop the DHCP Client if it is running. * * @param[in] tcpip_if Interface to stop the DHCP client * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS * - ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY */ esp_err_t tcpip_adapter_dhcpc_stop(tcpip_adapter_if_t tcpip_if); /** * @brief Receive an Ethernet frame from the Ethernet interface * * This function will automatically be installed by esp_eth_init(). The Ethernet driver layer will then call this function to forward frames to the TCP/IP stack. * * @note Application code does not usually need to use this function directly. * * @param[in] buffer Received data * @param[in] len Length of the data frame * @param[in] eb Pointer to internal Wi-Fi buffer (ignored for Ethernet) * * @return * - ESP_OK */ esp_err_t tcpip_adapter_eth_input(void *buffer, uint16_t len, void *eb); /** * @brief Receive an 802.11 data frame from the Wi-Fi Station interface * * This function should be installed by calling esp_wifi_reg_rxcb(). The Wi-Fi driver layer will then call this function to forward frames to the TCP/IP stack. * * @note Installation happens automatically in the default handler for the SYSTEM_EVENT_STA_CONNECTED event. * * @note Application code does not usually need to call this function directly. * * @param[in] buffer Received data * @param[in] len Length of the data frame * @param[in] eb Pointer to internal Wi-Fi buffer * * @return * - ESP_OK */ esp_err_t tcpip_adapter_sta_input(void *buffer, uint16_t len, void *eb); /** * @brief Receive an 802.11 data frame from the Wi-Fi AP interface * * This function should be installed by calling esp_wifi_reg_rxcb(). The Wi-Fi driver layer will then call this function to forward frames to the TCP/IP stack. * * @note Installation happens automatically in the default handler for the SYSTEM_EVENT_AP_START event. * * @note Application code does not usually need to call this function directly. * * @param[in] buffer Received data * @param[in] len Length of the data frame * @param[in] eb Pointer to internal Wi-Fi buffer * * @return * - ESP_OK */ esp_err_t tcpip_adapter_ap_input(void *buffer, uint16_t len, void *eb); /** * @brief Get network interface index * * Get network interface from TCP/IP implementation-specific interface pointer. * * @param[in] dev Implementation-specific TCP/IP stack interface pointer. * * @return * - ESP_IF_WIFI_STA * - ESP_IF_WIFI_AP * - ESP_IF_ETH * - ESP_IF_MAX - invalid parameter */ esp_interface_t tcpip_adapter_get_esp_if(void *dev); /** * @brief Get IP information for stations connected to the Wi-Fi AP interface * * @param[in] wifi_sta_list Wi-Fi station info list, returned from esp_wifi_ap_get_sta_list() * @param[out] tcpip_sta_list IP layer station info list, corresponding to MAC addresses provided in wifi_sta_list * * @return * - ESP_OK * - ESP_ERR_TCPIP_ADAPTER_NO_MEM * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS */ esp_err_t tcpip_adapter_get_sta_list(const wifi_sta_list_t *wifi_sta_list, tcpip_adapter_sta_list_t *tcpip_sta_list); #define TCPIP_HOSTNAME_MAX_SIZE 32 /** * @brief Set the hostname of an interface * * @param[in] tcpip_if Interface to set the hostname * @param[in] hostname New hostname for the interface. Maximum length 32 bytes. * * @return * - ESP_OK - success * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY - interface status error * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS - parameter error */ esp_err_t tcpip_adapter_set_hostname(tcpip_adapter_if_t tcpip_if, const char *hostname); /** * @brief Get interface hostname. * * @param[in] tcpip_if Interface to get the hostname * @param[out] hostname Returns a pointer to the hostname. May be NULL if no hostname is set. If set non-NULL, pointer remains valid (and string may change if the hostname changes). * * @return * - ESP_OK - success * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY - interface status error * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS - parameter error */ esp_err_t tcpip_adapter_get_hostname(tcpip_adapter_if_t tcpip_if, const char **hostname); /** * @brief Get the TCP/IP stack-specific interface that is assigned to a given interface * * @note For lwIP, this returns a pointer to a netif structure. * * @param[in] tcpip_if Interface to get the implementation-specific interface * @param[out] netif Pointer to the implementation-specific interface * * @return * - ESP_OK - success * - ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY - interface status error * - ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS - parameter error */ esp_err_t tcpip_adapter_get_netif(tcpip_adapter_if_t tcpip_if, void ** netif); /** * @brief Test if supplied interface is up or down * * @param[in] tcpip_if Interface to test up/down status * * @return * - true - Interface is up * - false - Interface is down */ bool tcpip_adapter_is_netif_up(tcpip_adapter_if_t tcpip_if); /** * @brief Install default event handlers for Ethernet interface * @return * - ESP_OK on success * - one of the errors from esp_event on failure */ esp_err_t tcpip_adapter_set_default_eth_handlers(); /** * @brief Uninstall default event handlers for Ethernet interface * @return * - ESP_OK on success * - one of the errors from esp_event on failure */ esp_err_t tcpip_adapter_clear_default_eth_handlers(); /** * @brief Install default event handlers for Wi-Fi interfaces (station and AP) * @return * - ESP_OK on success * - one of the errors from esp_event on failure */ esp_err_t tcpip_adapter_set_default_wifi_handlers(); /** * @brief Uninstall default event handlers for Wi-Fi interfaces (station and AP) * @return * - ESP_OK on success * - one of the errors from esp_event on failure */ esp_err_t tcpip_adapter_clear_default_wifi_handlers(); #ifdef __cplusplus } #endif #endif /* _TCPIP_ADAPTER_H_ */
{ "content_hash": "abdc8b5797932115ceb9116285af57ef", "timestamp": "", "source": "github", "line_count": 733, "max_line_length": 261, "avg_line_length": 38.30422919508867, "alnum_prop": 0.6904227659650247, "repo_name": "krzychb/rtd-test-bed", "id": "3953984264ea1109b5a44b3b25e805b6dfe4042a", "size": "28077", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/tcpip_adapter/include/tcpip_adapter.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "248929" }, { "name": "Batchfile", "bytes": "9428" }, { "name": "C", "bytes": "42611901" }, { "name": "C++", "bytes": "10437923" }, { "name": "CMake", "bytes": "316611" }, { "name": "CSS", "bytes": "1340" }, { "name": "Dockerfile", "bytes": "4319" }, { "name": "GDB", "bytes": "2764" }, { "name": "Go", "bytes": "146670" }, { "name": "HCL", "bytes": "468" }, { "name": "HTML", "bytes": "115431" }, { "name": "Inno Setup", "bytes": "14977" }, { "name": "Lex", "bytes": "7273" }, { "name": "M4", "bytes": "189150" }, { "name": "Makefile", "bytes": "439631" }, { "name": "Objective-C", "bytes": "133538" }, { "name": "PHP", "bytes": "498" }, { "name": "Pawn", "bytes": "151052" }, { "name": "Perl", "bytes": "141532" }, { "name": "Python", "bytes": "1868534" }, { "name": "Roff", "bytes": "102712" }, { "name": "Ruby", "bytes": "206821" }, { "name": "Shell", "bytes": "625528" }, { "name": "Smarty", "bytes": "5972" }, { "name": "Tcl", "bytes": "110" }, { "name": "TeX", "bytes": "1961" }, { "name": "Visual Basic", "bytes": "294" }, { "name": "XSLT", "bytes": "80335" }, { "name": "Yacc", "bytes": "15875" } ], "symlink_target": "" }
package org.apache.ofbiz.base.conversion.test; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.ofbiz.base.conversion.BooleanConverters; import org.apache.ofbiz.base.conversion.Converter; import org.apache.ofbiz.base.conversion.ConverterLoader; import org.apache.ofbiz.base.conversion.Converters; import junit.framework.TestCase; public class TestBooleanConverters extends TestCase { public TestBooleanConverters(String name) { super(name); } public static <T> void assertFromBoolean(String label, Converter<Boolean, T> converter, T trueResult, T falseResult) throws Exception { assertTrue(label + " can convert", converter.canConvert(Boolean.class, trueResult.getClass())); assertEquals(label + " registered", converter.getClass(), Converters.getConverter(Boolean.class, trueResult.getClass()).getClass()); assertEquals(label + " converted", trueResult, converter.convert(true)); assertEquals(label + " converted", falseResult, converter.convert(false)); } public static <S> void assertToBoolean(String label, Converter<S, Boolean> converter, S trueSource, S falseSource) throws Exception { assertTrue(label + " can convert", converter.canConvert(trueSource.getClass(), Boolean.class)); assertEquals(label + " registered", converter.getClass(), Converters.getConverter(trueSource.getClass(), Boolean.class).getClass()); assertEquals(label + " converted", Boolean.TRUE, converter.convert(trueSource)); assertEquals(label + " converted", Boolean.FALSE, converter.convert(falseSource)); } @SuppressWarnings("unchecked") public static <S> void assertToCollection(String label, S source) throws Exception { Converter<S, ? extends Collection> toList = (Converter<S, ? extends Collection>) Converters.getConverter(source.getClass(), List.class); Collection<S> listResult = toList.convert(source); assertEquals(label + " converted to List", source, listResult.toArray()[0]); Converter<S, ? extends Collection> toSet = (Converter<S, ? extends Collection>) Converters.getConverter(source.getClass(), Set.class); Collection<S> setResult = toSet.convert(source); assertEquals(label + " converted to Set", source, setResult.toArray()[0]); } public void testBooleanConverters() throws Exception { ConverterLoader loader = new BooleanConverters(); loader.loadConverters(); assertFromBoolean("BooleanToInteger", new BooleanConverters.BooleanToInteger(), 1, 0); assertFromBoolean("BooleanToString", new BooleanConverters.BooleanToString(), "true", "false"); assertToBoolean("IntegerToBoolean", new BooleanConverters.IntegerToBoolean(), 1, 0); assertToBoolean("StringToBoolean", new BooleanConverters.StringToBoolean(), "true", "false"); assertToCollection("BooleanToCollection", Boolean.TRUE); } }
{ "content_hash": "83a8a57338b6ffbfcc8f86043d085143", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 144, "avg_line_length": 54.72222222222222, "alnum_prop": 0.7289340101522843, "repo_name": "yuri0x7c1/ofbiz-explorer", "id": "22961dc48d09c8619c989e5bc4fe2e8776a9c2d9", "size": "3916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources/apache-ofbiz-17.12.04/framework/base/src/main/java/org/apache/ofbiz/base/conversion/test/TestBooleanConverters.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "17446" }, { "name": "CSS", "bytes": "1890137" }, { "name": "FreeMarker", "bytes": "4633734" }, { "name": "Groovy", "bytes": "1724859" }, { "name": "HTML", "bytes": "12835438" }, { "name": "Java", "bytes": "16138651" }, { "name": "JavaScript", "bytes": "4284839" }, { "name": "Makefile", "bytes": "25802" }, { "name": "PHP", "bytes": "150" }, { "name": "Perl", "bytes": "2756" }, { "name": "Python", "bytes": "19974" }, { "name": "Roff", "bytes": "4118" }, { "name": "Ruby", "bytes": "2533" }, { "name": "Shell", "bytes": "44075" }, { "name": "XSLT", "bytes": "8467700" } ], "symlink_target": "" }
// // GTLService.h // // Service object documentation: // https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Services_and_Tickets #import <Foundation/Foundation.h> #import "GTLDefines.h" // Fetcher bridging macros -- Internal library use only. // // GTL_USE_SESSION_FETCHER should be set to force the GTL library to use // GTMSessionFetcher rather than the older GTMHTTPFetcher. The session // fetcher requires iOS 7/OS X 10.9 and supports out-of-process uploads. #if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0) #ifndef GTM_USE_SESSION_FETCHER #define GTM_USE_SESSION_FETCHER 0 #endif #endif #if !defined(GTL_USE_SESSION_FETCHER) && defined(GTM_USE_SESSION_FETCHER) #define GTL_USE_SESSION_FETCHER GTM_USE_SESSION_FETCHER #endif // GTL_USE_SESSION_FETCHER #if GTL_USE_SESSION_FETCHER #define GTLUploadFetcherClass GTMSessionUploadFetcher #define GTLUploadFetcherClassStr @"GTMSessionUploadFetcher" #import "GTMSessionFetcher.h" #import "GTMSessionFetcherService.h" #else // !GTL_USE_SESSION_FETCHER #define GTLUploadFetcherClass GTMHTTPUploadFetcher #define GTLUploadFetcherClassStr @"GTMHTTPUploadFetcher" #import "GTMHTTPFetcher.h" #import "GTMHTTPFetcherService.h" #endif // GTL_USE_SESSION_FETCHER #import "GTLBatchQuery.h" #import "GTLBatchResult.h" #import "GTLDateTime.h" #import "GTLErrorObject.h" #import "GTLFramework.h" #import "GTLJSONParser.h" #import "GTLObject.h" #import "GTLQuery.h" #import "GTLUtilities.h" #import "GTMHTTPFetcher.h" // Error domains extern NSString *const kGTLServiceErrorDomain; enum { kGTLErrorQueryResultMissing = -3000, kGTLErrorWaitTimedOut = -3001 }; extern NSString *const kGTLJSONRPCErrorDomain; // We'll consistently store the server error string in the userInfo under // this key extern NSString *const kGTLServerErrorStringKey; extern Class const kGTLUseRegisteredClass; extern NSUInteger const kGTLStandardUploadChunkSize; // When servers return us structured JSON errors, the NSError will // contain a GTLErrorObject in the userInfo dictionary under the key // kGTLStructuredErrorsKey extern NSString *const kGTLStructuredErrorKey; // When specifying an ETag for updating or deleting a single entry, use // kGTLETagWildcard to tell the server to replace the current value // unconditionally. Do not use this in entries in a batch feed. extern NSString *const kGTLETagWildcard; // Notifications when parsing of a fetcher feed or entry begins or ends extern NSString *const kGTLServiceTicketParsingStartedNotification; extern NSString *const kGTLServiceTicketParsingStoppedNotification ; @class GTLServiceTicket; // Block types used for fetch callbacks typedef void (^GTLServiceCompletionHandler)(GTLServiceTicket *ticket, id object, NSError *error); typedef void (^GTLServiceUploadProgressBlock)(GTLServiceTicket *ticket, unsigned long long totalBytesUploaded, unsigned long long totalBytesExpectedToUpload); typedef BOOL (^GTLServiceRetryBlock)(GTLServiceTicket *ticket, BOOL suggestedWillRetry, NSError *error); #pragma mark - // // Service base class // @interface GTLService : NSObject { @private NSOperationQueue *parseQueue_; NSString *userAgent_; GTMHTTPFetcherService *fetcherService_; // GTMBridgeFetcherService *fetcherService_; NSString *userAgentAddition_; NSMutableDictionary *serviceProperties_; // initial values for properties in future tickets NSDictionary *surrogates_; // initial value for surrogates in future tickets SEL uploadProgressSelector_; // optional GTLServiceRetryBlock retryBlock_; GTLServiceUploadProgressBlock uploadProgressBlock_; GTLQueryTestBlock testBlock_; NSUInteger uploadChunkSize_; // zero when uploading via multi-part MIME http body BOOL isRetryEnabled_; // user allows auto-retries SEL retrySelector_; // optional; set with setServiceRetrySelector NSTimeInterval maxRetryInterval_; // default to 600. seconds BOOL shouldFetchNextPages_; BOOL allowInsecureQueries_; NSString *apiKey_; BOOL isRESTDataWrapperRequired_; NSString *apiVersion_; NSURL *rpcURL_; NSURL *rpcUploadURL_; NSDictionary *urlQueryParameters_; NSDictionary *additionalHTTPHeaders_; #if GTL_USE_SESSION_FETCHER NSArray *runLoopModes_; #endif } #pragma mark Query Execution // The finishedSelector has a signature matching: // // - (void)serviceTicket:(GTLServiceTicket *)ticket // finishedWithObject:(GTLObject *)object // error:(NSError *)error // // If an error occurs, the error parameter will be non-nil. Otherwise, // the object parameter will point to a GTLObject, if any was returned by // the fetch. (Delete fetches return no object, so the second parameter will // be nil.) // // If the query object is a GTLBatchQuery, the object passed to the callback // will be a GTLBatchResult; see the batch query documentation: // https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Batch_Operations - (GTLServiceTicket *)executeQuery:(id<GTLQueryProtocol>)query delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)executeQuery:(id<GTLQueryProtocol>)query completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); // Automatic page fetches // // Tickets can optionally do a sequence of fetches for queries where // repeated requests with nextPageToken or nextStartIndex values is required to // retrieve items of all pages of the response collection. The client's // callback is invoked only when all items have been retrieved, or an error has // occurred. During the fetch, the items accumulated so far are available from // the ticket. // // Note that the final object may be a combination of multiple page responses // so it may not be the same as if all results had been returned in a single // page. Some fields of the response such as total item counts may reflect only // the final page's values. // // Automatic page fetches will return an error if more than 25 page fetches are // required. For debug builds, this will log a warning to the console when more // than 2 page fetches occur, as a reminder that the query's maxResults // parameter should probably be increased to specify more items returned per // page. // // Default value is NO. @property (nonatomic, assign) BOOL shouldFetchNextPages; // Retrying; see comments on retry support at the top of GTMHTTPFetcher. // // Default value is NO. @property (nonatomic, assign, getter=isRetryEnabled) BOOL retryEnabled; // Some services require a developer key for quotas and limits. Setting this // will include it on all request sent to this service via a GTLQuery class. @property (nonatomic, copy) NSString *APIKey; // An authorizer adds user authentication headers to the request as needed. @property (nonatomic, retain) id <GTMFetcherAuthorizationProtocol> authorizer; // Retry selector is optional for retries. // // If present, it should have the signature: // -(BOOL)ticket:(GTLServiceTicket *)ticket willRetry:(BOOL)suggestedWillRetry forError:(NSError *)error // and return YES to cause a retry. Note that unlike the fetcher retry // selector, this selector's first argument is a ticket, not a fetcher. @property (nonatomic, assign) SEL retrySelector; @property (copy) GTLServiceRetryBlock retryBlock; @property (nonatomic, assign) NSTimeInterval maxRetryInterval; // A test block can be provided to test service calls without any network activity. // // See the description of GTLQueryTestBlock for additional details. @property (nonatomic, copy) GTLQueryTestBlock testBlock; // // Fetches may be done using RPC or REST APIs, without creating // a GTLQuery object // #pragma mark RPC Fetch Methods // // These methods may be used for RPC fetches without creating a GTLQuery object // - (GTLServiceTicket *)fetchObjectWithMethodNamed:(NSString *)methodName parameters:(NSDictionary *)parameters objectClass:(Class)objectClass delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectWithMethodNamed:(NSString *)methodName insertingObject:(GTLObject *)bodyObject objectClass:(Class)objectClass delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectWithMethodNamed:(NSString *)methodName parameters:(NSDictionary *)parameters insertingObject:(GTLObject *)bodyObject objectClass:(Class)objectClass delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectWithMethodNamed:(NSString *)methodName parameters:(NSDictionary *)parameters objectClass:(Class)objectClass completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectWithMethodNamed:(NSString *)methodName insertingObject:(GTLObject *)bodyObject objectClass:(Class)objectClass completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectWithMethodNamed:(NSString *)methodName parameters:(NSDictionary *)parameters insertingObject:(GTLObject *)bodyObject objectClass:(Class)objectClass completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); #pragma mark REST Fetch Methods - (GTLServiceTicket *)fetchObjectWithURL:(NSURL *)objectURL delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectWithURL:(NSURL *)objectURL objectClass:(Class)objectClass delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)fetchPublicObjectWithURL:(NSURL *)objectURL objectClass:(Class)objectClass delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectByInsertingObject:(GTLObject *)bodyToPut forURL:(NSURL *)destinationURL delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1,2)); - (GTLServiceTicket *)fetchObjectByUpdatingObject:(GTLObject *)bodyToPut forURL:(NSURL *)destinationURL delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1,2)); - (GTLServiceTicket *)deleteResourceURL:(NSURL *)destinationURL ETag:(NSString *)etagOrNil delegate:(id)delegate didFinishSelector:(SEL)finishedSelector GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectWithURL:(NSURL *)objectURL completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectByInsertingObject:(GTLObject *)bodyToPut forURL:(NSURL *)destinationURL completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); - (GTLServiceTicket *)fetchObjectByUpdatingObject:(GTLObject *)bodyToPut forURL:(NSURL *)destinationURL completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); - (GTLServiceTicket *)deleteResourceURL:(NSURL *)destinationURL ETag:(NSString *)etagOrNil completionHandler:(GTLServiceCompletionHandler)handler GTL_NONNULL((1)); #pragma mark User Properties // Properties and userData are supported for client convenience. // // Property keys beginning with _ are reserved by the library. // // The service properties dictionary is copied to become the initial property // dictionary for each ticket. - (void)setServiceProperty:(id)obj forKey:(NSString *)key GTL_NONNULL((2)); // pass nil obj to remove property - (id)servicePropertyForKey:(NSString *)key GTL_NONNULL((1)); @property (nonatomic, copy) NSDictionary *serviceProperties; // The service userData becomes the initial value for each future ticket's // userData. @property (nonatomic, retain) id serviceUserData; #pragma mark Request Settings // Set the surrogates to be used for future tickets. Surrogates are subclasses // to be used instead of standard classes when creating objects from the JSON. // For example, this code will make the framework generate objects // using MyCalendarItemSubclass instead of GTLItemCalendar and // MyCalendarEventSubclass instead of GTLItemCalendarEvent. // // NSDictionary *surrogates = @{ // [GTLItemCalendar class] : [MyCalendarEntrySubclass class], // [GTLItemCalendarEvent class] : [MyCalendarEventSubclass class] // }; // [calendarService setServiceSurrogates:surrogates]; // @property (nonatomic, retain) NSDictionary *surrogates; // On iOS 4 and later, the fetch may optionally continue in the background // until finished or stopped by OS expiration. // // The default value is NO. // // For Mac OS X, background fetches are always supported, and this property // is ignored. @property (nonatomic, assign) BOOL shouldFetchInBackground; // Callbacks can be invoked on an operation queue rather than via the run loop // starting on 10.7 and iOS 6. Do not specify both run loop modes and an // operation queue. Specifying a delegate queue typically looks like this: // // service.delegateQueue = [[[NSOperationQueue alloc] init] autorelease]; // // Since the callbacks will be on a thread of the operation queue, the client // may re-dispatch from the callbacks to a known dispatch queue or to the // main queue. @property (nonatomic, retain) NSOperationQueue *delegateQueue; // Run loop modes are used for scheduling NSURLConnections. // // The default value, nil, schedules connections using the current run // loop mode. To use the service during a modal dialog, be sure to specify // NSModalPanelRunLoopMode as one of the modes. @property (nonatomic, retain) GTL_NSArrayOf(NSString *) *runLoopModes; // Normally, API requests must be made only via SSL to protect the user's // data and the authentication token. This property allows the application // to make non-SSL requests and localhost requests for testing. // // Defaults to NO. @property (nonatomic, assign) BOOL allowInsecureQueries; // Applications needing an additional identifier in the server logs may specify // one. @property (nonatomic, copy) NSString *userAgentAddition; // Applications have a default user-agent based on the application signature // in the Info.plist settings. Most applications should not explicitly set // this property. Any string provided will be cleaned of inappropriate characters. @property (nonatomic, copy) NSString *userAgent; // The request user agent includes the library and OS version appended to the // base userAgent, along with the optional addition string. @property (nonatomic, readonly) NSString *requestUserAgent; // Applications can provide a precise userAgent string identifying the application. // No cleaning of characters is done. Library-specific details will be appended. - (void)setExactUserAgent:(NSString *)userAgent; // Applications may call requestForURL:httpMethod to get a request with the // proper user-agent and ETag headers // // For http method, pass nil (for default GET method), POST, PUT, or DELETE - (NSMutableURLRequest *)requestForURL:(NSURL *)url ETag:(NSString *)etagOrNil httpMethod:(NSString *)httpMethodOrNil GTL_NONNULL((1)); // objectRequestForURL returns an NSMutableURLRequest for a JSON GTL object // // The object is the object being sent to the server, or nil; // the http method may be nil for GET, or POST, PUT, DELETE - (NSMutableURLRequest *)objectRequestForURL:(NSURL *)url object:(GTLObject *)object ETag:(NSString *)etag httpMethod:(NSString *)httpMethod isREST:(BOOL)isREST additionalHeaders:(NSDictionary *)additionalHeaders ticket:(GTLServiceTicket *)ticket GTL_NONNULL((1)); // The queue used for parsing JSON responses (previously this property // was called operationQueue) @property (nonatomic, retain) NSOperationQueue *parseQueue; // The fetcher service object issues the fetcher instances // for this API service @property (nonatomic, retain) GTMHTTPFetcherService *fetcherService; //@property (nonatomic, retain) GTMBridgeFetcherService *fetcherService; // Default storage for cookies is in the service object's fetchHistory. // // Apps that want to share cookies between all standalone fetchers and the // service object may specify static application-wide cookie storage, // kGTMHTTPFetcherCookieStorageMethodStatic. #if !GTL_USE_SESSION_FETCHER @property (nonatomic, assign) NSInteger cookieStorageMethod; #endif // When sending REST style queries, should the payload be wrapped in a "data" // element, and will the reply be wrapped in an "data" element. @property (nonatomic, assign) BOOL isRESTDataWrapperRequired; // Any url query parameters to add to urls (useful for debugging with some // services). @property (copy) GTL_NSDictionaryOf(NSString *, NSString *) *urlQueryParameters; // Any extra http headers to set on requests for GTLObjects. @property (copy) GTL_NSDictionaryOf(NSString *, NSString *) *additionalHTTPHeaders; // The service API version. @property (nonatomic, copy) NSString *apiVersion; // The URL for sending RPC requests for this service. @property (nonatomic, retain) NSURL *rpcURL; // The URL for sending RPC requests which initiate file upload. @property (nonatomic, retain) NSURL *rpcUploadURL; // Set a non-zero value to enable uploading via chunked fetches // (resumable uploads); typically this defaults to kGTLStandardUploadChunkSize // for service subclasses that support chunked uploads @property (nonatomic, assign) NSUInteger serviceUploadChunkSize; // Service subclasses may specify their own default chunk size + (NSUInteger)defaultServiceUploadChunkSize; // The service uploadProgressSelector becomes the initial value for each future // ticket's uploadProgressSelector. // // The optional uploadProgressSelector will be called in the delegate as bytes // are uploaded to the server. It should have a signature matching // // - (void)ticket:(GTLServiceTicket *)ticket // hasDeliveredByteCount:(unsigned long long)numberOfBytesRead // ofTotalByteCount:(unsigned long long)dataLength; @property (nonatomic, assign) SEL uploadProgressSelector; @property (copy) GTLServiceUploadProgressBlock uploadProgressBlock; @end @interface GTLService (TestingSupport) // Convenience method to create a mock GTL service just for testing. // // Queries executed by this mock service will not perform any network operation, // but will invoke callbacks and provide the supplied data or error to the // completion handler. // // You can make more customized mocks by setting the test block property of the service // or query; the test block can inspect the query as ticket.originalQuery // // See the description of GTLQueryTestBlock for more details on customized testing. // // Example usage is in the unit test method testMockServiceConvenienceMethod. + (instancetype)mockServiceWithFakedObject:(id)objectOrNil fakedError:(NSError *)error; // Wait synchronously for fetch to complete (strongly discouraged) // // This just runs the current event loop until the fetch completes // or the timout limit is reached. This may discard unexpected events // that occur while spinning, so it's really not appropriate for use // in serious applications. // // Returns true if an object was successfully fetched. If the wait // timed out, returns false and the returned error is nil. // // The returned object or error, if any, will be already autoreleased // // This routine will likely be removed in some future releases of the library. - (BOOL)waitForTicket:(GTLServiceTicket *)ticket timeout:(NSTimeInterval)timeoutInSeconds fetchedObject:(GTLObject **)outObjectOrNil error:(NSError **)outErrorOrNil GTL_NONNULL((1)); @end #pragma mark - // // Ticket base class // @interface GTLServiceTicket : NSObject { @private GTLService *service_; NSMutableDictionary *ticketProperties_; NSDictionary *surrogates_; GTMHTTPFetcher *objectFetcher_; // GTMBridgeFetcher *objectFetcher_; SEL uploadProgressSelector_; BOOL shouldFetchNextPages_; BOOL isRetryEnabled_; SEL retrySelector_; NSTimeInterval maxRetryInterval_; GTLServiceRetryBlock retryBlock_; GTLServiceUploadProgressBlock uploadProgressBlock_; GTLObject *postedObject_; GTLObject *fetchedObject_; id<GTLQueryProtocol> executingQuery_; id<GTLQueryProtocol> originalQuery_; NSError *fetchError_; BOOL hasCalledCallback_; NSUInteger pagesFetchedCounter_; NSString *apiKey_; BOOL isREST_; NSOperation *parseOperation_; } + (instancetype)ticketForService:(GTLService *)service; - (instancetype)initWithService:(GTLService *)service; - (id)service; #pragma mark Execution Control // if cancelTicket is called, the fetch is stopped if it is in progress, // the callbacks will not be called, and the ticket will no longer be useful // (though the client must still release the ticket if it retained the ticket) - (void)cancelTicket; // chunked upload tickets may be paused - (void)pauseUpload; - (void)resumeUpload; - (BOOL)isUploadPaused; @property (nonatomic, retain) GTMHTTPFetcher *objectFetcher; //@property (nonatomic, retain) GTMBridgeFetcher *objectFetcher; @property (nonatomic, assign) SEL uploadProgressSelector; // Services which do not require an user authorization may require a developer // API key for quota management @property (nonatomic, copy) NSString *APIKey; #pragma mark User Properties // Properties and userData are supported for client convenience. // // Property keys beginning with _ are reserved by the library. - (void)setProperty:(id)obj forKey:(NSString *)key GTL_NONNULL((1)); // pass nil obj to remove property - (id)propertyForKey:(NSString *)key; @property (nonatomic, copy) GTL_NSDictionaryOf(NSString *, id) *properties; @property (nonatomic, retain) id userData; #pragma mark Payload @property (nonatomic, retain) GTLObject *postedObject; @property (nonatomic, retain) GTLObject *fetchedObject; @property (nonatomic, retain) id<GTLQueryProtocol> executingQuery; // Query currently being fetched by this ticket @property (nonatomic, retain) id<GTLQueryProtocol> originalQuery; // Query used to create this ticket - (GTLQuery *)queryForRequestID:(NSString *)requestID GTL_NONNULL((1)); // Returns the query from within the batch with the given id. @property (nonatomic, retain) GTL_NSDictionaryOf(Class, Class) *surrogates; #pragma mark Retry @property (nonatomic, assign, getter=isRetryEnabled) BOOL retryEnabled; @property (nonatomic, assign) SEL retrySelector; @property (copy) GTLServiceRetryBlock retryBlock; @property (nonatomic, assign) NSTimeInterval maxRetryInterval; #pragma mark Status @property (nonatomic, readonly) NSInteger statusCode; // server status from object fetch @property (nonatomic, retain) NSError *fetchError; @property (nonatomic, assign) BOOL hasCalledCallback; #pragma mark Pagination @property (nonatomic, assign) BOOL shouldFetchNextPages; @property (nonatomic, assign) NSUInteger pagesFetchedCounter; #pragma mark Upload @property (copy) GTLServiceUploadProgressBlock uploadProgressBlock; @end // Category to provide opaque access to tickets stored in fetcher properties @interface GTMHTTPFetcher (GTLServiceTicketAdditions) //@interface GTMBridgeFetcher (GTLServiceTicketAdditions) - (id)ticket; @end
{ "content_hash": "c9317ba08a4c70bf0ad450fea89fe346", "timestamp": "", "source": "github", "line_count": 633, "max_line_length": 133, "avg_line_length": 40.011058451816744, "alnum_prop": 0.7142575117463577, "repo_name": "creationst/google-api-objectivec-client", "id": "4db1070162074d8800676852376d6a50843c22fa", "size": "25922", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Objects/GTLService.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "2926" }, { "name": "Objective-C", "bytes": "6581452" } ], "symlink_target": "" }
package org.apache.flink.streaming.connectors.kafka; import org.apache.flink.networking.NetworkFailuresProxy; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.DataStreamSink; import org.apache.flink.streaming.api.operators.StreamSink; import org.apache.flink.streaming.connectors.kafka.partitioner.FlinkKafkaPartitioner; import org.apache.flink.streaming.connectors.kafka.testutils.ZooKeeperStringSerializer; import org.apache.flink.streaming.util.serialization.KeyedSerializationSchema; import org.apache.flink.util.NetUtils; import kafka.admin.AdminUtils; import kafka.common.KafkaException; import kafka.metrics.KafkaMetricsReporter; import kafka.server.KafkaConfig; import kafka.server.KafkaServer; import kafka.utils.ZkUtils; import org.I0Itec.zkclient.ZkClient; import org.apache.commons.collections.list.UnmodifiableList; import org.apache.commons.io.FileUtils; import org.apache.curator.test.TestingServer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.network.ListenerName; import org.apache.kafka.common.protocol.SecurityProtocol; import org.apache.kafka.common.requests.MetadataResponse; import org.apache.kafka.common.utils.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.BindException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import scala.collection.mutable.ArraySeq; import static org.apache.flink.util.NetUtils.hostAndPortToUrlString; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * An implementation of the KafkaServerProvider for Kafka 0.10 . */ public class KafkaTestEnvironmentImpl extends KafkaTestEnvironment { protected static final Logger LOG = LoggerFactory.getLogger(KafkaTestEnvironmentImpl.class); private File tmpZkDir; private File tmpKafkaParent; private List<File> tmpKafkaDirs; private List<KafkaServer> brokers; private TestingServer zookeeper; private String zookeeperConnectionString; private String brokerConnectionString = ""; private Properties standardProps; private Config config; // 6 seconds is default. Seems to be too small for travis. 30 seconds private int zkTimeout = 30000; public String getBrokerConnectionString() { return brokerConnectionString; } @Override public Properties getStandardProperties() { return standardProps; } @Override public Properties getSecureProperties() { Properties prop = new Properties(); if (config.isSecureMode()) { prop.put("security.inter.broker.protocol", "SASL_PLAINTEXT"); prop.put("security.protocol", "SASL_PLAINTEXT"); prop.put("sasl.kerberos.service.name", "kafka"); //add special timeout for Travis prop.setProperty("zookeeper.session.timeout.ms", String.valueOf(zkTimeout)); prop.setProperty("zookeeper.connection.timeout.ms", String.valueOf(zkTimeout)); prop.setProperty("metadata.fetch.timeout.ms", "120000"); } return prop; } @Override public String getVersion() { return "0.10"; } @Override public List<KafkaServer> getBrokers() { return brokers; } @Override public <T> FlinkKafkaConsumerBase<T> getConsumer(List<String> topics, KafkaDeserializationSchema<T> readSchema, Properties props) { return new FlinkKafkaConsumer010<>(topics, readSchema, props); } @Override public <K, V> Collection<ConsumerRecord<K, V>> getAllRecordsFromTopic(Properties properties, String topic, int partition, long timeout) { List<ConsumerRecord<K, V>> result = new ArrayList<>(); try (KafkaConsumer<K, V> consumer = new KafkaConsumer<>(properties)) { consumer.assign(Arrays.asList(new TopicPartition(topic, partition))); while (true) { boolean processedAtLeastOneRecord = false; // wait for new records with timeout and break the loop if we didn't get any Iterator<ConsumerRecord<K, V>> iterator = consumer.poll(timeout).iterator(); while (iterator.hasNext()) { ConsumerRecord<K, V> record = iterator.next(); result.add(record); processedAtLeastOneRecord = true; } if (!processedAtLeastOneRecord) { break; } } consumer.commitSync(); } return UnmodifiableList.decorate(result); } @Override public <T> StreamSink<T> getProducerSink(String topic, KeyedSerializationSchema<T> serSchema, Properties props, FlinkKafkaPartitioner<T> partitioner) { FlinkKafkaProducer010<T> prod = new FlinkKafkaProducer010<>(topic, serSchema, props, partitioner); prod.setFlushOnCheckpoint(true); return new StreamSink<>(prod); } @Override public <T> DataStreamSink<T> produceIntoKafka(DataStream<T> stream, String topic, KeyedSerializationSchema<T> serSchema, Properties props, FlinkKafkaPartitioner<T> partitioner) { FlinkKafkaProducer010<T> prod = new FlinkKafkaProducer010<>(topic, serSchema, props, partitioner); prod.setFlushOnCheckpoint(true); return stream.addSink(prod); } @Override public <T> DataStreamSink<T> writeToKafkaWithTimestamps(DataStream<T> stream, String topic, KeyedSerializationSchema<T> serSchema, Properties props) { FlinkKafkaProducer010<T> prod = new FlinkKafkaProducer010<>(topic, serSchema, props); prod.setFlushOnCheckpoint(true); prod.setWriteTimestampToKafka(true); return stream.addSink(prod); } @Override public KafkaOffsetHandler createOffsetHandler() { return new KafkaOffsetHandlerImpl(); } @Override public void restartBroker(int leaderId) throws Exception { brokers.set(leaderId, getKafkaServer(leaderId, tmpKafkaDirs.get(leaderId))); } @Override public int getLeaderToShutDown(String topic) throws Exception { ZkUtils zkUtils = getZkUtils(); try { MetadataResponse.PartitionMetadata firstPart = null; do { if (firstPart != null) { LOG.info("Unable to find leader. error code {}", firstPart.error().code()); // not the first try. Sleep a bit Thread.sleep(150); } List<MetadataResponse.PartitionMetadata> partitionMetadata = AdminUtils.fetchTopicMetadataFromZk(topic, zkUtils).partitionMetadata(); firstPart = partitionMetadata.get(0); } while (firstPart.error().code() != 0); return firstPart.leader().id(); } finally { zkUtils.close(); } } @Override public int getBrokerId(KafkaServer server) { return server.config().brokerId(); } @Override public boolean isSecureRunSupported() { return true; } @Override public void prepare(Config config) { //increase the timeout since in Travis ZK connection takes long time for secure connection. if (config.isSecureMode()) { //run only one kafka server to avoid multiple ZK connections from many instances - Travis timeout config.setKafkaServersNumber(1); zkTimeout = zkTimeout * 15; } this.config = config; File tempDir = new File(System.getProperty("java.io.tmpdir")); tmpZkDir = new File(tempDir, "kafkaITcase-zk-dir-" + (UUID.randomUUID().toString())); assertTrue("cannot create zookeeper temp dir", tmpZkDir.mkdirs()); tmpKafkaParent = new File(tempDir, "kafkaITcase-kafka-dir-" + (UUID.randomUUID().toString())); assertTrue("cannot create kafka temp dir", tmpKafkaParent.mkdirs()); tmpKafkaDirs = new ArrayList<>(config.getKafkaServersNumber()); for (int i = 0; i < config.getKafkaServersNumber(); i++) { File tmpDir = new File(tmpKafkaParent, "server-" + i); assertTrue("cannot create kafka temp dir", tmpDir.mkdir()); tmpKafkaDirs.add(tmpDir); } zookeeper = null; brokers = null; try { zookeeper = new TestingServer(-1, tmpZkDir); zookeeperConnectionString = zookeeper.getConnectString(); LOG.info("Starting Zookeeper with zookeeperConnectionString: {}", zookeeperConnectionString); LOG.info("Starting KafkaServer"); brokers = new ArrayList<>(config.getKafkaServersNumber()); ListenerName listenerName = ListenerName.forSecurityProtocol(config.isSecureMode() ? SecurityProtocol.SASL_PLAINTEXT : SecurityProtocol.PLAINTEXT); for (int i = 0; i < config.getKafkaServersNumber(); i++) { KafkaServer kafkaServer = getKafkaServer(i, tmpKafkaDirs.get(i)); brokers.add(kafkaServer); brokerConnectionString += hostAndPortToUrlString(KAFKA_HOST, kafkaServer.socketServer().boundPort(listenerName)); brokerConnectionString += ","; } LOG.info("ZK and KafkaServer started."); } catch (Throwable t) { t.printStackTrace(); fail("Test setup failed: " + t.getMessage()); } standardProps = new Properties(); standardProps.setProperty("zookeeper.connect", zookeeperConnectionString); standardProps.setProperty("bootstrap.servers", brokerConnectionString); standardProps.setProperty("group.id", "flink-tests"); standardProps.setProperty("enable.auto.commit", "false"); standardProps.setProperty("zookeeper.session.timeout.ms", String.valueOf(zkTimeout)); standardProps.setProperty("zookeeper.connection.timeout.ms", String.valueOf(zkTimeout)); standardProps.setProperty("auto.offset.reset", "earliest"); // read from the beginning. (earliest is kafka 0.10 value) standardProps.setProperty("max.partition.fetch.bytes", "256"); // make a lot of fetches (MESSAGES MUST BE SMALLER!) } @Override public void shutdown() throws Exception { for (KafkaServer broker : brokers) { if (broker != null) { broker.shutdown(); } } brokers.clear(); if (zookeeper != null) { try { zookeeper.stop(); } catch (Exception e) { LOG.warn("ZK.stop() failed", e); } zookeeper = null; } // clean up the temp spaces if (tmpKafkaParent != null && tmpKafkaParent.exists()) { try { FileUtils.deleteDirectory(tmpKafkaParent); } catch (Exception e) { // ignore } } if (tmpZkDir != null && tmpZkDir.exists()) { try { FileUtils.deleteDirectory(tmpZkDir); } catch (Exception e) { // ignore } } super.shutdown(); } public ZkUtils getZkUtils() { ZkClient creator = new ZkClient(zookeeperConnectionString, Integer.valueOf(standardProps.getProperty("zookeeper.session.timeout.ms")), Integer.valueOf(standardProps.getProperty("zookeeper.connection.timeout.ms")), new ZooKeeperStringSerializer()); return ZkUtils.apply(creator, false); } @Override public void createTestTopic(String topic, int numberOfPartitions, int replicationFactor, Properties topicConfig) { // create topic with one client LOG.info("Creating topic {}", topic); ZkUtils zkUtils = getZkUtils(); try { AdminUtils.createTopic(zkUtils, topic, numberOfPartitions, replicationFactor, topicConfig, kafka.admin.RackAwareMode.Enforced$.MODULE$); } finally { zkUtils.close(); } // validate that the topic has been created final long deadline = System.nanoTime() + 30_000_000_000L; do { try { if (config.isSecureMode()) { //increase wait time since in Travis ZK timeout occurs frequently int wait = zkTimeout / 100; LOG.info("waiting for {} msecs before the topic {} can be checked", wait, topic); Thread.sleep(wait); } else { Thread.sleep(100); } } catch (InterruptedException e) { // restore interrupted state } // we could use AdminUtils.topicExists(zkUtils, topic) here, but it's results are // not always correct. // create a new ZK utils connection ZkUtils checkZKConn = getZkUtils(); if (AdminUtils.topicExists(checkZKConn, topic)) { checkZKConn.close(); return; } checkZKConn.close(); } while (System.nanoTime() < deadline); fail("Test topic could not be created"); } @Override public void deleteTestTopic(String topic) { ZkUtils zkUtils = getZkUtils(); try { LOG.info("Deleting topic {}", topic); ZkClient zk = new ZkClient(zookeeperConnectionString, Integer.valueOf(standardProps.getProperty("zookeeper.session.timeout.ms")), Integer.valueOf(standardProps.getProperty("zookeeper.connection.timeout.ms")), new ZooKeeperStringSerializer()); AdminUtils.deleteTopic(zkUtils, topic); zk.close(); } finally { zkUtils.close(); } } /** * Copied from com.github.sakserv.minicluster.KafkaLocalBrokerIntegrationTest (ASL licensed). */ protected KafkaServer getKafkaServer(int brokerId, File tmpFolder) throws Exception { Properties kafkaProperties = new Properties(); // properties have to be Strings kafkaProperties.put("advertised.host.name", KAFKA_HOST); kafkaProperties.put("broker.id", Integer.toString(brokerId)); kafkaProperties.put("log.dir", tmpFolder.toString()); kafkaProperties.put("zookeeper.connect", zookeeperConnectionString); kafkaProperties.put("message.max.bytes", String.valueOf(50 * 1024 * 1024)); kafkaProperties.put("replica.fetch.max.bytes", String.valueOf(50 * 1024 * 1024)); // for CI stability, increase zookeeper session timeout kafkaProperties.put("zookeeper.session.timeout.ms", zkTimeout); kafkaProperties.put("zookeeper.connection.timeout.ms", zkTimeout); if (config.getKafkaServerProperties() != null) { kafkaProperties.putAll(config.getKafkaServerProperties()); } final int numTries = 5; for (int i = 1; i <= numTries; i++) { int kafkaPort = NetUtils.getAvailablePort(); kafkaProperties.put("port", Integer.toString(kafkaPort)); if (config.isHideKafkaBehindProxy()) { NetworkFailuresProxy proxy = createProxy(KAFKA_HOST, kafkaPort); kafkaProperties.put("advertised.port", proxy.getLocalPort()); } //to support secure kafka cluster if (config.isSecureMode()) { LOG.info("Adding Kafka secure configurations"); kafkaProperties.put("listeners", "SASL_PLAINTEXT://" + KAFKA_HOST + ":" + kafkaPort); kafkaProperties.put("advertised.listeners", "SASL_PLAINTEXT://" + KAFKA_HOST + ":" + kafkaPort); kafkaProperties.putAll(getSecureProperties()); } KafkaConfig kafkaConfig = new KafkaConfig(kafkaProperties); try { scala.Option<String> stringNone = scala.Option.apply(null); KafkaServer server = new KafkaServer(kafkaConfig, Time.SYSTEM, stringNone, new ArraySeq<KafkaMetricsReporter>(0)); server.startup(); return server; } catch (KafkaException e) { if (e.getCause() instanceof BindException) { // port conflict, retry... LOG.info("Port conflict when starting Kafka Broker. Retrying..."); } else { throw e; } } } throw new Exception("Could not start Kafka after " + numTries + " retries due to port conflicts."); } private class KafkaOffsetHandlerImpl implements KafkaOffsetHandler { private final KafkaConsumer<byte[], byte[]> offsetClient; public KafkaOffsetHandlerImpl() { Properties props = new Properties(); props.putAll(standardProps); props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer"); offsetClient = new KafkaConsumer<>(props); } @Override public Long getCommittedOffset(String topicName, int partition) { OffsetAndMetadata committed = offsetClient.committed(new TopicPartition(topicName, partition)); return (committed != null) ? committed.offset() : null; } @Override public void setCommittedOffset(String topicName, int partition, long offset) { Map<TopicPartition, OffsetAndMetadata> partitionAndOffset = new HashMap<>(); partitionAndOffset.put(new TopicPartition(topicName, partition), new OffsetAndMetadata(offset)); offsetClient.commitSync(partitionAndOffset); } @Override public void close() { offsetClient.close(); } } }
{ "content_hash": "b05b526db70fe7a1fa47e5838d3518e9", "timestamp": "", "source": "github", "line_count": 464, "max_line_length": 179, "avg_line_length": 34.07327586206897, "alnum_prop": 0.7399746995572423, "repo_name": "ueshin/apache-flink", "id": "8c69f36356727de01fdff5b87f09fd41676cf9b2", "size": "16610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-connectors/flink-connector-kafka-0.10/src/test/java/org/apache/flink/streaming/connectors/kafka/KafkaTestEnvironmentImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5667" }, { "name": "CSS", "bytes": "18100" }, { "name": "Clojure", "bytes": "88796" }, { "name": "CoffeeScript", "bytes": "91220" }, { "name": "Dockerfile", "bytes": "9788" }, { "name": "HTML", "bytes": "86821" }, { "name": "Java", "bytes": "42052018" }, { "name": "JavaScript", "bytes": "8267" }, { "name": "Python", "bytes": "249644" }, { "name": "Scala", "bytes": "8365242" }, { "name": "Shell", "bytes": "398033" } ], "symlink_target": "" }
<!-- ~ Copyright (C) 2015 The Android Open Source Project ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> <dimen name="card_height">304dp</dimen> <dimen name="md_keylines">16dp</dimen> <dimen name="tile_padding">8dp</dimen> <dimen name="tile_height">160dp</dimen> <dimen name="app_bar_height">256dp</dimen> <dimen name="article_keylines">72dp</dimen> <dimen name="avator_size">40dp</dimen> <dimen name="card_title_height">40dp</dimen> <dimen name="article_titles">20sp</dimen> <dimen name="cards_button_width">48dp</dimen> <dimen name="cards_button_height">48dp</dimen> <dimen name="article_subheading">16sp</dimen> <dimen name="card_image_height">200dp</dimen> <dimen name="list_body">14sp</dimen> <dimen name="navheader_height">222dp</dimen> <dimen name="keyline_spacing">16dp</dimen> <dimen name="fab_spacing">0dp</dimen> <dimen name="fab_list_spacing">88dp</dimen> <dimen name="sheet_width">210dp</dimen> <dimen name="sheet_spacing">10dp</dimen> <dimen name="sheet_item_spacing">@dimen/keyline_spacing</dimen> <dimen name="sheet_item_image_spacing">24dp</dimen> <dimen name="sheet_item_textsize">16sp</dimen> <dimen name="snackbar_height">48dp</dimen> <dimen name="snackbar_spacing">24dp</dimen> <dimen name="snackbar_textsize">14sp</dimen> <dimen name="toolbar_elevation">4dp</dimen> <dimen name="fab_elevation">4dp</dimen> <dimen name="fab_sheet_elevation">0dp</dimen> <dimen name="drawer_header_height">200dp</dimen> <dimen name="drawer_header_textsize">20sp</dimen> <dimen name="drawer_header_text_spacing">@dimen/keyline_spacing</dimen> <dimen name="note_spacing">4dp</dimen> <dimen name="note_content_spacing">16dp</dimen> <dimen name="note_corner_radius">2dp</dimen> <dimen name="note_textsize">14sp</dimen> <dimen name="note_title_textsize">24sp</dimen> <dimen name="g_top_margin">100dp</dimen> <dimen name="about_icon_size">34dp</dimen> <dimen name="about_staff_size">60dp</dimen> <dimen name="about_icon_padding">8dp</dimen> <dimen name="about_staff_padding">2dp</dimen> <dimen name="about_text_padding">8dp</dimen> <dimen name="about_group_text_padding">16dp</dimen> <dimen name="about_separator_height">0.5dp</dimen> <dimen name="about_description_text_size">16sp</dimen> <dimen name="about_item_text_size">16sp</dimen> <dimen name="about_job_text_size">16sp</dimen> <dimen name="about_group_item_text_size">18sp</dimen> </resources>
{ "content_hash": "de72e382d7fee73cebaef55386fcbc80", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 76, "avg_line_length": 46.098591549295776, "alnum_prop": 0.6889703635808128, "repo_name": "JakeFallin/RHSApplication", "id": "fa2871987e8535f920cc7361fb422ebf60881b83", "size": "3273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/dimens.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "22841" } ], "symlink_target": "" }
/** * @ngdoc directive * @name adf.directive:adfDashboard * @element div * @restrict EA * @scope * @description * * `adfDashboard` is a directive which renders the dashboard with all its * components. The directive requires a name attribute. The name of the * dashboard can be used to store the model. */ angular.module('adf') .directive('adfDashboard', function ($rootScope, $log, $modal, dashboard, adfTemplatePath) { 'use strict'; function copyWidgets(source, target) { if ( source.widgets && source.widgets.length > 0 ){ var w = source.widgets.shift(); while (w){ target.widgets.push(w); w = source.widgets.shift(); } } } /** * Copy widget from old columns to the new model * @param object root the model * @param array of columns * @param counter */ function fillStructure(root, columns, counter) { counter = counter || 0; if (angular.isDefined(root.rows)) { angular.forEach(root.rows, function (row) { angular.forEach(row.columns, function (column) { // if the widgets prop doesn't exist, create a new array for it. // this allows ui.sortable to do it's thing without error if (!column.widgets) { column.widgets = []; } // if a column exist at the counter index, copy over the column if (angular.isDefined(columns[counter])) { // do not add widgets to a column, which uses nested rows if (!angular.isDefined(column.rows)){ copyWidgets(columns[counter], column); counter++; } } // run fillStructure again for any sub rows/columns counter = fillStructure(column, columns, counter); }); }); } return counter; } /** * Read Columns: recursively searches an object for the 'columns' property * @param object model * @param array an array of existing columns; used when recursion happens */ function readColumns(root, columns) { columns = columns || []; if (angular.isDefined(root.rows)) { angular.forEach(root.rows, function (row) { angular.forEach(row.columns, function (col) { columns.push(col); // keep reading columns until we can't any more readColumns(col, columns); }); }); } return columns; } function changeStructure(model, structure){ var columns = readColumns(model); var counter = 0; model.rows = angular.copy(structure.rows); while ( counter < columns.length ){ counter = fillStructure(model, columns, counter); } } function createConfiguration(type){ var cfg = {}; var config = dashboard.widgets[type].config; if (config){ cfg = angular.copy(config); } return cfg; } /** * Find first widget column in model. * * @param dashboard model */ function findFirstWidgetColumn(model){ var column = null; if (!angular.isArray(model.rows)){ $log.error('model does not have any rows'); return null; } for (var i=0; i<model.rows.length; i++){ var row = model.rows[i]; if (angular.isArray(row.columns)){ for (var j=0; j<row.columns.length; j++){ var col = row.columns[j]; if (!col.rows){ column = col; break; } } } if (column){ break; } } return column; } /** * Adds the widget to first column of the model. * * @param dashboard model * @param widget to add to model */ function addNewWidgetToModel(model, widget){ if (model){ var column = findFirstWidgetColumn(model); if (column){ if (!column.widgets){ column.widgets = []; } column.widgets.unshift(widget); } else { $log.error('could not find first widget column'); } } else { $log.error('model is undefined'); } } return { replace: true, restrict: 'EA', transclude : false, scope: { structure: '@', name: '@', collapsible: '@', editable: '@', adfModel: '=', adfWidgetFilter: '=' }, controller: function($scope){ var model = {}; var structure = {}; var widgetFilter = null; var structureName = {}; var name = $scope.name; // Watching for changes on adfModel $scope.$watch('adfModel', function(oldVal, newVal) { // has model changed or is the model attribute not set if (newVal !== null || (oldVal === null && newVal === null)) { model = $scope.adfModel; widgetFilter = $scope.adfWidgetFilter; if ( ! model || ! model.rows ){ structureName = $scope.structure; structure = dashboard.structures[structureName]; if (structure){ if (model){ model.rows = angular.copy(structure).rows; } else { model = angular.copy(structure); } model.structure = structureName; } else { $log.error( 'could not find structure ' + structureName); } } if (model) { if (!model.title){ model.title = 'Dashboard'; } $scope.model = model; } else { $log.error('could not find or create model'); } } }, true); // edit mode $scope.editMode = false; $scope.editClass = ''; $scope.toggleEditMode = function(){ $scope.editMode = ! $scope.editMode; if ($scope.editMode){ $scope.modelCopy = angular.copy($scope.adfModel, {}); } if (!$scope.editMode){ $rootScope.$broadcast('adfDashboardChanged', name, model); } }; $scope.cancelEditMode = function(){ $scope.editMode = false; $scope.modelCopy = angular.copy($scope.modelCopy, $scope.adfModel); }; // edit dashboard settings $scope.editDashboardDialog = function(){ var editDashboardScope = $scope.$new(); // create a copy of the title, to avoid changing the title to // "dashboard" if the field is empty editDashboardScope.copy = { title: model.title }; editDashboardScope.structures = dashboard.structures; var instance = $modal.open({ scope: editDashboardScope, templateUrl: adfTemplatePath + 'dashboard-edit.html', backdrop: 'static' }); $scope.changeStructure = function(name, structure){ $log.info('change structure to ' + name); changeStructure(model, structure); }; editDashboardScope.closeDialog = function(){ // copy the new title back to the model model.title = editDashboardScope.copy.title; // close modal and destroy the scope instance.close(); editDashboardScope.$destroy(); }; }; // add widget dialog $scope.addWidgetDialog = function(){ var addScope = $scope.$new(); var model = $scope.model; var widgets; if (angular.isFunction(widgetFilter)){ widgets = {}; angular.forEach(dashboard.widgets, function(widget, type){ if (widgetFilter(widget, type, model)){ widgets[type] = widget; } }); } else { widgets = dashboard.widgets; } addScope.widgets = widgets; var opts = { scope: addScope, templateUrl: adfTemplatePath + 'widget-add.html', backdrop: 'static' }; var instance = $modal.open(opts); addScope.addWidget = function(widget){ var w = { type: widget, config: createConfiguration(widget) }; addNewWidgetToModel(model, w); // close and destroy instance.close(); addScope.$destroy(); }; addScope.closeDialog = function(){ // close and destroy instance.close(); addScope.$destroy(); }; }; }, compile: function($element, $attrs){ if (!angular.isDefined($attrs.editable)){ $attrs.editable = true; } }, link: function ($scope, $element, $attr) { // pass attributes to scope $scope.name = $attr.name; $scope.structure = $attr.structure; $scope.editable = $attr.editable; }, templateUrl: adfTemplatePath + 'dashboard.html' }; });
{ "content_hash": "6daad2285dabb5a88155ae4d7b03871a", "timestamp": "", "source": "github", "line_count": 307, "max_line_length": 94, "avg_line_length": 29.846905537459282, "alnum_prop": 0.5213358070500927, "repo_name": "foresterh/floter", "id": "acf833b51366a5fdc1689d1e32d7a72e74d453e6", "size": "10306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scripts/dashboard.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3972" }, { "name": "HTML", "bytes": "12329" }, { "name": "JavaScript", "bytes": "52992" }, { "name": "Python", "bytes": "276" } ], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #include "uint256.h" #include <stdarg.h> #ifndef WIN32 #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #endif #include <map> #include <list> #include <utility> #include <vector> #include <string> #include <boost/version.hpp> #include <boost/thread.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include "netbase.h" // for AddTimeData typedef long long int64; typedef unsigned long long uint64; static const int64 COIN = 100000000; static const int64 CENT = 1000000; #define loop for (;;) #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) #ifndef PRI64d #if defined(_MSC_VER) || defined(__MSVCRT__) #define PRI64d "I64d" #define PRI64u "I64u" #define PRI64x "I64x" #else #define PRI64d "lld" #define PRI64u "llu" #define PRI64x "llx" #endif #endif /* Format characters for (s)size_t and ptrdiff_t */ #if defined(_MSC_VER) || defined(__MSVCRT__) /* (s)size_t and ptrdiff_t have the same size specifier in MSVC: http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx */ #define PRIszx "Ix" #define PRIszu "Iu" #define PRIszd "Id" #define PRIpdx "Ix" #define PRIpdu "Iu" #define PRIpdd "Id" #else /* C99 standard */ #define PRIszx "zx" #define PRIszu "zu" #define PRIszd "zd" #define PRIpdx "tx" #define PRIpdu "tu" #define PRIpdd "td" #endif // This is needed because the foreach macro can't get over the comma in pair<t1, t2> #define PAIRTYPE(t1, t2) std::pair<t1, t2> // Align by increasing pointer, must have extra space at end of buffer template <size_t nBytes, typename T> T* alignup(T* p) { union { T* ptr; size_t n; } u; u.ptr = p; u.n = (u.n + (nBytes-1)) & ~(nBytes-1); return u.ptr; } #ifdef WIN32 #define MSG_NOSIGNAL 0 #define MSG_DONTWAIT 0 #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif #else #define MAX_PATH 1024 #endif inline void MilliSleep(int64 n) { // Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50 // until fixed in 1.52. Use the deprecated sleep method for the broken case. // See: https://svn.boost.org/trac/boost/ticket/7238 #if BOOST_VERSION >= 105000 && (!defined(BOOST_HAS_NANOSLEEP) || BOOST_VERSION >= 105200) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #else boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #endif } /* This GNU C extension enables the compiler to check the format string against the parameters provided. * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter. * Parameters count from 1. */ #ifdef __GNUC__ #define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y))) #else #define ATTR_WARN_PRINTF(X,Y) #endif extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fDebugNet; extern bool fPrintToConsole; extern bool fPrintToDebugger; extern bool fDaemon; extern bool fServer; extern bool fCommandLine; extern std::string strMiscWarning; extern bool fTestNet; extern bool fBloomFilters; extern bool fNoListen; extern bool fLogTimestamps; extern volatile bool fReopenDebugLog; void RandAddSeed(); void RandAddSeedPerfmon(); int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...); /* Rationale for the real_strprintf / strprintf construction: It is not allowed to use va_start with a pass-by-reference argument. (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a macro to keep similar semantics. */ /** Overload strprintf for char*, so that GCC format type warnings can be given */ std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...); /** Overload strprintf for std::string, to be able to use it with _ (translation). * This will not support GCC format type warnings (-Wformat) so be careful. */ std::string real_strprintf(const std::string &format, int dummy, ...); #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__) std::string vstrprintf(const char *format, va_list ap); bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...); /* Redefine printf so that it directs output to debug.log * * Do this *after* defining the other printf-like functions, because otherwise the * __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y))) * which confuses gcc. */ #define printf OutputDebugStringF void LogException(std::exception* pex, const char* pszThread); void PrintException(std::exception* pex, const char* pszThread); void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseString(const std::string& str, char c, std::vector<std::string>& v); std::string FormatMoney(int64 n, bool fPlus=false); bool ParseMoney(const std::string& str, int64& nRet); bool ParseMoney(const char* pszIn, int64& nRet); std::string SanitizeString(const std::string& str); std::vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const std::string& str); bool IsHex(const std::string& str); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const std::string& str); void ParseParameters(int argc, const char*const argv[]); bool WildcardMatch(const char* psz, const char* mask); bool WildcardMatch(const std::string& str, const std::string& mask); void FileCommit(FILE *fileout); int GetFilesize(FILE* file); bool TruncateFile(FILE *file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path &GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetPidFile(); #ifndef WIN32 void CreatePidFile(const boost::filesystem::path &path, pid_t pid); #endif void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif boost::filesystem::path GetTempPath(); void ShrinkDebugFile(); int GetRandInt(int nMax); uint64 GetRand(uint64 nMax); uint256 GetRandHash(); int64 GetTime(); void SetMockTime(int64 nMockTimeIn); int64 GetAdjustedTime(); int64 GetTimeOffset(); std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); void AddTimeData(const CNetAddr& ip, int64 nTime); void runCommand(std::string strCommand); void DoubleToNumeratorDenominator(double inDouble, long long *outNumerator, long long *outDenominator); inline std::string i64tostr(int64 n) { return strprintf("%"PRI64d, n); } inline std::string itostr(int n) { return strprintf("%d", n); } inline int64 atoi64(const char* psz) { #ifdef _MSC_VER return _atoi64(psz); #else return strtoll(psz, NULL, 10); #endif } inline int64 atoi64(const std::string& str) { #ifdef _MSC_VER return _atoi64(str.c_str()); #else return strtoll(str.c_str(), NULL, 10); #endif } inline int atoi(const std::string& str) { return atoi(str.c_str()); } inline int roundint(double d) { return (int)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 roundint64(double d) { return (int64)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 abs64(int64 n) { return (n >= 0 ? n : -n); } template<typename T> std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) { std::string rv; static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; rv.reserve((itend-itbegin)*3); for(T it = itbegin; it < itend; ++it) { unsigned char val = (unsigned char)(*it); if(fSpaces && it != itbegin) rv.push_back(' '); rv.push_back(hexmap[val>>4]); rv.push_back(hexmap[val&15]); } return rv; } template<typename T> inline std::string HexStr(const T& vch, bool fSpaces=false) { return HexStr(vch.begin(), vch.end(), fSpaces); } template<typename T> void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str()); } inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(vch, fSpaces).c_str()); } inline int64 GetPerformanceCounter() { int64 nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64) t.tv_sec * 1000000 + t.tv_usec; #endif return nCounter; } inline int64 GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } inline int64 GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime) { time_t n = nTime; struct tm* ptmTime = gmtime(&n); char pszTime[200]; strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime); return pszTime; } template<typename T> void skipspaces(T& it) { while (isspace(*it)) ++it; } inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64 GetArg(const std::string& strArg, int64 nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault=false); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * MWC RNG of George Marsaglia * This is intended to be fast. It has a period of 2^59.3, though the * least significant 16 bits only have a period of about 2^30.1. * * @return random value */ extern uint32_t insecure_rand_Rz; extern uint32_t insecure_rand_Rw; static inline uint32_t insecure_rand(void) { insecure_rand_Rz = 36969 * (insecure_rand_Rz & 65535) + (insecure_rand_Rz >> 16); insecure_rand_Rw = 18000 * (insecure_rand_Rw & 65535) + (insecure_rand_Rw >> 16); return (insecure_rand_Rw << 16) + insecure_rand_Rz; } /** * Seed insecure_rand using the random pool. * @param Deterministic Use a determinstic seed */ void seed_insecure_rand(bool fDeterministic=false); /** * Timing-attack-resistant comparison. * Takes time proportional to length * of first argument. */ template <typename T> bool TimingResistantEqual(const T& a, const T& b) { if (b.size() == 0) return a.size() == 0; size_t accumulator = a.size() ^ b.size(); for (size_t i = 0; i < a.size(); i++) accumulator |= a[i] ^ b[i%b.size()]; return accumulator == 0; } /** Median filter over a stream of values. * Returns the median of the last N numbers */ template <typename T> class CMedianFilter { private: std::vector<T> vValues; std::vector<T> vSorted; unsigned int nSize; public: CMedianFilter(unsigned int size, T initial_value): nSize(size) { vValues.reserve(size); vValues.push_back(initial_value); vSorted = vValues; } void input(T value) { if(vValues.size() == nSize) { vValues.erase(vValues.begin()); } vValues.push_back(value); vSorted.resize(vValues.size()); std::copy(vValues.begin(), vValues.end(), vSorted.begin()); std::sort(vSorted.begin(), vSorted.end()); } T median() const { int size = vSorted.size(); assert(size>0); if(size & 1) // Odd number of elements { return vSorted[size/2]; } else // Even number of elements { return (vSorted[size/2-1] + vSorted[size/2]) / 2; } } int size() const { return vValues.size(); } std::vector<T> sorted () const { return vSorted; } }; bool NewThread(void(*pfn)(void*), void* parg); #ifdef WIN32 inline void SetThreadPriority(int nPriority) { SetThreadPriority(GetCurrentThread(), nPriority); } #else #define THREAD_PRIORITY_LOWEST PRIO_MAX #define THREAD_PRIORITY_BELOW_NORMAL 2 #define THREAD_PRIORITY_NORMAL 0 #define THREAD_PRIORITY_ABOVE_NORMAL 0 inline void SetThreadPriority(int nPriority) { // It's unclear if it's even possible to change thread priorities on Linux, // but we really and truly need it for the generation threads. #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else setpriority(PRIO_PROCESS, 0, nPriority); #endif } inline void ExitThread(size_t nExitCode) { pthread_exit((void*)nExitCode); } #endif void RenameThread(const char* name); inline uint32_t ByteReverse(uint32_t value) { value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); return (value<<16) | (value>>16); } // Standard wrapper for do-something-forever thread functions. // "Forever" really means until the thread is interrupted. // Use it like: // new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 900000)); // or maybe: // boost::function<void()> f = boost::bind(&FunctionWithArg, argument); // threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds)); template <typename Callable> void LoopForever(const char* name, Callable func, int64 msecs) { std::string s = strprintf("bitcoin-%s", name); RenameThread(s.c_str()); printf("%s thread start\n", name); try { while (1) { MilliSleep(msecs); func(); } } catch (boost::thread_interrupted) { printf("%s thread stop\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } // .. and a wrapper that just calls func once template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("bitcoin-%s", name); RenameThread(s.c_str()); try { printf("%s thread start\n", name); func(); printf("%s thread exit\n", name); } catch (boost::thread_interrupted) { printf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } #endif
{ "content_hash": "53c367896b8cf59dacbb4604fdcebe86", "timestamp": "", "source": "github", "line_count": 610, "max_line_length": 143, "avg_line_length": 28.044262295081968, "alnum_prop": 0.667270707897352, "repo_name": "tam-vo/rubycoin", "id": "c6959e54e0c1355dc28e723d8c34162a0037e259", "size": "17107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/util.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "103297" }, { "name": "C++", "bytes": "2531559" }, { "name": "CSS", "bytes": "1127" }, { "name": "Erlang", "bytes": "6752" }, { "name": "IDL", "bytes": "14716" }, { "name": "JavaScript", "bytes": "81" }, { "name": "Nu", "bytes": "264" }, { "name": "Objective-C", "bytes": "5864" }, { "name": "PHP", "bytes": "2969" }, { "name": "Perl", "bytes": "22272" }, { "name": "Python", "bytes": "69714" }, { "name": "Shell", "bytes": "25296" }, { "name": "TypeScript", "bytes": "5236293" } ], "symlink_target": "" }
The easiest way to discover [Flight](http://flightjs.github.io) components. ## Contributing to this project Anyone and everyone is welcome to contribute. Please take a moment to review the [guidelines for contributing](CONTRIBUTING.md). * [Bug reports](CONTRIBUTING.md#bugs) * [Feature requests](CONTRIBUTING.md#features) * [Pull requests](CONTRIBUTING.md#pull-requests)
{ "content_hash": "952b2d9235f9b7aa2ec61a3a74ddf147", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 75, "avg_line_length": 37.4, "alnum_prop": 0.7807486631016043, "repo_name": "flightjs/flight-components", "id": "24cb4d5aef95000e8bfeea03d1f1224d66a09f44", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "989" }, { "name": "JavaScript", "bytes": "9701" } ], "symlink_target": "" }
package com.amazonaws.services.autoscaling.model.transform; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Map.Entry; import javax.xml.stream.events.XMLEvent; import com.amazonaws.services.autoscaling.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.MapEntry; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * DescribeAutoScalingNotificationTypesResult StAX Unmarshaller */ public class DescribeAutoScalingNotificationTypesResultStaxUnmarshaller implements Unmarshaller<DescribeAutoScalingNotificationTypesResult, StaxUnmarshallerContext> { public DescribeAutoScalingNotificationTypesResult unmarshall( StaxUnmarshallerContext context) throws Exception { DescribeAutoScalingNotificationTypesResult describeAutoScalingNotificationTypesResult = new DescribeAutoScalingNotificationTypesResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 2; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return describeAutoScalingNotificationTypesResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression( "AutoScalingNotificationTypes/member", targetDepth)) { describeAutoScalingNotificationTypesResult .withAutoScalingNotificationTypes(StringStaxUnmarshaller .getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return describeAutoScalingNotificationTypesResult; } } } } private static DescribeAutoScalingNotificationTypesResultStaxUnmarshaller instance; public static DescribeAutoScalingNotificationTypesResultStaxUnmarshaller getInstance() { if (instance == null) instance = new DescribeAutoScalingNotificationTypesResultStaxUnmarshaller(); return instance; } }
{ "content_hash": "3a58fad8f15b6573b8d890b8707fbe81", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 145, "avg_line_length": 37.359375, "alnum_prop": 0.6951066499372648, "repo_name": "nterry/aws-sdk-java", "id": "ce4260c49545a472bd58d948efd83ac865186052", "size": "2978", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-java-sdk-autoscaling/src/main/java/com/amazonaws/services/autoscaling/model/transform/DescribeAutoScalingNotificationTypesResultStaxUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "126417" }, { "name": "Java", "bytes": "113994954" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
/* * BillListItem Messages * * This contains all the text for the BillListItem component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.components.BillListItem.header', defaultMessage: 'Counted between {from} and {to}', }, issued: { id: 'app.components.BillListItem.issued', defaultMessage: 'Issued at {date}', }, download: { id: 'app.components.BillListItem.download', defaultMessage: 'Download as .pdf', }, heat: { id: 'app.components.BillListItem.heat', defaultMessage: 'Heat', }, hotWater: { id: 'app.components.BillListItem.hotWater', defaultMessage: 'Hot water', }, coldWater: { id: 'app.components.BillListItem.coldWater', defaultMessage: 'Cold water', }, item: { id: 'app.components.BillListItem.item', defaultMessage: 'Item', }, quantity: { id: 'app.components.BillListItem.quantity', defaultMessage: 'Quantity', }, unitPrice: { id: 'app.components.BillListItem.unitPrice', defaultMessage: 'Unit Price', }, amount: { id: 'app.components.BillListItem.amount', defaultMessage: 'Amount', }, total: { id: 'app.components.BillListItem.total', defaultMessage: 'Total: {total} {currency}', }, });
{ "content_hash": "81fc4d364531d2a7b2885ceda95f4349", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 61, "avg_line_length": 24.32075471698113, "alnum_prop": 0.6516679596586501, "repo_name": "balintsoos/app.rezsi.io", "id": "08aef14aafb0b3ed2973cfbc0ec04ee81fffa7c3", "size": "1289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/components/BillListItem/messages.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "12075" }, { "name": "JavaScript", "bytes": "266549" } ], "symlink_target": "" }
go build -o botbox-sandbox docker build ./ -t "botbox-sandbox" --no-cache
{ "content_hash": "f99eb845d984cbb8d7b50f854a0e8a28", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 46, "avg_line_length": 25, "alnum_prop": 0.7066666666666667, "repo_name": "crestonbunch/botbox", "id": "aa5da04a4c60780d4532a216016ebf207d0a927c", "size": "88", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/sandbox/server/build.sh", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4862" }, { "name": "Go", "bytes": "241569" }, { "name": "HTML", "bytes": "10660" }, { "name": "JavaScript", "bytes": "141791" }, { "name": "Nginx", "bytes": "1044" }, { "name": "Python", "bytes": "3811" }, { "name": "Shell", "bytes": "4556" }, { "name": "TypeScript", "bytes": "26941" } ], "symlink_target": "" }
using System; namespace NetworkModel.Networking { public class NetworkMessageReceivedEventArgs : EventArgs { public int Senderid { get; private set; } public NetworkMessage NetworkMessage { get; private set; } public NetworkMessageReceivedEventArgs(int senderid, NetworkMessage networkMessage) { Senderid = senderid; NetworkMessage = networkMessage; } } }
{ "content_hash": "4311e9784cd07620057f3c38775f3546", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 91, "avg_line_length": 27.0625, "alnum_prop": 0.6697459584295612, "repo_name": "Omnicrola/remote-planning", "id": "378ef24485901b1e8880c90d3a0fb6d8500f5302", "size": "433", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RemotePlanning/NetworkModel/Networking/NetworkMessageReceivedEventArgs.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "79186" } ], "symlink_target": "" }
require 'spec_helper' include SimpleSecrets describe Packet do let(:master_key){ "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd".force_encoding 'BINARY' } let(:data){ 'foobar' } let(:nonce){ '11'.hex_to_bin 16 } # Generated with Primitives.nonce let(:test_body){ "\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\xA6foobar".force_encoding 'BINARY' } let(:bad_id){ 'fd'.hex_to_bin 6 } let(:bad_mac){ 'fd'.hex_to_bin 32 } subject{ Packet.new master_key } describe '#initialize' do it 'sets its master key' do its_key = subject.instance_variable_get(:@master_key) expect(its_key.unpack('H*').first).to eq(master_key) expect(its_key.encoding).to eq(Encoding::ASCII_8BIT) end it 'sets its identity' do identity = Primitives.identify subject.instance_variable_get(:@master_key) expect(subject.instance_variable_get(:@identity)).to eq(identity) end end describe '#build_body' do it 'concatenates the serialized body with a nonce' do expect(Primitives).to receive(:nonce) { nonce } expect(subject.build_body(data)).to eq(test_body) end end describe '#body_to_data' do it 'it splits out the nonce and deserializes the body' do expect(subject.body_to_data(test_body)).to eq(data) end end describe '#encrypt_body and #decrypt_body' do it 'encrypts the data and then decrypts it back' do key = subject.instance_variable_get(:@master_key) cipher_data = subject.encrypt_body test_body, key decrypted_body = subject.decrypt_body cipher_data, key expect(test_body).not_to eq(cipher_data) expect(cipher_data).not_to eq(decrypted_body) expect(decrypted_body).to eq(test_body) end end describe '#authenticate and #verify' do it 'creates an authentication signature and then verifies it' do key = subject.instance_variable_get(:@master_key) id = subject.instance_variable_get(:@identity) packet = subject.authenticate test_body, key, id data = subject.verify packet, key, id expect(data).to eq(test_body) end it 'returns nil if the key identity does not match' do key = subject.instance_variable_get(:@master_key) id = subject.instance_variable_get(:@identity) packet = subject.authenticate test_body, key, bad_id data = subject.verify packet, key, id expect(data).to be_nil end it 'returns nil if the MAC does not match' do key = subject.instance_variable_get(:@master_key) id = subject.instance_variable_get(:@identity) packet = subject.authenticate test_body, key, id packet = "#{packet[0...-32]}#{bad_mac}" data = subject.verify packet, key, id expect(data).to be_nil end end describe '.pack and .unpack' do it 'encrypts and signs data into web-safe string, then verifies and decrypts it back' do packed_data = subject.pack data expect(packed_data).not_to eq(data) unpacked_data = subject.unpack packed_data expect(unpacked_data).to eq(data) end end end
{ "content_hash": "bd9b8cb8fc13209b9e01d4b8ff7720a9", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 121, "avg_line_length": 32.705263157894734, "alnum_prop": 0.6755712906340522, "repo_name": "timshadel/simple-secrets.rb", "id": "cabb006d954622926e17710f76dae69bed4c6316", "size": "3107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/packet_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "35697" } ], "symlink_target": "" }
import * as b from 'bobril'; import container from './container'; import toggleButton from './toggleButton'; import * as h from './bobrilHelpers'; export interface IItem { label: string; value: string; onSelect: () => void; } export interface IData { header: b.IBobrilChildren leftItems?: IItem[] centerItems?: b.IBobrilChildren[] rightItems?: IItem[] activeItem?: string isFixedOnTop?: boolean isFluid?: boolean } interface ICtx extends b.IBobrilCtx { data: IData; } export default b.createComponent<IData>({ render(ctx: ICtx, me: b.IBobrilNode) { me.tag = 'nav'; me.className = 'navbar navbar-default'; if (ctx.data.isFixedOnTop) me.className += ' navbar-fixed-top'; me.children = container({ isFluid: !!ctx.data.isFluid, content: [ h.styledDiv([ toggleButton({}), h.styledDiv(ctx.data.header, 'navbar-brand') ], 'navbar-header'), h.styledDiv([ ctx.data.leftItems && h.styledUl( ctx.data.leftItems.map(r => h.styledLi({ content: r.label, onClick: r.onSelect, isActive: b.isActive(r.value) || r.value === ctx.data.activeItem })) , 'nav navbar-nav'), ctx.data.rightItems && h.styledUl([ ctx.data.rightItems.map(r => h.styledLi({ content: r.label, onClick: r.onSelect, isActive: b.isActive(r.value) || r.value === ctx.data.activeItem })) ], 'nav navbar-nav navbar-right') ], 'navbar-collapse collapse') ] }); } });
{ "content_hash": "96a5c7cf71f0539784221e99d716395d", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 173, "avg_line_length": 33.86, "alnum_prop": 0.5522740696987596, "repo_name": "karelsteinmetz/bobril-css-bootstrap", "id": "5c853e9f1c80bf433d320bfd05829fabc98e4214", "size": "1693", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/navBar.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "764" }, { "name": "JavaScript", "bytes": "19405" }, { "name": "TypeScript", "bytes": "22167" } ], "symlink_target": "" }
def main(j, args, params, tags, tasklet): doc = args.doc nid = args.getTag('nid') nidstr = str(nid) rediscl = j.clients.redis.getByInstance('system') out = list() out.append('||Port||Status||Memory Used||') rstatus = rediscl.hget('healthcheck:monitoring', 'results') errors = rediscl.hget('healthcheck:monitoring', 'errors') rstatus = j.data.serializer.json.loads(rstatus) if rstatus else dict() errors = j.data.serializer.json.loads(errors) if errors else dict() for data in [rstatus, errors]: if nidstr in data: if 'redis' in data.get(nidstr, dict()): rnstatus = data[nidstr].get('redis', dict()) for stat in rnstatus: if 'state' not in stat: continue state = j.core.grid.healthchecker.getWikiStatus(stat.get('state', 'UNKNOWN')) usage = "%s / %s" % (stat.get('memory_usage', ''), stat.get('memory_max', '')) out.append('|%s|%s|%s|' % (stat.get('port', -1), state, usage)) out = '\n'.join(out) params.result = (out, doc) return params def match(j, args, params, tags, tasklet): return True
{ "content_hash": "caf2655e750d0310fa22d234460da301", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 98, "avg_line_length": 33.833333333333336, "alnum_prop": 0.5640394088669951, "repo_name": "Jumpscale/jumpscale_portal8", "id": "c1c6748763a5dae7ce6ab1083961509b0c9d0d02", "size": "1218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/gridportal/base/Grid/.macros/wiki/redisstatus/1_redisstatus.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "482591" }, { "name": "HTML", "bytes": "313255" }, { "name": "JavaScript", "bytes": "8815099" }, { "name": "PHP", "bytes": "205758" }, { "name": "Python", "bytes": "974012" }, { "name": "Ruby", "bytes": "28925" }, { "name": "Shell", "bytes": "291" } ], "symlink_target": "" }
"""WebSDL URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import reverse_lazy from django.conf.urls.static import static from accounts.views import UserRegistrationView, UserUpdateView, logout_view #BASE_URL = settings.SITE_URL[1:] BASE_URL = '' login_configuration = { 'redirect_field_name': 'next' } logout_configuration = { 'next_page': reverse_lazy('home') } password_reset_configuration = { 'post_reset_redirect': 'password_reset_done' } password_done_configuration = { 'post_reset_redirect': 'password_reset_complete' } urlpatterns = [ url(r'^' + BASE_URL + 'password-reset/$', auth_views.PasswordResetView.as_view(), password_reset_configuration, name='password_reset'), url(r'^' + BASE_URL + 'password-reset/done/$', auth_views.PasswordChangeView.as_view(), name='password_reset_done'), url(r'^' + BASE_URL + 'password-reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', auth_views.PasswordResetConfirmView.as_view(), password_done_configuration, name='password_reset_confirm'), url(r'^' + BASE_URL + 'password-reset/completed/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), url(r'^' + BASE_URL + 'admin/', admin.site.urls), url(r'^' + BASE_URL + 'login/$', auth_views.LoginView.as_view(), login_configuration, name='login'), url(r'^' + BASE_URL + 'logout/$', logout_view, name='logout'), url(r'^' + BASE_URL + 'register/$', UserRegistrationView.as_view(), name='user_registration'), url(r'^' + BASE_URL + 'account/$', UserUpdateView.as_view(), name='user_account'), url(r'^' + BASE_URL + 'api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^' + BASE_URL + 'hydroshare/', include('hydroshare.urls', namespace='hydroshare')), url(BASE_URL, include('dataloaderinterface.urls')), url(BASE_URL, include('dataloaderservices.urls')), url(BASE_URL, include('timeseries_visualization.urls')) ] + static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) # if settings.DEBUG: # import debug_toolbar # urlpatterns = [ # url(r'^__debug__/', include(debug_toolbar.urls)), # ] + urlpatterns
{ "content_hash": "6403e84ccbf9732655fcc6c4ec452c53", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 192, "avg_line_length": 44.10606060606061, "alnum_prop": 0.689110271384404, "repo_name": "ODM2/ODM2WebSDL", "id": "201a1ebbe2d98ad1ad8a06c60c835aeb42fb37df", "size": "2911", "binary": false, "copies": "1", "ref": "refs/heads/StreamWatch", "path": "src/WebSDL/urls.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "20704" }, { "name": "HTML", "bytes": "125578" }, { "name": "JavaScript", "bytes": "62876" }, { "name": "Python", "bytes": "199614" } ], "symlink_target": "" }
/** * Created by mtorres on 7/05/17. */ var express = require('express'); var router = express.Router(); var db_conf = require('../db_conf'); var isAuthenticated = function (req, res, next) { if (req.isAuthenticated()){ return next(); } res.redirect('/'); }; //eventos del calendario router.post('/sales/data.json', isAuthenticated, function (req, res ){ db_conf.db.manyOrNone("select concat ( 'Ventas: ', count(*) ) as title, to_char(fecha, 'YYYY-MM-DD') as start from ventas, transferencia where transferencia.id_venta = ventas.id group by fecha").then(function (data) { res.jsonp( data ); }).catch(function (error) { console.log(error); res.jsonp(error); }); }); module.exports = router;
{ "content_hash": "d0808ccb4eb4f822fc769e6651b0ea51", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 221, "avg_line_length": 27.925925925925927, "alnum_prop": 0.629973474801061, "repo_name": "mariotorres/storeManager", "id": "dc4cbf93d8457c56d12ba0098d1f78531df00183", "size": "754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "routes/calendar.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14032" }, { "name": "HTML", "bytes": "280629" }, { "name": "JavaScript", "bytes": "345666" }, { "name": "R", "bytes": "4321" }, { "name": "TSQL", "bytes": "23833" } ], "symlink_target": "" }
* [AMD](td.modulekind.md#amd) * [CommonJS](td.modulekind.md#commonjs) * [None](td.modulekind.md#none) ## Enumeration members ### AMD: * Defined in [td/Options.ts:73](https://github.com/kimamula/typedoc/blob/HEAD/src/td/Options.ts#L73) ### CommonJS: * Defined in [td/Options.ts:72](https://github.com/kimamula/typedoc/blob/HEAD/src/td/Options.ts#L72) ### None: * Defined in [td/Options.ts:71](https://github.com/kimamula/typedoc/blob/HEAD/src/td/Options.ts#L71) Generated using [TypeDoc](http://typedoc.io)
{ "content_hash": "3b6c367d9a56d10d2a0219a6310c3c53", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 100, "avg_line_length": 22.652173913043477, "alnum_prop": 0.7044145873320538, "repo_name": "kimamula/typedoc-markdown-theme", "id": "12bc127afde35343e1c46ac33b8239447240211b", "size": "582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/typedoc/enums/td.modulekind.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "9016" }, { "name": "JavaScript", "bytes": "7359" }, { "name": "TypeScript", "bytes": "8257" } ], "symlink_target": "" }
Graphs Component 1.0.1 ====== This is a CanvasJS Implementation made to simplify the use of CanvasJS in web projects. ###How it works The script search the soruce for divs with the CSS class "canvasjs" and reads their respective data attributes. ####General settings ``` <input type="hidden" class="canvasjs-settings" data-colorsetname="default" data-bacakgroundcolor="#ffffff" data-fontsize="20" data-fontfamily="Arial" data-colorset="#003d59,#ecc500,#d3693b,#a6bbc5,#4c778a,#26a489,#dc825a,#118baf,#419dbe,#62b29d,#333332" /> ``` * class: Must be set to "canvasjs-settings" in order to the script to identify the element. * data-fontsize: Font size, integer value * data-fontfamily: Font family, string value * data-colorset: A list of colors in hex format * data-colorsetname: Name of the color set ####Graph specific settings ``` <div class="canvasjs" id="graph3" data-graphtype="column" data-stats="json/dummy-graphdata.json" data-title="Title of graph"></div> ``` * id: This must be unique and is used to separate the graps * data-graphtype: specify the type of graph you wish to use. Please see the [documentation](http://canvasjs.com/html5-javascript-column-chart/) * data-stats: The JSON data to populate the graph. * data-title: The name/title of the graph ####The JSON data In this first release the JSON data is very simple and not much can be modified. * X coordinate * Y coordinate * color * Label ``` [{ "label": "Playstation", "y": 357, "x": 10, "color": "" }, { "label": "Xbox", "y": 400, "x": 20, "color": "" }, { "label": "Nintendo", "y": 1358, "x": 30, "color": "" }] ``` ####Alternative using data attributes ``` <div class="canvasjs" id="graph5" data-graphtype="column" data-title="Title of graph"> <div class="graphdata" data-label="Playstation" data-y="357" data-x="10" data-color="#003d59"></div> <div class="graphdata" data-label="Xbox" data-y="400" data-x="10" data-color="#118baf"></div> <div class="graphdata" data-label="Nintendo" data-y="1358" data-x="10" data-color="#26a489"></div> </div> ``` ####Exception "Gaping" Donut Chart ``` <div class="canvasjs" id="graph4" data-graphtype="IncompleteDonut" data-value="42" data-color="#edc600"></div> <div id="graph4-total" class="IncompleteDonut_value">300</div> <div id="graph4-label" class="IncompleteDonut_label">Candy</div> ``` * data-value: The Value. Only one value is possible with this special Donut * data-color: The color of this donut. * No JSON is required or possible with this special donut chart. ###Notice Note that CanvasJS is **not** open source. It's under a [different license](http://canvasjs.com/license-canvasjs/) ####Read more about the graph library itself http://canvasjs.com ###Version History ####1.0.1 * Added support for background-color as ```transparent``` doesn't work in IE8 * Removed ```console.log``` ####1.0.0 * Added support for alternative graphdata loading using data attributes ####0.9 Initial release.
{ "content_hash": "4957e2b30f1cab6c49f5797d272f664b", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 256, "avg_line_length": 33.89772727272727, "alnum_prop": 0.6992960107274556, "repo_name": "KnowitLabs/Graphs", "id": "91335b3a11c6eab8dd6c92c6532d6c7d9150ad87", "size": "2983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "604" }, { "name": "JavaScript", "bytes": "9738" } ], "symlink_target": "" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.FindUsages; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor.FindUsages { [Shared] [ExportLanguageService(typeof(IFindUsagesService), LanguageNames.FSharp)] internal class FSharpFindUsagesService : IFindUsagesService { private readonly IFSharpFindUsagesService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpFindUsagesService(IFSharpFindUsagesService service) { _service = service; } public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context) { return _service.FindImplementationsAsync(document, position, new FSharpFindUsagesContext(context)); } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context) { return _service.FindReferencesAsync(document, position, new FSharpFindUsagesContext(context)); } } }
{ "content_hash": "e07c4527f983199893145a04d59c3fd4", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 161, "avg_line_length": 40.19444444444444, "alnum_prop": 0.7505183137525916, "repo_name": "nguerrera/roslyn", "id": "b5329a67717265aa0913663ecfc533d77617064a", "size": "1449", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Tools/ExternalAccess/FSharp/Internal/Editor/FindUsages/FSharpFindUsagesService.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "8757" }, { "name": "C#", "bytes": "122747926" }, { "name": "C++", "bytes": "5392" }, { "name": "CMake", "bytes": "9153" }, { "name": "Dockerfile", "bytes": "2102" }, { "name": "F#", "bytes": "508" }, { "name": "PowerShell", "bytes": "217803" }, { "name": "Rich Text Format", "bytes": "14887" }, { "name": "Shell", "bytes": "83770" }, { "name": "Smalltalk", "bytes": "622" }, { "name": "Visual Basic", "bytes": "70046841" } ], "symlink_target": "" }
package org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging; import com.intellij.psi.PsiModifierListOwner; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement; import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement; /** * @author ilyas */ public interface GrPackageDefinition extends GrTopStatement, PsiModifierListOwner { @Nullable String getPackageName(); @Nullable GrCodeReferenceElement getPackageReference(); @Nullable GrModifierList getAnnotationList(); }
{ "content_hash": "7561eb90868ee3d578585973cfb05c2c", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 84, "avg_line_length": 28.82608695652174, "alnum_prop": 0.8174962292609351, "repo_name": "joewalnes/idea-community", "id": "49f9b4dfb3c665575635cedc5d20fe03281507ab", "size": "1263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/packaging/GrPackageDefinition.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "387" }, { "name": "C", "bytes": "136045" }, { "name": "C#", "bytes": "103" }, { "name": "C++", "bytes": "40449" }, { "name": "Emacs Lisp", "bytes": "2507" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "361320" }, { "name": "Java", "bytes": "89694599" }, { "name": "JavaScript", "bytes": "978" }, { "name": "Objective-C", "bytes": "1877" }, { "name": "PHP", "bytes": "145" }, { "name": "Perl", "bytes": "6523" }, { "name": "Python", "bytes": "1699274" }, { "name": "Shell", "bytes": "6965" }, { "name": "VimL", "bytes": "5950" } ], "symlink_target": "" }
package org.tensorflow.lite.support.image.ops; import org.checkerframework.checker.nullness.qual.NonNull; import org.tensorflow.lite.support.common.SupportPrecondtions; import org.tensorflow.lite.support.common.TensorOperator; import org.tensorflow.lite.support.image.ImageOperator; import org.tensorflow.lite.support.image.TensorImage; /** * The adapter that makes a TensorOperator able to run with TensorImage. * * @see org.tensorflow.lite.support.common.TensorOperator * @see org.tensorflow.lite.support.image.TensorImage */ public class TensorOperatorWrapper implements ImageOperator { private final TensorOperator tensorOp; /** * Wraps a {@link TensorOperator} object as an {@link ImageOperator}, so that the {@link * TensorOperator} could handle {@link TensorImage} objects by handling its underlying {@link * org.tensorflow.lite.support.tensorbuffer.TensorBuffer}. * * @param op The created operator. */ public TensorOperatorWrapper(TensorOperator op) { tensorOp = op; } @Override @NonNull public TensorImage apply(@NonNull TensorImage image) { SupportPrecondtions.checkNotNull(image, "Op cannot apply on null image."); image.load(tensorOp.apply(image.getTensorBuffer())); return image; } }
{ "content_hash": "75a12fac545aab45eaa32b5f9dc0d78f", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 95, "avg_line_length": 32.30769230769231, "alnum_prop": 0.7642857142857142, "repo_name": "ppwwyyxx/tensorflow", "id": "61f4df3c316173cec8f620a6aa08b85e74c7ae97", "size": "1928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/lite/experimental/support/java/src/java/org/tensorflow/lite/support/image/ops/TensorOperatorWrapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "5003" }, { "name": "Batchfile", "bytes": "45318" }, { "name": "C", "bytes": "796611" }, { "name": "C#", "bytes": "8562" }, { "name": "C++", "bytes": "76521274" }, { "name": "CMake", "bytes": "6545" }, { "name": "Dockerfile", "bytes": "81136" }, { "name": "Go", "bytes": "1679107" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "952883" }, { "name": "Jupyter Notebook", "bytes": "567243" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "1254789" }, { "name": "Makefile", "bytes": "61284" }, { "name": "Objective-C", "bytes": "104706" }, { "name": "Objective-C++", "bytes": "297774" }, { "name": "PHP", "bytes": "24055" }, { "name": "Pascal", "bytes": "3752" }, { "name": "Pawn", "bytes": "17546" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "38709528" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "7469" }, { "name": "Shell", "bytes": "643731" }, { "name": "Smarty", "bytes": "34743" }, { "name": "Swift", "bytes": "62814" } ], "symlink_target": "" }
<?php /** * @see Zend_Navigation_Page */ require_once 'Zend/Navigation/Page.php'; /** * @see Zend_Controller_Action_HelperBroker */ require_once 'Zend/Controller/Action/HelperBroker.php'; /** * Used to check if page is active * * @see Zend_Controller_Front */ require_once 'Zend/Controller/Front.php'; /** * Represents a page that is defined using module, controller, action, route * name and route params to assemble the href * * @category Zend * @package Zend_Navigation * @subpackage Page * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Navigation_Page_Mvc extends Zend_Navigation_Page { /** * Action name to use when assembling URL * * @var string */ protected $_action; /** * Controller name to use when assembling URL * * @var string */ protected $_controller; /** * Module name to use when assembling URL * * @var string */ protected $_module; /** * Params to use when assembling URL * * @see getHref() * @var array */ protected $_params = array(); /** * Route name to use when assembling URL * * @see getHref() * @var string */ protected $_route; /** * Whether params should be reset when assembling URL * * @see getHref() * @var bool */ protected $_resetParams = true; /** * Whether href should be encoded when assembling URL * * @see getHref() * @var bool */ protected $_encodeUrl = true; /** * Whether this page should be considered active * * @var bool */ protected $_active = null; /** * Scheme to use when assembling URL * * @see getHref() * @var string */ protected $_scheme; /** * Cached href * * The use of this variable minimizes execution time when getHref() is * called more than once during the lifetime of a request. If a property * is updated, the cache is invalidated. * * @var string */ protected $_hrefCache; /** * Action helper for assembling URLs * * @see getHref() * @var Zend_Controller_Action_Helper_Url */ protected static $_urlHelper = null; /** * View helper for assembling URLs with schemes * * @see getHref() * @var Zend_View_Helper_ServerUrl */ protected static $_schemeHelper = null; // Accessors: /** * Returns whether page should be considered active or not * * This method will compare the page properties against the request object * that is found in the front controller. * * @param bool $recursive [optional] whether page should be considered * active if any child pages are active. Default is * false. * @return bool whether page should be considered active or not */ public function isActive($recursive = false) { if (null === $this->_active) { $front = Zend_Controller_Front::getInstance(); $request = $front->getRequest(); $reqParams = array(); if ($request) { $reqParams = $request->getParams(); if (!array_key_exists('module', $reqParams)) { $reqParams['module'] = $front->getDefaultModule(); } } $myParams = $this->_params; if ($this->_route) { $route = $front->getRouter()->getRoute($this->_route); if(method_exists($route, 'getDefaults')) { $myParams = array_merge($route->getDefaults(), $myParams); } } if (null !== $this->_module) { $myParams['module'] = $this->_module; } elseif(!array_key_exists('module', $myParams)) { $myParams['module'] = $front->getDefaultModule(); } if (null !== $this->_controller) { $myParams['controller'] = $this->_controller; } elseif(!array_key_exists('controller', $myParams)) { $myParams['controller'] = $front->getDefaultControllerName(); } if (null !== $this->_action) { $myParams['action'] = $this->_action; } elseif(!array_key_exists('action', $myParams)) { $myParams['action'] = $front->getDefaultAction(); } foreach($myParams as $key => $value) { if(null === $value) { unset($myParams[$key]); } } if (count(array_intersect_assoc($reqParams, $myParams)) == count($myParams)) { $this->_active = true; return true; } $this->_active = false; } return parent::isActive($recursive); } /** * Returns href for this page * * This method uses {@link Zend_Controller_Action_Helper_Url} to assemble * the href based on the page's properties. * * @return string page href */ public function getHref() { if ($this->_hrefCache) { return $this->_hrefCache; } if (null === self::$_urlHelper) { self::$_urlHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('Url'); } $params = $this->getParams(); if ($param = $this->getModule()) { $params['module'] = $param; } if ($param = $this->getController()) { $params['controller'] = $param; } if ($param = $this->getAction()) { $params['action'] = $param; } $url = self::$_urlHelper->url($params, $this->getRoute(), $this->getResetParams(), $this->getEncodeUrl()); // Use scheme? $scheme = $this->getScheme(); if (null !== $scheme) { if (null === self::$_schemeHelper) { require_once 'Zend/View/Helper/ServerUrl.php'; self::$_schemeHelper = new Zend_View_Helper_ServerUrl(); } $url = self::$_schemeHelper->setScheme($scheme)->serverUrl($url); } // Add the fragment identifier if it is set $fragment = $this->getFragment(); if (null !== $fragment) { $url .= '#' . $fragment; } return $this->_hrefCache = $url; } /** * Sets action name to use when assembling URL * * @see getHref() * * @param string $action action name * @return Zend_Navigation_Page_Mvc fluent interface, returns self * @throws Zend_Navigation_Exception if invalid $action is given */ public function setAction($action) { if (null !== $action && !is_string($action)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $action must be a string or null'); } $this->_action = $action; $this->_hrefCache = null; return $this; } /** * Returns action name to use when assembling URL * * @see getHref() * * @return string|null action name */ public function getAction() { return $this->_action; } /** * Sets controller name to use when assembling URL * * @see getHref() * * @param string|null $controller controller name * @return Zend_Navigation_Page_Mvc fluent interface, returns self * @throws Zend_Navigation_Exception if invalid controller name is given */ public function setController($controller) { if (null !== $controller && !is_string($controller)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $controller must be a string or null'); } $this->_controller = $controller; $this->_hrefCache = null; return $this; } /** * Returns controller name to use when assembling URL * * @see getHref() * * @return string|null controller name or null */ public function getController() { return $this->_controller; } /** * Sets module name to use when assembling URL * * @see getHref() * * @param string|null $module module name * @return Zend_Navigation_Page_Mvc fluent interface, returns self * @throws Zend_Navigation_Exception if invalid module name is given */ public function setModule($module) { if (null !== $module && !is_string($module)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $module must be a string or null'); } $this->_module = $module; $this->_hrefCache = null; return $this; } /** * Returns module name to use when assembling URL * * @see getHref() * * @return string|null module name or null */ public function getModule() { return $this->_module; } /** * Set multiple parameters (to use when assembling URL) at once * * URL options passed to the url action helper for assembling URLs. * Overwrites any previously set parameters! * * @see getHref() * * @param array|null $params [optional] paramters as array * ('name' => 'value'). Default is null * which clears all params. * @return Zend_Navigation_Page_Mvc fluent interface, returns self */ public function setParams(array $params = null) { $this->clearParams(); if (is_array($params)) { $this->addParams($params); } return $this; } /** * Set parameter (to use when assembling URL) * * URL option passed to the url action helper for assembling URLs. * * @see getHref() * * @param string $name parameter name * @param mixed $value parameter value * @return Zend_Navigation_Page_Mvc fluent interface, returns self */ public function setParam($name, $value) { $name = (string) $name; $this->_params[$name] = $value; $this->_hrefCache = null; return $this; } /** * Add multiple parameters (to use when assembling URL) at once * * URL options passed to the url action helper for assembling URLs. * * @see getHref() * * @param array $params paramters as array ('name' => 'value') * @return Zend_Navigation_Page_Mvc fluent interface, returns self */ public function addParams(array $params) { foreach ($params as $name => $value) { $this->setParam($name, $value); } return $this; } /** * Remove parameter (to use when assembling URL) * * @see getHref() * * @param string $name * @return bool */ public function removeParam($name) { if (array_key_exists($name, $this->_params)) { unset($this->_params[$name]); $this->_hrefCache = null; return true; } return false; } /** * Clear all parameters (to use when assembling URL) * * @see getHref() * * @return Zend_Navigation_Page_Mvc fluent interface, returns self */ public function clearParams() { $this->_params = array(); $this->_hrefCache = null; return $this; } /** * Retrieve all parameters (to use when assembling URL) * * @see getHref() * * @return array parameters as array ('name' => 'value') */ public function getParams() { return $this->_params; } /** * Retrieve a single parameter (to use when assembling URL) * * @see getHref() * * @param string $name parameter name * @return mixed */ public function getParam($name) { $name = (string) $name; if (!array_key_exists($name, $this->_params)) { return null; } return $this->_params[$name]; } /** * Sets route name to use when assembling URL * * @see getHref() * * @param string $route route name to use when assembling URL * @return Zend_Navigation_Page_Mvc fluent interface, returns self * @throws Zend_Navigation_Exception if invalid $route is given */ public function setRoute($route) { if (null !== $route && (!is_string($route) || strlen($route) < 1)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $route must be a non-empty string or null'); } $this->_route = $route; $this->_hrefCache = null; return $this; } /** * Returns route name to use when assembling URL * * @see getHref() * * @return string route name */ public function getRoute() { return $this->_route; } /** * Sets whether params should be reset when assembling URL * * @see getHref() * * @param bool $resetParams whether params should be reset when * assembling URL * @return Zend_Navigation_Page_Mvc fluent interface, returns self */ public function setResetParams($resetParams) { $this->_resetParams = (bool) $resetParams; $this->_hrefCache = null; return $this; } /** * Returns whether params should be reset when assembling URL * * @see getHref() * * @return bool whether params should be reset when assembling URL */ public function getResetParams() { return $this->_resetParams; } /** * Sets whether href should be encoded when assembling URL * * @see getHref() * * @param bool $resetParams whether href should be encoded when * assembling URL * @return Zend_Navigation_Page_Mvc fluent interface, returns self */ public function setEncodeUrl($encodeUrl) { $this->_encodeUrl = (bool) $encodeUrl; $this->_hrefCache = null; return $this; } /** * Returns whether herf should be encoded when assembling URL * * @see getHref() * * @return bool whether herf should be encoded when assembling URL */ public function getEncodeUrl() { return $this->_encodeUrl; } /** * Sets scheme to use when assembling URL * * @see getHref() * * @param string|null $scheme scheme * @return Zend_Navigation_Page_Mvc fluent interface, returns self */ public function setScheme($scheme) { if (null !== $scheme && !is_string($scheme)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $scheme must be a string or null' ); } $this->_scheme = $scheme; return $this; } /** * Returns scheme to use when assembling URL * * @see getHref() * * @return string|null scheme or null */ public function getScheme() { return $this->_scheme; } /** * Sets action helper for assembling URLs * * @see getHref() * * @param Zend_Controller_Action_Helper_Url $uh URL helper * @return void */ public static function setUrlHelper(Zend_Controller_Action_Helper_Url $uh) { self::$_urlHelper = $uh; } /** * Sets view helper for assembling URLs with schemes * * @see getHref() * * @param Zend_View_Helper_ServerUrl $sh scheme helper * @return void */ public static function setSchemeHelper(Zend_View_Helper_ServerUrl $sh) { self::$_schemeHelper = $sh; } // Public methods: /** * Returns an array representation of the page * * @return array associative array containing all page properties */ public function toArray() { return array_merge( parent::toArray(), array( 'action' => $this->getAction(), 'controller' => $this->getController(), 'module' => $this->getModule(), 'params' => $this->getParams(), 'route' => $this->getRoute(), 'reset_params' => $this->getResetParams(), 'encodeUrl' => $this->getEncodeUrl(), 'scheme' => $this->getScheme(), ) ); } }
{ "content_hash": "9944d3e7ee1f427d4fcb90c48c9226f5", "timestamp": "", "source": "github", "line_count": 661, "max_line_length": 87, "avg_line_length": 27.60211800302572, "alnum_prop": 0.503370786516854, "repo_name": "BBBManager/web-api", "id": "1355e3f1d175c678364becc99bf8f7b6ce0baed8", "size": "19024", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "private/library/Zend/Navigation/Page/Mvc.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "436" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "HTML", "bytes": "14129" }, { "name": "PHP", "bytes": "23061930" }, { "name": "PLSQL", "bytes": "10324" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Shell", "bytes": "400" } ], "symlink_target": "" }
package cache import ( "sort" "sync/atomic" "time" "github.com/lomik/go-carbon/points" ) type queueItem struct { points *points.Points orderKey int64 } type queue []queueItem type byOrderKey queue func (v byOrderKey) Len() int { return len(v) } func (v byOrderKey) Swap(i, j int) { v[i], v[j] = v[j], v[i] } func (v byOrderKey) Less(i, j int) bool { return v[i].orderKey < v[j].orderKey } func (c *Cache) makeQueue() chan *points.Points { c.Lock() writeStrategy := c.writeStrategy prevBuild := c.queueLastBuild c.Unlock() if !prevBuild.IsZero() { // @TODO: may be max (with atomic cas) atomic.StoreUint32(&c.stat.queueWriteoutTime, uint32(time.Since(prevBuild)/time.Second)) } start := time.Now() defer func() { atomic.AddUint32(&c.stat.queueBuildTimeMs, uint32(time.Since(start)/time.Millisecond)) atomic.AddUint32(&c.stat.queueBuildCnt, 1) c.Lock() c.queueLastBuild = time.Now() c.Unlock() }() orderKey := func(p *points.Points) int64 { return 0 } switch writeStrategy { case MaximumLength: orderKey = func(p *points.Points) int64 { return int64(len(p.Data)) } case TimestampOrder: orderKey = func(p *points.Points) int64 { return p.Data[0].Timestamp } } size := c.Len() * 2 q := make(queue, size) index := int32(0) for i := 0; i < shardCount; i++ { shard := c.data[i] shard.Lock() for _, p := range shard.items { if index < size { q[index].points = p q[index].orderKey = orderKey(p) } else { q = append(q, queueItem{p, orderKey(p)}) } index++ } shard.Unlock() } q = q[:index] switch writeStrategy { case MaximumLength: sort.Sort(sort.Reverse(byOrderKey(q))) case TimestampOrder: sort.Sort(byOrderKey(q)) } l := len(q) if l == 0 { return nil } ch := make(chan *points.Points, l) for _, i := range q { ch <- i.points } return ch }
{ "content_hash": "58a28af2d47314d0282058a96b4b05c1", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 90, "avg_line_length": 18.441176470588236, "alnum_prop": 0.6347687400318979, "repo_name": "drawks/go-carbon", "id": "fb097a484b0b42d13d2edc01bebe870e7d492e97", "size": "1881", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cache/queue.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "277368" }, { "name": "Makefile", "bytes": "3631" }, { "name": "Python", "bytes": "2499" }, { "name": "Shell", "bytes": "4536" } ], "symlink_target": "" }
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKMERGECELLSWRAP_H #define NATIVE_EXTENSION_VTK_VTKMERGECELLSWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkMergeCells.h> #include "vtkObjectWrap.h" #include "../../plus/plus.h" class VtkMergeCellsWrap : public VtkObjectWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkMergeCellsWrap(vtkSmartPointer<vtkMergeCells>); VtkMergeCellsWrap(); ~VtkMergeCellsWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void Finish(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetMergeDuplicatePoints(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPointMergeTolerance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPointMergeToleranceMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPointMergeToleranceMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetTotalNumberOfDataSets(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUnstructuredGrid(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUseGlobalCellIds(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUseGlobalIds(const Nan::FunctionCallbackInfo<v8::Value>& info); static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info); static void MergeDataSet(const Nan::FunctionCallbackInfo<v8::Value>& info); static void MergeDuplicatePointsOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void MergeDuplicatePointsOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetMergeDuplicatePoints(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPointMergeTolerance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetTotalNumberOfDataSets(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetUnstructuredGrid(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetUseGlobalCellIds(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetUseGlobalIds(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKMERGECELLSWRAP_CLASSDEF VTK_NODE_PLUS_VTKMERGECELLSWRAP_CLASSDEF #endif }; #endif
{ "content_hash": "89cdece1c52930fda3e28faf80ec3796", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 95, "avg_line_length": 46.18032786885246, "alnum_prop": 0.7834575789847356, "repo_name": "axkibe/node-vtk", "id": "1bfa973b0c93ec2eadbbf2549efc55a1ab7d3f20", "size": "2817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wrappers/7.0.0/vtkMergeCellsWrap.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "75388342" }, { "name": "CMake", "bytes": "915" }, { "name": "JavaScript", "bytes": "70" }, { "name": "Roff", "bytes": "145455" } ], "symlink_target": "" }
/* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L0xx_LL_PWR_H #define __STM32L0xx_LL_PWR_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l0xx.h" /** @addtogroup STM32L0xx_LL_Driver * @{ */ #if defined(PWR) /** @defgroup PWR_LL PWR * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup PWR_LL_Exported_Constants PWR Exported Constants * @{ */ /** @defgroup PWR_LL_EC_CLEAR_FLAG Clear Flags Defines * @brief Flags defines which can be used with LL_PWR_WriteReg function * @{ */ #define LL_PWR_CR_CSBF PWR_CR_CSBF /*!< Clear standby flag */ #define LL_PWR_CR_CWUF PWR_CR_CWUF /*!< Clear wakeup flag */ /** * @} */ /** @defgroup PWR_LL_EC_GET_FLAG Get Flags Defines * @brief Flags defines which can be used with LL_PWR_ReadReg function * @{ */ #define LL_PWR_CSR_WUF PWR_CSR_WUF /*!< Wakeup flag */ #define LL_PWR_CSR_SBF PWR_CSR_SBF /*!< Standby flag */ #if defined(PWR_PVD_SUPPORT) #define LL_PWR_CSR_PVDO PWR_CSR_PVDO /*!< Power voltage detector output flag */ #endif /* PWR_PVD_SUPPORT */ #if defined(PWR_CSR_VREFINTRDYF) #define LL_PWR_CSR_VREFINTRDYF PWR_CSR_VREFINTRDYF /*!< VREFINT ready flag */ #endif /* PWR_CSR_VREFINTRDYF */ #define LL_PWR_CSR_VOS PWR_CSR_VOSF /*!< Voltage scaling select flag */ #define LL_PWR_CSR_REGLPF PWR_CSR_REGLPF /*!< Regulator low power flag */ #define LL_PWR_CSR_EWUP1 PWR_CSR_EWUP1 /*!< Enable WKUP pin 1 */ #define LL_PWR_CSR_EWUP2 PWR_CSR_EWUP2 /*!< Enable WKUP pin 2 */ #if defined(PWR_CSR_EWUP3) #define LL_PWR_CSR_EWUP3 PWR_CSR_EWUP3 /*!< Enable WKUP pin 3 */ #endif /* PWR_CSR_EWUP3 */ /** * @} */ /** @defgroup PWR_LL_EC_REGU_VOLTAGE Regulator Voltage * @{ */ #define LL_PWR_REGU_VOLTAGE_SCALE1 (PWR_CR_VOS_0) /*!< 1.8V (range 1) */ #define LL_PWR_REGU_VOLTAGE_SCALE2 (PWR_CR_VOS_1) /*!< 1.5V (range 2) */ #define LL_PWR_REGU_VOLTAGE_SCALE3 (PWR_CR_VOS_0 | PWR_CR_VOS_1) /*!< 1.2V (range 3) */ /** * @} */ /** @defgroup PWR_LL_EC_MODE_PWR Mode Power * @{ */ #define LL_PWR_MODE_STOP 0x00000000U /*!< Enter Stop mode when the CPU enters deepsleep */ #define LL_PWR_MODE_STANDBY (PWR_CR_PDDS) /*!< Enter Standby mode when the CPU enters deepsleep */ /** * @} */ /** @defgroup PWR_LL_EC_REGU_MODE_LP_MODES Regulator Mode In Low Power Modes * @{ */ #define LL_PWR_REGU_LPMODES_MAIN 0x00000000U /*!< Voltage regulator in main mode during deepsleep/sleep/low-power run mode */ #define LL_PWR_REGU_LPMODES_LOW_POWER (PWR_CR_LPSDSR) /*!< Voltage regulator in low-power mode during deepsleep/sleep/low-power run mode */ /** * @} */ #if defined(PWR_CR_LPDS) /** @defgroup PWR_LL_EC_REGU_MODE_DS_MODE Regulator Mode In Deep Sleep Mode * @{ */ #define LL_PWR_REGU_DSMODE_MAIN 0x00000000U /*!< Voltage regulator in main mode during deepsleep mode when PWR_CR_LPSDSR = 0 */ #define LL_PWR_REGU_DSMODE_LOW_POWER (PWR_CR_LPDS) /*!< Voltage regulator in low-power mode during deepsleep mode when PWR_CR_LPSDSR = 0 */ /** * @} */ #endif /* PWR_CR_LPDS */ #if defined(PWR_PVD_SUPPORT) /** @defgroup PWR_LL_EC_PVDLEVEL Power Voltage Detector Level * @{ */ #define LL_PWR_PVDLEVEL_0 (PWR_CR_PLS_LEV0) /*!< Voltage threshold detected by PVD 1.9 V */ #define LL_PWR_PVDLEVEL_1 (PWR_CR_PLS_LEV1) /*!< Voltage threshold detected by PVD 2.1 V */ #define LL_PWR_PVDLEVEL_2 (PWR_CR_PLS_LEV2) /*!< Voltage threshold detected by PVD 2.3 V */ #define LL_PWR_PVDLEVEL_3 (PWR_CR_PLS_LEV3) /*!< Voltage threshold detected by PVD 2.5 V */ #define LL_PWR_PVDLEVEL_4 (PWR_CR_PLS_LEV4) /*!< Voltage threshold detected by PVD 2.7 V */ #define LL_PWR_PVDLEVEL_5 (PWR_CR_PLS_LEV5) /*!< Voltage threshold detected by PVD 2.9 V */ #define LL_PWR_PVDLEVEL_6 (PWR_CR_PLS_LEV6) /*!< Voltage threshold detected by PVD 3.1 V */ #define LL_PWR_PVDLEVEL_7 (PWR_CR_PLS_LEV7) /*!< External input analog voltage (Compare internally to VREFINT) */ /** * @} */ #endif /* PWR_PVD_SUPPORT */ /** @defgroup PWR_LL_EC_WAKEUP_PIN Wakeup Pins * @{ */ #define LL_PWR_WAKEUP_PIN1 (PWR_CSR_EWUP1) /*!< WKUP pin 1 : PA0 */ #define LL_PWR_WAKEUP_PIN2 (PWR_CSR_EWUP2) /*!< WKUP pin 2 : PC13 */ #if defined(PWR_CSR_EWUP3) #define LL_PWR_WAKEUP_PIN3 (PWR_CSR_EWUP3) /*!< WKUP pin 3 : PE6 or PA2 according to device */ #endif /* PWR_CSR_EWUP3 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup PWR_LL_Exported_Macros PWR Exported Macros * @{ */ /** @defgroup PWR_LL_EM_WRITE_READ Common write and read registers Macros * @{ */ /** * @brief Write a value in PWR register * @param __REG__ Register to be written * @param __VALUE__ Value to be written in the register * @retval None */ #define LL_PWR_WriteReg(__REG__, __VALUE__) WRITE_REG(PWR->__REG__, (__VALUE__)) /** * @brief Read a value in PWR register * @param __REG__ Register to be read * @retval Register value */ #define LL_PWR_ReadReg(__REG__) READ_REG(PWR->__REG__) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup PWR_LL_Exported_Functions PWR Exported Functions * @{ */ /** @defgroup PWR_LL_EF_Configuration Configuration * @{ */ /** * @brief Switch the regulator from main mode to low-power mode * @rmtoll CR LPRUN LL_PWR_EnableLowPowerRunMode * @note Remind to set the regulator to low power before enabling * LowPower run mode (bit @ref LL_PWR_REGU_LPMODES_LOW_POWER). * @retval None */ __STATIC_INLINE void LL_PWR_EnableLowPowerRunMode(void) { SET_BIT(PWR->CR, PWR_CR_LPRUN); } /** * @brief Switch the regulator from low-power mode to main mode * @rmtoll CR LPRUN LL_PWR_DisableLowPowerRunMode * @retval None */ __STATIC_INLINE void LL_PWR_DisableLowPowerRunMode(void) { CLEAR_BIT(PWR->CR, PWR_CR_LPRUN); } /** * @brief Check if the regulator is in low-power mode * @rmtoll CR LPRUN LL_PWR_IsEnabledLowPowerRunMode * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledLowPowerRunMode(void) { return (READ_BIT(PWR->CR, PWR_CR_LPRUN) == (PWR_CR_LPRUN)); } /** * @brief Set voltage regulator to low-power and switch from * run main mode to run low-power mode. * @rmtoll CR LPSDSR LL_PWR_EnterLowPowerRunMode\n * CR LPRUN LL_PWR_EnterLowPowerRunMode * @note This "high level" function is introduced to provide functional * compatibility with other families. Notice that the two registers * have to be written sequentially, so this function is not atomic. * To assure atomicity you can call separately the following functions: * - @ref LL_PWR_SetRegulModeLP(@ref LL_PWR_REGU_LPMODES_LOW_POWER); * - @ref LL_PWR_EnableLowPowerRunMode(); * @retval None */ __STATIC_INLINE void LL_PWR_EnterLowPowerRunMode(void) { SET_BIT(PWR->CR, PWR_CR_LPSDSR); /* => LL_PWR_SetRegulModeLP(LL_PWR_REGU_LPMODES_LOW_POWER) */ SET_BIT(PWR->CR, PWR_CR_LPRUN); /* => LL_PWR_EnableLowPowerRunMode() */ } /** * @brief Set voltage regulator to main and switch from * run main mode to low-power mode. * @rmtoll CR LPSDSR LL_PWR_ExitLowPowerRunMode\n * CR LPRUN LL_PWR_ExitLowPowerRunMode * @note This "high level" function is introduced to provide functional * compatibility with other families. Notice that the two registers * have to be written sequentially, so this function is not atomic. * To assure atomicity you can call separately the following functions: * - @ref LL_PWR_DisableLowPowerRunMode(); * - @ref LL_PWR_SetRegulModeLP(@ref LL_PWR_REGU_LPMODES_MAIN); * @retval None */ __STATIC_INLINE void LL_PWR_ExitLowPowerRunMode(void) { CLEAR_BIT(PWR->CR, PWR_CR_LPRUN); /* => LL_PWR_DisableLowPowerRunMode() */ CLEAR_BIT(PWR->CR, PWR_CR_LPSDSR); /* => LL_PWR_SetRegulModeLP(LL_PWR_REGU_LPMODES_MAIN) */ } /** * @brief Set the main internal regulator output voltage * @rmtoll CR VOS LL_PWR_SetRegulVoltageScaling * @param VoltageScaling This parameter can be one of the following values: * @arg @ref LL_PWR_REGU_VOLTAGE_SCALE1 * @arg @ref LL_PWR_REGU_VOLTAGE_SCALE2 * @arg @ref LL_PWR_REGU_VOLTAGE_SCALE3 * @retval None */ __STATIC_INLINE void LL_PWR_SetRegulVoltageScaling(uint32_t VoltageScaling) { MODIFY_REG(PWR->CR, PWR_CR_VOS, VoltageScaling); } /** * @brief Get the main internal regulator output voltage * @rmtoll CR VOS LL_PWR_GetRegulVoltageScaling * @retval Returned value can be one of the following values: * @arg @ref LL_PWR_REGU_VOLTAGE_SCALE1 * @arg @ref LL_PWR_REGU_VOLTAGE_SCALE2 * @arg @ref LL_PWR_REGU_VOLTAGE_SCALE3 */ __STATIC_INLINE uint32_t LL_PWR_GetRegulVoltageScaling(void) { return (uint32_t)(READ_BIT(PWR->CR, PWR_CR_VOS)); } /** * @brief Enable access to the backup domain * @rmtoll CR DBP LL_PWR_EnableBkUpAccess * @retval None */ __STATIC_INLINE void LL_PWR_EnableBkUpAccess(void) { SET_BIT(PWR->CR, PWR_CR_DBP); } /** * @brief Disable access to the backup domain * @rmtoll CR DBP LL_PWR_DisableBkUpAccess * @retval None */ __STATIC_INLINE void LL_PWR_DisableBkUpAccess(void) { CLEAR_BIT(PWR->CR, PWR_CR_DBP); } /** * @brief Check if the backup domain is enabled * @rmtoll CR DBP LL_PWR_IsEnabledBkUpAccess * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledBkUpAccess(void) { return (READ_BIT(PWR->CR, PWR_CR_DBP) == (PWR_CR_DBP)); } /** * @brief Set voltage regulator mode during low power modes * @rmtoll CR LPSDSR LL_PWR_SetRegulModeLP * @param RegulMode This parameter can be one of the following values: * @arg @ref LL_PWR_REGU_LPMODES_MAIN * @arg @ref LL_PWR_REGU_LPMODES_LOW_POWER * @retval None */ __STATIC_INLINE void LL_PWR_SetRegulModeLP(uint32_t RegulMode) { MODIFY_REG(PWR->CR, PWR_CR_LPSDSR, RegulMode); } /** * @brief Get voltage regulator mode during low power modes * @rmtoll CR LPSDSR LL_PWR_GetRegulModeLP * @retval Returned value can be one of the following values: * @arg @ref LL_PWR_REGU_LPMODES_MAIN * @arg @ref LL_PWR_REGU_LPMODES_LOW_POWER */ __STATIC_INLINE uint32_t LL_PWR_GetRegulModeLP(void) { return (uint32_t)(READ_BIT(PWR->CR, PWR_CR_LPSDSR)); } #if defined(PWR_CR_LPDS) /** * @brief Set voltage regulator mode during deep sleep mode * @rmtoll CR LPDS LL_PWR_SetRegulModeDS * @param RegulMode This parameter can be one of the following values: * @arg @ref LL_PWR_REGU_DSMODE_MAIN * @arg @ref LL_PWR_REGU_DSMODE_LOW_POWER * @retval None */ __STATIC_INLINE void LL_PWR_SetRegulModeDS(uint32_t RegulMode) { MODIFY_REG(PWR->CR, PWR_CR_LPDS, RegulMode); } /** * @brief Get voltage regulator mode during deep sleep mode * @rmtoll CR LPDS LL_PWR_GetRegulModeDS * @retval Returned value can be one of the following values: * @arg @ref LL_PWR_REGU_DSMODE_MAIN * @arg @ref LL_PWR_REGU_DSMODE_LOW_POWER */ __STATIC_INLINE uint32_t LL_PWR_GetRegulModeDS(void) { return (uint32_t)(READ_BIT(PWR->CR, PWR_CR_LPDS)); } #endif /* PWR_CR_LPDS */ /** * @brief Set power down mode when CPU enters deepsleep * @rmtoll CR PDDS LL_PWR_SetPowerMode * @param PDMode This parameter can be one of the following values: * @arg @ref LL_PWR_MODE_STOP * @arg @ref LL_PWR_MODE_STANDBY * @note Set the regulator to low power (bit @ref LL_PWR_REGU_LPMODES_LOW_POWER) * before setting MODE_STOP. If the regulator remains in "main mode", * it consumes more power without providing any additional feature. * In MODE_STANDBY the regulator is automatically off. * @retval None */ __STATIC_INLINE void LL_PWR_SetPowerMode(uint32_t PDMode) { MODIFY_REG(PWR->CR, PWR_CR_PDDS, PDMode); } /** * @brief Get power down mode when CPU enters deepsleep * @rmtoll CR PDDS LL_PWR_GetPowerMode * @retval Returned value can be one of the following values: * @arg @ref LL_PWR_MODE_STOP * @arg @ref LL_PWR_MODE_STANDBY */ __STATIC_INLINE uint32_t LL_PWR_GetPowerMode(void) { return (uint32_t)(READ_BIT(PWR->CR, PWR_CR_PDDS)); } #if defined(PWR_PVD_SUPPORT) /** * @brief Configure the voltage threshold detected by the Power Voltage Detector * @rmtoll CR PLS LL_PWR_SetPVDLevel * @param PVDLevel This parameter can be one of the following values: * @arg @ref LL_PWR_PVDLEVEL_0 * @arg @ref LL_PWR_PVDLEVEL_1 * @arg @ref LL_PWR_PVDLEVEL_2 * @arg @ref LL_PWR_PVDLEVEL_3 * @arg @ref LL_PWR_PVDLEVEL_4 * @arg @ref LL_PWR_PVDLEVEL_5 * @arg @ref LL_PWR_PVDLEVEL_6 * @arg @ref LL_PWR_PVDLEVEL_7 * @retval None */ __STATIC_INLINE void LL_PWR_SetPVDLevel(uint32_t PVDLevel) { MODIFY_REG(PWR->CR, PWR_CR_PLS, PVDLevel); } /** * @brief Get the voltage threshold detection * @rmtoll CR PLS LL_PWR_GetPVDLevel * @retval Returned value can be one of the following values: * @arg @ref LL_PWR_PVDLEVEL_0 * @arg @ref LL_PWR_PVDLEVEL_1 * @arg @ref LL_PWR_PVDLEVEL_2 * @arg @ref LL_PWR_PVDLEVEL_3 * @arg @ref LL_PWR_PVDLEVEL_4 * @arg @ref LL_PWR_PVDLEVEL_5 * @arg @ref LL_PWR_PVDLEVEL_6 * @arg @ref LL_PWR_PVDLEVEL_7 */ __STATIC_INLINE uint32_t LL_PWR_GetPVDLevel(void) { return (uint32_t)(READ_BIT(PWR->CR, PWR_CR_PLS)); } /** * @brief Enable Power Voltage Detector * @rmtoll CR PVDE LL_PWR_EnablePVD * @retval None */ __STATIC_INLINE void LL_PWR_EnablePVD(void) { SET_BIT(PWR->CR, PWR_CR_PVDE); } /** * @brief Disable Power Voltage Detector * @rmtoll CR PVDE LL_PWR_DisablePVD * @retval None */ __STATIC_INLINE void LL_PWR_DisablePVD(void) { CLEAR_BIT(PWR->CR, PWR_CR_PVDE); } /** * @brief Check if Power Voltage Detector is enabled * @rmtoll CR PVDE LL_PWR_IsEnabledPVD * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledPVD(void) { return (READ_BIT(PWR->CR, PWR_CR_PVDE) == (PWR_CR_PVDE)); } #endif /* PWR_PVD_SUPPORT */ /** * @brief Enable the WakeUp PINx functionality * @rmtoll CSR EWUP1 LL_PWR_EnableWakeUpPin\n * @rmtoll CSR EWUP2 LL_PWR_EnableWakeUpPin\n * @rmtoll CSR EWUP3 LL_PWR_EnableWakeUpPin * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 (*) * * (*) not available on all devices * @retval None */ __STATIC_INLINE void LL_PWR_EnableWakeUpPin(uint32_t WakeUpPin) { SET_BIT(PWR->CSR, WakeUpPin); } /** * @brief Disable the WakeUp PINx functionality * @rmtoll CSR EWUP1 LL_PWR_DisableWakeUpPin\n * @rmtoll CSR EWUP2 LL_PWR_DisableWakeUpPin\n * @rmtoll CSR EWUP3 LL_PWR_DisableWakeUpPin * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 (*) * * (*) not available on all devices * @retval None */ __STATIC_INLINE void LL_PWR_DisableWakeUpPin(uint32_t WakeUpPin) { CLEAR_BIT(PWR->CSR, WakeUpPin); } /** * @brief Check if the WakeUp PINx functionality is enabled * @rmtoll CSR EWUP1 LL_PWR_IsEnabledWakeUpPin\n * @rmtoll CSR EWUP2 LL_PWR_IsEnabledWakeUpPin\n * @rmtoll CSR EWUP3 LL_PWR_IsEnabledWakeUpPin * @param WakeUpPin This parameter can be one of the following values: * @arg @ref LL_PWR_WAKEUP_PIN1 * @arg @ref LL_PWR_WAKEUP_PIN2 * @arg @ref LL_PWR_WAKEUP_PIN3 (*) * * (*) not available on all devices * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledWakeUpPin(uint32_t WakeUpPin) { return (READ_BIT(PWR->CSR, WakeUpPin) == (WakeUpPin)); } /** * @brief Enable ultra low-power mode by enabling VREFINT switch off in low-power modes * @rmtoll CR ULP LL_PWR_EnableUltraLowPower * @retval None */ __STATIC_INLINE void LL_PWR_EnableUltraLowPower(void) { SET_BIT(PWR->CR, PWR_CR_ULP); } /** * @brief Disable ultra low-power mode by disabling VREFINT switch off in low-power modes * @rmtoll CR ULP LL_PWR_DisableUltraLowPower * @retval None */ __STATIC_INLINE void LL_PWR_DisableUltraLowPower(void) { CLEAR_BIT(PWR->CR, PWR_CR_ULP); } /** * @brief Check if ultra low-power mode is enabled by checking if VREFINT switch off in low-power modes is enabled * @rmtoll CR ULP LL_PWR_IsEnabledUltraLowPower * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledUltraLowPower(void) { return (READ_BIT(PWR->CR, PWR_CR_ULP) == (PWR_CR_ULP)); } /** * @brief Enable fast wakeup by ignoring VREFINT startup time when exiting from low-power mode * @rmtoll CR FWU LL_PWR_EnableFastWakeUp * @note Works in conjunction with ultra low power mode. * @retval None */ __STATIC_INLINE void LL_PWR_EnableFastWakeUp(void) { SET_BIT(PWR->CR, PWR_CR_FWU); } /** * @brief Disable fast wakeup by waiting VREFINT startup time when exiting from low-power mode * @rmtoll CR FWU LL_PWR_DisableFastWakeUp * @note Works in conjunction with ultra low power mode. * @retval None */ __STATIC_INLINE void LL_PWR_DisableFastWakeUp(void) { CLEAR_BIT(PWR->CR, PWR_CR_FWU); } /** * @brief Check if fast wakeup is enabled by checking if VREFINT startup time when exiting from low-power mode is ignored * @rmtoll CR FWU LL_PWR_IsEnabledFastWakeUp * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledFastWakeUp(void) { return (READ_BIT(PWR->CR, PWR_CR_FWU) == (PWR_CR_FWU)); } /** * @brief Enable non-volatile memory (Flash and EEPROM) keeping off feature when exiting from low-power mode * @rmtoll CR DS_EE_KOFF LL_PWR_EnableNVMKeptOff * @note When enabled, after entering low-power mode (Stop or Standby only), if RUN_PD of FLASH_ACR register * is also set, the Flash memory will not be woken up when exiting from deepsleep mode. * When enabled, the EEPROM will not be woken up when exiting from low-power mode (if the bit RUN_PD is set) * @retval None */ __STATIC_INLINE void LL_PWR_EnableNVMKeptOff(void) { SET_BIT(PWR->CR, PWR_CR_DSEEKOFF); } /** * @brief Disable non-volatile memory (Flash and EEPROM) keeping off feature when exiting from low-power mode * @rmtoll CR DS_EE_KOFF LL_PWR_DisableNVMKeptOff * @note When disabled, Flash memory is woken up when exiting from deepsleep mode even if the bit RUN_PD is set * @retval None */ __STATIC_INLINE void LL_PWR_DisableNVMKeptOff(void) { CLEAR_BIT(PWR->CR, PWR_CR_DSEEKOFF); } /** * @brief Check if non-volatile memory (Flash and EEPROM) keeping off feature when exiting from low-power mode is enabled * @rmtoll CR DS_EE_KOFF LL_PWR_IsEnabledNVMKeptOff * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsEnabledNVMKeptOff(void) { return (READ_BIT(PWR->CR, PWR_CR_DSEEKOFF) == (PWR_CR_DSEEKOFF)); } /** * @} */ /** @defgroup PWR_LL_EF_FLAG_Management FLAG_Management * @{ */ /** * @brief Get Wake-up Flag * @rmtoll CSR WUF LL_PWR_IsActiveFlag_WU * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_WU(void) { return (READ_BIT(PWR->CSR, PWR_CSR_WUF) == (PWR_CSR_WUF)); } /** * @brief Get Standby Flag * @rmtoll CSR SBF LL_PWR_IsActiveFlag_SB * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_SB(void) { return (READ_BIT(PWR->CSR, PWR_CSR_SBF) == (PWR_CSR_SBF)); } #if defined(PWR_PVD_SUPPORT) /** * @brief Indicate whether VDD voltage is below the selected PVD threshold * @rmtoll CSR PVDO LL_PWR_IsActiveFlag_PVDO * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_PVDO(void) { return (READ_BIT(PWR->CSR, PWR_CSR_PVDO) == (PWR_CSR_PVDO)); } #endif /* PWR_PVD_SUPPORT */ #if defined(PWR_CSR_VREFINTRDYF) /** * @brief Get Internal Reference VrefInt Flag * @rmtoll CSR VREFINTRDYF LL_PWR_IsActiveFlag_VREFINTRDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_VREFINTRDY(void) { return (READ_BIT(PWR->CSR, PWR_CSR_VREFINTRDYF) == (PWR_CSR_VREFINTRDYF)); } #endif /* PWR_CSR_VREFINTRDYF */ /** * @brief Indicate whether the regulator is ready in the selected voltage range or if its output voltage is still changing to the required voltage level * @rmtoll CSR VOSF LL_PWR_IsActiveFlag_VOSF * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_VOSF(void) { return (READ_BIT(PWR->CSR, LL_PWR_CSR_VOS) == (LL_PWR_CSR_VOS)); } /** * @brief Indicate whether the regulator is ready in main mode or is in low-power mode * @rmtoll CSR REGLPF LL_PWR_IsActiveFlag_REGLPF * @note Take care, return value "0" means the regulator is ready. Return value "1" means the output voltage range is still changing. * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_PWR_IsActiveFlag_REGLPF(void) { return (READ_BIT(PWR->CSR, PWR_CSR_REGLPF) == (PWR_CSR_REGLPF)); } /** * @brief Clear Standby Flag * @rmtoll CR CSBF LL_PWR_ClearFlag_SB * @retval None */ __STATIC_INLINE void LL_PWR_ClearFlag_SB(void) { SET_BIT(PWR->CR, PWR_CR_CSBF); } /** * @brief Clear Wake-up Flags * @rmtoll CR CWUF LL_PWR_ClearFlag_WU * @retval None */ __STATIC_INLINE void LL_PWR_ClearFlag_WU(void) { SET_BIT(PWR->CR, PWR_CR_CWUF); } #if defined(USE_FULL_LL_DRIVER) /** @defgroup PWR_LL_EF_Init De-initialization function * @{ */ ErrorStatus LL_PWR_DeInit(void); /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /** * @} */ /** * @} */ /** * @} */ #endif /* defined(PWR) */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32L0xx_LL_PWR_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "content_hash": "5c1e5b57aec6b250379c3db4074b7904", "timestamp": "", "source": "github", "line_count": 726, "max_line_length": 154, "avg_line_length": 33.65564738292011, "alnum_prop": 0.5942129819104527, "repo_name": "florincosta/lora_di", "id": "0fec8f22ac8b99f9683d80f6efe17a50a065f62b", "size": "26517", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Drivers/STM32L0xx_HAL_Driver/Inc/stm32l0xx_ll_pwr.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6868475" }, { "name": "C++", "bytes": "267381" }, { "name": "HTML", "bytes": "210318" } ], "symlink_target": "" }
'use strict'; const ShelfPack = require('@mapbox/shelf-pack'); const util = require('../util/util'); const SIZE_GROWTH_RATE = 4; const DEFAULT_SIZE = 128; // must be "DEFAULT_SIZE * SIZE_GROWTH_RATE ^ n" for some integer n const MAX_SIZE = 2048; class GlyphAtlas { constructor() { this.width = DEFAULT_SIZE; this.height = DEFAULT_SIZE; this.atlas = new ShelfPack(this.width, this.height); this.index = {}; this.ids = {}; this.data = new Uint8Array(this.width * this.height); } getGlyphs() { const glyphs = {}; let split, name, id; for (const key in this.ids) { split = key.split('#'); name = split[0]; id = split[1]; if (!glyphs[name]) glyphs[name] = []; glyphs[name].push(id); } return glyphs; } getRects() { const rects = {}; let split, name, id; for (const key in this.ids) { split = key.split('#'); name = split[0]; id = split[1]; if (!rects[name]) rects[name] = {}; rects[name][id] = this.index[key]; } return rects; } addGlyph(id, name, glyph, buffer) { if (!glyph) return null; const key = `${name}#${glyph.id}`; // The glyph is already in this texture. if (this.index[key]) { if (this.ids[key].indexOf(id) < 0) { this.ids[key].push(id); } return this.index[key]; } // The glyph bitmap has zero width. if (!glyph.bitmap) { return null; } const bufferedWidth = glyph.width + buffer * 2; const bufferedHeight = glyph.height + buffer * 2; // Add a 1px border around every image. const padding = 1; let packWidth = bufferedWidth + 2 * padding; let packHeight = bufferedHeight + 2 * padding; // Increase to next number divisible by 4, but at least 1. // This is so we can scale down the texture coordinates and pack them // into fewer bytes. packWidth += (4 - packWidth % 4); packHeight += (4 - packHeight % 4); let rect = this.atlas.packOne(packWidth, packHeight); if (!rect) { this.resize(); rect = this.atlas.packOne(packWidth, packHeight); } if (!rect) { util.warnOnce('glyph bitmap overflow'); return null; } this.index[key] = rect; this.ids[key] = [id]; const target = this.data; const source = glyph.bitmap; for (let y = 0; y < bufferedHeight; y++) { const y1 = this.width * (rect.y + y + padding) + rect.x + padding; const y2 = bufferedWidth * y; for (let x = 0; x < bufferedWidth; x++) { target[y1 + x] = source[y2 + x]; } } this.dirty = true; return rect; } resize() { const prevWidth = this.width; const prevHeight = this.height; if (prevWidth >= MAX_SIZE || prevHeight >= MAX_SIZE) return; if (this.texture) { if (this.gl) { this.gl.deleteTexture(this.texture); } this.texture = null; } this.width *= SIZE_GROWTH_RATE; this.height *= SIZE_GROWTH_RATE; this.atlas.resize(this.width, this.height); const buf = new ArrayBuffer(this.width * this.height); for (let i = 0; i < prevHeight; i++) { const src = new Uint8Array(this.data.buffer, prevHeight * i, prevWidth); const dst = new Uint8Array(buf, prevHeight * i * SIZE_GROWTH_RATE, prevWidth); dst.set(src); } this.data = new Uint8Array(buf); } bind(gl) { this.gl = gl; if (!this.texture) { this.texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, null); } else { gl.bindTexture(gl.TEXTURE_2D, this.texture); } } updateTexture(gl) { this.bind(gl); if (this.dirty) { gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data); this.dirty = false; } } } module.exports = GlyphAtlas;
{ "content_hash": "d65efe9968d97925b603ff6e8521f23c", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 117, "avg_line_length": 28.6, "alnum_prop": 0.5195392842451666, "repo_name": "stl-florida/casestudy-riskmap", "id": "c0dbdffe42938ea27ff9b13d10350c4f7c0f77f3", "size": "4862", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/mapbox-gl/src/symbol/glyph_atlas.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2670" }, { "name": "HTML", "bytes": "3264" }, { "name": "JavaScript", "bytes": "1776505" } ], "symlink_target": "" }
package org.elasticsearch.xpack.security.authc; import org.elasticsearch.Version; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.client.Client; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.test.ClusterServiceUtils; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.xpack.core.XPackSettings; import org.elasticsearch.xpack.core.security.authc.Authentication; import org.elasticsearch.xpack.core.security.authc.Authentication.AuthenticationType; import org.elasticsearch.xpack.core.security.authc.Authentication.RealmRef; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; import org.elasticsearch.xpack.core.security.authc.support.Hasher; import org.elasticsearch.xpack.core.security.authz.RoleDescriptor; import org.elasticsearch.xpack.core.security.authz.privilege.ApplicationPrivilege; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.security.authc.ApiKeyService.ApiKeyCredentials; import org.elasticsearch.xpack.security.authc.ApiKeyService.ApiKeyRoleDescriptors; import org.elasticsearch.xpack.security.authc.ApiKeyService.CachedApiKeyHashResult; import org.elasticsearch.xpack.security.authz.store.NativePrivilegeStore; import org.elasticsearch.xpack.security.support.SecurityIndexManager; import org.elasticsearch.xpack.security.test.SecurityMocks; import org.junit.After; import org.junit.Before; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.elasticsearch.xpack.core.security.authz.store.ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ApiKeyServiceTests extends ESTestCase { private ThreadPool threadPool; private XPackLicenseState licenseState; private Client client; private SecurityIndexManager securityIndex; @Before public void createThreadPool() { threadPool = new TestThreadPool("api key service tests"); } @After public void stopThreadPool() { terminate(threadPool); } @Before public void setupMocks() { this.licenseState = mock(XPackLicenseState.class); when(licenseState.isApiKeyServiceAllowed()).thenReturn(true); this.client = mock(Client.class); this.securityIndex = SecurityMocks.mockSecurityIndexManager(); } public void testGetCredentialsFromThreadContext() { ThreadContext threadContext = threadPool.getThreadContext(); assertNull(ApiKeyService.getCredentialsFromHeader(threadContext)); final String apiKeyAuthScheme = randomFrom("apikey", "apiKey", "ApiKey", "APikey", "APIKEY"); final String id = randomAlphaOfLength(12); final String key = randomAlphaOfLength(16); String headerValue = apiKeyAuthScheme + " " + Base64.getEncoder().encodeToString((id + ":" + key).getBytes(StandardCharsets.UTF_8)); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { threadContext.putHeader("Authorization", headerValue); ApiKeyService.ApiKeyCredentials creds = ApiKeyService.getCredentialsFromHeader(threadContext); assertNotNull(creds); assertEquals(id, creds.getId()); assertEquals(key, creds.getKey().toString()); } // missing space headerValue = apiKeyAuthScheme + Base64.getEncoder().encodeToString((id + ":" + key).getBytes(StandardCharsets.UTF_8)); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { threadContext.putHeader("Authorization", headerValue); ApiKeyService.ApiKeyCredentials creds = ApiKeyService.getCredentialsFromHeader(threadContext); assertNull(creds); } // missing colon headerValue = apiKeyAuthScheme + " " + Base64.getEncoder().encodeToString((id + key).getBytes(StandardCharsets.UTF_8)); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { threadContext.putHeader("Authorization", headerValue); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> ApiKeyService.getCredentialsFromHeader(threadContext)); assertEquals("invalid ApiKey value", e.getMessage()); } } public void testAuthenticateWithApiKey() throws Exception { final Settings settings = Settings.builder().put(XPackSettings.API_KEY_SERVICE_ENABLED_SETTING.getKey(), true).build(); final ApiKeyService service = createApiKeyService(settings); final String id = randomAlphaOfLength(12); final String key = randomAlphaOfLength(16); mockKeyDocument(service, id, key, new User("hulk", "superuser")); final AuthenticationResult auth = tryAuthenticate(service, id, key); assertThat(auth.getStatus(), is(AuthenticationResult.Status.SUCCESS)); assertThat(auth.getUser(), notNullValue()); assertThat(auth.getUser().principal(), is("hulk")); } public void testAuthenticationIsSkippedIfLicenseDoesNotAllowIt() throws Exception { final Settings settings = Settings.builder().put(XPackSettings.API_KEY_SERVICE_ENABLED_SETTING.getKey(), true).build(); final ApiKeyService service = createApiKeyService(settings); final String id = randomAlphaOfLength(12); final String key = randomAlphaOfLength(16); mockKeyDocument(service, id, key, new User(randomAlphaOfLength(6), randomAlphaOfLength(12))); when(licenseState.isApiKeyServiceAllowed()).thenReturn(false); final AuthenticationResult auth = tryAuthenticate(service, id, key); assertThat(auth.getStatus(), is(AuthenticationResult.Status.CONTINUE)); assertThat(auth.getUser(), nullValue()); } public void testAuthenticationFailureWithInvalidatedApiKey() throws Exception { final Settings settings = Settings.builder().put(XPackSettings.API_KEY_SERVICE_ENABLED_SETTING.getKey(), true).build(); final ApiKeyService service = createApiKeyService(settings); final String id = randomAlphaOfLength(12); final String key = randomAlphaOfLength(16); mockKeyDocument(service, id, key, new User("hulk", "superuser"), true, Duration.ofSeconds(3600)); final AuthenticationResult auth = tryAuthenticate(service, id, key); assertThat(auth.getStatus(), is(AuthenticationResult.Status.CONTINUE)); assertThat(auth.getUser(), nullValue()); assertThat(auth.getMessage(), containsString("invalidated")); } public void testAuthenticationFailureWithInvalidCredentials() throws Exception { final Settings settings = Settings.builder().put(XPackSettings.API_KEY_SERVICE_ENABLED_SETTING.getKey(), true).build(); final ApiKeyService service = createApiKeyService(settings); final String id = randomAlphaOfLength(12); final String realKey = randomAlphaOfLength(16); final String wrongKey = "#" + realKey.substring(1); mockKeyDocument(service, id, realKey, new User("hulk", "superuser")); final AuthenticationResult auth = tryAuthenticate(service, id, wrongKey); assertThat(auth.getStatus(), is(AuthenticationResult.Status.CONTINUE)); assertThat(auth.getUser(), nullValue()); assertThat(auth.getMessage(), containsString("invalid credentials")); } public void testAuthenticationFailureWithExpiredKey() throws Exception { final Settings settings = Settings.builder().put(XPackSettings.API_KEY_SERVICE_ENABLED_SETTING.getKey(), true).build(); final ApiKeyService service = createApiKeyService(settings); final String id = randomAlphaOfLength(12); final String key = randomAlphaOfLength(16); mockKeyDocument(service, id, key, new User("hulk", "superuser"), false, Duration.ofSeconds(-1)); final AuthenticationResult auth = tryAuthenticate(service, id, key); assertThat(auth.getStatus(), is(AuthenticationResult.Status.CONTINUE)); assertThat(auth.getUser(), nullValue()); assertThat(auth.getMessage(), containsString("expired")); } /** * We cache valid and invalid responses. This test verifies that we handle these correctly. */ public void testMixingValidAndInvalidCredentials() throws Exception { final Settings settings = Settings.builder().put(XPackSettings.API_KEY_SERVICE_ENABLED_SETTING.getKey(), true).build(); final ApiKeyService service = createApiKeyService(settings); final String id = randomAlphaOfLength(12); final String realKey = randomAlphaOfLength(16); mockKeyDocument(service, id, realKey, new User("hulk", "superuser")); for (int i = 0; i < 3; i++) { final String wrongKey = "=" + randomAlphaOfLength(14) + "@"; AuthenticationResult auth = tryAuthenticate(service, id, wrongKey); assertThat(auth.getStatus(), is(AuthenticationResult.Status.CONTINUE)); assertThat(auth.getUser(), nullValue()); assertThat(auth.getMessage(), containsString("invalid credentials")); auth = tryAuthenticate(service, id, realKey); assertThat(auth.getStatus(), is(AuthenticationResult.Status.SUCCESS)); assertThat(auth.getUser(), notNullValue()); assertThat(auth.getUser().principal(), is("hulk")); } } private void mockKeyDocument(ApiKeyService service, String id, String key, User user) throws IOException { mockKeyDocument(service, id, key, user, false, Duration.ofSeconds(3600)); } private void mockKeyDocument(ApiKeyService service, String id, String key, User user, boolean invalidated, Duration expiry) throws IOException { final Authentication authentication = new Authentication(user, new RealmRef("realm1", "native", "node01"), null, Version.CURRENT); XContentBuilder docSource = service.newDocument(new SecureString(key.toCharArray()), "test", authentication, Collections.singleton(SUPERUSER_ROLE_DESCRIPTOR), Instant.now(), Instant.now().plus(expiry), null, Version.CURRENT); if (invalidated) { Map<String, Object> map = XContentHelper.convertToMap(BytesReference.bytes(docSource), true, XContentType.JSON).v2(); map.put("api_key_invalidated", true); docSource = XContentBuilder.builder(XContentType.JSON.xContent()).map(map); } SecurityMocks.mockGetRequest(client, id, BytesReference.bytes(docSource)); } private AuthenticationResult tryAuthenticate(ApiKeyService service, String id, String key) throws Exception { final ThreadContext threadContext = threadPool.getThreadContext(); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { final String header = "ApiKey " + Base64.getEncoder().encodeToString((id + ":" + key).getBytes(StandardCharsets.UTF_8)); threadContext.putHeader("Authorization", header); final PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>(); service.authenticateWithApiKeyIfPresent(threadContext, future); final AuthenticationResult auth = future.get(); assertThat(auth, notNullValue()); return auth; } } public void testValidateApiKey() throws Exception { final String apiKey = randomAlphaOfLength(16); Hasher hasher = randomFrom(Hasher.PBKDF2, Hasher.BCRYPT4, Hasher.BCRYPT); final char[] hash = hasher.hash(new SecureString(apiKey.toCharArray())); Map<String, Object> sourceMap = new HashMap<>(); sourceMap.put("doc_type", "api_key"); sourceMap.put("api_key_hash", new String(hash)); sourceMap.put("role_descriptors", Collections.singletonMap("a role", Collections.singletonMap("cluster", "all"))); sourceMap.put("limited_by_role_descriptors", Collections.singletonMap("limited role", Collections.singletonMap("cluster", "all"))); Map<String, Object> creatorMap = new HashMap<>(); creatorMap.put("principal", "test_user"); creatorMap.put("realm", "realm1"); creatorMap.put("metadata", Collections.emptyMap()); sourceMap.put("creator", creatorMap); sourceMap.put("api_key_invalidated", false); ApiKeyService service = createApiKeyService(Settings.EMPTY); ApiKeyService.ApiKeyCredentials creds = new ApiKeyService.ApiKeyCredentials(randomAlphaOfLength(12), new SecureString(apiKey.toCharArray())); PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); AuthenticationResult result = future.get(); assertNotNull(result); assertTrue(result.isAuthenticated()); assertThat(result.getUser().principal(), is("test_user")); assertThat(result.getUser().roles(), arrayContaining("a role")); assertThat(result.getUser().metadata(), is(Collections.emptyMap())); assertThat(result.getMetadata().get(ApiKeyService.API_KEY_ROLE_DESCRIPTORS_KEY), equalTo(sourceMap.get("role_descriptors"))); assertThat(result.getMetadata().get(ApiKeyService.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY), equalTo(sourceMap.get("limited_by_role_descriptors"))); assertThat(result.getMetadata().get(ApiKeyService.API_KEY_CREATOR_REALM), is("realm1")); sourceMap.put("expiration_time", Clock.systemUTC().instant().plus(1L, ChronoUnit.HOURS).toEpochMilli()); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.get(); assertNotNull(result); assertTrue(result.isAuthenticated()); assertThat(result.getUser().principal(), is("test_user")); assertThat(result.getUser().roles(), arrayContaining("a role")); assertThat(result.getUser().metadata(), is(Collections.emptyMap())); assertThat(result.getMetadata().get(ApiKeyService.API_KEY_ROLE_DESCRIPTORS_KEY), equalTo(sourceMap.get("role_descriptors"))); assertThat(result.getMetadata().get(ApiKeyService.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY), equalTo(sourceMap.get("limited_by_role_descriptors"))); assertThat(result.getMetadata().get(ApiKeyService.API_KEY_CREATOR_REALM), is("realm1")); sourceMap.put("expiration_time", Clock.systemUTC().instant().minus(1L, ChronoUnit.HOURS).toEpochMilli()); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.get(); assertNotNull(result); assertFalse(result.isAuthenticated()); sourceMap.remove("expiration_time"); creds = new ApiKeyService.ApiKeyCredentials(randomAlphaOfLength(12), new SecureString(randomAlphaOfLength(15).toCharArray())); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.get(); assertNotNull(result); assertFalse(result.isAuthenticated()); sourceMap.put("api_key_invalidated", true); creds = new ApiKeyService.ApiKeyCredentials(randomAlphaOfLength(12), new SecureString(randomAlphaOfLength(15).toCharArray())); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.get(); assertNotNull(result); assertFalse(result.isAuthenticated()); } public void testGetRolesForApiKeyNotInContext() throws Exception { Map<String, Object> superUserRdMap; try (XContentBuilder builder = JsonXContent.contentBuilder()) { superUserRdMap = XContentHelper.convertToMap(XContentType.JSON.xContent(), BytesReference.bytes(SUPERUSER_ROLE_DESCRIPTOR .toXContent(builder, ToXContent.EMPTY_PARAMS, true)) .streamInput(), false); } Map<String, Object> authMetadata = new HashMap<>(); authMetadata.put(ApiKeyService.API_KEY_ID_KEY, randomAlphaOfLength(12)); authMetadata.put(ApiKeyService.API_KEY_ROLE_DESCRIPTORS_KEY, Collections.singletonMap(SUPERUSER_ROLE_DESCRIPTOR.getName(), superUserRdMap)); authMetadata.put(ApiKeyService.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY, Collections.singletonMap(SUPERUSER_ROLE_DESCRIPTOR.getName(), superUserRdMap)); final Authentication authentication = new Authentication(new User("joe"), new RealmRef("apikey", "apikey", "node"), null, Version.CURRENT, AuthenticationType.API_KEY, authMetadata); ApiKeyService service = createApiKeyService(Settings.EMPTY); PlainActionFuture<ApiKeyRoleDescriptors> roleFuture = new PlainActionFuture<>(); service.getRoleForApiKey(authentication, roleFuture); ApiKeyRoleDescriptors result = roleFuture.get(); assertThat(result.getRoleDescriptors().size(), is(1)); assertThat(result.getRoleDescriptors().get(0).getName(), is("superuser")); } public void testGetRolesForApiKey() throws Exception { Map<String, Object> authMetadata = new HashMap<>(); authMetadata.put(ApiKeyService.API_KEY_ID_KEY, randomAlphaOfLength(12)); boolean emptyApiKeyRoleDescriptor = randomBoolean(); final RoleDescriptor roleARoleDescriptor = new RoleDescriptor("a role", new String[] { "monitor" }, new RoleDescriptor.IndicesPrivileges[] { RoleDescriptor.IndicesPrivileges.builder().indices("*").privileges("monitor").build() }, null); Map<String, Object> roleARDMap; try (XContentBuilder builder = JsonXContent.contentBuilder()) { roleARDMap = XContentHelper.convertToMap(XContentType.JSON.xContent(), BytesReference.bytes(roleARoleDescriptor.toXContent(builder, ToXContent.EMPTY_PARAMS, true)).streamInput(), false); } authMetadata.put(ApiKeyService.API_KEY_ROLE_DESCRIPTORS_KEY, (emptyApiKeyRoleDescriptor) ? randomFrom(Arrays.asList(null, Collections.emptyMap())) : Collections.singletonMap("a role", roleARDMap)); final RoleDescriptor limitedRoleDescriptor = new RoleDescriptor("limited role", new String[] { "all" }, new RoleDescriptor.IndicesPrivileges[] { RoleDescriptor.IndicesPrivileges.builder().indices("*").privileges("all").build() }, null); Map<String, Object> limitedRdMap; try (XContentBuilder builder = JsonXContent.contentBuilder()) { limitedRdMap = XContentHelper.convertToMap(XContentType.JSON.xContent(), BytesReference.bytes(limitedRoleDescriptor .toXContent(builder, ToXContent.EMPTY_PARAMS, true)) .streamInput(), false); } authMetadata.put(ApiKeyService.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY, Collections.singletonMap("limited role", limitedRdMap)); final Authentication authentication = new Authentication(new User("joe"), new RealmRef("apikey", "apikey", "node"), null, Version.CURRENT, AuthenticationType.API_KEY, authMetadata); final NativePrivilegeStore privilegesStore = mock(NativePrivilegeStore.class); doAnswer(i -> { assertThat(i.getArguments().length, equalTo(3)); final Object arg2 = i.getArguments()[2]; assertThat(arg2, instanceOf(ActionListener.class)); ActionListener<Collection<ApplicationPrivilege>> listener = (ActionListener<Collection<ApplicationPrivilege>>) arg2; listener.onResponse(Collections.emptyList()); return null; } ).when(privilegesStore).getPrivileges(any(Collection.class), any(Collection.class), any(ActionListener.class)); ApiKeyService service = createApiKeyService(Settings.EMPTY); PlainActionFuture<ApiKeyRoleDescriptors> roleFuture = new PlainActionFuture<>(); service.getRoleForApiKey(authentication, roleFuture); ApiKeyRoleDescriptors result = roleFuture.get(); if (emptyApiKeyRoleDescriptor) { assertNull(result.getLimitedByRoleDescriptors()); assertThat(result.getRoleDescriptors().size(), is(1)); assertThat(result.getRoleDescriptors().get(0).getName(), is("limited role")); } else { assertThat(result.getRoleDescriptors().size(), is(1)); assertThat(result.getLimitedByRoleDescriptors().size(), is(1)); assertThat(result.getRoleDescriptors().get(0).getName(), is("a role")); assertThat(result.getLimitedByRoleDescriptors().get(0).getName(), is("limited role")); } } public void testApiKeyCache() { final String apiKey = randomAlphaOfLength(16); Hasher hasher = randomFrom(Hasher.PBKDF2, Hasher.BCRYPT4, Hasher.BCRYPT); final char[] hash = hasher.hash(new SecureString(apiKey.toCharArray())); Map<String, Object> sourceMap = new HashMap<>(); sourceMap.put("doc_type", "api_key"); sourceMap.put("api_key_hash", new String(hash)); sourceMap.put("role_descriptors", Collections.singletonMap("a role", Collections.singletonMap("cluster", "all"))); sourceMap.put("limited_by_role_descriptors", Collections.singletonMap("limited role", Collections.singletonMap("cluster", "all"))); Map<String, Object> creatorMap = new HashMap<>(); creatorMap.put("principal", "test_user"); creatorMap.put("metadata", Collections.emptyMap()); sourceMap.put("creator", creatorMap); sourceMap.put("api_key_invalidated", false); ApiKeyService service = createApiKeyService(Settings.EMPTY); ApiKeyCredentials creds = new ApiKeyCredentials(randomAlphaOfLength(12), new SecureString(apiKey.toCharArray())); PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); AuthenticationResult result = future.actionGet(); assertThat(result.isAuthenticated(), is(true)); CachedApiKeyHashResult cachedApiKeyHashResult = service.getFromCache(creds.getId()); assertNotNull(cachedApiKeyHashResult); assertThat(cachedApiKeyHashResult.success, is(true)); creds = new ApiKeyCredentials(creds.getId(), new SecureString("foobar".toCharArray())); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.actionGet(); assertThat(result.isAuthenticated(), is(false)); final CachedApiKeyHashResult shouldBeSame = service.getFromCache(creds.getId()); assertNotNull(shouldBeSame); assertThat(shouldBeSame, sameInstance(cachedApiKeyHashResult)); sourceMap.put("api_key_hash", new String(hasher.hash(new SecureString("foobar".toCharArray())))); creds = new ApiKeyCredentials(randomAlphaOfLength(12), new SecureString("foobar1".toCharArray())); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.actionGet(); assertThat(result.isAuthenticated(), is(false)); cachedApiKeyHashResult = service.getFromCache(creds.getId()); assertNotNull(cachedApiKeyHashResult); assertThat(cachedApiKeyHashResult.success, is(false)); creds = new ApiKeyCredentials(creds.getId(), new SecureString("foobar2".toCharArray())); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.actionGet(); assertThat(result.isAuthenticated(), is(false)); assertThat(service.getFromCache(creds.getId()), not(sameInstance(cachedApiKeyHashResult))); assertThat(service.getFromCache(creds.getId()).success, is(false)); creds = new ApiKeyCredentials(creds.getId(), new SecureString("foobar".toCharArray())); future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); result = future.actionGet(); assertThat(result.isAuthenticated(), is(true)); assertThat(service.getFromCache(creds.getId()), not(sameInstance(cachedApiKeyHashResult))); assertThat(service.getFromCache(creds.getId()).success, is(true)); } public void testApiKeyCacheDisabled() { final String apiKey = randomAlphaOfLength(16); Hasher hasher = randomFrom(Hasher.PBKDF2, Hasher.BCRYPT4, Hasher.BCRYPT); final char[] hash = hasher.hash(new SecureString(apiKey.toCharArray())); final Settings settings = Settings.builder() .put(ApiKeyService.CACHE_TTL_SETTING.getKey(), "0s") .build(); Map<String, Object> sourceMap = new HashMap<>(); sourceMap.put("doc_type", "api_key"); sourceMap.put("api_key_hash", new String(hash)); sourceMap.put("role_descriptors", Collections.singletonMap("a role", Collections.singletonMap("cluster", "all"))); sourceMap.put("limited_by_role_descriptors", Collections.singletonMap("limited role", Collections.singletonMap("cluster", "all"))); Map<String, Object> creatorMap = new HashMap<>(); creatorMap.put("principal", "test_user"); creatorMap.put("metadata", Collections.emptyMap()); sourceMap.put("creator", creatorMap); sourceMap.put("api_key_invalidated", false); ApiKeyService service = createApiKeyService(settings); ApiKeyCredentials creds = new ApiKeyCredentials(randomAlphaOfLength(12), new SecureString(apiKey.toCharArray())); PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>(); service.validateApiKeyCredentials(creds.getId(), sourceMap, creds, Clock.systemUTC(), future); AuthenticationResult result = future.actionGet(); assertThat(result.isAuthenticated(), is(true)); CachedApiKeyHashResult cachedApiKeyHashResult = service.getFromCache(creds.getId()); assertNull(cachedApiKeyHashResult); } private ApiKeyService createApiKeyService(Settings settings) { return new ApiKeyService(settings, Clock.systemUTC(), client, licenseState, securityIndex, ClusterServiceUtils.createClusterService(threadPool), threadPool); } }
{ "content_hash": "de61c154a11589a1c1f91c51c4d980b7", "timestamp": "", "source": "github", "line_count": 522, "max_line_length": 140, "avg_line_length": 54.44827586206897, "alnum_prop": 0.7050524241784533, "repo_name": "coding0011/elasticsearch", "id": "88cbc0a80695d0df6a78149acd5a7d777e9c531e", "size": "28663", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11081" }, { "name": "Batchfile", "bytes": "18064" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "312193" }, { "name": "HTML", "bytes": "5519" }, { "name": "Java", "bytes": "41505710" }, { "name": "Perl", "bytes": "7271" }, { "name": "Python", "bytes": "55163" }, { "name": "Shell", "bytes": "119286" } ], "symlink_target": "" }
package ubung2001Ctvrty; public class Person extends SuperKlasse implements Int, Int2 { String name; public Person() { name = "Dima"; } @Override public void Lesen() { System.out.println("Ich kann lesen"); } @Override public void schwimmen() { System.out.println("Ich schwimme"); } @Override public void sagHallo() { System.out.println("hallo" + name); } }
{ "content_hash": "46e23898f5dcb4f50898457192bd036d", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 62, "avg_line_length": 14.785714285714286, "alnum_prop": 0.6280193236714976, "repo_name": "dmpe/OOPaPrechod", "id": "a4ee82c037d8c1bcc1a29b2fb505d3401c21b881", "size": "414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ubung2001Ctvrty/Person.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "178589" } ], "symlink_target": "" }
RenderableRepo::RenderableRepo() : RepoBase( mDefaultRenderable ) { Init(); } void RenderableRepo::Init() { ElementMap_t Renderables; fs_utils::for_each( "actors", ".sprite", [&]( Json::Value const& desc, boost::filesystem::path const& path ) { std::string PathStr; auto const& ActorVisuals = desc["actor_visuals"]; if (!ActorVisuals.isArray()) { return; } if (!Json::GetStr( desc["texture_path"], PathStr )) { return; } bool isAbsolute = PathStr.size() > 1 && (PathStr.substr( 0, 2 ) == ":/" || PathStr.substr( 0, 2 ) == ":\\"); boost::filesystem::path newPath; if (!isAbsolute) { L2( "Path is not absolute %s, %s\n", path.generic_string().c_str(), PathStr.c_str() ); newPath = path.parent_path() / PathStr; } else { newPath = boost::filesystem::path( PathStr.substr( 2 ) ); L2( "Path is absolute %s\n", newPath.generic_string().c_str() ); } int32_t TexId = AutoId( newPath.generic_string() ); for (auto&& ActorVisualDesc : ActorVisuals) { if (!ActorVisualDesc.isObject()) { return; } std::auto_ptr<SpriteCollection> Renderable( new SpriteCollection ); if (!Renderable->Load( TexId, ActorVisualDesc )) { return; } int32_t Id = Renderable->Id(); ElementMap_t::iterator It = Renderables.find( Id ); if (It == Renderables.end()) { Renderables.insert( Id, Renderable.release() ); } else { It->second->Merge( *Renderable ); } } } ); for( auto i = Renderables.begin(), e = Renderables.end(); i != e; ++i ) { auto const& spriteColl = *i->second; float max = 0.0f; for( auto ii = spriteColl.begin(), ee = spriteColl.end(); ii != ee; ++ii) { if( max < ii->second->GetScale() ) { max = ii->second->GetScale(); } } mMaxScaleMap[i->first] = max; } // all done using std::swap; swap( mElements, Renderables ); } float RenderableRepo::GetMaxScale( int32_t actorId ) const { auto it = mMaxScaleMap.find( actorId ); return it == mMaxScaleMap.end() ? 1.0 : it->second; }
{ "content_hash": "5936b2a6bd5e5b543a8123af6604a4e6", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 116, "avg_line_length": 30.74074074074074, "alnum_prop": 0.4947791164658635, "repo_name": "HalalUr/Reaping2", "id": "db2a4bde6ebac9d2a346513f5caaf80e37c5ece9", "size": "2612", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/render/renderable_repo.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "380" }, { "name": "C", "bytes": "1997" }, { "name": "C++", "bytes": "2216517" }, { "name": "CMake", "bytes": "33501" }, { "name": "GLSL", "bytes": "19662" } ], "symlink_target": "" }
package org.olat.system.support.mail.service; /** * Initial Date: 21.12.2011 <br> * * @author guretzki */ public abstract class CommonMailTO { protected String toMailAddress; protected String fromMailAddress; protected String subject; protected String replyTo; protected String ccMailAddress; protected CommonMailTO(String toMailAddress, String fromMailAddress, String subject) { this.toMailAddress = toMailAddress; this.fromMailAddress = fromMailAddress; this.subject = subject; } public void validate() { if (toMailAddress == null || toMailAddress.isEmpty()) { throw new IllegalArgumentException("toMailAdress is not set."); } if (fromMailAddress == null || fromMailAddress.isEmpty()) { throw new IllegalArgumentException("fromMailAddress is not set."); } if (subject == null || subject.isEmpty()) { throw new IllegalArgumentException("Mail subject is not set."); } } public String getToMailAddress() { return toMailAddress; } public String getFromMailAddress() { return fromMailAddress; } public String getSubject() { return subject; } public String getReplyTo() { return replyTo; } public String getCcMailAddress() { return ccMailAddress; } public void setCcMailAddress(String ccMailAddress) { this.ccMailAddress = ccMailAddress; } public void setReplyTo(String replyTo) { this.replyTo = replyTo; } public boolean hasReplyTo() { return replyTo != null && !replyTo.isEmpty(); } public boolean hasCcMailAddress() { return ccMailAddress != null && !ccMailAddress.isEmpty(); } }
{ "content_hash": "cfa8b8603f547823ab5d298488967ef8", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 90, "avg_line_length": 25.169014084507044, "alnum_prop": 0.6390598768886402, "repo_name": "huihoo/olat", "id": "9bba9656715db87ffc3e0bc0c72243919bc0896f", "size": "2583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OLAT-LMS/src/main/java/org/olat/system/support/mail/service/CommonMailTO.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "24445" }, { "name": "AspectJ", "bytes": "36132" }, { "name": "CSS", "bytes": "2135670" }, { "name": "HTML", "bytes": "2950677" }, { "name": "Java", "bytes": "50804277" }, { "name": "JavaScript", "bytes": "31237972" }, { "name": "PLSQL", "bytes": "64492" }, { "name": "Perl", "bytes": "10717" }, { "name": "Shell", "bytes": "79994" }, { "name": "XSLT", "bytes": "186520" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "65970bab45b5285df117e6a3eea00a1d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "a56b8a9e92aa9b3d8e0f394d02bc2d408a307790", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Cyperus/Cyperus confertus/ Syn. Cyperus confertus gracillimus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.1 20151215//EN" "http://jats.nlm.nih.gov/publishing/1.1/JATS-journalpublishing1.dtd"> <article xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xlink="http://www.w3.org/1999/xlink" article-type="letter" dtd-version="1.1" specific-use="sps-1.9" xml:lang="en"> <front> <journal-meta> <journal-id journal-id-type="nlm-ta">J Bras Pneumol</journal-id> <journal-id journal-id-type="publisher-id">jbpneu</journal-id> <journal-title-group> <journal-title>Jornal Brasileiro de Pneumologia</journal-title> <abbrev-journal-title abbrev-type="publisher">J. bras. pneumol.</abbrev-journal-title> </journal-title-group> <issn pub-type="epub">1806-3756</issn> <publisher> <publisher-name>Sociedade Brasileira de Pneumologia e Tisiologia</publisher-name> </publisher> </journal-meta> <article-meta> <article-id specific-use="scielo-v3" pub-id-type="publisher-id">GZYfdY6BDfMGKwrXQYxsZFd</article-id> <article-id specific-use="scielo-v2" pub-id-type="publisher-id">S1806-37132022000201100</article-id> <article-id pub-id-type="doi">10.36416/1806-3756/e20220072</article-id> <article-id pub-id-type="other">01100</article-id> <article-categories> <subj-group subj-group-type="heading"> <subject>CORRESPONDENCE</subject> </subj-group> </article-categories> <title-group> <article-title>ELMO helmet for CPAP to treat COVID-19-related acute hypoxemic respiratory failure outside the ICU: aspects of/comments on its assembly and methodology</article-title> </title-group> <contrib-group> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0001-5259-1648</contrib-id> <name> <surname>Mazza</surname> <given-names>Mariano</given-names> </name> <xref ref-type="aff" rid="aff1"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-2523-9769</contrib-id> <name> <surname>Fiorentino</surname> <given-names>Giuseppe</given-names> </name> <xref ref-type="aff" rid="aff2"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0003-0571-2050</contrib-id> <name> <surname>Esquinas</surname> <given-names>Antonio M.</given-names> </name> <xref ref-type="aff" rid="aff3"> <sup>3</sup> </xref> </contrib> </contrib-group> <aff id="aff1"> <label>1</label> <institution content-type="original">. Unità Operativa Complessa di Pneumologia Semintensiva COVID, Azienda Ospedaliera Sant’Anna e San Sebastiano di Rilievo Nazionale e alta Specializzazione, Caserta, Italia.</institution> <institution content-type="orgdiv1">Unità Operativa Complessa di Pneumologia Semintensiva COVID</institution> <institution content-type="orgname">Azienda Ospedaliera Sant’Anna e San Sebastiano di Rilievo Nazionale e alta Specializzazione</institution> <addr-line> <city>Caserta</city> </addr-line> <country country="IT">Italia</country> </aff> <aff id="aff2"> <label>2</label> <institution content-type="original">. Unità Operativa Complessa di Fisiopatologia e Riabilitazione Respiratoria P.O. Monaldi, 1o Utsir Covid PO, Ospedale Cotugno, Azienda Ospedaliera dei Colli, Napoli, Italia.</institution> <institution content-type="orgdiv2">1o Utsir Covid PO</institution> <institution content-type="orgdiv1">Ospedale Cotugno</institution> <institution content-type="orgname">Azienda Ospedaliera dei Colli</institution> <addr-line> <city>Napoli</city> </addr-line> <country country="IT">Italia</country> </aff> <aff id="aff3"> <label>3</label> <institution content-type="original">. Intensive Care and Non Invasive Ventilatory Unit, Hospital General Universitario Jose M Morales Meseguer, Murcia, España.</institution> <institution content-type="orgdiv1">Intensive Care and Non Invasive Ventilatory Unit</institution> <institution content-type="orgname">Hospital General Universitario Jose M Morales Meseguer</institution> <addr-line> <city>Murcia</city> </addr-line> <country country="ES">España</country> </aff> <pub-date date-type="pub" publication-format="electronic"> <day>13</day> <month>05</month> <year>2022</year> </pub-date> <pub-date date-type="collection" publication-format="electronic"> <year>2022</year> </pub-date> <volume>48</volume> <issue>02</issue> <elocation-id>e20220072</elocation-id> <permissions> <license license-type="open-access" xlink:href="https://creativecommons.org/licenses/by-nc/4.0/" xml:lang="en"> <license-p>This is an open-access article distributed under the terms of the Creative Commons Attribution License</license-p> </license> </permissions> <counts> <fig-count count="0"/> <table-count count="0"/> <equation-count count="0"/> <ref-count count="6"/> </counts> </article-meta> </front> <body> <p>We have read with great interest the study by Tomaz et al.,<xref ref-type="bibr" rid="B1"><sup>1</sup></xref> which analyzes the clinical efficacy of a new model of a helmet-CPAP system, designated ELMOcpap, in COVID-19-related acute hypoxemic respiratory failure. We consider that that study published in the last issue of <italic>Jornal Brasileiro de Pneumologia</italic> represents a great advance regarding CPAP therapy, showing a new model of a helmet-CPAP device, and contributes to extend the use of such devices outside ICUs. However, we believe that there are some clinical and technical aspects that should be discussed.</p> <p>First, Table 1 <xref ref-type="bibr" rid="B1"><sup>1</sup></xref> shows that all patients were affected by alkalosis (pH &gt; 7.48) before starting therapy with the device, and the observed RR was not very high and not significantly different from that after its use (28.5 [24.5-34.0] vs. 26.5 [23.5-32.5] breaths/min; p = 0.866). We wonder if the authors considered the possibility of the presence of mixed alkalosis and if these data could be associated with successive helmet-CPAP setting adjustments. We think that this may also predispose patients to self-induced lung injury (P-SILI),<xref ref-type="bibr" rid="B2"><sup>2</sup></xref> and we recommend that future studies about ELMOcpap should evaluate, by means of bench or clinical trials, data regarding Vt measurements, ELMOcpap settings, and P-SILI prevention.<xref ref-type="bibr" rid="B3"><sup>3</sup></xref> </p> <p>Second, according to Figure 1 in that study,<xref ref-type="bibr" rid="B1"><sup>1</sup></xref> we observed that the authors have combined two humidification systems: an active humidifying jar system and a heat and moisture exchanger filter. We consider that this association could predispose to obstruction of the system by condensation, CPAP asynchrony, and, consequently, P-SILI,<xref ref-type="bibr" rid="B2"><sup>2</sup></xref> particularly in such patients. Referring to the fact that “None of the research team members or hospital staff acquired COVID-19 during the study,” it has not been stated in which way safety or diffusibility through the interface to prevent the spread of the virus was evaluated. Data about environmental air analysis would have been useful, so as to exclude that no one got infected only because the staff wore personal protective equipment and not because of interface security.</p> <p>Additionally, an important aspect for a future design could be the measurement of internal helmet gas volume, the use of antiviral filters both on the inspiratory and expiratory ports, and the implementation of an anti-suffocation valve.</p> <p>Lastly, we observed a great variability of total ELMOcpap therapy time, because the range of daily duration of the sessions was 60-1,230 min, and it is not clear whether defined criteria were established as a guideline, or whether the duration was dependent only on the patient; in addition, it is unclear whether other oxygen therapy options while ELMOcpap was not connected were applied. This is controversial if we consider the level of disease severity and gas exchange at admission showed in Table 2. <xref ref-type="bibr" rid="B1"><sup>1</sup></xref> We also wonder if the authors designed the ELMOcpap device for continuous noninvasive support application outside the ICU as well, considering that they conducted the study with patients with moderate to severe ARDS, which is evident in Figure 3,<xref ref-type="bibr" rid="B1"><sup>1</sup></xref> where we find values of Pa<sub>O2</sub>/Fi<sub>O2</sub> &lt; 150.</p> <p>Further clinical trials are needed to evaluate some methodological and technical aspects of this new helmet-CPAP system to be used outside ICUs.</p> </body> <back> <ref-list> <title>REFERENCES</title> <ref id="B1"> <label>1</label> <mixed-citation>1 Tomaz BS, Gomes GC, Lino JA, Menezes DGA, Soares JB, Furtado V, et al. ELMO, a new helmet interface for CPAP to treat COVID-19-related acute hypoxemic respiratory failure outside the ICU: a feasibility study. J Bras Pneumol. 2022;48(1):e20210349. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.36416/1806-3756/e20210349">https://doi.org/10.36416/1806-3756/e20210349</ext-link> </mixed-citation> <element-citation publication-type="journal"> <person-group person-group-type="author"> <name> <surname>Tomaz</surname> <given-names>BS</given-names> </name> <name> <surname>Gomes</surname> <given-names>GC</given-names> </name> <name> <surname>Lino</surname> <given-names>JA</given-names> </name> <name> <surname>Menezes</surname> <given-names>DGA</given-names> </name> <name> <surname>Soares</surname> <given-names>JB</given-names> </name> <name> <surname>Furtado</surname> <given-names>V</given-names> </name> </person-group> <article-title>ELMO, a new helmet interface for CPAP to treat COVID-19-related acute hypoxemic respiratory failure outside the ICU a feasibility study</article-title> <source>J Bras Pneumol</source> <year>2022</year> <volume>48</volume> <issue>1</issue> <elocation-id>e20210349</elocation-id> <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.36416/1806-3756/e20210349">https://doi.org/10.36416/1806-3756/e20210349</ext-link> </element-citation> </ref> <ref id="B2"> <label>2</label> <mixed-citation>2 Akoumianaki E, Vaporidi K, Georgopoulos D. The Injurious Effects of Elevated or Nonelevated Respiratory Rate during Mechanical Ventilation. Am J Respir Crit Care Med. 2019;199(2):149-157. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1164/rccm.201804-0726CI">https://doi.org/10.1164/rccm.201804-0726CI</ext-link> </mixed-citation> <element-citation publication-type="journal"> <person-group person-group-type="author"> <name> <surname>Akoumianaki</surname> <given-names>E</given-names> </name> <name> <surname>Vaporidi</surname> <given-names>K</given-names> </name> <name> <surname>Georgopoulos</surname> <given-names>D</given-names> </name> </person-group> <article-title>The Injurious Effects of Elevated or Nonelevated Respiratory Rate during Mechanical Ventilation</article-title> <source>Am J Respir Crit Care Med</source> <year>2019</year> <volume>199</volume> <issue>2</issue> <fpage>149</fpage> <lpage>157</lpage> <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1164/rccm.201804-0726CI">https://doi.org/10.1164/rccm.201804-0726CI</ext-link> </element-citation> </ref> <ref id="B3"> <label>3</label> <mixed-citation>3 Chiappero C, Misseri G, Mattei A, Ippolito M, Albera C, Pivetta E, Effectiveness and safety of a new helmet CPAP configuration allowing tidal volume monitoring in patients with COVID-19. Pulmonology. 2021;S2531-0437(21)00135-5. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1016/j.pulmoe.2021.06.012">https://doi.org/10.1016/j.pulmoe.2021.06.012</ext-link> </mixed-citation> <element-citation publication-type="journal"> <person-group person-group-type="author"> <name> <surname>Chiappero</surname> <given-names>C</given-names> </name> <name> <surname>Misseri</surname> <given-names>G</given-names> </name> <name> <surname>Mattei</surname> <given-names>A</given-names> </name> <name> <surname>Ippolito</surname> <given-names>M</given-names> </name> <name> <surname>Albera</surname> <given-names>C</given-names> </name> <name> <surname>Pivetta</surname> <given-names>E</given-names> </name> </person-group> <article-title>Effectiveness and safety of a new helmet CPAP configuration allowing tidal volume monitoring in patients with COVID-19</article-title> <source>Pulmonology</source> <year>2021</year> <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1016/j.pulmoe.2021.06.012">https://doi.org/10.1016/j.pulmoe.2021.06.012</ext-link> </element-citation> </ref> </ref-list> </back> <sub-article article-type="reply" id="s1" xml:lang="en"> <front-stub> <article-categories> <subj-group subj-group-type="heading"> <subject>Authors’ reply</subject> </subj-group> </article-categories> <title-group> <article-title>Authors’ reply</article-title> </title-group> <contrib-group> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-2523-7296</contrib-id> <name> <surname>Tomaz</surname> <given-names>Betina Santos</given-names> </name> <xref ref-type="aff" rid="aff1n"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-9342-7737</contrib-id> <name> <surname>Gomes</surname> <given-names>Gabriela Carvalho</given-names> </name> <xref ref-type="aff" rid="aff2n"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0003-0968-4800</contrib-id> <name> <surname>Lino</surname> <given-names>Juliana Arcanjo</given-names> </name> <xref ref-type="aff" rid="aff2n"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0001-5546-5591</contrib-id> <name> <surname>Menezes</surname> <given-names>David Guabiraba Abitbol de</given-names> </name> <xref ref-type="aff" rid="aff2n"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-2940-6309</contrib-id> <name> <surname>Soares</surname> <given-names>Jorge Barbosa</given-names> </name> <xref ref-type="aff" rid="aff2n"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0001-8721-4308</contrib-id> <name> <surname>Furtado</surname> <given-names>Vasco</given-names> </name> <xref ref-type="aff" rid="aff3n"> <sup>3</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-1555-049X</contrib-id> <name> <surname>Soares</surname> <given-names>Luiz</given-names> <suffix>Júnior</suffix> </name> <xref ref-type="aff" rid="aff1n"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-9597-3512</contrib-id> <name> <surname>Farias</surname> <given-names>Maria do Socorro Quintino</given-names> </name> <xref ref-type="aff" rid="aff4n"> <sup>4</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-4575-3386</contrib-id> <name> <surname>Lima</surname> <given-names>Debora Lilian Nascimento</given-names> </name> <xref ref-type="aff" rid="aff4n"> <sup>4</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-4414-3164</contrib-id> <name> <surname>Pereira</surname> <given-names>Eanes Delgado Barros</given-names> </name> <xref ref-type="aff" rid="aff1n"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-6002-0084</contrib-id> <name> <surname>Holanda</surname> <given-names>Marcelo Alcantara</given-names> </name> <xref ref-type="aff" rid="aff1n"> <sup>1</sup> </xref> <xref ref-type="aff" rid="aff5n"> <sup>5</sup> </xref> </contrib> </contrib-group> <aff id="aff1n"> <label>1</label> <institution content-type="original">. Universidade Federal do Ceará - UFC - Fortaleza (CE) Brasil.</institution> <institution content-type="orgname">Universidade Federal do Ceará</institution> <addr-line> <city>Fortaleza</city> <state>CE</state> </addr-line> <country country="BR">Brazil</country> </aff> <aff id="aff2n"> <label>2</label> <institution content-type="original">. Fundação Cearense de Apoio ao Desenvolvimento Científico e Tecnológico - FUNCAP - Fortaleza (CE) Brasil.</institution> <institution content-type="orgname">Fundação Cearense de Apoio ao Desenvolvimento Científico e Tecnológico</institution> <addr-line> <city>Fortaleza</city> <state>CE</state> </addr-line> <country country="BR">Brasil</country> </aff> <aff id="aff3n"> <label>3</label> <institution content-type="original">. Universidade de Fortaleza - UNIFOR - Fortaleza (CE) Brasil.</institution> <institution content-type="orgname">Universidade de Fortaleza</institution> <addr-line> <city>Fortaleza</city> <state>CE</state> </addr-line> <country country="BR">Brazil</country> </aff> <aff id="aff4n"> <label>4</label> <institution content-type="original">. Hospital Estadual Leonardo da Vinci, Fortaleza (CE) Brasil.</institution> <institution content-type="orgname">Hospital Estadual Leonardo da Vinci</institution> <addr-line> <city>Fortaleza</city> <state>CE</state> </addr-line> <country country="BR">Brasil</country> </aff> <aff id="aff5n"> <label>5</label> <institution content-type="original">. Escola de Saúde Pública do Ceará Paulo Marcelo Martins Rodrigues, Fortaleza (CE) Brasil.</institution> <institution content-type="orgname">Escola de Saúde Pública do Ceará Paulo Marcelo Martins Rodrigues</institution> <addr-line> <city>Fortaleza</city> <state>CE</state> </addr-line> <country country="BR">Brasil</country> </aff> </front-stub> <body> <p>We thank the authors for their comments and questions regarding our study entitled “ELMO, a new helmet interface for CPAP to treat COVID-19-related acute hypoxemic respiratory failure outside the ICU: a feasibility study.”</p> <p>Concerning the first point mentioned by the authors, we agree with the observation regarding the coexistence of metabolic alkalosis in at least 8 of the 10 patients whose arterial blood gas analysis at admission, before the use of ELMO, showed base excess values above 2.0 mEq/L. A possible cause would be the pharmacological therapy with corticosteroids routinely used in patients before their inclusion in the study. Therefore, metabolic alkalosis is not related to the sequential application of CPAP with the helmet.</p> <p>The fact that some patients presented with hyperventilation in accordance with the respiratory alkalosis component is compatible with an increase in the respiratory drive, and, yes, that is possibly associated with an increase in transpulmonary pressure, a mechanism related to the occurrence of self-inflicted lung injury. In the absence of transpulmonary pressure measurement, we believe that Vt monitoring in devices such as the ELMO can identify those patients with a greater propensity to self-inflicted lung injury. The effects of the application of CPAP by helmet or another interface on Vt require investigation in clinical trials in the future, evaluating its relationship with the progression of lung injury or not. It is worth noting that, experimentally, the application of CPAP can attenuate the variation of transpulmonary pressure in ARDS.<xref ref-type="bibr" rid="B1n"><sup>1</sup></xref> </p> <p>Concerning the second point, it is worth explaining the following: first, the heat and moisture exchanger filter used in the ELMO inspiratory branch serves only as a “damper” for the noise generated by the high flow of gases and not for its primary function (heat/humidity); second, the gas passage through the unheated jar was just a practical resource to offer the mixture of gases without raising their temperature. We even observed that this fact prevented condensation inside the helmet and, in volunteers, it was associated with a better sensation of comfort during the use of ELMOcpap due to the slightly cooler temperature around the head and face.<xref ref-type="bibr" rid="B2n"><sup>2</sup></xref> Because the CPAP mechanism has a continuous flow of gases, there is no occurrence of asynchrony, unlike helmets coupled to mechanical ventilators, and current trigger mechanisms are not designed for this interface.</p> <p>The safety of the interface regarding the diffusibility of the virus was not the object of our study since it has already been reported in the literature<xref ref-type="bibr" rid="B3n"><sup>3</sup></xref>; the helmet interface has been considered safe and leakage is negligible when compared with face masks. The description of the absence of COVID-19 cases among researchers should not be seen as proof of this concept; however, we thought it best to report the data for recording purposes.</p> <p>We agree with the idea of continuing to improve the design of the ELMO helmet on several fronts, including the improvement of anti-suffocation mechanisms, the coupling of filters in the gas inlet and outlet, the optimization of its internal volume to reduce the predisposition to CO<sub>2</sub> rebreathing, the monitoring of respiratory variables, such as RR, Vt, and Fio<sub>2</sub>, as well as of intra-helmet pressure level, humidity, temperature, and others.</p> <p>Given the innovation of the characteristics of that study with this type of device, our group considered that the total time of therapy would be the maximum tolerated by the patient, and, in agreement with the medical team, we alternated it with the only oxygen therapy then available (reservoir mask), because a high-flow nasal cannula was not available. The degree of comfort observed was great, and the large-scale use after the feasibility study revealed cases of continuous use of ELMOcpap for periods as long as 12-24 h (unpublished data), which is in line with other reports in the literature.</p> </body> <back> <ref-list> <title>REFERENCES</title> <ref id="B1n"> <label>1</label> <mixed-citation>1 Yoshida T, Grieco DL, Brochard L, Fujino Y. Patient self-inflicted lung injury and positive end-expiratory pressure for safe spontaneous breathing. Curr Opin Crit Care. 2020;26(1):59-65. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1097/MCC.0000000000000691">https://doi.org/10.1097/MCC.0000000000000691</ext-link> </mixed-citation> <element-citation publication-type="journal"> <person-group person-group-type="author"> <name> <surname>Yoshida</surname> <given-names>T</given-names> </name> <name> <surname>Grieco</surname> <given-names>DL</given-names> </name> <name> <surname>Brochard</surname> <given-names>L</given-names> </name> <name> <surname>Fujino</surname> <given-names>Y</given-names> </name> </person-group> <article-title>Patient self-inflicted lung injury and positive end-expiratory pressure for safe spontaneous breathing</article-title> <source>Curr Opin Crit Care</source> <year>2020</year> <volume>26</volume> <issue>1</issue> <fpage>59</fpage> <lpage>65</lpage> <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1097/MCC.0000000000000691">https://doi.org/10.1097/MCC.0000000000000691</ext-link> </element-citation> </ref> <ref id="B2n"> <label>2</label> <mixed-citation>2 Holanda MA, Tomaz BS, Menezes DGA, Lino JA, Gomes GC. ELMO 1.0: a helmet interface for CPAP and high-flow oxygen delivery. J Bras Pneumol. 2021;47(3):e20200590. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.36416/1806-3756/e20200590">https://doi.org/10.36416/1806-3756/e20200590</ext-link>.</mixed-citation> <element-citation publication-type="journal"> <person-group person-group-type="author"> <name> <surname>Holanda</surname> <given-names>MA</given-names> </name> <name> <surname>Tomaz</surname> <given-names>BS</given-names> </name> <name> <surname>Menezes</surname> <given-names>DGA</given-names> </name> <name> <surname>Lino</surname> <given-names>JA</given-names> </name> <name> <surname>Gomes</surname> <given-names>GC</given-names> </name> </person-group> <article-title>ELMO 1 0: a helmet interface for CPAP and high-flow oxygen delivery</article-title> <source>J Bras Pneumol</source> <year>2021</year> <volume>47</volume> <issue>3</issue> <elocation-id>e20200590</elocation-id> <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.36416/1806-3756/e20200590">https://doi.org/10.36416/1806-3756/e20200590</ext-link> </element-citation> </ref> <ref id="B3n"> <label>3</label> <mixed-citation>3 Ferioli M, Cisternino C, Leo V, Pisani L, Palange P, Nava S. Protecting healthcare workers from SARS-CoV-2 infection: practical indications. Eur Respir Rev. 2020;29(155):200068. <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1183/16000617.0068-2020">https://doi.org/10.1183/16000617.0068-2020</ext-link> </mixed-citation> <element-citation publication-type="journal"> <person-group person-group-type="author"> <name> <surname>Ferioli</surname> <given-names>M</given-names> </name> <name> <surname>Cisternino</surname> <given-names>C</given-names> </name> <name> <surname>Leo</surname> <given-names>V</given-names> </name> <name> <surname>Pisani</surname> <given-names>L</given-names> </name> <name> <surname>Palange</surname> <given-names>P</given-names> </name> <name> <surname>Nava</surname> <given-names>S</given-names> </name> </person-group> <article-title>Protecting healthcare workers from SARS-CoV-2 infection practical indications</article-title> <source>Eur Respir Rev</source> <year>2020</year> <volume>29</volume> <issue>155</issue> <fpage>200068</fpage> <lpage>200068</lpage> <ext-link ext-link-type="uri" xlink:href="https://doi.org/10.1183/16000617.0068-2020">https://doi.org/10.1183/16000617.0068-2020</ext-link> </element-citation> </ref> </ref-list> </back> </sub-article> <sub-article article-type="translation" id="s2" xml:lang="pt"> <front-stub> <article-categories> <subj-group subj-group-type="heading"> <subject>CORRESPONDÊNCIA</subject> </subj-group> </article-categories> <title-group> <article-title>Capacete ELMO para CPAP no tratamento da insuficiência respiratória aguda hipoxêmica por COVID-19 fora da UTI: aspectos/comentários sobre sua montagem e metodologia</article-title> </title-group> <contrib-group> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0001-5259-1648</contrib-id> <name> <surname>Mazza</surname> <given-names>Mariano</given-names> </name> <xref ref-type="aff" rid="aff1s"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-2523-9769</contrib-id> <name> <surname>Fiorentino</surname> <given-names>Giuseppe</given-names> </name> <xref ref-type="aff" rid="aff2s"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0003-0571-2050</contrib-id> <name> <surname>Esquinas</surname> <given-names>Antonio M.</given-names> </name> <xref ref-type="aff" rid="aff3s"> <sup>3</sup> </xref> </contrib> </contrib-group> <aff id="aff1s"> <label>1</label> <institution content-type="original">. Unità Operativa Complessa di Pneumologia Semintensiva COVID, Azienda Ospedaliera Sant’Anna e San Sebastiano di Rilievo Nazionale e alta Specializzazione, Caserta, Italia.</institution> </aff> <aff id="aff2s"> <label>2</label> <institution content-type="original">. Unità Operativa Complessa di Fisiopatologia e Riabilitazione Respiratoria P.O. Monaldi, 1o Utsir Covid PO, Ospedale Cotugno, Azienda Ospedaliera dei Colli, Napoli, Italia.</institution> </aff> <aff id="aff3s"> <label>3</label> <institution content-type="original">. Intensive Care and Non Invasive Ventilatory Unit, Hospital General Universitario Jose M Morales Meseguer, Murcia, España.</institution> </aff> </front-stub> <body> <p>Lemos com grande interesse o estudo de Tomaz et al.,<xref ref-type="bibr" rid="B1"><sup>1</sup></xref> que analisa a eficácia clínica de um novo modelo de sistema de CPAP com capacete, denominado ELMOcpap, na insuficiência respiratória aguda hipoxêmica por COVID-19. Consideramos que esse estudo publicado no último número do Jornal Brasileiro de Pneumologia representa um grande avanço na terapia com CPAP, apresentando um novo modelo de dispositivo de CPAP com capacete, e contribui para a ampliação do uso de tais dispositivos fora das UTIs. No entanto, acreditamos que existem alguns aspectos clínicos e técnicos que devem ser discutidos.</p> <p>Em primeiro lugar, a Tabela 1 <xref ref-type="bibr" rid="B1"><sup>1</sup></xref> mostra que todos os pacientes já apresentavam alcalose (pH &gt; 7,48) antes de iniciar a terapia com o dispositivo, e a FR observada não foi muito alta nem significativamente diferente daquela observada após seu uso (28,5 [24,5-34,0] vs. 26,5 [23,5-32,5] ciclos/min; p = 0,866). Perguntamo-nos se os autores consideraram a possibilidade da presença de alcalose mista e se esses dados poderiam estar associados a sucessivos ajustes das configurações de CPAP com capacete. Achamos que isso também pode predispor os pacientes à <italic>self-induced lung injury</italic> (P-SILI, lesão pulmonar autoinduzida),<xref ref-type="bibr" rid="B2"><sup>2</sup></xref> e recomendamos que futuros estudos sobre o ELMOcpap avaliem, por meio de ensaios de bancada ou clínicos, dados sobre medidas de Vt, configurações de ELMOcpap, e a prevenção da P-SILI.<xref ref-type="bibr" rid="B3"><sup>3</sup></xref> </p> <p>Em segundo lugar, de acordo com a Figura 1 desse estudo,<xref ref-type="bibr" rid="B1"><sup>1</sup></xref> observamos que os autores combinaram dois sistemas de umidificação: um sistema de jarra umidificadora ativo e um filtro trocador de calor e umidade. Consideramos que essa associação poderia predispor à obstrução do sistema por condensação, assincronia de CPAP e, consequentemente, P-SILI,<xref ref-type="bibr" rid="B2"><sup>2</sup></xref><sup>)</sup> principalmente em tais pacientes. Quanto ao fato de que “Nenhum dos membros da equipe de pesquisa ou da equipe do hospital contraiu COVID-19 durante o estudo”, não foi mencionado de que forma foi avaliada a segurança ou difusibilidade através da interface para evitar a propagação do vírus. Dados sobre a análise do ar ambiente teriam sido úteis, de forma a excluir que ninguém se infectou apenas porque a equipe do hospital usava equipamentos de proteção individual e não por causa da segurança da interface.</p> <p>Além disso, um aspecto importante para um futuro projeto poderia ser a medida do volume de gás interno do capacete, o uso de filtros antivirais nos ramos inspiratório e expiratório e a implantação de uma válvula anti-asfixia.</p> <p>Por fim, observamos uma grande variabilidade do tempo total de terapia com o ELMOcpap, pois a variação da duração diária das sessões foi de 60-1.230 min, e não está claro se foram estabelecidos critérios definidos como diretriz, ou se a duração dependeu apenas do paciente; além disso, não está claro se foram aplicadas outras opções de oxigenoterapia enquanto o ELMOcpap não estava conectado. Isso é controverso se considerarmos o nível de gravidade da doença e as trocas gasosas na admissão mostrados na Tabela 2. Também nos perguntamos se os autores projetaram o dispositivo ELMOcpap para aplicação de suporte não invasivo contínuo também fora da UTI, considerando que eles realizaram o estudo com pacientes com SDRA moderada a grave, o que fica evidente na Figura 3,<xref ref-type="bibr" rid="B1"><sup>1</sup></xref> onde encontramos valores de Pa<sub>O2</sub>/Fi<sub>O2</sub> &lt; 150.</p> <p>Mais ensaios clínicos são necessários para avaliar alguns aspectos metodológicos e técnicos desse novo sistema de CPAP com capacete para uso fora da UTI.</p> </body> <sub-article article-type="reply" id="s3" xml:lang="pt"> <front-stub> <article-categories> <subj-group subj-group-type="heading"> <subject>Resposta dos autores</subject> </subj-group> </article-categories> <title-group> <article-title>Resposta dos autores</article-title> </title-group> <contrib-group> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-2523-7296</contrib-id> <name> <surname>Tomaz</surname> <given-names>Betina Santos</given-names> </name> <xref ref-type="aff" rid="aff1ns"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-9342-7737</contrib-id> <name> <surname>Gomes</surname> <given-names>Gabriela Carvalho</given-names> </name> <xref ref-type="aff" rid="aff2ns"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0003-0968-4800</contrib-id> <name> <surname>Lino</surname> <given-names>Juliana Arcanjo</given-names> </name> <xref ref-type="aff" rid="aff2ns"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0001-5546-5591</contrib-id> <name> <surname>Menezes</surname> <given-names>David Guabiraba Abitbol de</given-names> </name> <xref ref-type="aff" rid="aff2ns"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-2940-6309</contrib-id> <name> <surname>Soares</surname> <given-names>Jorge Barbosa</given-names> </name> <xref ref-type="aff" rid="aff2ns"> <sup>2</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0001-8721-4308</contrib-id> <name> <surname>Furtado</surname> <given-names>Vasco</given-names> </name> <xref ref-type="aff" rid="aff3ns"> <sup>3</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-1555-049X</contrib-id> <name> <surname>Soares</surname> <given-names>Luiz</given-names> <suffix>Júnior</suffix> </name> <xref ref-type="aff" rid="aff1ns"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-9597-3512</contrib-id> <name> <surname>Farias</surname> <given-names>Maria do Socorro Quintino</given-names> </name> <xref ref-type="aff" rid="aff4ns"> <sup>4</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-4575-3386</contrib-id> <name> <surname>Lima</surname> <given-names>Debora Lilian Nascimento</given-names> </name> <xref ref-type="aff" rid="aff4ns"> <sup>4</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-4414-3164</contrib-id> <name> <surname>Pereira</surname> <given-names>Eanes Delgado Barros</given-names> </name> <xref ref-type="aff" rid="aff1ns"> <sup>1</sup> </xref> </contrib> <contrib contrib-type="author"> <contrib-id contrib-id-type="orcid">0000-0002-6002-0084</contrib-id> <name> <surname>Holanda</surname> <given-names>Marcelo Alcantara</given-names> </name> <xref ref-type="aff" rid="aff1ns"> <sup>1</sup> </xref> <xref ref-type="aff" rid="aff5ns"> <sup>5</sup> </xref> </contrib> </contrib-group> <aff id="aff1ns"> <label>1</label> <institution content-type="original">. Universidade Federal do Ceará - UFC - Fortaleza (CE) Brasil.</institution> </aff> <aff id="aff2ns"> <label>2</label> <institution content-type="original">. Fundação Cearense de Apoio ao Desenvolvimento Científico e Tecnológico - FUNCAP - Fortaleza (CE) Brasil.</institution> </aff> <aff id="aff3ns"> <label>3</label> <institution content-type="original">. Universidade de Fortaleza - UNIFOR - Fortaleza (CE) Brasil.</institution> </aff> <aff id="aff4ns"> <label>4</label> <institution content-type="original">. Hospital Estadual Leonardo da Vinci, Fortaleza (CE) Brasil.</institution> </aff> <aff id="aff5ns"> <label>5</label> <institution content-type="original">. Escola de Saúde Pública do Ceará Paulo Marcelo Martins Rodrigues, Fortaleza (CE) Brasil.</institution> </aff> </front-stub> <body> <p>Agradecemos aos autores os comentários e perguntas sobre nosso estudo intitulado “ELMO, uma nova interface do tipo capacete para CPAP no tratamento da insuficiência respiratória aguda hipoxêmica por COVID-19 fora da UTI: estudo de viabilidade”.</p> <p>No tocante ao primeiro ponto citado pelos autores, concordamos com a observação sobre a coexistência de alcalose metabólica em pelo menos 8 dos 10 pacientes cuja gasometria arterial na admissão, antes do uso do ELMO, mostrou valores de excesso de bases acima de 2,0 mEq/L. Uma possível causa seria a terapia farmacológica com corticosteroides utilizada rotineiramente nos pacientes antes de sua inclusão no estudo. Portanto, a alcalose metabólica não está relacionada à aplicação sequencial de CPAP com o capacete.</p> <p>O fato de alguns pacientes apresentarem hiperventilação segundo o componente alcalose respiratória é compatível com o aumento do <italic>drive</italic> respiratório, e, sim, isso possivelmente está associado ao aumento da pressão transpulmonar, mecanismo relacionado à ocorrência de lesão pulmonar autoinfligida. Na ausência da medição da pressão transpulmonar, acreditamos que a monitorização do Vt em aparelhos como o ELMO possa identificar aqueles pacientes com maior propensão à lesão pulmonar autoinfligida. Os efeitos da aplicação de CPAP por capacete ou outra interface no Vt requerem investigação em ensaios clínicos no futuro, avaliando sua relação com a progressão da lesão pulmonar ou não. Vale ressaltar que, experimentalmente, a aplicação de CPAP pode atenuar a variação da pressão transpulmonar na SDRA.<xref ref-type="bibr" rid="B1n"><sup>1</sup></xref> </p> <p>No tocante ao segundo ponto, vale esclarecer o seguinte: primeiro, o filtro trocador de calor e umidade utilizado no ramo inspiratório do ELMO serve apenas como “abafador” para o ruído gerado pelo alto fluxo de gases e não para sua função primária (calor/umidade); segundo, a passagem dos gases pela jarra não aquecida era apenas um recurso prático para oferecer a mistura de gases sem elevar sua temperatura. Observamos inclusive que esse fato impediu a condensação no interior do capacete e, em voluntários, esteve associado a uma maior sensação de conforto durante o uso do ELMOcpap em virtude da temperatura um pouco mais fria ao redor da cabeça e do rosto.<xref ref-type="bibr" rid="B2n"><sup>2</sup></xref> Como o mecanismo de CPAP tem um fluxo contínuo de gases, não há ocorrência de assincronia, diferentemente dos capacetes acoplados a ventiladores mecânicos, e os mecanismos de disparo atuais não são projetados para essa interface.</p> <p>A segurança da interface em relação à difusibilidade do vírus não foi objeto do nosso estudo, pois já foi relatada na literatura<xref ref-type="bibr" rid="B3n"><sup>3</sup></xref>; a interface do tipo capacete foi considerada segura e o vazamento é insignificante em comparação com as máscaras faciais. A descrição da ausência de casos de COVID-19 entre os pesquisadores não deve ser vista como prova desse conceito; no entanto, achamos melhor relatar os dados para fins de registro.</p> <p>Concordamos com a ideia de continuar a melhorar o desenho do capacete ELMO em várias frentes, incluindo a melhoria dos mecanismos antiasfixia, o acoplamento de filtros na entrada e saída de gases, a otimização do seu volume interno para reduzir a predisposição à reinalação de CO<sub>2</sub>, a monitorização de variáveis respiratórias, como FR, Vt e Fio<sub>2</sub>, bem como do nível de pressão, da umidade e da temperatura dentro do capacete, e outros.</p> <p>Dada a inovação das características do estudo com esse tipo de dispositivo, nosso grupo considerou que o tempo total de terapia seria o máximo tolerado pelo paciente, e, em acordo com a equipe médica, o alternamos com a única oxigenoterapia então disponível (máscara com reservatório), pois não havia disponibilidade de cânula nasal de alto fluxo. O grau de conforto observado foi grande, e o uso em larga escala após o estudo de viabilidade revelou casos de uso contínuo do ELMOcpap por períodos de até 12-24 h (dados não publicados), o que está de acordo com outros relatos na literatura.</p> </body> </sub-article> </sub-article> </article>
{ "content_hash": "86af3a9fef2489ed1d91d553cbb467fa", "timestamp": "", "source": "github", "line_count": 752, "max_line_length": 984, "avg_line_length": 62.712765957446805, "alnum_prop": 0.6398854961832061, "repo_name": "scieloorg/packtools", "id": "4170216c5eef81dd9c8da292465e6e62481ff468", "size": "47443", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/fixtures/htmlgenerator/sub-article_translation_with_sub-article_reply/GZYfdY6BDfMGKwrXQYxsZFd.xml", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "11822" }, { "name": "Dockerfile", "bytes": "982" }, { "name": "HTML", "bytes": "34245" }, { "name": "Makefile", "bytes": "2421" }, { "name": "Python", "bytes": "2928346" }, { "name": "Shell", "bytes": "1508" }, { "name": "XSLT", "bytes": "273710" } ], "symlink_target": "" }
package de.alpharogroup.lang.model; import static org.testng.AssertJUnit.assertNotNull; import org.meanbean.test.BeanTester; import org.meanbean.test.Configuration; import org.meanbean.test.ConfigurationBuilder; import org.testng.annotations.Test; import de.alpharogroup.collections.array.ArrayFactory; import de.alpharogroup.evaluate.object.verifier.ContractVerifier; import de.alpharogroup.meanbean.factories.ObjectArrayFactory; /** * The unit test class for the class {@link PropertiesKeyAndParameters}. */ public class PropertiesKeyAndParametersTest { /** * Test method for {@link PropertiesKeyAndParameters} constructors */ @Test public final void testConstructors() { PropertiesKeyAndParameters model = new PropertiesKeyAndParameters(); assertNotNull(model); /** The key. */ String key = ""; /** The parameters. */ Object[] parameters = ArrayFactory.newArray("foo", "bar"); model = new PropertiesKeyAndParameters(key, parameters); assertNotNull(model); model = PropertiesKeyAndParameters.builder().build(); assertNotNull(model); } /** * Test method for {@link PropertiesKeyAndParameters#equals(Object)} , * {@link PropertiesKeyAndParameters#hashCode()} and * {@link PropertiesKeyAndParameters#toString()} */ @Test public void verifyEqualsHashcodeAndToStringContracts() { ContractVerifier.of(PropertiesKeyAndParameters.class).verify(); } /** * Test method for {@link PropertiesKeyAndParameters} */ @Test public void testWithBeanTester() { final Configuration configuration = new ConfigurationBuilder() .overrideFactory("parameters", new ObjectArrayFactory()).build(); final BeanTester beanTester = new BeanTester(); beanTester.addCustomConfiguration(PropertiesKeyAndParameters.class, configuration); beanTester.testBean(PropertiesKeyAndParameters.class); } }
{ "content_hash": "041e50f95444eee980b7cb10cc155499", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 85, "avg_line_length": 29.19047619047619, "alnum_prop": 0.7721587819467102, "repo_name": "lightblueseas/jcommons-lang", "id": "08d1cf97f7b5d3a6de538529b7effae118c8a6bf", "size": "2984", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/java/de/alpharogroup/lang/model/PropertiesKeyAndParametersTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1236" }, { "name": "HTML", "bytes": "3195" }, { "name": "Java", "bytes": "169133" }, { "name": "JavaScript", "bytes": "3483" } ], "symlink_target": "" }
import charlsFactory from '@cornerstonejs/codec-charls/dist/charlswasm_decode.js'; // import charlsFactory from '@cornerstonejs/codec-charls/dist/debug/charlswasm.js'; // Webpack asset/resource copies this to our output folder import charlsWasm from '@cornerstonejs/codec-charls/dist/charlswasm_decode.wasm'; // import charlsWasm from '@cornerstonejs/codec-charls/dist/debug/charlswasm.wasm'; const local = { codec: undefined, decoder: undefined, decodeConfig: {}, }; function getExceptionMessage(exception) { return typeof exception === 'number' ? local.codec.getExceptionMessage(exception) : exception; } export function initialize(decodeConfig) { local.decodeConfig = decodeConfig; if (local.codec) { return Promise.resolve(); } const charlsModule = charlsFactory({ locateFile: (f) => { if (f.endsWith('.wasm')) { return charlsWasm; } return f; }, }); return new Promise((resolve, reject) => { charlsModule.then((instance) => { local.codec = instance; local.decoder = new instance.JpegLSDecoder(); resolve(); }, reject); }); } /** * * @param {*} compressedImageFrame * @param {object} imageInfo * @param {boolean} imageInfo.signed - (pixelRepresentation === 1) */ async function decodeAsync(compressedImageFrame, imageInfo) { try { await initialize(); const decoder = local.decoder; // get pointer to the source/encoded bit stream buffer in WASM memory // that can hold the encoded bitstream const encodedBufferInWASM = decoder.getEncodedBuffer( compressedImageFrame.length ); // copy the encoded bitstream into WASM memory buffer encodedBufferInWASM.set(compressedImageFrame); // decode it decoder.decode(); // get information about the decoded image const frameInfo = decoder.getFrameInfo(); const interleaveMode = decoder.getInterleaveMode(); const nearLossless = decoder.getNearLossless(); // get the decoded pixels const decodedPixelsInWASM = decoder.getDecodedBuffer(); const encodedImageInfo = { columns: frameInfo.width, rows: frameInfo.height, bitsPerPixel: frameInfo.bitsPerSample, signed: imageInfo.signed, bytesPerPixel: imageInfo.bytesPerPixel, componentsPerPixel: frameInfo.componentCount, }; const pixelData = getPixelData( frameInfo, decodedPixelsInWASM, imageInfo.signed ); const encodeOptions = { nearLossless, interleaveMode, frameInfo, }; // local.codec.doLeakCheck(); return { ...imageInfo, pixelData, imageInfo: encodedImageInfo, encodeOptions, ...encodeOptions, ...encodedImageInfo, }; } catch (error) { // Handle cases where WASM throws an error internally, and it only gives JS a number // See https://emscripten.org/docs/porting/Debugging.html#handling-c-exceptions-from-javascript // TODO: Copy to other codecs as well throw getExceptionMessage(error); } } function getPixelData(frameInfo, decodedBuffer, signed) { if (frameInfo.bitsPerSample > 8) { if (signed) { return new Int16Array( decodedBuffer.buffer, decodedBuffer.byteOffset, decodedBuffer.byteLength / 2 ); } return new Uint16Array( decodedBuffer.buffer, decodedBuffer.byteOffset, decodedBuffer.byteLength / 2 ); } if (signed) { return new Int8Array( decodedBuffer.buffer, decodedBuffer.byteOffset, decodedBuffer.byteLength ); } return new Uint8Array( decodedBuffer.buffer, decodedBuffer.byteOffset, decodedBuffer.byteLength ); } export default decodeAsync;
{ "content_hash": "26f15e79e1c8438e21f7945a14caf666", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 99, "avg_line_length": 25.18918918918919, "alnum_prop": 0.6786480686695279, "repo_name": "chafey/cornerstoneWADOImageLoader", "id": "111f69578bca50baaec41faf5d3c3ec00471cfd2", "size": "3728", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/shared/decoders/decodeJPEGLS.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "33689" }, { "name": "JavaScript", "bytes": "183358" }, { "name": "Shell", "bytes": "1428" } ], "symlink_target": "" }
"""Cement core foundation module.""" import os import sys import signal import platform from time import sleep from ..core import backend, exc, log, config, plugin from ..core import output, extension, arg, controller, meta, cache, mail from ..core.handler import HandlerManager from ..core.hook import HookManager from ..utils.misc import is_true, minimal_logger from ..utils import fs # The `imp` module is deprecated in favor of `importlib` in 3.4, but it # wasn't introduced until 3.1. Finally, reload is a builtin on Python < 3 pyver = sys.version_info if pyver[0] >= 3 and pyver[1] >= 4: # pragma: nocover # noqa from importlib import reload as reload_module # pragma: nocover # noqa elif pyver[0] >= 3: # pragma: nocover # noqa from imp import reload as reload_module # pragma: nocover # noqa else: # pragma: nocover # noqa reload_module = reload # pragma: nocover # noqa LOG = minimal_logger(__name__) if platform.system() == 'Windows': SIGNALS = [signal.SIGTERM, signal.SIGINT] # pragma: nocover else: SIGNALS = [signal.SIGTERM, signal.SIGINT, signal.SIGHUP] def add_handler_override_options(app): """ This is a ``post_setup`` hook that adds the handler override options to the argument parser :param app: The application object. """ if app._meta.handler_override_options is None: return for i in app._meta.handler_override_options: if i not in app.handler.list_types(): LOG.debug("interface '%s'" % i + " is not defined, can not override handlers") continue if len(app.handler.list(i)) > 1: handlers = [] for h in app.handler.list(i): handlers.append(h()) choices = [x._meta.label for x in handlers if x._meta.overridable is True] # don't display the option if no handlers are overridable if not len(choices) > 0: LOG.debug("no handlers are overridable within the " + "%s interface" % i) continue # override things that we need to control argument_kw = app._meta.handler_override_options[i][1] argument_kw['dest'] = '%s_handler_override' % i argument_kw['action'] = 'store' argument_kw['choices'] = choices app.args.add_argument( *app._meta.handler_override_options[i][0], **app._meta.handler_override_options[i][1] ) def handler_override(app): """ This is a ``post_argument_parsing`` hook that overrides a configured handler if defined in ``CementApp.Meta.handler_override_options`` and the option is passed at command line with a valid handler label. :param app: The application object. """ if app._meta.handler_override_options is None: return for i in app._meta.handler_override_options.keys(): if not hasattr(app.pargs, '%s_handler_override' % i): continue elif getattr(app.pargs, '%s_handler_override' % i) is None: continue else: # get the argument value from command line argument = getattr(app.pargs, '%s_handler_override' % i) setattr(app._meta, '%s_handler' % i, argument) # and then re-setup the handler getattr(app, '_setup_%s_handler' % i)() def cement_signal_handler(signum, frame): """ Catch a signal, run the 'signal' hook, and then raise an exception allowing the app to handle logic elsewhere. :param signum: The signal number :param frame: The signal frame. :raises: cement.core.exc.CaughtSignal """ LOG.debug('Caught signal %s' % signum) # FIXME: Maybe this isn't ideal... purhaps make # CementApp.Meta.signal_handler a decorator that take the app object # and wraps/returns the actually signal handler? for f_global in frame.f_globals.values(): if isinstance(f_global, CementApp): app = f_global for res in app.hook.run('signal', app, signum, frame): pass # pragma: nocover raise exc.CaughtSignal(signum, frame) class CementApp(meta.MetaMixin): """ The primary class to build applications from. Usage: The following is the simplest CementApp: .. code-block:: python from cement.core.foundation import CementApp with CementApp('helloworld') as app: app.run() Alternatively, the above could be written as: .. code-block:: python from cement.core.foundation import CementApp app = foundation.CementApp('helloworld') app.setup() app.run() app.close() A more advanced example looks like: .. code-block:: python from cement.core.foundation import CementApp from cement.core.controller import CementBaseController, expose class MyController(CementBaseController): class Meta: label = 'base' arguments = [ ( ['-f', '--foo'], dict(help='Notorious foo option') ), ] config_defaults = dict( debug=False, some_config_param='some_value', ) @expose(help='This is the default command', hide=True) def default(self): print('Hello World') class MyApp(CementApp): class Meta: label = 'helloworld' extensions = ['daemon','json',] base_controller = MyController with MyApp() as app: app.run() """ class Meta: """ Application meta-data (can also be passed as keyword arguments to the parent class). """ label = None """ The name of the application. This should be the common name as you would see and use at the command line. For example 'helloworld', or 'my-awesome-app'. """ debug = False """ Used internally, and should not be used by developers. This is set to `True` if `--debug` is passed at command line.""" exit_on_close = False """ Whether or not to call ``sys.exit()`` when ``close()`` is called. The default is ``False``, however if ``True`` then the app will call ``sys.exit(X)`` where ``X`` is ``self.exit_code``. """ config_extension = '.conf' """ Extension used to identify application and plugin configuration files. """ config_files = None """ List of config files to parse. Note: Though Meta.config_section defaults to None, Cement will set this to a default list based on Meta.label (or in other words, the name of the application). This will equate to: .. code-block:: python ['/etc/<app_label>/<app_label>.conf', '~/.<app_label>.conf', '~/.<app_label>/config'] Files are loaded in order, and have precedence in order. Therefore, the last configuration loaded has precedence (and overwrites settings loaded from previous configuration files). Note that ``.conf`` is the default config file extension, defined by ``CementApp.Meta.config_extension``. """ plugins = [] """ A list of plugins to load. This is generally considered bad practice since plugins should be dynamically enabled/disabled via a plugin config file. """ plugin_config_dirs = None """ A list of directory paths where plugin config files can be found. Files must end in ``.conf`` (or the extension defined by ``CementApp.Meta.config_extension``) or they will be ignored. Note: Though ``CementApp.Meta.plugin_config_dirs`` is ``None``, Cement will set this to a default list based on ``CementApp.Meta.label``. This will equate to: .. code-block:: python ['/etc/<app_label>/plugins.d', '~/.<app_label>/plugin.d'] Files are loaded in order, and have precedence in that order. Therefore, the last configuration loaded has precedence (and overwrites settings loaded from previous configuration files). """ plugin_config_dir = None """ A directory path where plugin config files can be found. Files must end in ``.conf`` (or the extension defined by ``CementApp.Meta.config_extension``) or they will be ignored. By default, this setting is also overridden by the ``[<app_label>] -> plugin_config_dir`` config setting parsed in any of the application configuration files. If set, this item will be **appended** to ``CementApp.Meta.plugin_config_dirs`` so that it's settings will have presedence over other configuration files. In general, this setting should not be defined by the developer, as it is primarily used to allow the end-user to define a ``plugin_config_dir`` without completely trumping the hard-coded list of default ``plugin_config_dirs`` defined by the app/developer. """ plugin_bootstrap = None """ A python package (dotted import path) where plugin code can be loaded from. This is generally something like ``myapp.plugins`` where a plugin file would live at ``myapp/plugins/myplugin.py``. This provides a facility for applications that have builtin plugins that ship with the applications source code and live in the same Python module. Note: Though the meta default is ``None``, Cement will set this to ``<app_label>.plugins`` if not set. """ plugin_dirs = None """ A list of directory paths where plugin code (modules) can be loaded from. Note: Though ``CementApp.Meta.plugin_dirs`` is None, Cement will set this to a default list based on ``CementApp.Meta.label`` if not set. This will equate to: .. code-block:: python ['~/.<app_label>/plugins', '/usr/lib/<app_label>/plugins'] Modules are attempted to be loaded in order, and will stop loading once a plugin is successfully loaded from a directory. Therefore this is the oposite of configuration file loading, in that here the first has precedence. """ plugin_dir = None """ A directory path where plugin code (modules) can be loaded from. By default, this setting is also overridden by the ``[<app_label>] -> plugin_dir`` config setting parsed in any of the application configuration files. If set, this item will be **prepended** to ``Meta.plugin_dirs`` so that a users defined ``plugin_dir`` has precedence over others. In general, this setting should not be defined by the developer, as it is primarily used to allow the end-user to define a ``plugin_dir`` without completely trumping the hard-coded list of default ``plugin_dirs`` defined by the app/developer. """ argv = None """ A list of arguments to use for parsing command line arguments and options. Note: Though Meta.argv defaults to None, Cement will set this to ``list(sys.argv[1:])`` if no argv is set in Meta during setup(). """ arguments_override_config = False """ A boolean to toggle whether command line arguments should override configuration values if the argument name matches the config key. I.e. --foo=bar would override config['myapp']['foo']. This is different from ``override_arguments`` in that if ``arguments_override_config`` is ``True``, then all arguments will override (you don't have to list them all). """ override_arguments = ['debug'] """ List of arguments that override their configuration counter-part. For example, if ``--debug`` is passed (and it's config value is ``debug``) then the ``debug`` key of all configuration sections will be overridden by the value of the command line option (``True`` in this example). This is different from ``arguments_override_config`` in that this is a selective list of specific arguments to override the config with (and not all arguments that match the config). This list will take affect whether ``arguments_override_config`` is ``True`` or ``False``. """ core_handler_override_options = dict( output=(['-o'], dict(help='output handler')), ) """ Similar to ``CementApp.Meta.handler_override_options`` but these are the core defaults required by Cement. This dictionary can be overridden by ``CementApp.Meta.handler_override_options`` (when they are merged together). """ handler_override_options = {} """ Dictionary of handler override options that will be added to the argument parser, and allow the end-user to override handlers. Useful for interfaces that have multiple uses within the same application (for example: Output Handler (json, yaml, etc) or maybe a Cloud Provider Handler (rackspace, digitalocean, amazon, etc). This dictionary will merge with ``CementApp.Meta.core_handler_override_options`` but this one has precedence. Dictionary Format: .. code-block:: text <interface_name> = (option_arguments, help_text) See ``CementApp.Meta.core_handler_override_options`` for an example of what this should look like. Note, if set to ``None`` then no options will be defined, and the ``CementApp.Meta.core_meta_override_options`` will be ignore (not recommended as some extensions rely on this feature). """ config_section = None """ The base configuration section for the application. Note: Though Meta.config_section defaults to None, Cement will set this to the value of Meta.label (or in other words, the name of the application). """ config_defaults = None """Default configuration dictionary. Must be of type 'dict'.""" meta_defaults = {} """ Default metadata dictionary used to pass high level options from the application down to handlers at the point they are registered by the framework **if the handler has not already been instantiated**. For example, if requiring the ``json`` extension, you might want to override ``JsonOutputHandler.Meta.json_module`` with ``ujson`` by doing the following .. code-block:: python from cement.core.foundation import CementApp from cement.utils.misc import init_defaults META = init_defaults('output.json') META['output.json']['json_module'] = 'ujson' class MyApp(CementApp): class Meta: label = 'myapp' extensions = ['json'] meta_defaults = META """ catch_signals = SIGNALS """ List of signals to catch, and raise exc.CaughtSignal for. Can be set to None to disable signal handling. """ signal_handler = cement_signal_handler """A function that is called to handle any caught signals.""" config_handler = 'configparser' """ A handler class that implements the IConfig interface. """ mail_handler = 'dummy' """ A handler class that implements the IMail interface. """ extension_handler = 'cement' """ A handler class that implements the IExtension interface. """ log_handler = 'logging' """ A handler class that implements the ILog interface. """ plugin_handler = 'cement' """ A handler class that implements the IPlugin interface. """ argument_handler = 'argparse' """ A handler class that implements the IArgument interface. """ output_handler = 'dummy' """ A handler class that implements the IOutput interface. """ cache_handler = None """ A handler class that implements the ICache interface. """ base_controller = None """ This is the base application controller. If a controller is set, runtime operations are passed to the controller for command dispatch and argument parsing when CementApp.run() is called. Note that cement will automatically set the `base_controller` to a registered controller whose label is 'base' (only if `base_controller` is not currently set). """ extensions = [] """List of additional framework extensions to load.""" bootstrap = None """ A bootstrapping module to load after app creation, and before app.setup() is called. This is useful for larger applications that need to offload their bootstrapping code such as registering hooks/handlers/etc to another file. This must be a dotted python module path. I.e. 'myapp.bootstrap' (myapp/bootstrap.py). Cement will then import the module, and if the module has a 'load()' function, that will also be called. Essentially, this is the same as an extension or plugin, but as a facility for the application itself to bootstrap 'hardcoded' application code. It is also called before plugins are loaded. """ core_extensions = [ 'cement.ext.ext_dummy', 'cement.ext.ext_smtp', 'cement.ext.ext_plugin', 'cement.ext.ext_configparser', 'cement.ext.ext_logging', 'cement.ext.ext_argparse', ] """ List of Cement core extensions. These are generally required by Cement and should only be modified if you know what you're doing. Use 'extensions' to add to this list, rather than overriding core extensions. That said if you want to prune down your application, you can remove core extensions if they are not necessary (for example if using your own log handler extension you likely don't want/need LoggingLogHandler to be registered). """ core_meta_override = [ 'debug', 'plugin_config_dir', 'plugin_dir', 'ignore_deprecation_warnings', 'template_dir', 'mail_handler', 'cache_handler', 'log_handler', 'output_handler', ] """ List of meta options that can/will be overridden by config options of the '[base]' config section (where [base] is the base configuration section of the application which is determined by Meta.config_section but defaults to Meta.label). These overrides are required by the framework to function properly and should not be used by end user (developers) unless you really know what you're doing. To add your own extended meta overrides please use 'meta_override'. """ meta_override = [] """ List of meta options that can/will be overridden by config options of the '[base]' config section (where [base] is the base configuration section of the application which is determined by Meta.config_section but defaults to Meta.label). """ ignore_deprecation_warnings = False """Disable deprecation warnings from being logged by Cement.""" template_module = None """ A python package (dotted import path) where template files can be loaded from. This is generally something like ``myapp.templates`` where a plugin file would live at ``myapp/templates/mytemplate.txt``. Templates are first loaded from ``CementApp.Meta.template_dirs``, and and secondly from ``CementApp.Meta.template_module``. The ``template_dirs`` setting has presedence. """ template_dirs = None """ A list of directory paths where template files can be loaded from. Note: Though ``CementApp.Meta.template_dirs`` defaults to ``None``, Cement will set this to a default list based on ``CementApp.Meta.label``. This will equate to: .. code-block:: python ['~/.<app_label>/templates', '/usr/lib/<app_label>/templates'] Templates are attempted to be loaded in order, and will stop loading once a template is successfully loaded from a directory. """ template_dir = None """ A directory path where template files can be loaded from. By default, this setting is also overridden by the ``[<app_label>] -> template_dir`` config setting parsed in any of the application configuration files . If set, this item will be **prepended** to ``CementApp.Meta.template_dirs`` (giving it precedence over other ``template_dirs``. """ framework_logging = True """ Whether or not to enable Cement framework logging. This is separate from the application log, and is generally used for debugging issues with the framework and/or extensions primarily in development. This option is overridden by the environment variable `CEMENT_FRAMEWORK_LOGGING`. Therefore, if in production you do not want the Cement framework log enabled, you can set this option to ``False`` but override it in your environment by doing something like ``export CEMENT_FRAMEWORK_LOGGING=1`` in your shell whenever you need it enabled. """ define_hooks = [] """ List of hook definitions (label). Will be passed to ``self.hook.define(<hook_label>)``. Must be a list of strings. I.e. ``['my_custom_hook', 'some_other_hook']`` """ hooks = [] """ List of hooks to register when the app is created. Will be passed to ``self.hook.register(<hook_label>, <hook_func>)``. Must be a list of tuples in the form of ``(<hook_label>, <hook_func>)``. I.e. ``[('post_argument_parsing', my_hook_func)]``. """ define_handlers = [] """ List of interfaces classes to define handlers. Must be a list of uninstantiated interface classes. I.e. ``['MyCustomInterface', 'SomeOtherInterface']`` """ handlers = [] """ List of handler classes to register. Will be passed to ``handler.register(<handler_class>)``. Must be a list of uninstantiated handler classes. I.e. ``[MyCustomHandler, SomeOtherHandler]`` """ use_backend_globals = True """ This is a backward compatibility feature. Cement 2.x.x relies on several global variables hidden in ``cement.core.backend`` used for things like storing hooks and handlers. Future versions of Cement will no longer use this mechanism, however in order to maintain backward compatibility this is still the default. By disabling this feature allows multiple instances of CementApp to be created from within the same runtime space without clobbering eachothers hooks/handers/etc. Be warned that use of third-party extensions might break as they were built using backend globals, and probably have no idea this feature has changed or exists. """ alternative_module_mapping = {} """ EXPERIMENTAL FEATURE: This is an experimental feature added in Cement 2.9.x and may or may not be removed in future versions of Cement. Dictionary of alternative, **drop-in** replacement modules to use selectively throughout the application, framework, or extensions. Developers can optionally use the ``CementApp.__import__()`` method to import simple modules, and if that module exists in this mapping it will import the alternative library in it's place. This is a low-level feature, and may not produce the results you are expecting. It's purpose is to allow the developer to replace specific modules at a high level. Example: For an application wanting to use ``ujson`` in place of ``json``, the developer could set the following: .. code-block:: python alternative_module_mapping = { 'json' : 'ujson', } In the app, you would then load ``json`` as: .. code-block:: python _json = app.__import__('json') _json.dumps(data) Obviously, the replacement module **must be** a drop-in replace and function the same. """ def __init__(self, label=None, **kw): super(CementApp, self).__init__(**kw) # disable framework logging? if 'CEMENT_FRAMEWORK_LOGGING' not in os.environ.keys(): if self._meta.framework_logging is True: os.environ['CEMENT_FRAMEWORK_LOGGING'] = '1' else: os.environ['CEMENT_FRAMEWORK_LOGGING'] = '0' # for convenience we translate this to _meta if label: self._meta.label = label self._validate_label() self._loaded_bootstrap = None self._parsed_args = None self._last_rendered = None self._extended_members = [] self.__saved_stdout__ = None self.__saved_stderr__ = None self.__retry_hooks__ = [] self.handler = None self.hook = None self.exit_code = 0 self.ext = None self.config = None self.log = None self.plugin = None self.args = None self.output = None self.controller = None self.cache = None self.mail = None # setup argv... this has to happen before lay_cement() if self._meta.argv is None: self._meta.argv = list(sys.argv[1:]) # hack for command line --debug if '--debug' in self.argv: self._meta.debug = True # setup the cement framework self._lay_cement() @property def debug(self): """ Returns boolean based on whether ``--debug`` was passed at command line or set via the application's configuration file. :returns: boolean """ return self._meta.debug @property def argv(self): """The arguments list that will be used when self.run() is called.""" return self._meta.argv def extend(self, member_name, member_object): """ Extend the CementApp() object with additional functions/classes such as 'app.my_custom_function()', etc. It provides an interface for extensions to provide functionality that travel along with the application object. :param member_name: The name to attach the object to. :type member_name: ``str`` :param member_object: The function or class object to attach to CementApp(). :raises: cement.core.exc.FrameworkError """ if hasattr(self, member_name): raise exc.FrameworkError("App member '%s' already exists!" % member_name) LOG.debug("extending appication with '.%s' (%s)" % (member_name, member_object)) setattr(self, member_name, member_object) if member_name not in self._extended_members: self._extended_members.append(member_name) def _validate_label(self): if not self._meta.label: raise exc.FrameworkError("Application name missing.") # validate the name is ok ok = ['_', '-'] for char in self._meta.label: if char in ok: continue if not char.isalnum(): raise exc.FrameworkError( "App label can only contain alpha-numeric, dashes, " + "or underscores." ) def setup(self): """ This function wraps all '_setup' actons in one call. It is called before self.run(), allowing the application to be _setup but not executed (possibly letting the developer perform other actions before full execution.). All handlers should be instantiated and callable after setup is complete. """ LOG.debug("now setting up the '%s' application" % self._meta.label) if self._meta.bootstrap is not None: LOG.debug("importing bootstrap code from %s" % self._meta.bootstrap) if self._meta.bootstrap not in sys.modules \ or self._loaded_bootstrap is None: __import__(self._meta.bootstrap, globals(), locals(), [], 0) if hasattr(sys.modules[self._meta.bootstrap], 'load'): sys.modules[self._meta.bootstrap].load(self) self._loaded_bootstrap = sys.modules[self._meta.bootstrap] else: reload_module(self._loaded_bootstrap) for res in self.hook.run('pre_setup', self): pass self._setup_extension_handler() self._setup_signals() self._setup_config_handler() self._setup_mail_handler() self._setup_cache_handler() self._setup_log_handler() self._setup_plugin_handler() self._setup_arg_handler() self._setup_output_handler() self._setup_controllers() for hook_spec in self.__retry_hooks__: self.hook.register(*hook_spec) for res in self.hook.run('post_setup', self): pass def run(self): """ This function wraps everything together (after self._setup() is called) to run the application. :returns: Returns the result of the executed controller function if a base controller is set and a controller function is called, otherwise ``None`` if no controller dispatched or no controller function was called. """ return_val = None LOG.debug('running pre_run hook') for res in self.hook.run('pre_run', self): pass # If controller exists, then dispatch it if self.controller: return_val = self.controller._dispatch() else: self._parse_args() LOG.debug('running post_run hook') for res in self.hook.run('post_run', self): pass return return_val def run_forever(self, interval=1, tb=True): """ This function wraps ``run()`` with an endless while loop. If any exception is encountered it will be logged and then the application will be reloaded. :param interval: The number of seconds to sleep before reloading the the appliction. :param tb: Whether or not to print traceback if exception occurs. :returns: It should never return. """ if tb is True: import traceback while True: LOG.debug('inside run_forever() eternal loop') try: self.run() except Exception as e: self.log.fatal('Caught Exception: %s' % e) if tb is True: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception( exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout ) sleep(interval) self.reload() def reload(self): """ This function is useful for reloading a running applications, for example to reload configuration settings, etc. :returns: ``None`` """ LOG.debug('reloading the %s application' % self._meta.label) for member in self._extended_members: delattr(self, member) self._extended_members = [] self.handler.__handlers__ = {} self.hook.__hooks__ = {} self._lay_cement() self.setup() def close(self, code=None): """ Close the application. This runs the ``pre_close`` and ``post_close`` hooks allowing plugins/extensions/etc to cleanup at the end of program execution. :param code: An exit code to exit with (``int``), if ``None`` is passed then exit with whatever ``self.exit_code`` is currently set to. Note: ``sys.exit()`` will only be called if ``CementApp.Meta.exit_on_close==True``. """ for res in self.hook.run('pre_close', self): pass LOG.debug("closing the %s application" % self._meta.label) for res in self.hook.run('post_close', self): pass for member in self._extended_members: delattr(self, member) if code is not None: assert type(code) == int, \ "Invalid exit status code (must be integer)" self.exit_code = code if self._meta.exit_on_close is True: sys.exit(self.exit_code) def render(self, data, template=None, out=sys.stdout, **kw): """ This is a simple wrapper around self.output.render() which simply returns an empty string if no self.output handler is defined. :param data: The data dictionary to render. :param template: The template to render to. Default: None (some output handlers do not use templates). :param out: A file like object (sys.stdout, or actual file). Set to ``None`` is no output is desired (just render and return). Default: sys.stdout """ for res in self.hook.run('pre_render', self, data): if not type(res) is dict: LOG.debug("pre_render hook did not return a dict().") else: data = res kw['template'] = template if self.output is None: LOG.debug('render() called, but no output handler defined.') out_text = '' else: out_text = self.output.render(data, **kw) for res in self.hook.run('post_render', self, out_text): if not type(res) is str: LOG.debug('post_render hook did not return a str()') else: out_text = str(res) if out is not None and not hasattr(out, 'write'): raise TypeError("Argument 'out' must be a 'file' like object") elif out is not None and out_text is None: LOG.debug('render() called but output text is None') elif out: out.write(out_text) self._last_rendered = (data, out_text) return out_text def get_last_rendered(self): """ DEPRECATION WARNING: This function is deprecated as of Cement 2.1.3 in favor of the `self.last_rendered` property, and will be removed in future versions of Cement. Return the (data, output_text) tuple of the last time self.render() was called. :returns: tuple (data, output_text) """ if not is_true(self._meta.ignore_deprecation_warnings): self.log.warning("Cement Deprecation Warning: " + "CementApp.get_last_rendered() has been " + "deprecated, and will be removed in future " + "versions of Cement. You should use the " + "CementApp.last_rendered property instead.") return self._last_rendered @property def last_rendered(self): """ Return the (data, output_text) tuple of the last time self.render() was called. :returns: tuple (data, output_text) """ return self._last_rendered @property def pargs(self): """ Returns the `parsed_args` object as returned by self.args.parse(). """ return self._parsed_args def add_arg(self, *args, **kw): """A shortcut for self.args.add_argument.""" self.args.add_argument(*args, **kw) def _suppress_output(self): if self._meta.debug is True: LOG.debug('not suppressing console output because of debug mode') return LOG.debug('suppressing all console output') self.__saved_stdout__ = sys.stdout self.__saved_stderr__ = sys.stderr sys.stdout = open(os.devnull, 'w') sys.stderr = open(os.devnull, 'w') def _unsuppress_output(self): LOG.debug('unsuppressing all console output') sys.stdout = self.__saved_stdout__ sys.stderr = self.__saved_stderr__ def _lay_cement(self): """Initialize the framework.""" LOG.debug("laying cement for the '%s' application" % self._meta.label) if '--debug' in self._meta.argv: self._meta.debug = True elif '--quiet' in self._meta.argv: self._suppress_output() # Forward/Backward compat, see Issue #311 if self._meta.use_backend_globals is True: backend.__hooks__ = {} backend.__handlers__ = {} self.handler = HandlerManager(use_backend_globals=True) self.hook = HookManager(use_backend_globals=True) else: self.handler = HandlerManager(use_backend_globals=False) self.hook = HookManager(use_backend_globals=False) # define framework hooks self.hook.define('pre_setup') self.hook.define('post_setup') self.hook.define('pre_run') self.hook.define('post_run') self.hook.define('pre_argument_parsing') self.hook.define('post_argument_parsing') self.hook.define('pre_close') self.hook.define('post_close') self.hook.define('signal') self.hook.define('pre_render') self.hook.define('post_render') # define application hooks from meta for label in self._meta.define_hooks: self.hook.define(label) # register some built-in framework hooks self.hook.register('post_setup', add_handler_override_options, weight=-99) self.hook.register('post_argument_parsing', handler_override, weight=-99) # register application hooks from meta. the hooks listed in # CementApp.Meta.hooks are registered here, so obviously can not be # for any hooks other than the builtin framework hooks that we just # defined here (above). Anything that we couldn't register here # will be retried after setup self.__retry_hooks__ = [] for hook_spec in self._meta.hooks: if not self.hook.defined(hook_spec[0]): LOG.debug('hook %s not defined, will retry after setup' % hook_spec[0]) self.__retry_hooks__.append(hook_spec) else: self.hook.register(*hook_spec) # define and register handlers self.handler.define(extension.IExtension) self.handler.define(log.ILog) self.handler.define(config.IConfig) self.handler.define(mail.IMail) self.handler.define(plugin.IPlugin) self.handler.define(output.IOutput) self.handler.define(arg.IArgument) self.handler.define(controller.IController) self.handler.define(cache.ICache) # define application handlers for interface_class in self._meta.define_handlers: self.handler.define(interface_class) # extension handler is the only thing that can't be loaded... as, # well, an extension. ;) self.handler.register(extension.CementExtensionHandler) # register application handlers for handler_class in self._meta.handlers: self.handler.register(handler_class) def _parse_args(self): for res in self.hook.run('pre_argument_parsing', self): pass self._parsed_args = self.args.parse(self.argv) if self._meta.arguments_override_config is True: for member in dir(self._parsed_args): if member and member.startswith('_'): continue # don't override config values for options that weren't passed # or in otherwords are None elif getattr(self._parsed_args, member) is None: continue for section in self.config.get_sections(): if member in self.config.keys(section): self.config.set(section, member, getattr(self._parsed_args, member)) for member in self._meta.override_arguments: for section in self.config.get_sections(): if member in self.config.keys(section): self.config.set(section, member, getattr(self._parsed_args, member)) for res in self.hook.run('post_argument_parsing', self): pass def catch_signal(self, signum): """ Add ``signum`` to the list of signals to catch and handle by Cement. :param signum: The signal number to catch. See Python ``signal`` library. """ LOG.debug("adding signal handler %s for signal %s" % ( self._meta.signal_handler, signum) ) signal.signal(signum, self._meta.signal_handler) def _setup_signals(self): if self._meta.catch_signals is None: LOG.debug("catch_signals=None... not handling any signals") return for signum in self._meta.catch_signals: self.catch_signal(signum) def _resolve_handler(self, handler_type, handler_def, raise_error=True): meta_defaults = {} if type(handler_def) == str: _meta_label = "%s.%s" % (handler_type, handler_def) meta_defaults = self._meta.meta_defaults.get(_meta_label, {}) elif hasattr(handler_def, 'Meta'): _meta_label = "%s.%s" % (handler_type, handler_def.Meta.label) meta_defaults = self._meta.meta_defaults.get(_meta_label, {}) han = self.handler.resolve(handler_type, handler_def, raise_error=raise_error, meta_defaults=meta_defaults) if han is not None: han._setup(self) return han def _setup_extension_handler(self): LOG.debug("setting up %s.extension handler" % self._meta.label) self.ext = self._resolve_handler('extension', self._meta.extension_handler) self.ext.load_extensions(self._meta.core_extensions) self.ext.load_extensions(self._meta.extensions) def _setup_config_handler(self): LOG.debug("setting up %s.config handler" % self._meta.label) self.config = self._resolve_handler('config', self._meta.config_handler) if self._meta.config_section is None: self._meta.config_section = self._meta.label self.config.add_section(self._meta.config_section) if self._meta.config_defaults is not None: self.config.merge(self._meta.config_defaults) if self._meta.config_files is None: label = self._meta.label ext = self._meta.config_extension self._meta.config_files = [ os.path.join('/', 'etc', label, '%s%s' % (label, ext)), os.path.join(fs.HOME_DIR, '.%s%s' % (label, ext)), os.path.join(fs.HOME_DIR, '.%s' % label, 'config'), ] for _file in self._meta.config_files: self.config.parse_file(_file) self.validate_config() # hack for --debug if '--debug' in self.argv or self._meta.debug is True: self.config.set(self._meta.config_section, 'debug', True) # override select Meta via config base_dict = self.config.get_section_dict(self._meta.config_section) for key in base_dict: if key in self._meta.core_meta_override or \ key in self._meta.meta_override: # kind of a hack for core_meta_override if key in ['debug']: setattr(self._meta, key, is_true(base_dict[key])) else: setattr(self._meta, key, base_dict[key]) # load extensions from configuraton file if 'extensions' in self.config.keys(self._meta.label): exts = self.config.get(self._meta.label, 'extensions') # convert a comma-separated string to a list if type(exts) is str: ext_list = exts.split(',') # clean up extra space if they had it inbetween commas ext_list = [x.strip() for x in ext_list] # set the new extensions value in the config self.config.set(self._meta.label, 'extensions', ext_list) # otherwise, if it's a list (ConfigObj?) elif type(exts) is list: ext_list = exts for ext in ext_list: # load the extension self.ext.load_extension(ext) # add to meta data self._meta.extensions.append(ext) def _setup_mail_handler(self): LOG.debug("setting up %s.mail handler" % self._meta.label) self.mail = self._resolve_handler('mail', self._meta.mail_handler) def _setup_log_handler(self): LOG.debug("setting up %s.log handler" % self._meta.label) self.log = self._resolve_handler('log', self._meta.log_handler) def _setup_plugin_handler(self): LOG.debug("setting up %s.plugin handler" % self._meta.label) label = self._meta.label # plugin config dirs if self._meta.plugin_config_dirs is None: self._meta.plugin_config_dirs = [ '/etc/%s/plugins.d/' % self._meta.label, os.path.join(fs.HOME_DIR, '.%s' % label, 'plugins.d'), ] config_dir = self._meta.plugin_config_dir if config_dir is not None: if config_dir not in self._meta.plugin_config_dirs: # append so that this config has precedence self._meta.plugin_config_dirs.append(config_dir) # plugin dirs if self._meta.plugin_dirs is None: self._meta.plugin_dirs = [ os.path.join(fs.HOME_DIR, '.%s' % label, 'plugins'), '/usr/lib/%s/plugins' % self._meta.label, ] plugin_dir = self._meta.plugin_dir if plugin_dir is not None: if plugin_dir not in self._meta.plugin_dirs: # insert so that this dir has precedence self._meta.plugin_dirs.insert(0, plugin_dir) # plugin bootstrap if self._meta.plugin_bootstrap is None: self._meta.plugin_bootstrap = '%s.plugins' % self._meta.label self.plugin = self._resolve_handler('plugin', self._meta.plugin_handler) self.plugin.load_plugins(self._meta.plugins) self.plugin.load_plugins(self.plugin.get_enabled_plugins()) def _setup_output_handler(self): if self._meta.output_handler is None: LOG.debug("no output handler defined, skipping.") return label = self._meta.label LOG.debug("setting up %s.output handler" % self._meta.label) self.output = self._resolve_handler('output', self._meta.output_handler, raise_error=False) # template module if self._meta.template_module is None: self._meta.template_module = '%s.templates' % label # template dirs if self._meta.template_dirs is None: self._meta.template_dirs = [] paths = [ os.path.join(fs.HOME_DIR, '.%s' % label, 'templates'), '/usr/lib/%s/templates' % label, ] for path in paths: self.add_template_dir(path) template_dir = self._meta.template_dir if template_dir is not None: if template_dir not in self._meta.template_dirs: # insert so that this dir has precedence self._meta.template_dirs.insert(0, template_dir) def _setup_cache_handler(self): if self._meta.cache_handler is None: LOG.debug("no cache handler defined, skipping.") return LOG.debug("setting up %s.cache handler" % self._meta.label) self.cache = self._resolve_handler('cache', self._meta.cache_handler, raise_error=False) def _setup_arg_handler(self): LOG.debug("setting up %s.arg handler" % self._meta.label) self.args = self._resolve_handler('argument', self._meta.argument_handler) self.args.prog = self._meta.label self.args.add_argument('--debug', dest='debug', action='store_true', help='toggle debug output') self.args.add_argument('--quiet', dest='suppress_output', action='store_true', help='suppress all output') # merge handler override meta data if self._meta.handler_override_options is not None: # fucking long names... fuck. anyway, merge the core handler # override options with developer defined options core = self._meta.core_handler_override_options.copy() dev = self._meta.handler_override_options.copy() core.update(dev) self._meta.handler_override_options = core def _setup_controllers(self): LOG.debug("setting up application controllers") if self._meta.base_controller is not None: cntr = self._resolve_handler('controller', self._meta.base_controller) self.controller = cntr self._meta.base_controller = self.controller elif self._meta.base_controller is None: if self.handler.registered('controller', 'base'): self.controller = self._resolve_handler('controller', 'base') self._meta.base_controller = self.controller # This is necessary for some backend usage if self._meta.base_controller is not None: if self._meta.base_controller._meta.label != 'base': raise exc.FrameworkError("Base controllers must have " + "a label of 'base'.") def validate_config(self): """ Validate application config settings. Usage: .. code-block:: python import os from cement.core import foundation class MyApp(foundation.CementApp): class Meta: label = 'myapp' def validate_config(self): super(MyApp, self).validate_config() # test that the log file directory exist, if not create it logdir = os.path.dirname(self.config.get('log', 'file')) if not os.path.exists(logdir): os.makedirs(logdir) """ pass def add_template_dir(self, path): """ Append a directory path to the list of template directories to parse for templates. :param path: Directory path that contains template files. Usage: .. code-block:: python app.add_template_dir('/path/to/my/templates') """ path = fs.abspath(path) if path not in self._meta.template_dirs: self._meta.template_dirs.append(path) def remove_template_dir(self, path): """ Remove a directory path from the list of template directories to parse for templates. :param path: Directory path that contains template files. Usage: .. code-block:: python app.remove_template_dir('/path/to/my/templates') """ path = fs.abspath(path) if path in self._meta.template_dirs: self._meta.template_dirs.remove(path) def __import__(self, obj, from_module=None): # EXPERIMENTAL == UNDOCUMENTED mapping = self._meta.alternative_module_mapping if from_module is not None: _from = mapping.get(from_module, from_module) _loaded = __import__(_from, globals(), locals(), [obj], 0) return getattr(_loaded, obj) else: obj = mapping.get(obj, obj) _loaded = __import__(obj, globals(), locals(), [], 0) return _loaded def __enter__(self): self.setup() return self def __exit__(self, exc_type, exc_value, exc_traceback): # only close the app if there are no unhandled exceptions if exc_type is None: self.close()
{ "content_hash": "44c2b54f6b4dbaab65936df7406b58af", "timestamp": "", "source": "github", "line_count": 1503, "max_line_length": 79, "avg_line_length": 36.19028609447771, "alnum_prop": 0.5793102180387543, "repo_name": "akhilman/cement", "id": "68ba7f4a6eaa1a53d74718028fc60fac5c934072", "size": "54394", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cement/core/foundation.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "186" }, { "name": "Makefile", "bytes": "317" }, { "name": "PowerShell", "bytes": "2184" }, { "name": "Python", "bytes": "512585" }, { "name": "Shell", "bytes": "1964" } ], "symlink_target": "" }
struct AcceleratedSurfaceMsg_BufferPresented_Params; struct GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params; struct GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params; struct GpuHostMsg_AcceleratedSurfaceRelease_Params; namespace gfx { class GLSurface; } namespace gpu { class GpuScheduler; class PreemptionFlag; namespace gles2 { class GLES2Decoder; } } namespace content { class GpuChannelManager; class GpuCommandBufferStub; // The GPU process is agnostic as to how it displays results. On some platforms // it renders directly to window. On others it renders offscreen and transports // the results to the browser process to display. This file provides a simple // framework for making the offscreen path seem more like the onscreen path. // // The ImageTransportSurface class defines an simple interface for events that // should be responded to. The factory returns an offscreen surface that looks // a lot like an onscreen surface to the GPU process. // // The ImageTransportSurfaceHelper provides some glue to the outside world: // making sure outside events reach the ImageTransportSurface and // allowing the ImageTransportSurface to send events to the outside world. class ImageTransportSurface { public: ImageTransportSurface(); virtual void OnBufferPresented( const AcceleratedSurfaceMsg_BufferPresented_Params& params) = 0; virtual void OnResizeViewACK() = 0; virtual void OnResize(gfx::Size size) = 0; // Creates the appropriate surface depending on the GL implementation. static scoped_refptr<gfx::GLSurface> CreateSurface(GpuChannelManager* manager, GpuCommandBufferStub* stub, const gfx::GLSurfaceHandle& handle); virtual gfx::Size GetSize() = 0; protected: virtual ~ImageTransportSurface(); private: DISALLOW_COPY_AND_ASSIGN(ImageTransportSurface); }; class ImageTransportHelper : public IPC::Listener, public base::SupportsWeakPtr<ImageTransportHelper> { public: // Takes weak pointers to objects that outlive the helper. ImageTransportHelper(ImageTransportSurface* surface, GpuChannelManager* manager, GpuCommandBufferStub* stub, gfx::PluginWindowHandle handle); virtual ~ImageTransportHelper(); bool Initialize(); void Destroy(); // IPC::Listener implementation: virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; // Helper send functions. Caller fills in the surface specific params // like size and surface id. The helper fills in the rest. void SendAcceleratedSurfaceBuffersSwapped( GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params); void SendAcceleratedSurfacePostSubBuffer( GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params params); void SendAcceleratedSurfaceRelease( GpuHostMsg_AcceleratedSurfaceRelease_Params params); void SendResizeView(const gfx::Size& size); void SendUpdateVSyncParameters( base::TimeTicks timebase, base::TimeDelta interval); // Whether or not we should execute more commands. void SetScheduled(bool is_scheduled); void DeferToFence(base::Closure task); void SetPreemptByFlag( scoped_refptr<gpu::PreemptionFlag> preemption_flag); // Make the surface's context current. bool MakeCurrent(); // Set the default swap interval on the surface. static void SetSwapInterval(gfx::GLContext* context); void Suspend(); GpuChannelManager* manager() const { return manager_; } GpuCommandBufferStub* stub() const { return stub_.get(); } private: gpu::GpuScheduler* Scheduler(); gpu::gles2::GLES2Decoder* Decoder(); // IPC::Message handlers. void OnBufferPresented( const AcceleratedSurfaceMsg_BufferPresented_Params& params); void OnResizeViewACK(); // Backbuffer resize callback. void Resize(gfx::Size size); // Weak pointers that point to objects that outlive this helper. ImageTransportSurface* surface_; GpuChannelManager* manager_; base::WeakPtr<GpuCommandBufferStub> stub_; int32 route_id_; gfx::PluginWindowHandle handle_; DISALLOW_COPY_AND_ASSIGN(ImageTransportHelper); }; // An implementation of ImageTransportSurface that implements GLSurface through // GLSurfaceAdapter, thereby forwarding GLSurface methods through to it. class PassThroughImageTransportSurface : public gfx::GLSurfaceAdapter, public ImageTransportSurface { public: PassThroughImageTransportSurface(GpuChannelManager* manager, GpuCommandBufferStub* stub, gfx::GLSurface* surface, bool transport); // GLSurface implementation. virtual bool Initialize() OVERRIDE; virtual void Destroy() OVERRIDE; virtual bool DeferDraws() OVERRIDE; virtual bool SwapBuffers() OVERRIDE; virtual bool PostSubBuffer(int x, int y, int width, int height) OVERRIDE; virtual bool OnMakeCurrent(gfx::GLContext* context) OVERRIDE; // ImageTransportSurface implementation. virtual void OnBufferPresented( const AcceleratedSurfaceMsg_BufferPresented_Params& params) OVERRIDE; virtual void OnResizeViewACK() OVERRIDE; virtual void OnResize(gfx::Size size) OVERRIDE; virtual gfx::Size GetSize() OVERRIDE; protected: virtual ~PassThroughImageTransportSurface(); // If updated vsync parameters can be determined, send this information to // the browser. virtual void SendVSyncUpdateIfAvailable(); private: scoped_ptr<ImageTransportHelper> helper_; gfx::Size new_size_; bool transport_; bool did_set_swap_interval_; bool did_unschedule_; bool is_swap_buffers_pending_; DISALLOW_COPY_AND_ASSIGN(PassThroughImageTransportSurface); }; } // namespace content #endif // CONTENT_COMMON_GPU_IMAGE_TRANSPORT_SURFACE_H_
{ "content_hash": "33714e4f5087058b03bee82302fd664e", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 79, "avg_line_length": 32.96022727272727, "alnum_prop": 0.746940182727116, "repo_name": "zcbenz/cefode-chromium", "id": "562b4b316e63fce2b2e027b25007451ddb58670d", "size": "6487", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "content/common/gpu/image_transport_surface.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1174304" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "76026099" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "157904700" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "3225038" }, { "name": "JavaScript", "bytes": "18180217" }, { "name": "Logos", "bytes": "4517" }, { "name": "Matlab", "bytes": "5234" }, { "name": "Objective-C", "bytes": "7139426" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "932901" }, { "name": "Python", "bytes": "8654916" }, { "name": "R", "bytes": "262" }, { "name": "Ragel in Ruby Host", "bytes": "3621" }, { "name": "Shell", "bytes": "1533012" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XML", "bytes": "13493" } ], "symlink_target": "" }
sudo apt-get install --only-upgrade python3-django=1.8.7-1ubuntu5.4 -y sudo apt-get install --only-upgrade python-django=1.8.7-1ubuntu5.4 -y
{ "content_hash": "6c27b4fc05a976ef15e02ab5162d5335", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 70, "avg_line_length": 70.5, "alnum_prop": 0.7588652482269503, "repo_name": "Cyberwatch/cbw-security-fixes", "id": "368d06430284cb444283f9194bc2006484f7f4c1", "size": "784", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ubuntu_16.04_LTS/x86_64/2016/USN-3039-1.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "26564468" } ], "symlink_target": "" }
; (function ($) { if ($.os.ios) { var gesture = {}, gestureTimeout function parentIfText(node) { return 'tagName' in node ? node : node.parentNode } $(document).bind('gesturestart', function (e) { var now = Date.now(), delta = now - (gesture.last || now) gesture.target = parentIfText(e.target) gestureTimeout && clearTimeout(gestureTimeout) gesture.e1 = e.scale gesture.last = now }).bind('gesturechange', function (e) { gesture.e2 = e.scale }).bind('gestureend', function (e) { if (gesture.e2 > 0) { Math.abs(gesture.e1 - gesture.e2) != 0 && $(gesture.target).trigger('pinch') && $(gesture.target).trigger('pinch' + (gesture.e1 - gesture.e2 > 0 ? 'In' : 'Out')) gesture.e1 = gesture.e2 = gesture.last = 0 } else if ('last' in gesture) { gesture = {} } }) ; ['pinch', 'pinchIn', 'pinchOut'].forEach(function (m) { $.fn[m] = function (callback) { return this.bind(m, callback) } }) } })(Zepto)
{ "content_hash": "10b0c9d9351b45faf0de5cdde96ebcbb", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 97, "avg_line_length": 34.542857142857144, "alnum_prop": 0.48304383788254757, "repo_name": "Jackey-Sparrow/source-code-hot", "id": "c0a367df961450f4633eb851fd18c5186537d476", "size": "1325", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "12-Zepto-2016-01-14/lib/src/gesture.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "11123" }, { "name": "JavaScript", "bytes": "1666122" } ], "symlink_target": "" }
import * as Ajv from "ajv"; import { transformFromAst } from "babel-core"; import { parse } from "babylon"; import { basename } from "path"; import * as ts from "typescript"; import { getDefaultArgs as getDefaultJsonSchemaGeneratorArgs, JsonSchemaGenerator } from "typescript-json-schema"; import mergeIfStatements from "../compiler/mergeIfStatements"; import rewriteAjv from "../compiler/rewriteAjv"; import simplifyBlockStatements from "../compiler/simplifyBlockStatements"; import { packageRelative } from "../fileUtils"; import { typescript } from "../lazy-modules"; import { once } from "../memoize"; import { VirtualModule } from "./index"; const validatorsPathPattern = /\!validators$/; const typescriptExtensions = [".ts", ".tsx", ".d.ts"]; function existingPathForValidatorPath(path: string) { const strippedPath = path.replace(validatorsPathPattern, ""); for (const ext of typescriptExtensions) { const newPath = strippedPath + ext; if (typescript.sys.fileExists(newPath)) { return newPath; } } } function buildSchemas(path: string, compilerOptions: ts.CompilerOptions) { const program = typescript.createProgram([path, packageRelative("dist/common/preact")], compilerOptions); const sourceFile = program.getSourceFile(path); if (!sourceFile) { throw new Error("Could not find types for " + path); } const localNames: string[] = []; const tc = program.getTypeChecker(); const allSymbols: { [name: string]: ts.Type } = {}; const userSymbols: { [name: string]: ts.Symbol } = {}; const inheritingTypes: { [baseName: string]: string[] } = {}; function visit(node: ts.Node) { if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.EnumDeclaration || node.kind === ts.SyntaxKind.TypeAliasDeclaration ) { const symbol: ts.Symbol = (node as any).symbol; const localName = tc.getFullyQualifiedName(symbol).replace(/".*"\./, ""); const nodeType = tc.getTypeAtLocation(node); allSymbols[localName] = nodeType; if (typescript.getCombinedModifierFlags(node as ts.Declaration) & ts.ModifierFlags.Export) { localNames.push(localName); } userSymbols[localName] = symbol; for (const baseType of nodeType.getBaseTypes() || []) { const baseName = tc.typeToString(baseType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType); (inheritingTypes[baseName] || (inheritingTypes[baseName] = [])).push(localName); } } else { typescript.forEachChild(node, visit); } } visit(sourceFile); const generator = new JsonSchemaGenerator([], allSymbols, userSymbols, inheritingTypes, tc, Object.assign(getDefaultJsonSchemaGeneratorArgs(), { strictNullChecks: true, ref: true, topRef: true, required: true, rejectDateType: true, })); return localNames.map((name) => ({ name, schema: generator.getSchemaForSymbol(name) })); } // Ajv configured to support draft-04 JSON schemas const ajv = new Ajv({ meta: false, extendRefs: true, unknownFormats: "ignore", }); ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-06.json")); ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-07.json")); export default function(projectPath: string, path: string, minify: boolean, fileRead: (path: string) => void, compilerOptions: ts.CompilerOptions): VirtualModule | void { if (!validatorsPathPattern.test(path)) { return; } const modulePath = existingPathForValidatorPath(path); if (typeof modulePath === "undefined") { return; } fileRead(modulePath); const schemas = once(() => buildSchemas(modulePath, compilerOptions)); return { generateTypeDeclaration() { const entries: string[] = []; for (const { name } of schemas()) { entries.push(`import { ${name} as ${name}Type } from ${JSON.stringify("./" + basename(modulePath).replace(/(\.d)?\.tsx?$/, ""))};`); entries.push(`export function ${name}(value: unknown): value is ${name}Type;`); } return entries.join("\n"); }, generateModule() { // Compile and optimize validators for each of the types in the parent module const entries: string[] = []; for (const { name, schema } of schemas()) { entries.push(`export const ${name} = ${ajv.compile(schema).toString()};`); } const original = entries.join("\n"); const ast = parse(original, { sourceType: "module" }); return transformFromAst(ast, original, { plugins: [ [rewriteAjv, {}], [simplifyBlockStatements, {}], [mergeIfStatements, {}], ], compact: true, }).code!; }, instantiateModule() { // Compile validators for each of the types in the parent module const exports: any = {}; Object.defineProperty(exports, "__esModule", { value: true }); for (const { name, schema } of schemas()) { let compiled: ReturnType<typeof ajv.compile> | undefined; exports[name] = (value: any) => (typeof compiled !== "undefined" ? compiled : (compiled = ajv.compile(schema)))(value); } return (global) => { global.exports = exports; }; }, }; }
{ "content_hash": "57562b3ccb93c7c4b77590504c271e29", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 170, "avg_line_length": 38.46511627906977, "alnum_prop": 0.6910519951632407, "repo_name": "rpetrich/mobius", "id": "ce6caccf3e0b5c7af3ce455a8637bfd68e41296f", "size": "4962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "host/modules/validation.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "76" }, { "name": "Makefile", "bytes": "2512" }, { "name": "Shell", "bytes": "83" }, { "name": "TypeScript", "bytes": "208763" } ], "symlink_target": "" }
package cn.sswukang.library.adapter.single; import androidx.annotation.LayoutRes; import androidx.annotation.Nullable; import android.view.View; import java.util.List; import cn.sswukang.library.adapter.base.BaseAdapter; import cn.sswukang.library.adapter.base.BaseViewHolder; /** * single item Adapter * * @author sswukang on 2017/2/17 10:33 * @version 1.0 */ public abstract class SingleAdapter<T> extends BaseAdapter<T, BaseViewHolder> { /** * @param layoutId adapter需要的布局资源id * @param data 数据 */ protected SingleAdapter(@LayoutRes int layoutId, List<T> data) { super(layoutId, data); } @Override public final void onItemClick(View itemView, int position, @LayoutRes int layoutId) { onItemClick(itemView, position, getDataItem(position)); } @Override public final boolean onItemLongClick(View itemView, int position, @LayoutRes int layoutId) { return onItemLongClick(itemView, position, getDataItem(position)); } /** * item的单击事件 * * @param itemView 点击的item {@link BaseViewHolder#itemView} * @param position 当前点击的position,采用{@link BaseViewHolder#getLayoutPosition()}(无限轮播时会超过数据总个数) * @param t position 对应的对象(无限轮播时为对数据总个数取余后对应的对象) */ public void onItemClick(View itemView, int position, @Nullable T t) { // do something... } /** * item的长按事件 * * @param itemView 点击的item {@link BaseViewHolder#itemView} * @param position 当前点击的position,采用{@link BaseViewHolder#getLayoutPosition()}(无限轮播时会超过数据总个数) * @param t position 对应的对象(无限轮播时为对数据总个数取余后对应的对象) * @return 长按事件是否被消费 */ public boolean onItemLongClick(View itemView, int position, @Nullable T t) { return false; } }
{ "content_hash": "8dfa340aeb3a2095a6b440435e266879", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 96, "avg_line_length": 30.016949152542374, "alnum_prop": 0.6866177300959909, "repo_name": "sswukang/RvAdapter", "id": "b6bf0963c6e4bf8551d7bb41d34a7c967ac713a6", "size": "2039", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/java/cn/sswukang/library/adapter/single/SingleAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "127040" } ], "symlink_target": "" }
#include "web/WebPluginContainerImpl.h" #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/ScriptSourceCode.h" #include "bindings/core/v8/V8Element.h" #include "core/HTMLNames.h" #include "core/clipboard/DataObject.h" #include "core/clipboard/DataTransfer.h" #include "core/dom/DocumentUserGestureToken.h" #include "core/dom/ExecutionContext.h" #include "core/dom/Fullscreen.h" #include "core/events/DragEvent.h" #include "core/events/EventQueue.h" #include "core/events/GestureEvent.h" #include "core/events/KeyboardEvent.h" #include "core/events/MouseEvent.h" #include "core/events/ProgressEvent.h" #include "core/events/ResourceProgressEvent.h" #include "core/events/TouchEvent.h" #include "core/events/WheelEvent.h" #include "core/frame/EventHandlerRegistry.h" #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/html/HTMLFormElement.h" #include "core/html/HTMLPlugInElement.h" #include "core/input/EventHandler.h" #include "core/layout/HitTestResult.h" #include "core/layout/LayoutBox.h" #include "core/layout/LayoutView.h" #include "core/layout/api/LayoutPartItem.h" #include "core/layout/api/LayoutViewItem.h" #include "core/loader/FrameLoadRequest.h" #include "core/page/FocusController.h" #include "core/page/Page.h" #include "core/page/scrolling/ScrollingCoordinator.h" #include "core/paint/LayoutObjectDrawingRecorder.h" #include "core/paint/PaintLayer.h" #include "modules/plugins/PluginOcclusionSupport.h" #include "platform/HostWindow.h" #include "platform/KeyboardCodes.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/UserGestureIndicator.h" #include "platform/exported/WrappedResourceResponse.h" #include "platform/geometry/LayoutRect.h" #include "platform/graphics/GraphicsContext.h" #include "platform/graphics/GraphicsLayer.h" #include "platform/graphics/paint/CullRect.h" #include "platform/graphics/paint/ForeignLayerDisplayItem.h" #include "platform/scroll/ScrollAnimatorBase.h" #include "platform/scroll/ScrollbarTheme.h" #include "public/platform/Platform.h" #include "public/platform/WebClipboard.h" #include "public/platform/WebCompositorSupport.h" #include "public/platform/WebCursorInfo.h" #include "public/platform/WebDragData.h" #include "public/platform/WebExternalTextureLayer.h" #include "public/platform/WebInputEvent.h" #include "public/platform/WebRect.h" #include "public/platform/WebString.h" #include "public/platform/WebURL.h" #include "public/platform/WebURLError.h" #include "public/platform/WebURLRequest.h" #include "public/web/WebDOMMessageEvent.h" #include "public/web/WebDocument.h" #include "public/web/WebElement.h" #include "public/web/WebFrameClient.h" #include "public/web/WebPlugin.h" #include "public/web/WebPrintParams.h" #include "public/web/WebPrintPresetOptions.h" #include "public/web/WebViewClient.h" #include "web/ChromeClientImpl.h" #include "web/WebDataSourceImpl.h" #include "web/WebInputEventConversion.h" #include "web/WebLocalFrameImpl.h" #include "web/WebViewImpl.h" #include "wtf/Assertions.h" namespace blink { // Public methods -------------------------------------------------------------- void WebPluginContainerImpl::setFrameRect(const IntRect& frameRect) { Widget::setFrameRect(frameRect); } void WebPluginContainerImpl::updateAllLifecyclePhases() { if (!m_webPlugin) return; m_webPlugin->updateAllLifecyclePhases(); } void WebPluginContainerImpl::paint(GraphicsContext& context, const CullRect& cullRect) const { if (!parent()) return; // Don't paint anything if the plugin doesn't intersect. if (!cullRect.intersectsCullRect(frameRect())) return; if (RuntimeEnabledFeatures::slimmingPaintV2Enabled() && m_webLayer) { // With Slimming Paint v2, composited plugins should have their layers // inserted rather than invoking WebPlugin::paint. recordForeignLayer(context, *m_element->layoutObject(), DisplayItem::kForeignLayerPlugin, m_webLayer, location(), size()); return; } if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible( context, *m_element->layoutObject(), DisplayItem::Type::kWebPlugin)) return; LayoutObjectDrawingRecorder drawingRecorder( context, *m_element->layoutObject(), DisplayItem::Type::kWebPlugin, cullRect.m_rect); context.save(); DCHECK(parent()->isFrameView()); FrameView* view = toFrameView(parent()); // The plugin is positioned in the root frame's coordinates, so it needs to // be painted in them too. IntPoint origin = view->contentsToRootFrame(IntPoint(0, 0)); context.translate(static_cast<float>(-origin.x()), static_cast<float>(-origin.y())); WebCanvas* canvas = context.canvas(); IntRect windowRect = view->contentsToRootFrame(cullRect.m_rect); m_webPlugin->paint(canvas, windowRect); context.restore(); } void WebPluginContainerImpl::invalidateRect(const IntRect& rect) { if (!parent()) return; LayoutBox* layoutObject = toLayoutBox(m_element->layoutObject()); if (!layoutObject) return; IntRect dirtyRect = rect; dirtyRect.move( (layoutObject->borderLeft() + layoutObject->paddingLeft()).toInt(), (layoutObject->borderTop() + layoutObject->paddingTop()).toInt()); m_pendingInvalidationRect.unite(dirtyRect); layoutObject->setMayNeedPaintInvalidation(); } void WebPluginContainerImpl::setFocused(bool focused, WebFocusType focusType) { Widget::setFocused(focused, focusType); m_webPlugin->updateFocus(focused, focusType); } void WebPluginContainerImpl::show() { setSelfVisible(true); m_webPlugin->updateVisibility(true); Widget::show(); } void WebPluginContainerImpl::hide() { setSelfVisible(false); m_webPlugin->updateVisibility(false); Widget::hide(); } void WebPluginContainerImpl::handleEvent(Event* event) { // The events we pass are defined at: // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000 // Don't take the documentation as truth, however. There are many cases // where mozilla behaves differently than the spec. if (event->isMouseEvent()) handleMouseEvent(toMouseEvent(event)); else if (event->isWheelEvent()) handleWheelEvent(toWheelEvent(event)); else if (event->isKeyboardEvent()) handleKeyboardEvent(toKeyboardEvent(event)); else if (event->isTouchEvent()) handleTouchEvent(toTouchEvent(event)); else if (event->isGestureEvent()) handleGestureEvent(toGestureEvent(event)); else if (event->isDragEvent() && m_webPlugin->canProcessDrag()) handleDragEvent(toDragEvent(event)); // FIXME: it would be cleaner if Widget::handleEvent returned true/false and // HTMLPluginElement called setDefaultHandled or defaultEventHandler. if (!event->defaultHandled()) m_element->Node::defaultEventHandler(event); } void WebPluginContainerImpl::frameRectsChanged() { Widget::frameRectsChanged(); reportGeometry(); } void WebPluginContainerImpl::widgetGeometryMayHaveChanged() { Widget::widgetGeometryMayHaveChanged(); reportGeometry(); } void WebPluginContainerImpl::eventListenersRemoved() { // We're no longer registered to receive touch events, so don't try to remove // the touch event handlers in our destructor. m_touchEventRequestType = TouchEventRequestTypeNone; } void WebPluginContainerImpl::setParentVisible(bool parentVisible) { // We override this function to make sure that geometry updates are sent // over to the plugin. For e.g. when a plugin is instantiated it does not // have a valid parent. As a result the first geometry update from webkit // is ignored. This function is called when the plugin eventually gets a // parent. if (isParentVisible() == parentVisible) return; // No change. Widget::setParentVisible(parentVisible); if (!isSelfVisible()) return; // This widget has explicitely been marked as not visible. if (m_webPlugin) m_webPlugin->updateVisibility(isVisible()); } void WebPluginContainerImpl::setPlugin(WebPlugin* plugin) { if (plugin == m_webPlugin) return; m_element->resetInstance(); m_webPlugin = plugin; m_isDisposed = false; } float WebPluginContainerImpl::deviceScaleFactor() { Page* page = m_element->document().page(); if (!page) return 1.0; return page->deviceScaleFactor(); } float WebPluginContainerImpl::pageScaleFactor() { Page* page = m_element->document().page(); if (!page) return 1.0; return page->pageScaleFactor(); } float WebPluginContainerImpl::pageZoomFactor() { LocalFrame* frame = m_element->document().frame(); if (!frame) return 1.0; return frame->pageZoomFactor(); } void WebPluginContainerImpl::setWebLayer(WebLayer* layer) { if (m_webLayer == layer) return; if (m_webLayer) GraphicsLayer::unregisterContentsLayer(m_webLayer); if (layer) GraphicsLayer::registerContentsLayer(layer); m_webLayer = layer; if (m_element) m_element->setNeedsCompositingUpdate(); } void WebPluginContainerImpl::requestFullscreen() { Fullscreen::requestFullscreen(*m_element); } bool WebPluginContainerImpl::isFullscreenElement() const { return Fullscreen::isFullscreenElement(*m_element); } void WebPluginContainerImpl::cancelFullscreen() { Fullscreen::fullyExitFullscreen(m_element->document()); } bool WebPluginContainerImpl::supportsPaginatedPrint() const { return m_webPlugin->supportsPaginatedPrint(); } bool WebPluginContainerImpl::isPrintScalingDisabled() const { return m_webPlugin->isPrintScalingDisabled(); } bool WebPluginContainerImpl::getPrintPresetOptionsFromDocument( WebPrintPresetOptions* presetOptions) const { return m_webPlugin->getPrintPresetOptionsFromDocument(presetOptions); } int WebPluginContainerImpl::printBegin( const WebPrintParams& printParams) const { return m_webPlugin->printBegin(printParams); } void WebPluginContainerImpl::printPage(int pageNumber, GraphicsContext& gc, const IntRect& printRect) { if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible( gc, *m_element->layoutObject(), DisplayItem::Type::kWebPlugin)) return; LayoutObjectDrawingRecorder drawingRecorder( gc, *m_element->layoutObject(), DisplayItem::Type::kWebPlugin, printRect); gc.save(); WebCanvas* canvas = gc.canvas(); m_webPlugin->printPage(pageNumber, canvas); gc.restore(); } void WebPluginContainerImpl::printEnd() { m_webPlugin->printEnd(); } void WebPluginContainerImpl::copy() { if (!m_webPlugin->hasSelection()) return; Platform::current()->clipboard()->writeHTML( m_webPlugin->selectionAsMarkup(), WebURL(), m_webPlugin->selectionAsText(), false); } bool WebPluginContainerImpl::executeEditCommand(const WebString& name) { if (m_webPlugin->executeEditCommand(name)) return true; if (name != "Copy") return false; copy(); return true; } bool WebPluginContainerImpl::executeEditCommand(const WebString& name, const WebString& value) { return m_webPlugin->executeEditCommand(name, value); } WebElement WebPluginContainerImpl::element() { return WebElement(m_element); } WebDocument WebPluginContainerImpl::document() { return WebDocument(&m_element->document()); } void WebPluginContainerImpl::dispatchProgressEvent(const WebString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total, const WebString& url) { ProgressEvent* event; if (url.isEmpty()) { event = ProgressEvent::create(type, lengthComputable, loaded, total); } else { event = ResourceProgressEvent::create(type, lengthComputable, loaded, total, url); } m_element->dispatchEvent(event); } void WebPluginContainerImpl::enqueueMessageEvent( const WebDOMMessageEvent& event) { static_cast<Event*>(event)->setTarget(m_element); m_element->getExecutionContext()->getEventQueue()->enqueueEvent(event); } void WebPluginContainerImpl::invalidate() { Widget::invalidate(); } void WebPluginContainerImpl::invalidateRect(const WebRect& rect) { invalidateRect(static_cast<IntRect>(rect)); } void WebPluginContainerImpl::scrollRect(const WebRect& rect) { invalidateRect(rect); } void WebPluginContainerImpl::scheduleAnimation() { if (auto* frameView = m_element->document().view()) frameView->scheduleAnimation(); } void WebPluginContainerImpl::reportGeometry() { // We cannot compute geometry without a parent or layoutObject. if (!parent() || !m_element || !m_element->layoutObject() || !m_webPlugin) return; IntRect windowRect, clipRect, unobscuredRect; Vector<IntRect> cutOutRects; calculateGeometry(windowRect, clipRect, unobscuredRect, cutOutRects); m_webPlugin->updateGeometry(windowRect, clipRect, unobscuredRect, cutOutRects, isVisible()); } v8::Local<v8::Object> WebPluginContainerImpl::v8ObjectForElement() { LocalFrame* frame = m_element->document().frame(); if (!frame) return v8::Local<v8::Object>(); if (!frame->script().canExecuteScripts(NotAboutToExecuteScript)) return v8::Local<v8::Object>(); ScriptState* scriptState = ScriptState::forMainWorld(frame); if (!scriptState) return v8::Local<v8::Object>(); v8::Local<v8::Value> v8value = ToV8(m_element.get(), scriptState->context()->Global(), scriptState->isolate()); if (v8value.IsEmpty()) return v8::Local<v8::Object>(); DCHECK(v8value->IsObject()); return v8::Local<v8::Object>::Cast(v8value); } WebString WebPluginContainerImpl::executeScriptURL(const WebURL& url, bool popupsAllowed) { LocalFrame* frame = m_element->document().frame(); if (!frame) return WebString(); if (!m_element->document().contentSecurityPolicy()->allowJavaScriptURLs( m_element, m_element->document().url(), OrdinalNumber())) { return WebString(); } const KURL& kurl = url; DCHECK(kurl.protocolIs("javascript")); String script = decodeURLEscapeSequences( kurl.getString().substring(strlen("javascript:"))); UserGestureIndicator gestureIndicator( popupsAllowed ? DocumentUserGestureToken::create( frame->document(), UserGestureToken::NewGesture) : nullptr); v8::HandleScope handleScope(toIsolate(frame)); v8::Local<v8::Value> result = frame->script().executeScriptInMainWorldAndReturnValue( ScriptSourceCode(script)); // Failure is reported as a null string. if (result.IsEmpty() || !result->IsString()) return WebString(); return toCoreString(v8::Local<v8::String>::Cast(result)); } void WebPluginContainerImpl::loadFrameRequest(const WebURLRequest& request, const WebString& target) { LocalFrame* frame = m_element->document().frame(); if (!frame || !frame->loader().documentLoader()) return; // FIXME: send a notification in this case? FrameLoadRequest frameRequest(frame->document(), request.toResourceRequest(), target); frame->loader().load(frameRequest); } bool WebPluginContainerImpl::isRectTopmost(const WebRect& rect) { // Disallow access to the frame during dispose(), because it is not guaranteed // to be valid memory once this object has started disposal. In particular, // we might be being disposed because the frame has already be deleted and // then something else dropped the // last reference to the this object. if (m_isDisposed || !m_element) return false; LocalFrame* frame = m_element->document().frame(); if (!frame) return false; IntRect documentRect(x() + rect.x, y() + rect.y, rect.width, rect.height); // hitTestResultAtPoint() takes a padding rectangle. // FIXME: We'll be off by 1 when the width or height is even. LayoutPoint center = documentRect.center(); // Make the rect we're checking (the point surrounded by padding rects) // contained inside the requested rect. (Note that -1/2 is 0.) LayoutSize padding((documentRect.width() - 1) / 2, (documentRect.height() - 1) / 2); HitTestResult result = frame->eventHandler().hitTestResultAtPoint( center, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ListBased, padding); const HitTestResult::NodeSet& nodes = result.listBasedTestResult(); if (nodes.size() != 1) return false; return nodes.first().get() == m_element; } void WebPluginContainerImpl::requestTouchEventType( TouchEventRequestType requestType) { if (m_touchEventRequestType == requestType || !m_element) return; if (FrameHost* frameHost = m_element->document().frameHost()) { EventHandlerRegistry& registry = frameHost->eventHandlerRegistry(); if (requestType != TouchEventRequestTypeNone && m_touchEventRequestType == TouchEventRequestTypeNone) registry.didAddEventHandler( *m_element, EventHandlerRegistry::TouchStartOrMoveEventBlocking); else if (requestType == TouchEventRequestTypeNone && m_touchEventRequestType != TouchEventRequestTypeNone) registry.didRemoveEventHandler( *m_element, EventHandlerRegistry::TouchStartOrMoveEventBlocking); } m_touchEventRequestType = requestType; } void WebPluginContainerImpl::setWantsWheelEvents(bool wantsWheelEvents) { if (m_wantsWheelEvents == wantsWheelEvents) return; if (FrameHost* frameHost = m_element->document().frameHost()) { EventHandlerRegistry& registry = frameHost->eventHandlerRegistry(); if (wantsWheelEvents) registry.didAddEventHandler(*m_element, EventHandlerRegistry::WheelEventBlocking); else registry.didRemoveEventHandler(*m_element, EventHandlerRegistry::WheelEventBlocking); } m_wantsWheelEvents = wantsWheelEvents; if (Page* page = m_element->document().page()) { if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) { if (parent() && parent()->isFrameView()) scrollingCoordinator->notifyGeometryChanged(); } } } WebPoint WebPluginContainerImpl::rootFrameToLocalPoint( const WebPoint& pointInRootFrame) { FrameView* view = toFrameView(parent()); if (!view) return pointInRootFrame; WebPoint pointInContent = view->rootFrameToContents(pointInRootFrame); return roundedIntPoint(m_element->layoutObject()->absoluteToLocal( FloatPoint(pointInContent), UseTransforms)); } WebPoint WebPluginContainerImpl::localToRootFramePoint( const WebPoint& pointInLocal) { FrameView* view = toFrameView(parent()); if (!view) return pointInLocal; IntPoint absolutePoint = roundedIntPoint(m_element->layoutObject()->localToAbsolute( FloatPoint(pointInLocal), UseTransforms)); return view->contentsToRootFrame(absolutePoint); } void WebPluginContainerImpl::didReceiveResponse( const ResourceResponse& response) { // Make sure that the plugin receives window geometry before data, or else // plugins misbehave. frameRectsChanged(); WrappedResourceResponse urlResponse(response); m_webPlugin->didReceiveResponse(urlResponse); } void WebPluginContainerImpl::didReceiveData(const char* data, int dataLength) { m_webPlugin->didReceiveData(data, dataLength); } void WebPluginContainerImpl::didFinishLoading() { m_webPlugin->didFinishLoading(); } void WebPluginContainerImpl::didFailLoading(const ResourceError& error) { m_webPlugin->didFailLoading(error); } WebLayer* WebPluginContainerImpl::platformLayer() const { return m_webLayer; } v8::Local<v8::Object> WebPluginContainerImpl::scriptableObject( v8::Isolate* isolate) { // With Oilpan, on plugin element detach dispose() will be called to safely // clear out references, including the pre-emptive destruction of the plugin. // // It clearly has no scriptable object if in such a disposed state. if (!m_webPlugin) return v8::Local<v8::Object>(); v8::Local<v8::Object> object = m_webPlugin->v8ScriptableObject(isolate); // If the plugin has been destroyed and the reference on the stack is the // only one left, then don't return the scriptable object. if (!m_webPlugin) return v8::Local<v8::Object>(); return object; } bool WebPluginContainerImpl::supportsKeyboardFocus() const { return m_webPlugin->supportsKeyboardFocus(); } bool WebPluginContainerImpl::supportsInputMethod() const { return m_webPlugin->supportsInputMethod(); } bool WebPluginContainerImpl::canProcessDrag() const { return m_webPlugin->canProcessDrag(); } bool WebPluginContainerImpl::wantsWheelEvents() { return m_wantsWheelEvents; } // Private methods ------------------------------------------------------------- WebPluginContainerImpl::WebPluginContainerImpl(HTMLPlugInElement* element, WebPlugin* webPlugin) : ContextClient(element->document().frame()), m_element(element), m_webPlugin(webPlugin), m_webLayer(nullptr), m_touchEventRequestType(TouchEventRequestTypeNone), m_wantsWheelEvents(false), m_isDisposed(false) {} WebPluginContainerImpl::~WebPluginContainerImpl() { // The plugin container must have been disposed of by now. DCHECK(!m_webPlugin); } void WebPluginContainerImpl::dispose() { m_isDisposed = true; requestTouchEventType(TouchEventRequestTypeNone); setWantsWheelEvents(false); if (m_webPlugin) { CHECK(m_webPlugin->container() == this); m_webPlugin->destroy(); m_webPlugin = nullptr; } if (m_webLayer) { GraphicsLayer::unregisterContentsLayer(m_webLayer); m_webLayer = nullptr; } } DEFINE_TRACE(WebPluginContainerImpl) { visitor->trace(m_element); ContextClient::trace(visitor); PluginView::trace(visitor); } void WebPluginContainerImpl::handleMouseEvent(MouseEvent* event) { DCHECK(parent()->isFrameView()); // We cache the parent FrameView here as the plugin widget could be deleted // in the call to HandleEvent. See http://b/issue?id=1362948 FrameView* parentView = toFrameView(parent()); WebMouseEventBuilder webEvent(this, LayoutItem(m_element->layoutObject()), *event); if (webEvent.type() == WebInputEvent::Undefined) return; if (event->type() == EventTypeNames::mousedown) focusPlugin(); WebCursorInfo cursorInfo; if (m_webPlugin->handleInputEvent(webEvent, cursorInfo) != WebInputEventResult::NotHandled) event->setDefaultHandled(); // A windowless plugin can change the cursor in response to a mouse move // event. We need to reflect the changed cursor in the frame view as the // mouse is moved in the boundaries of the windowless plugin. Page* page = parentView->frame().page(); if (!page) return; toChromeClientImpl(page->chromeClient()) .setCursorForPlugin(cursorInfo, parentView->frame().localFrameRoot()); } void WebPluginContainerImpl::handleDragEvent(MouseEvent* event) { DCHECK(event->isDragEvent()); WebDragStatus dragStatus = WebDragStatusUnknown; if (event->type() == EventTypeNames::dragenter) dragStatus = WebDragStatusEnter; else if (event->type() == EventTypeNames::dragleave) dragStatus = WebDragStatusLeave; else if (event->type() == EventTypeNames::dragover) dragStatus = WebDragStatusOver; else if (event->type() == EventTypeNames::drop) dragStatus = WebDragStatusDrop; if (dragStatus == WebDragStatusUnknown) return; DataTransfer* dataTransfer = event->getDataTransfer(); WebDragData dragData = dataTransfer->dataObject()->toWebDragData(); WebDragOperationsMask dragOperationMask = static_cast<WebDragOperationsMask>(dataTransfer->sourceOperation()); WebPoint dragScreenLocation(event->screenX(), event->screenY()); WebPoint dragLocation(event->absoluteLocation().x() - location().x(), event->absoluteLocation().y() - location().y()); m_webPlugin->handleDragStatusUpdate(dragStatus, dragData, dragOperationMask, dragLocation, dragScreenLocation); } void WebPluginContainerImpl::handleWheelEvent(WheelEvent* event) { WebFloatPoint absoluteRootFrameLocation = event->nativeEvent().positionInRootFrame(); IntPoint localPoint = roundedIntPoint(m_element->layoutObject()->absoluteToLocal( absoluteRootFrameLocation, UseTransforms)); WebMouseWheelEvent translatedEvent = event->nativeEvent().flattenTransform(); translatedEvent.x = localPoint.x(); translatedEvent.y = localPoint.y(); WebCursorInfo cursorInfo; if (m_webPlugin->handleInputEvent(translatedEvent, cursorInfo) != WebInputEventResult::NotHandled) event->setDefaultHandled(); } void WebPluginContainerImpl::handleKeyboardEvent(KeyboardEvent* event) { WebKeyboardEventBuilder webEvent(*event); if (webEvent.type() == WebInputEvent::Undefined) return; if (webEvent.type() == WebInputEvent::KeyDown) { #if OS(MACOSX) if ((webEvent.modifiers() & WebInputEvent::InputModifiers) == WebInputEvent::MetaKey #else if ((webEvent.modifiers() & WebInputEvent::InputModifiers) == WebInputEvent::ControlKey #endif && (webEvent.windowsKeyCode == VKEY_C || webEvent.windowsKeyCode == VKEY_INSERT) // Only copy if there's a selection, so that we only ever do this // for Pepper plugins that support copying. Windowless NPAPI // plugins will get the event as before. && m_webPlugin->hasSelection()) { copy(); event->setDefaultHandled(); return; } } // Give the client a chance to issue edit comamnds. WebLocalFrameImpl* webFrame = WebLocalFrameImpl::fromFrame(m_element->document().frame()); if (m_webPlugin->supportsEditCommands()) webFrame->client()->handleCurrentKeyboardEvent(); WebCursorInfo cursorInfo; if (m_webPlugin->handleInputEvent(webEvent, cursorInfo) != WebInputEventResult::NotHandled) event->setDefaultHandled(); } void WebPluginContainerImpl::handleTouchEvent(TouchEvent* event) { switch (m_touchEventRequestType) { case TouchEventRequestTypeNone: return; case TouchEventRequestTypeRaw: { WebTouchEventBuilder webEvent(LayoutItem(m_element->layoutObject()), *event); if (webEvent.type() == WebInputEvent::Undefined) return; if (event->type() == EventTypeNames::touchstart) focusPlugin(); WebCursorInfo cursorInfo; if (m_webPlugin->handleInputEvent(webEvent, cursorInfo) != WebInputEventResult::NotHandled) event->setDefaultHandled(); // FIXME: Can a plugin change the cursor from a touch-event callback? return; } case TouchEventRequestTypeSynthesizedMouse: synthesizeMouseEventIfPossible(event); return; } } void WebPluginContainerImpl::handleGestureEvent(GestureEvent* event) { if (event->nativeEvent().type() == WebInputEvent::Undefined) return; if (event->nativeEvent().type() == WebInputEvent::GestureTapDown) focusPlugin(); // Take a copy of the event and translate it into the coordinate // system of the plugin. WebGestureEvent translatedEvent = event->nativeEvent(); WebFloatPoint absoluteRootFrameLocation = event->nativeEvent().positionInRootFrame(); IntPoint localPoint = roundedIntPoint(m_element->layoutObject()->absoluteToLocal( absoluteRootFrameLocation, UseTransforms)); translatedEvent.flattenTransform(); translatedEvent.x = localPoint.x(); translatedEvent.y = localPoint.y(); WebCursorInfo cursorInfo; if (m_webPlugin->handleInputEvent(translatedEvent, cursorInfo) != WebInputEventResult::NotHandled) { event->setDefaultHandled(); return; } // FIXME: Can a plugin change the cursor from a touch-event callback? } void WebPluginContainerImpl::synthesizeMouseEventIfPossible(TouchEvent* event) { WebMouseEventBuilder webEvent(this, LayoutItem(m_element->layoutObject()), *event); if (webEvent.type() == WebInputEvent::Undefined) return; WebCursorInfo cursorInfo; if (m_webPlugin->handleInputEvent(webEvent, cursorInfo) != WebInputEventResult::NotHandled) event->setDefaultHandled(); } void WebPluginContainerImpl::focusPlugin() { LocalFrame& containingFrame = toFrameView(parent())->frame(); if (Page* currentPage = containingFrame.page()) currentPage->focusController().setFocusedElement(m_element, &containingFrame); else containingFrame.document()->setFocusedElement( m_element, FocusParams(SelectionBehaviorOnFocus::None, WebFocusTypeNone, nullptr)); } void WebPluginContainerImpl::issuePaintInvalidations() { if (m_pendingInvalidationRect.isEmpty()) return; LayoutBox* layoutObject = toLayoutBox(m_element->layoutObject()); if (!layoutObject) return; layoutObject->invalidatePaintRectangle(LayoutRect(m_pendingInvalidationRect)); m_pendingInvalidationRect = IntRect(); } void WebPluginContainerImpl::computeClipRectsForPlugin( const HTMLFrameOwnerElement* ownerElement, IntRect& windowRect, IntRect& clippedLocalRect, IntRect& unclippedIntLocalRect) const { DCHECK(ownerElement); if (!ownerElement->layoutObject()) { clippedLocalRect = IntRect(); unclippedIntLocalRect = IntRect(); return; } LayoutView* rootView = m_element->document().view()->layoutView(); while (rootView->frame()->ownerLayoutObject()) rootView = rootView->frame()->ownerLayoutObject()->view(); LayoutBox* box = toLayoutBox(ownerElement->layoutObject()); // Note: frameRect() for this plugin is equal to contentBoxRect, mapped to the // containing view space, and rounded off. // See LayoutPart.cpp::updateWidgetGeometryInternal. To remove the lossy // effect of rounding off, use contentBoxRect directly. LayoutRect unclippedAbsoluteRect(box->contentBoxRect()); box->mapToVisualRectInAncestorSpace(rootView, unclippedAbsoluteRect); // The frameRect is already in absolute space of the local frame to the // plugin. windowRect = frameRect(); // Map up to the root frame. LayoutRect layoutWindowRect = LayoutRect(m_element->document() .view() ->layoutViewItem() .localToAbsoluteQuad(FloatQuad(FloatRect(frameRect())), TraverseDocumentBoundaries) .boundingBox()); // Finally, adjust for scrolling of the root frame, which the above does not // take into account. layoutWindowRect.moveBy(-rootView->viewRect().location()); windowRect = pixelSnappedIntRect(layoutWindowRect); LayoutRect layoutClippedLocalRect = unclippedAbsoluteRect; LayoutRect unclippedLayoutLocalRect = layoutClippedLocalRect; layoutClippedLocalRect.intersect( LayoutRect(rootView->frameView()->visibleContentRect())); unclippedIntLocalRect = box->absoluteToLocalQuad(FloatRect(unclippedLayoutLocalRect), TraverseDocumentBoundaries | UseTransforms) .enclosingBoundingBox(); // As a performance optimization, map the clipped rect separately if is // different than the unclipped rect. if (layoutClippedLocalRect != unclippedLayoutLocalRect) clippedLocalRect = box->absoluteToLocalQuad(FloatRect(layoutClippedLocalRect), TraverseDocumentBoundaries | UseTransforms) .enclosingBoundingBox(); else clippedLocalRect = unclippedIntLocalRect; } void WebPluginContainerImpl::calculateGeometry(IntRect& windowRect, IntRect& clipRect, IntRect& unobscuredRect, Vector<IntRect>& cutOutRects) { // document().layoutView() can be null when we receive messages from the // plugins while we are destroying a frame. // FIXME: Can we just check m_element->document().isActive() ? if (!m_element->layoutObject()->document().layoutViewItem().isNull()) { // Take our element and get the clip rect from the enclosing layer and // frame view. computeClipRectsForPlugin(m_element, windowRect, clipRect, unobscuredRect); } getPluginOcclusions(m_element, this->parent(), frameRect(), cutOutRects); // Convert to the plugin position. for (size_t i = 0; i < cutOutRects.size(); i++) cutOutRects[i].move(-frameRect().x(), -frameRect().y()); } } // namespace blink
{ "content_hash": "a0ebaafb7a2580dff570dba1ffe25e8f", "timestamp": "", "source": "github", "line_count": 953, "max_line_length": 96, "avg_line_length": 34.66107030430221, "alnum_prop": 0.7061334463550496, "repo_name": "google-ar/WebARonARCore", "id": "f30d629d300f88ce4147923ef6bf401a71e1a127", "size": "34657", "binary": false, "copies": "1", "ref": "refs/heads/webarcore_57.0.2987.5", "path": "third_party/WebKit/Source/web/WebPluginContainerImpl.cpp", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<span>&nbsp;</span>
{ "content_hash": "58960c533e25432fb5413476112833d2", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 19, "avg_line_length": 20, "alnum_prop": 0.6, "repo_name": "jakt/angular-gulp-boilerplate", "id": "35e5a0b247f9e89904073a057d163b77c99c146b", "size": "20", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/common/some-directive/some-directive.tpl.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2698" }, { "name": "HTML", "bytes": "17378" }, { "name": "JavaScript", "bytes": "12972" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2 Version: 3.2.0 Author: KeenThemes Website: http://www.keenthemes.com/ Contact: support@keenthemes.com Follow: www.twitter.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. --> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8"/> <title>Metronic | Page Layouts - Disabled Menu Links</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta content="" name="description"/> <meta content="" name="author"/> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN THEME STYLES --> <link href="../../assets/global/css/components-md.css" id="style_components" rel="stylesheet" type="text/css"> <link href="../../assets/global/css/plugins-md.css" rel="stylesheet" type="text/css"> <link href="../../assets/admin/layout3/css/layout.css" rel="stylesheet" type="text/css"> <link href="../../assets/admin/layout3/css/themes/default.css" rel="stylesheet" type="text/css" id="style_color"> <link href="../../assets/admin/layout3/css/custom.css" rel="stylesheet" type="text/css"> <!-- END THEME STYLES --> <link rel="shortcut icon" href="favicon.ico"/> </head> <!-- END HEAD --> <!-- BEGIN BODY --> <!-- DOC: Apply "page-header-menu-fixed" class to set the mega menu fixed --> <!-- DOC: Apply "page-header-top-fixed" class to set the top menu fixed --> <body class="page-md"> <!-- BEGIN HEADER --> <div class="page-header"> <!-- BEGIN HEADER TOP --> <div class="page-header-top"> <div class="container"> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"><img src="../../assets/admin/layout3/img/logo-default.png" alt="logo" class="logo-default"></a> </div> <!-- END LOGO --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler"></a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <!-- BEGIN NOTIFICATION DROPDOWN --> <li class="dropdown dropdown-extended dropdown-dark dropdown-notification" id="header_notification_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-default">7</span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <strong>12 pending</strong> tasks</h3> <a href="javascript:;">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <!-- BEGIN TODO DROPDOWN --> <li class="dropdown dropdown-extended dropdown-dark dropdown-tasks disabled-link" id="header_task_bar"> <a href="javascript:;" class="dropdown-toggle disable-target" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-default">3</span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <strong>12 pending</strong> tasks</h3> <a href="javascript:;">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span> </span> </a> </li> </ul> </li> </ul> </li> <!-- END TODO DROPDOWN --> <li class="droddown dropdown-separator"> <span class="separator"></span> </li> <!-- BEGIN INBOX DROPDOWN --> <li class="dropdown dropdown-extended dropdown-dark dropdown-inbox" id="header_inbox_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <span class="circle">3</span> <span class="corner"></span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <strong>7 New</strong> Messages</h3> <a href="javascript:;">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">16 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Bob Nilson </span> <span class="time">2 hrs </span> </span> <span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">40 mins </span> </span> <span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">46 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <li class="dropdown dropdown-user dropdown-dark"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <img alt="" class="img-circle" src="../../assets/admin/layout3/img/avatar9.jpg"> <span class="username username-hide-mobile">Nick</span> </a> <ul class="dropdown-menu dropdown-menu-default"> <li> <a href="extra_profile.html"> <i class="icon-user"></i> My Profile </a> </li> <li class="disabled-link"> <a href="page_calendar.html" class="disable-target"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li class="disabled-link"> <a href="javascript:;" class="disable-target"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="extra_lock.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="login.html"> <i class="icon-key"></i> Log Out </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> </div> <!-- END HEADER TOP --> <!-- BEGIN HEADER MENU --> <div class="page-header-menu"> <div class="container"> <!-- BEGIN HEADER SEARCH BOX --> <form class="search-form" action="extra_search.html" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN MEGA MENU --> <!-- DOC: Apply "hor-menu-light" class after the "hor-menu" class below to have a horizontal menu with white background --> <!-- DOC: Remove data-hover="dropdown" and data-close-others="true" attributes below to disable the dropdown opening on mouse hover --> <div class="hor-menu "> <ul class="nav navbar-nav"> <li> <a href="index.html">Dashboard</a> </li> <li class="menu-dropdown mega-menu-dropdown "> <a data-hover="megamenu-dropdown" data-close-others="true" data-toggle="dropdown" href="javascript:;" class="dropdown-toggle"> Features <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu" style="min-width: 710px"> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <h3>eCommerce</h3> </li> <li> <a href="ecommerce_index.html" class="iconify"> <i class="icon-home"></i> Dashboard </a> </li> <li class="disabled-link"> <a href="ecommerce_orders.html" class="iconify disable-target"> <i class="icon-basket"></i> Manage Orders </a> </li> <li> <a href="ecommerce_orders_view.html" class="iconify"> <i class="icon-tag"></i> Order View </a> </li> <li> <a href="ecommerce_products.html" class="iconify"> <i class="icon-handbag"></i> Manage Products </a> </li> <li> <a href="ecommerce_products_edit.html" class="iconify"> <i class="icon-pencil"></i> Product Edit </a> </li> </ul> </div> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <h3>Layouts</h3> </li> <li class="disabled-link"> <a href="layout_fluid.html" class="iconify disable-target"> <i class="icon-cursor-move"></i> Fluid Layout </a> </li> <li> <a href="layout_mega_menu_fixed.html" class="iconify"> <i class="icon-pin"></i> Fixed Mega Menu </a> </li> <li class="disabled-link"> <a href="layout_top_bar_fixed.html" class="iconify disable-target"> <i class="icon-bar-chart"></i> Fixed Top Bar </a> </li> <li> <a href="layout_light_header.html" class="iconify"> <i class="icon-paper-plane"></i> Light Header Dropdowns </a> </li> <li> <a href="layout_blank_page.html" class="iconify"> <i class="icon-doc"></i> Blank Page </a> </li> </ul> </div> <div class="col-md-4"> <ul class="mega-menu-submenu"> <li> <h3>More Layouts</h3> </li> <li> <a href="layout_click_dropdowns.html" class="iconify"> <i class="icon-speech"></i> Click vs. Hover Dropdowns </a> </li> <li> <a href="layout_fontawesome_icons.html" class="iconify"> <i class="icon-link"></i> Layout with Fontawesome </a> </li> <li class="disabled-link"> <a href="layout_glyphicons.html" class="iconify disable-target"> <i class="icon-settings"></i> Layout with Glyphicon </a> </li> <li class="disabled-link"> <a href="layout_language_bar.html" class="iconify disable-target"> <i class="icon-globe"></i> Language Switch Bar </a> </li> <li> <a href="layout_disabled_menu.html" class="iconify"> <i class=" icon-lock"></i> Disabled Menu Links </a> </li> </ul> </div> </div> </div> </li> </ul> </li> <li class="menu-dropdown mega-menu-dropdown mega-menu-full "> <a data-hover="megamenu-dropdown" data-close-others="true" data-toggle="dropdown" href="javascript:;" class="dropdown-toggle"> UI Components <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu"> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>UI Components</h3> </li> <li> <a href="ui_general.html"> <i class="fa fa-angle-right"></i> General </a> </li> <li> <a href="ui_buttons.html"> <i class="fa fa-angle-right"></i> Buttons </a> </li> <li> <a href="ui_confirmations.html"> <i class="fa fa-angle-right"></i> Popover Confirmations </a> </li> <li> <a href="ui_icons.html"> <i class="fa fa-angle-right"></i> Font Icons </a> </li> <li> <a href="ui_colors.html"> <i class="fa fa-angle-right"></i> Flat UI Colors </a> </li> <li> <a href="ui_typography.html"> <i class="fa fa-angle-right"></i> Typography </a> </li> <li> <a href="ui_tabs_accordions_navs.html"> <i class="fa fa-angle-right"></i> Tabs, Accordions & Navs </a> </li> <li> <a href="ui_tree.html"> <i class="fa fa-angle-right"></i> Tree View </a> </li> <li> <a href="ui_page_progress_style_1.html"> <i class="fa fa-angle-right"></i> Page Progress Bar <span class="badge badge-roundless badge-warning">new</span></a> </li> <li> <a href="ui_blockui.html"> <i class="fa fa-angle-right"></i> Block UI </a> </li> <li> <a href="ui_notific8.html"> <i class="fa fa-angle-right"></i> Notific8 Notifications </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>More UI Components</h3> </li> <li> <a href="ui_toastr.html"> <i class="fa fa-angle-right"></i> Toastr Notifications </a> </li> <li> <a href="ui_alert_dialog_api.html"> <i class="fa fa-angle-right"></i> Alerts & Dialogs API <span class="badge badge-roundless badge-danger">new</span></a> </li> <li> <a href="ui_session_timeout.html"> <i class="fa fa-angle-right"></i> Session Timeout </a> </li> <li> <a href="ui_idle_timeout.html"> <i class="fa fa-angle-right"></i> User Idle Timeout </a> </li> <li> <a href="ui_modals.html"> <i class="fa fa-angle-right"></i> Modals </a> </li> <li> <a href="ui_extended_modals.html"> <i class="fa fa-angle-right"></i> Extended Modals </a> </li> <li> <a href="ui_tiles.html"> <i class="fa fa-angle-right"></i> Tiles </a> </li> <li> <a href="ui_datepaginator.html"> <i class="fa fa-angle-right"></i> Date Paginator </a> </li> <li> <a href="ui_nestable.html"> <i class="fa fa-angle-right"></i> Nestable List </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Form Stuff</h3> </li> <li> <a href="form_controls.html"> <i class="fa fa-angle-right"></i> Form Controls </a> </li> <li> <a href="form_layouts.html"> <i class="fa fa-angle-right"></i> Form Layouts </a> </li> <li> <a href="form_editable.html"> <i class="fa fa-angle-right"></i> Form X-editable <span class="badge badge-roundless badge-success">new</span></a> </li> <li> <a href="form_wizard.html"> <i class="fa fa-angle-right"></i> Form Wizard </a> </li> <li> <a href="form_validation.html"> <i class="fa fa-angle-right"></i> Form Validation </a> </li> <li> <a href="form_image_crop.html"> <i class="fa fa-angle-right"></i> Image Cropping </a> </li> <li> <a href="form_fileupload.html"> <i class="fa fa-angle-right"></i> Multiple File Upload </a> </li> <li> <a href="form_dropzone.html"> <i class="fa fa-angle-right"></i> Dropzone File Upload </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Form Components</h3> </li> <li> <a href="components_pickers.html"> <i class="fa fa-angle-right"></i> Pickers </a> </li> <li> <a href="components_dropdowns.html"> <i class="fa fa-angle-right"></i> Custom Dropdowns </a> </li> <li> <a href="components_form_tools.html"> <i class="fa fa-angle-right"></i> Form Tools </a> </li> <li> <a href="components_editors.html"> <i class="fa fa-angle-right"></i> Markdown & WYSIWYG Editors </a> </li> <li> <a href="components_ion_sliders.html"> <i class="fa fa-angle-right"></i> Ion Range Sliders </a> </li> <li> <a href="components_noui_sliders.html"> <i class="fa fa-angle-right"></i> NoUI Range Sliders </a> </li> <li> <a href="components_jqueryui_sliders.html"> <i class="fa fa-angle-right"></i> jQuery UI Sliders </a> </li> <li> <a href="components_knob_dials.html"> <i class="fa fa-angle-right"></i> Knob Circle Dials </a> </li> </ul> </div> </div> </div> </li> </ul> </li> <li class="menu-dropdown classic-menu-dropdown "> <a data-hover="megamenu-dropdown" data-close-others="true" data-toggle="dropdown" href="javascript:;"> Extra <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu pull-left"> <li class=" dropdown-submenu disabled-link"> <a href="javascript:;" class="disable-target"> <i class="icon-briefcase"></i> Data Tables </a> <ul class="dropdown-menu"> <li class=" "> <a href="table_basic.html"> Basic Datatables </a> </li> <li class=" "> <a href="table_responsive.html"> Responsive Datatables </a> </li> <li class=" "> <a href="table_managed.html"> Managed Datatables </a> </li> <li class=" "> <a href="table_editable.html"> Editable Datatables </a> </li> <li class=" "> <a href="table_advanced.html"> Advanced Datatables </a> </li> <li class=" "> <a href="table_ajax.html"> Ajax Datatables </a> </li> </ul> </li> <li class=" dropdown-submenu"> <a href="javascript:;"> <i class="icon-wallet"></i> Portlets </a> <ul class="dropdown-menu"> <li class=" "> <a href="portlet_general.html"> General Portlets </a> </li> <li class=" "> <a href="portlet_general2.html"> New Portlets #1 <span class="badge badge-roundless badge-danger">new</span> </a> </li> <li class=" "> <a href="portlet_general3.html"> New Portlets #2 <span class="badge badge-roundless badge-danger">new</span> </a> </li> <li class=" "> <a href="portlet_ajax.html"> Ajax Portlets </a> </li> <li class=" "> <a href="portlet_draggable.html"> Draggable Portlets </a> </li> </ul> </li> <li class=" dropdown-submenu"> <a href="javascript:;"> <i class="icon-pointer"></i> Maps </a> <ul class="dropdown-menu"> <li class=" "> <a href="maps_google.html"> Google Maps </a> </li> <li class=" "> <a href="maps_vector.html"> Vector Maps </a> </li> </ul> </li> <li class=" "> <a href="charts.html"> <i class="icon-bar-chart"></i> Visual Charts </a> </li> <li class="divider"> </li> <li class=" dropdown-submenu"> <a href="javascript:;"> <i class="icon-puzzle"></i> Multi Level </a> <ul class="dropdown-menu"> <li class=" "> <a href="javascript:;"> <i class="icon-settings"></i> Item 1 </a> </li> <li class=" "> <a href="javascript:;"> <i class="icon-user"></i> Item 2 </a> </li> <li class=" "> <a href="javascript:;"> <i class="icon-globe"></i> Item 3 </a> </li> <li class=" dropdown-submenu"> <a href="javascript:;"> <i class="icon-folder"></i> Sub Items </a> <ul class="dropdown-menu"> <li class=" "> <a href="javascript:;"> Item 1 </a> </li> <li class=" "> <a href="javascript:;"> Item 2 </a> </li> <li class=" "> <a href="javascript:;"> Item 3 </a> </li> <li class=" "> <a href="javascript:;"> Item 4 </a> </li> </ul> </li> <li class=" "> <a href="javascript:;"> <i class="icon-share"></i> Item 4 </a> </li> <li class=" "> <a href="javascript:;"> <i class="icon-bar-chart"></i> Item 5 </a> </li> </ul> </li> </ul> </li> <li class="menu-dropdown mega-menu-dropdown mega-menu-full "> <a data-hover="megamenu-dropdown" data-close-others="true" data-toggle="dropdown" href="javascript:;" class="dropdown-toggle"> Pages <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu"> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>User Pages</h3> </li> <li> <a href="page_timeline.html"> <i class="fa fa-angle-right"></i> New Timeline <span class="badge badge-warning">2</span> </a> </li> <li> <a href="page_todo.html"> <i class="fa fa-angle-right"></i> Todo & Tasks <span class="badge badge-danger">4</span></a> </li> <li> <a href="inbox.html"> <i class="fa fa-angle-right"></i> User Inbox <span class="badge badge-success">4</span></a> </li> <li> <a href="page_calendar.html"> <i class="fa fa-angle-right"></i> User Calendar <span class="badge badge-warning">14</span></a> </li> <li> <a href="extra_profile.html"> <i class="fa fa-angle-right"></i> User Profile </a> </li> <li> <a href="extra_lock.html"> <i class="fa fa-angle-right"></i> Lock Screen </a> </li> <li> <a href="login.html"> <i class="fa fa-angle-right"></i> Login Form 1 </a> </li> <li> <a href="login_soft.html"> <i class="fa fa-angle-right"></i> Login Form 2 </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>General Pages</h3> </li> <li> <a href="extra_faq.html"> <i class="fa fa-angle-right"></i> FAQ Page </a> </li> <li> <a href="page_portfolio.html"> <i class="fa fa-angle-right"></i> Portfolio </a> </li> <li> <a href="page_timeline.html"> <i class="fa fa-angle-right"></i> Old Timeline <span class="badge badge-info">4</span></a> </li> <li> <a href="page_coming_soon.html"> <i class="fa fa-angle-right"></i> Coming Soon </a> </li> <li> <a href="extra_invoice.html"> <i class="fa fa-angle-right"></i> Invoice </a> </li> <li> <a href="page_blog.html"> <i class="fa fa-angle-right"></i> Blog </a> </li> <li> <a href="page_blog_item.html"> <i class="fa fa-angle-right"></i> Blog Post </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Custom Pages</h3> </li> <li> <a href="page_news.html"> <i class="fa fa-angle-right"></i> News <span class="badge badge-success">9</span></a> </li> <li> <a href="page_news_item.html"> <i class="fa fa-angle-right"></i> News View </a> </li> <li> <a href="page_about.html"> <i class="fa fa-angle-right"></i> About Us </a> </li> <li> <a href="page_contact.html"> <i class="fa fa-angle-right"></i> Contact Us </a> </li> <li> <a href="extra_search.html"> <i class="fa fa-angle-right"></i> Search Results </a> </li> <li> <a href="extra_pricing_table.html"> <i class="fa fa-angle-right"></i> Pricing Tables </a> </li> </ul> </div> <div class="col-md-3"> <ul class="mega-menu-submenu"> <li> <h3>Miscellaneous</h3> </li> <li> <a href="extra_404_option1.html"> <i class="fa fa-angle-right"></i> 404 Page Option 1 </a> </li> <li> <a href="extra_404_option2.html"> <i class="fa fa-angle-right"></i> 404 Page Option 2 </a> </li> <li> <a href="extra_404_option3.html"> <i class="fa fa-angle-right"></i> 404 Page Option 3 </a> </li> <li> <a href="extra_500_option1.html"> <i class="fa fa-angle-right"></i> 500 Page Option 1 </a> </li> <li> <a href="extra_500_option2.html"> <i class="fa fa-angle-right"></i> 500 Page Option 2 </a> </li> <li> <a href="email_newsletter.html" target="_blank"> <i class="fa fa-angle-right"></i> Newsletter Email Template </a> </li> <li> <a href="email_system.html" target="_blank"> <i class="fa fa-angle-right"></i> System Email Template </a> </li> </ul> </div> </div> </div> </li> </ul> </li> <!-- begin: mega menu with custom content --> <li class="menu-dropdown mega-menu-dropdown mega-menu-full hide"> <a data-hover="megamenu-dropdown" data-close-others="true" data-toggle="dropdown" href="javascript:;" class="dropdown-toggle"> Mega Menu <i class="fa fa-angle-down"></i> </a> <ul class="dropdown-menu"> <li> <div class="mega-menu-content"> <div class="row"> <div class="col-md-6"> <div id="accordion" class="panel-group"> <div class="panel panel-success"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="collapsed"> Mega Menu Info #1 </a> </h4> </div> <div id="collapseOne" class="panel-collapse in"> <div class="panel-body"> <p> Metronic Mega Menu Works for fixed and responsive layout and has the facility to include (almost) any Bootstrap elements and jquery plugins. </p> <p> Duis mollis, est non commodo luctus, nisi erat mattis consectetur purus sit amet porttitor ligula. nisi erat mattis consectetur purus </p> </div> </div> </div> <div class="panel panel-danger"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" class="collapsed"> Mega Menu Info #2 </a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse"> <div class="panel-body"> <p> Metronic Mega Menu Works for fixed and responsive layout and has the facility to include (almost) any Bootstrap elements and jquery plugins. </p> <p> Duis mollis, est non commodo luctus, nisi erat mattis consectetur purus sit amet porttitor ligula. nisi erat mattis consectetur purus </p> </div> </div> </div> <div class="panel panel-info"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree"> Mega Menu Info #3 </a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse"> <div class="panel-body"> <p> Metronic Mega Menu Works for fixed and responsive layout and has the facility to include (almost) any Bootstrap elements and jquery plugins. </p> <p> Duis mollis, est non commodo luctus, nisi erat mattis consectetur purus sit amet porttitor ligula. nisi erat mattis consectetur purus </p> </div> </div> </div> </div> </div> <div class="col-md-6"> <div class="portlet light"> <div class="portlet-title"> <div class="caption"> <i class="fa fa-cogs font-red-sunglo"></i> <span class="caption-subject font-red-sunglo bold uppercase">Notes</span> <span class="caption-helper">notes samples...</span> </div> <div class="tools"> <a href="javascript:;" class="collapse"> </a> <a href="#portlet-config" data-toggle="modal" class="config"> </a> <a href="javascript:;" class="reload"> </a> <a href="javascript:;" class="remove"> </a> </div> </div> <div class="portlet-body"> <div class="note note-success"> <h4 class="block">Success! Some Header Goes Here</h4> <p> Duis mollis, est non commodo luctus, nisi erat mattis consectetur purus sit amet porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum. </p> </div> </div> </div> </div> </div> </div> </li> </ul> </li> <!-- end: mega menu with custom content --> </ul> </div> <!-- END MEGA MENU --> </div> </div> <!-- END HEADER MENU --> </div> <!-- END HEADER --> <!-- BEGIN PAGE CONTAINER --> <div class="page-container"> <!-- BEGIN PAGE HEAD --> <div class="page-head"> <div class="container"> <!-- BEGIN PAGE TITLE --> <div class="page-title"> <h1>Disabled Menu <small>Subtitle</small></h1> </div> <!-- END PAGE TITLE --> <!-- BEGIN PAGE TOOLBAR --> <div class="page-toolbar"> <!-- BEGIN THEME PANEL --> <div class="btn-group btn-theme-panel"> <a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown"> <i class="icon-settings"></i> </a> <div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <h3>THEME COLORS</h3> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <ul class="theme-colors"> <li class="theme-color theme-color-default" data-theme="default"> <span class="theme-color-view"></span> <span class="theme-color-name">Default</span> </li> <li class="theme-color theme-color-blue-hoki" data-theme="blue-hoki"> <span class="theme-color-view"></span> <span class="theme-color-name">Blue Hoki</span> </li> <li class="theme-color theme-color-blue-steel" data-theme="blue-steel"> <span class="theme-color-view"></span> <span class="theme-color-name">Blue Steel</span> </li> <li class="theme-color theme-color-yellow-orange" data-theme="yellow-orange"> <span class="theme-color-view"></span> <span class="theme-color-name">Orange</span> </li> <li class="theme-color theme-color-yellow-crusta" data-theme="yellow-crusta"> <span class="theme-color-view"></span> <span class="theme-color-name">Yellow Crusta</span> </li> </ul> </div> <div class="col-md-6 col-sm-6 col-xs-12"> <ul class="theme-colors"> <li class="theme-color theme-color-green-haze" data-theme="green-haze"> <span class="theme-color-view"></span> <span class="theme-color-name">Green Haze</span> </li> <li class="theme-color theme-color-red-sunglo" data-theme="red-sunglo"> <span class="theme-color-view"></span> <span class="theme-color-name">Red Sunglo</span> </li> <li class="theme-color theme-color-red-intense" data-theme="red-intense"> <span class="theme-color-view"></span> <span class="theme-color-name">Red Intense</span> </li> <li class="theme-color theme-color-purple-plum" data-theme="purple-plum"> <span class="theme-color-view"></span> <span class="theme-color-name">Purple Plum</span> </li> <li class="theme-color theme-color-purple-studio" data-theme="purple-studio"> <span class="theme-color-view"></span> <span class="theme-color-name">Purple Studio</span> </li> </ul> </div> </div> </div> <div class="col-md-6 col-sm-6 col-xs-12 seperator"> <h3>LAYOUT</h3> <ul class="theme-settings"> <li> Theme Style <select class="theme-setting theme-setting-style form-control input-sm input-small input-inline tooltips" data-original-title="Change theme style" data-container="body" data-placement="left"> <option value="boxed" selected="selected">Square corners</option> <option value="rounded">Rounded corners</option> </select> </li> <li> Layout <select class="theme-setting theme-setting-layout form-control input-sm input-small input-inline tooltips" data-original-title="Change layout type" data-container="body" data-placement="left"> <option value="boxed" selected="selected">Boxed</option> <option value="fluid">Fluid</option> </select> </li> <li> Top Menu Style <select class="theme-setting theme-setting-top-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change top menu dropdowns style" data-container="body" data-placement="left"> <option value="dark" selected="selected">Dark</option> <option value="light">Light</option> </select> </li> <li> Top Menu Mode <select class="theme-setting theme-setting-top-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) top menu" data-container="body" data-placement="left"> <option value="fixed">Fixed</option> <option value="not-fixed" selected="selected">Not Fixed</option> </select> </li> <li> Mega Menu Style <select class="theme-setting theme-setting-mega-menu-style form-control input-sm input-small input-inline tooltips" data-original-title="Change mega menu dropdowns style" data-container="body" data-placement="left"> <option value="dark" selected="selected">Dark</option> <option value="light">Light</option> </select> </li> <li> Mega Menu Mode <select class="theme-setting theme-setting-mega-menu-mode form-control input-sm input-small input-inline tooltips" data-original-title="Enable fixed(sticky) mega menu" data-container="body" data-placement="left"> <option value="fixed" selected="selected">Fixed</option> <option value="not-fixed">Not Fixed</option> </select> </li> </ul> </div> </div> </div> </div> <!-- END THEME PANEL --> </div> <!-- END PAGE TOOLBAR --> </div> </div> <!-- END PAGE HEAD --> <!-- BEGIN PAGE CONTENT --> <div class="page-content"> <div class="container"> <!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM--> <div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> Widget settings form goes here </div> <div class="modal-footer"> <button type="button" class="btn blue">Save changes</button> <button type="button" class="btn default" data-dismiss="modal">Close</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> <!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM--> <!-- BEGIN PAGE BREADCRUMB --> <ul class="page-breadcrumb breadcrumb"> <li> <a href="javascript:;">Home</a><i class="fa fa-circle"></i> </li> <li> <a href="javascript:;">Portlets</a><i class="fa fa-circle"></i> </li> <li class="active"> General </li> </ul> <!-- END PAGE BREADCRUMB --> <!-- BEGIN PAGE CONTENT INNER --> <div class="row"> <div class="col-md-12"> Page content goes here </div> </div> <!-- END PAGE CONTENT INNER --> </div> </div> <!-- END PAGE CONTENT --> </div> <!-- END PAGE CONTAINER --> <!-- BEGIN PRE-FOOTER --> <div class="page-prefooter"> <div class="container"> <div class="row"> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>About</h2> <p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam dolore. </p> </div> <div class="col-md-3 col-sm-6 col-xs12 footer-block"> <h2>Subscribe Email</h2> <div class="subscribe-form"> <form action="javascript:;"> <div class="input-group"> <input type="text" placeholder="mail@email.com" class="form-control"> <span class="input-group-btn"> <button class="btn" type="submit">Submit</button> </span> </div> </form> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>Follow Us On</h2> <ul class="social-icons"> <li> <a href="javascript:;" data-original-title="rss" class="rss"></a> </li> <li> <a href="javascript:;" data-original-title="facebook" class="facebook"></a> </li> <li> <a href="javascript:;" data-original-title="twitter" class="twitter"></a> </li> <li> <a href="javascript:;" data-original-title="googleplus" class="googleplus"></a> </li> <li> <a href="javascript:;" data-original-title="linkedin" class="linkedin"></a> </li> <li> <a href="javascript:;" data-original-title="youtube" class="youtube"></a> </li> <li> <a href="javascript:;" data-original-title="vimeo" class="vimeo"></a> </li> </ul> </div> <div class="col-md-3 col-sm-6 col-xs-12 footer-block"> <h2>Contacts</h2> <address class="margin-bottom-40"> Phone: 800 123 3456<br> Email: <a href="mailto:info@metronic.com">info@metronic.com</a> </address> </div> </div> </div> </div> <!-- END PRE-FOOTER --> <!-- BEGIN FOOTER --> <div class="page-footer"> <div class="container"> 2014 &copy; Metronic. All Rights Reserved. </div> </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> <!-- END FOOTER --> <!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) --> <!-- BEGIN CORE PLUGINS --> <!--[if lt IE 9]> <script src="../../assets/global/plugins/respond.min.js"></script> <script src="../../assets/global/plugins/excanvas.min.js"></script> <![endif]--> <script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script> <!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip --> <script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script> <script src="../../assets/admin/layout3/scripts/layout.js" type="text/javascript"></script> <script src="../../assets/admin/layout3/scripts/demo.js" type="text/javascript"></script> <script> jQuery(document).ready(function() { Metronic.init(); // init metronic core components Layout.init(); // init current layout Demo.init(); // init demo features }); </script> <!-- END JAVASCRIPTS --> </body> <!-- END BODY --> </html>
{ "content_hash": "fd98a3e04da224070140a1c146355756", "timestamp": "", "source": "github", "line_count": 1469, "max_line_length": 225, "avg_line_length": 36.26684819605173, "alnum_prop": 0.5013889931676553, "repo_name": "zzsoszz/metronicv37", "id": "9ec3eded01efcfe172a5f019205591784c3059c1", "size": "53276", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "theme/templates/admin3_material_design/layout_disabled_menu.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "580" }, { "name": "ApacheConf", "bytes": "932" }, { "name": "CSS", "bytes": "9993928" }, { "name": "CoffeeScript", "bytes": "167262" }, { "name": "HTML", "bytes": "155512809" }, { "name": "JavaScript", "bytes": "12960293" }, { "name": "PHP", "bytes": "599248" }, { "name": "Shell", "bytes": "888" } ], "symlink_target": "" }
class LanguagePack::Helpers::RailsRunner # This class is used to help pull configuration values # from a rails application. It takes in a configuration key # and a reference to the parent RailsRunner object which # allows it obtain the `rails runner` output and success # status of the operation. # # For example: # # config = RailsConfig.new("active_storage.service", rails_runner) # config.to_command # => "puts %Q{heroku.detecting.config.for.active_storage.service=Rails.application.config.try(:active_storage).try(:service)}; " # class RailsConfig def initialize(config, rails_runner, options={}) @config = config @rails_runner = rails_runner @debug = options[:debug] @success = nil @did_time_out = false @heroku_key = "heroku.detecting.config.for.#{config}" @rails_config = String.new('#{') @rails_config << 'Rails.application.config' config.split('.').each do |part| @rails_config << ".try(:#{part})" end @rails_config << '}' end def success? @rails_runner.success? && @rails_runner.output =~ %r(#{@heroku_key}) end def did_match?(val) @rails_runner.output =~ %r(#{@heroku_key}=#{val}) end def to_command cmd = String.new('begin; ') cmd << 'puts %Q{' cmd << "#{@heroku_key}=#{@rails_config}" cmd << '}; ' cmd << 'rescue => e; ' cmd << 'puts e; puts e.backtrace; ' if @debug cmd << 'end;' cmd end end include LanguagePack::ShellHelpers def initialize(debug = env('DEBUG_RAILS_RUNNER'), timeout = 65) @command_array = [] @output = nil @success = false @debug = debug @timeout_val = timeout # seconds end def detect(config_string) config = RailsConfig.new(config_string, self, debug: @debug) @command_array << config.to_command config end def output @output ||= call end def success? output && @success end def command %Q{rails runner "#{@command_array.join(' ')}"} end def timeout? @did_time_out end private def call topic("Detecting rails configuration") puts "$ #{command}" if @debug out = execute_command! puts out if @debug out end def execute_command! process = ProcessSpawn.new(command, user_env: true, timeout: @timeout_val, file: "./.heroku/ruby/config_detect/rails.txt" ) @success = process.success? @did_time_out = process.timeout? out = process.output if timeout? message = String.new("Detecting rails configuration timeout\n") message << "set DEBUG_RAILS_RUNNER=1 to debug" unless @debug warn(message) mcount("warn.rails.runner.timeout") elsif !@success message = String.new("Detecting rails configuration failed\n") message << "set DEBUG_RAILS_RUNNER=1 to debug" unless @debug warn(message) mcount("warn.rails.runner.fail") end return out end end
{ "content_hash": "ac5e0bd5f71191c9ccb60f3582b289b3", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 153, "avg_line_length": 26.33050847457627, "alnum_prop": 0.5938204055358867, "repo_name": "Scalingo/ruby-buildpack", "id": "9e89a9d3e1eb2f64fa85a1d319a86f8209787ec1", "size": "3900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/language_pack/helpers/rails_runner.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "222587" }, { "name": "Shell", "bytes": "22609" } ], "symlink_target": "" }
'use strict'; const Lab = require('lab'); const Code = require('code'); const lab = exports.lab = Lab.script(); const describe = lab.describe; const it = lab.it; const expect = Code.expect; const superagent = require('superagent'); const API_URL = 'localhost:8081'; describe('/api/v1/users endpoints', () => { describe('GET /api/v1/users', () => { it('handle naked request', (done) => { superagent .get(API_URL + '/api/v1/users') .end((err, res) => { expect(res.statusCode).to.equal(200); done(); }); }); }); });
{ "content_hash": "8faedcde5a4042cd2c416e57b405c6f7", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 47, "avg_line_length": 23.08, "alnum_prop": 0.5719237435008665, "repo_name": "wordist/wordist.xyz", "id": "9214d4894f8f4fd7aeb3896ab2c35cc2f10ab8b8", "size": "577", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/api/v1/users/get.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "120591" }, { "name": "HTML", "bytes": "6285" }, { "name": "JavaScript", "bytes": "292589" }, { "name": "Shell", "bytes": "366" } ], "symlink_target": "" }
<?php namespace Site\TrailBundle\Services; use Site\TrailBundle\Entity\Parcours; class EvenementService { protected $entityManager; public function __construct(\Doctrine\ORM\EntityManager $em) { $this->entityManager = $em; } public function getEventAndEventUsed($idIti) { $listeEvenements = array(); $listeEvenementsUtilises = array(); $arrayEventId = array(); $listeParcours = $this->entityManager->getRepository("SiteTrailBundle:Parcours")->findBy(array('idItineraire' => $idIti)); foreach($listeParcours as $parcours) { $arrayEventId[] = $parcours->getEvenement()->getId(); } if(sizeof($arrayEventId) == 0) { $arrayEventId[] = 0; } $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Entrainement eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; //$query .= "AND event.id NOT IN (".implode(',', $arrayEventId).")"; $listeEvenements[] = $this->entityManager->createQuery($query)->getResult(); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Entrainementpersonnel eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; //$query .= "AND event.id NOT IN (".implode(',', $arrayEventId).")"; $listeEvenements[] = $this->entityManager->createQuery($query)->getResult(); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Evenementdivers eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; //$query .= "AND event.id NOT IN (".implode(',', $arrayEventId).")"; $listeEvenements[] = $this->entityManager->createQuery($query)->getResult(); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Sortiedecouverte eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; //$query .= "AND event.id NOT IN (".implode(',', $arrayEventId).")"; $listeEvenements[] = $this->entityManager->createQuery($query)->getResult(); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Courseofficielle eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; //$query .= "AND event.id NOT IN (".implode(',', $arrayEventId).")"; $listeEvenements[] = $this->entityManager->createQuery($query)->getResult(); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Entrainement eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; $query .= "AND event.id IN (".implode(',', $arrayEventId).")"; $listeEvenementsUtilises = $this->entityManager->createQuery($query)->getResult(); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Entrainementpersonnel eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; $query .= "AND event.id IN (".implode(',', $arrayEventId).")"; $listeEvenementsUtilises = array_merge($listeEvenementsUtilises, $this->entityManager->createQuery($query)->getResult()); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Evenementdivers eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; $query .= "AND event.id IN (".implode(',', $arrayEventId).")"; $listeEvenementsUtilises = array_merge($listeEvenementsUtilises, $this->entityManager->createQuery($query)->getResult()); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Sortiedecouverte eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; $query .= "AND event.id IN (".implode(',', $arrayEventId).")"; $listeEvenementsUtilises = array_merge($listeEvenementsUtilises, $this->entityManager->createQuery($query)->getResult()); $query = "SELECT eventCat "; $query .= "FROM SiteTrailBundle:Courseofficielle eventCat, SiteTrailBundle:Evenement event "; $query .= "WHERE eventCat.evenement = event.id "; $query .= "AND event.id IN (".implode(',', $arrayEventId).")"; $listeEvenementsUtilises = array_merge($listeEvenementsUtilises, $this->entityManager->createQuery($query)->getResult()); $res = array('allEvent' => $listeEvenements, 'usedEvent' => $listeEvenementsUtilises); return $res; } public function updateParcours($arrayIdEvenement, $idItineraire) { $listeParcours = $this->entityManager->getRepository("SiteTrailBundle:Parcours")->findBy(array('idItineraire' => $idItineraire)); if(is_array($listeParcours)) { foreach($listeParcours as $eventIti) { $this->entityManager->remove($eventIti); $this->entityManager->flush(); } } if(is_array($arrayIdEvenement)) { foreach($arrayIdEvenement as $id) { $parcours = new Parcours(); $evenement = $this->entityManager->getRepository("SiteTrailBundle:Evenement")->findOneById($id); $parcours->setEvenement($evenement); $parcours->setIdItineraire($idItineraire); $this->entityManager->persist($parcours); $this->entityManager->flush(); } } } public function getUsedIti($idEvent) { $evenement = $this->entityManager->getRepository("SiteTrailBundle:Evenement")->findOneBy(array('id' => $idEvent)); $listeParcours = $this->entityManager->getRepository("SiteTrailBundle:Parcours")->findBy(array('evenement' => $evenement)); $listeIdIti = array(); foreach($listeParcours as $parcours) { $listeIdIti[] = $parcours->getIdItineraire(); } return $listeIdIti; } }
{ "content_hash": "09e1b335fd1fedde0f45259565fded5e", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 137, "avg_line_length": 46.46762589928058, "alnum_prop": 0.5881715435825979, "repo_name": "kalazard/Trail", "id": "8a8be8755cb5b4094b8a982566d0ed48805d6a75", "size": "6459", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Site/TrailBundle/Services/EvenementService.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "Batchfile", "bytes": "405" }, { "name": "CSS", "bytes": "32186" }, { "name": "HTML", "bytes": "155313" }, { "name": "JavaScript", "bytes": "38659" }, { "name": "PHP", "bytes": "331331" }, { "name": "Shell", "bytes": "637" } ], "symlink_target": "" }
This is the subpackage consisting [`computational-algebra` project](https://konn.github.io/computational-algebra). It currently provides the basic classes and various types for polynomial ring, and easy interface for Gröbner basis computation. See [Project Page](https://konn.github.io/computational-algebra) for more detail.
{ "content_hash": "73103c2440f113902de6716f9dfbc8f9", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 128, "avg_line_length": 81.75, "alnum_prop": 0.8103975535168195, "repo_name": "konn/computational-algebra", "id": "dba33c49ac4c13438221cf534fc962c7614acded", "size": "347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "halg-polynomials/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Dhall", "bytes": "15510" }, { "name": "Dockerfile", "bytes": "6148" }, { "name": "Emacs Lisp", "bytes": "630" }, { "name": "HTML", "bytes": "2492897" }, { "name": "Haskell", "bytes": "769054" }, { "name": "Shell", "bytes": "980" } ], "symlink_target": "" }
"""Retrieves information about the available datasets.""" import enum from . import coco_info from . import magazine_info from . import publaynet_info from . import rico_info @enum.unique class DatasetName(enum.Enum): COCO = "COCO" RICO = "RICO" PUBLAYNET = "PubLayNet" MAGAZINE = "MAGAZINE" def get_number_classes(dataset_name): """Retrieves the number of labels for a given dataset.""" if dataset_name == DatasetName.RICO: return rico_info.NUMBER_LABELS elif dataset_name == DatasetName.PUBLAYNET: return publaynet_info.NUMBER_LABELS elif dataset_name == DatasetName.MAGAZINE: return magazine_info.NUMBER_LABELS elif dataset_name == DatasetName.COCO: return coco_info.NUMBER_LABELS else: raise ValueError(f"Unknown dataset '{dataset_name}'") def get_id_to_label_map(dataset_name): """Retrieves the id to label map for a given dataset.""" if dataset_name == DatasetName.RICO: return rico_info.ID_TO_LABEL elif dataset_name == DatasetName.PUBLAYNET: return publaynet_info.ID_TO_LABEL elif dataset_name == DatasetName.MAGAZINE: return magazine_info.ID_TO_LABEL elif dataset_name == DatasetName.COCO: return coco_info.ID_TO_LABEL else: raise ValueError(f"Unknown dataset '{dataset_name}'")
{ "content_hash": "bd750a9a321be0050edd2704a08891bd", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 59, "avg_line_length": 28.818181818181817, "alnum_prop": 0.7247634069400631, "repo_name": "google-research/google-research", "id": "4d032a8d1dc6635191079bc962b519f2130ea7b5", "size": "1876", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "layout-blt/datasets/datasets_info.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "9817" }, { "name": "C++", "bytes": "4166670" }, { "name": "CMake", "bytes": "6412" }, { "name": "CSS", "bytes": "27092" }, { "name": "Cuda", "bytes": "1431" }, { "name": "Dockerfile", "bytes": "7145" }, { "name": "Gnuplot", "bytes": "11125" }, { "name": "HTML", "bytes": "77599" }, { "name": "ImageJ Macro", "bytes": "50488" }, { "name": "Java", "bytes": "487585" }, { "name": "JavaScript", "bytes": "896512" }, { "name": "Julia", "bytes": "67986" }, { "name": "Jupyter Notebook", "bytes": "71290299" }, { "name": "Lua", "bytes": "29905" }, { "name": "MATLAB", "bytes": "103813" }, { "name": "Makefile", "bytes": "5636" }, { "name": "NASL", "bytes": "63883" }, { "name": "Perl", "bytes": "8590" }, { "name": "Python", "bytes": "53790200" }, { "name": "R", "bytes": "101058" }, { "name": "Roff", "bytes": "1208" }, { "name": "Rust", "bytes": "2389" }, { "name": "Shell", "bytes": "730444" }, { "name": "Smarty", "bytes": "5966" }, { "name": "Starlark", "bytes": "245038" } ], "symlink_target": "" }
package id.goindonesia.area.indonesia.repositories.search; import id.goindonesia.area.indonesia.commons.component.BaseSearchRepository; import id.goindonesia.area.indonesia.models.DistrictEntity; /** * Created by ghostzali on 25/04/17. */ public interface DistrictSearchRepository extends BaseSearchRepository<DistrictEntity> { }
{ "content_hash": "b1beb3b6f88493005afc75c42bf96e39", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 88, "avg_line_length": 33.4, "alnum_prop": 0.8293413173652695, "repo_name": "ghostzali-lib/area-indonesia", "id": "b8cbf6ee0faf53c253a0ed171e07ccf69a59a209", "size": "334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/id/goindonesia/area/indonesia/repositories/search/DistrictSearchRepository.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "68697" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Tabs { public enum TabType { File, Normal, Tab, Url, Member, } }
{ "content_hash": "1f1999797f38cd20dd091eb06d837534", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 71, "avg_line_length": 23.666666666666668, "alnum_prop": 0.6366197183098592, "repo_name": "EPTamminga/Dnn.Platform", "id": "39b83b79763825bc24e9403e4460cb4152933448", "size": "357", "binary": false, "copies": "1", "ref": "refs/heads/Issue_4029", "path": "DNN Platform/Library/Entities/Tabs/TabType.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "572447" }, { "name": "Batchfile", "bytes": "405" }, { "name": "C#", "bytes": "21818693" }, { "name": "CSS", "bytes": "1653890" }, { "name": "HTML", "bytes": "528314" }, { "name": "JavaScript", "bytes": "8363259" }, { "name": "PLpgSQL", "bytes": "53478" }, { "name": "PowerShell", "bytes": "10808" }, { "name": "Smalltalk", "bytes": "2410" }, { "name": "TSQL", "bytes": "56032" }, { "name": "Visual Basic", "bytes": "139195" }, { "name": "XSLT", "bytes": "10488" } ], "symlink_target": "" }
def ask(question, kind="string") print question + " " answer = gets.chomp answer = answer.to_i if kind == "number" return answer end answer = ask("What is your name?") puts answer def add_contact contact = {"name" => "", "phone_numbers" => []} contact["name"] = ask("What is the person's name?") answer = "" while answer != "n" answer = ask("Do you want to add a phone number? (y/n)") if answer == "y" phone = ask("Enter phone number:") contact["phone_numbers"].push(phone) end end return contact end contact_list = [] answer = "" while answer != "n" contact_list.push(add_contact()) answer = ask("Add another? (y/n)") end puts "---" contact_list.each do |contact| puts "Name: #{contact["name"]}" if contact["phone_numbers"].size > 0 contact["phone_numbers"].each do |phone_number| puts "Phone: #{phone_number}" end end puts "---\n" end
{ "content_hash": "a29fa2332baac90f82abf9e5c29cc9dd", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 58, "avg_line_length": 19.977272727272727, "alnum_prop": 0.6325369738339022, "repo_name": "josectello/ruby_practice", "id": "68bd725c9d3e2575247a2acdcfcfcebbe3f10ba8", "size": "879", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "contact_list.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "18876" } ], "symlink_target": "" }
<?php $this->startSetup(); //$this->run("ADD YOUR SQL HERE"); $this->endSetup();
{ "content_hash": "18b23cce7cec7a4e5e52b096b64bd171", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 36, "avg_line_length": 21.75, "alnum_prop": 0.5747126436781609, "repo_name": "falodunos/ravepay.checkout", "id": "4952b37f3f02d6e7d5798e60fd478009c2078e5e", "size": "87", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/code/local/Rave/Ravecheckout/sql/ravecheckout_setup/mysql4-install-0.1.0.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "687" }, { "name": "JavaScript", "bytes": "4586" }, { "name": "PHP", "bytes": "18148" } ], "symlink_target": "" }
package org.apache.zeppelin.spark; import org.apache.hadoop.util.VersionInfo; import org.apache.hadoop.util.VersionUtil; import org.apache.zeppelin.interpreter.InterpreterContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.util.Map; import java.util.Properties; /** * This is abstract class for anything that is api incompatible between spark1 and spark2. It will * load the correct version of SparkShims based on the version of Spark. */ public abstract class SparkShims { // the following lines for checking specific versions private static final String HADOOP_VERSION_2_6_6 = "2.6.6"; private static final String HADOOP_VERSION_2_7_0 = "2.7.0"; private static final String HADOOP_VERSION_2_7_4 = "2.7.4"; private static final String HADOOP_VERSION_2_8_0 = "2.8.0"; private static final String HADOOP_VERSION_2_8_2 = "2.8.2"; private static final String HADOOP_VERSION_2_9_0 = "2.9.0"; private static final String HADOOP_VERSION_3_0_0 = "3.0.0"; private static final String HADOOP_VERSION_3_0_0_ALPHA4 = "3.0.0-alpha4"; private static final Logger LOGGER = LoggerFactory.getLogger(SparkShims.class); private static SparkShims sparkShims; private static SparkShims loadShims(String sparkVersion) throws ReflectiveOperationException { Class<?> sparkShimsClass; if ("2".equals(sparkVersion)) { LOGGER.info("Initializing shims for Spark 2.x"); sparkShimsClass = Class.forName("org.apache.zeppelin.spark.Spark2Shims"); } else { LOGGER.info("Initializing shims for Spark 1.x"); sparkShimsClass = Class.forName("org.apache.zeppelin.spark.Spark1Shims"); } Constructor c = sparkShimsClass.getConstructor(); return (SparkShims) c.newInstance(); } public static SparkShims getInstance(String sparkVersion) { if (sparkShims == null) { String sparkMajorVersion = getSparkMajorVersion(sparkVersion); try { sparkShims = loadShims(sparkMajorVersion); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } return sparkShims; } private static String getSparkMajorVersion(String sparkVersion) { return sparkVersion.startsWith("2") ? "2" : "1"; } /** * This is due to SparkListener api change between spark1 and spark2. SparkListener is trait in * spark1 while it is abstract class in spark2. */ public abstract void setupSparkListener(String master, String sparkWebUrl, InterpreterContext context); protected String getNoteId(String jobgroupId) { int indexOf = jobgroupId.indexOf("-"); int secondIndex = jobgroupId.indexOf("-", indexOf + 1); return jobgroupId.substring(indexOf + 1, secondIndex); } protected String getParagraphId(String jobgroupId) { int indexOf = jobgroupId.indexOf("-"); int secondIndex = jobgroupId.indexOf("-", indexOf + 1); return jobgroupId.substring(secondIndex + 1, jobgroupId.length()); } protected void buildSparkJobUrl(String master, String sparkWebUrl, int jobId, Properties jobProperties, InterpreterContext context) { String uiEnabled = jobProperties.getProperty("spark.ui.enabled"); String jobUrl = sparkWebUrl + "/jobs/job?id=" + jobId; // Button visible if Spark UI property not set, set as invalid boolean or true boolean showSparkUI = uiEnabled == null || !uiEnabled.trim().toLowerCase().equals("false"); String version = VersionInfo.getVersion(); if (master.toLowerCase().contains("yarn") && !supportYarn6615(version)) { jobUrl = sparkWebUrl + "/jobs"; } if (showSparkUI && jobUrl != null) { Map<String, String> infos = new java.util.HashMap<String, String>(); infos.put("jobUrl", jobUrl); infos.put("label", "SPARK JOB"); infos.put("tooltip", "View in Spark web UI"); infos.put("noteId", context.getNoteId()); infos.put("paraId", context.getParagraphId()); context.getIntpEventClient().onParaInfosReceived(infos); } } /** * This is temporal patch for support old versions of Yarn which is not adopted YARN-6615 * * @return true if YARN-6615 is patched, false otherwise */ protected boolean supportYarn6615(String version) { return (VersionUtil.compareVersions(HADOOP_VERSION_2_6_6, version) <= 0 && VersionUtil.compareVersions(HADOOP_VERSION_2_7_0, version) > 0) || (VersionUtil.compareVersions(HADOOP_VERSION_2_7_4, version) <= 0 && VersionUtil.compareVersions(HADOOP_VERSION_2_8_0, version) > 0) || (VersionUtil.compareVersions(HADOOP_VERSION_2_8_2, version) <= 0 && VersionUtil.compareVersions(HADOOP_VERSION_2_9_0, version) > 0) || (VersionUtil.compareVersions(HADOOP_VERSION_2_9_0, version) <= 0 && VersionUtil.compareVersions(HADOOP_VERSION_3_0_0, version) > 0) || (VersionUtil.compareVersions(HADOOP_VERSION_3_0_0_ALPHA4, version) <= 0) || (VersionUtil.compareVersions(HADOOP_VERSION_3_0_0, version) <= 0); } }
{ "content_hash": "a778688cbdd790514bccb597863e18cd", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 98, "avg_line_length": 41.39370078740158, "alnum_prop": 0.673197641240251, "repo_name": "herval/zeppelin", "id": "6d45b0693d142664176cc7379c0b4810550b8b78", "size": "6057", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spark/spark-shims/src/main/scala/org/apache/zeppelin/spark/SparkShims.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "11970" }, { "name": "CSS", "bytes": "87087" }, { "name": "Groovy", "bytes": "9274" }, { "name": "HTML", "bytes": "305732" }, { "name": "Java", "bytes": "4157175" }, { "name": "JavaScript", "bytes": "571145" }, { "name": "Jupyter Notebook", "bytes": "84915" }, { "name": "Python", "bytes": "74417" }, { "name": "R", "bytes": "21301" }, { "name": "Roff", "bytes": "60995" }, { "name": "Ruby", "bytes": "3101" }, { "name": "Scala", "bytes": "344318" }, { "name": "Shell", "bytes": "77121" }, { "name": "Thrift", "bytes": "5084" }, { "name": "XSLT", "bytes": "1326" } ], "symlink_target": "" }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(registration, updateMask) { // [START domains_v1_generated_Domains_ConfigureContactSettings_async] /** * This snippet has been automatically generated and should be regarded as a code template only. * It will require modifications to work. * It may require correct/in-range values for request initialization. * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The name of the `Registration` whose contact settings are being updated, * in the format `projects/* /locations/* /registrations/*`. */ // const registration = 'abc123' /** * Fields of the `ContactSettings` to update. */ // const contactSettings = {} /** * Required. The field mask describing which fields to update as a comma-separated list. * For example, if only the registrant contact is being updated, the * `update_mask` is `"registrant_contact"`. */ // const updateMask = {} /** * The list of contact notices that the caller acknowledges. The notices * needed here depend on the values specified in `contact_settings`. */ // const contactNotices = 1234 /** * Validate the request without actually updating the contact settings. */ // const validateOnly = true // Imports the Domains library const {DomainsClient} = require('@google-cloud/domains').v1; // Instantiates a client const domainsClient = new DomainsClient(); async function callConfigureContactSettings() { // Construct request const request = { registration, updateMask, }; // Run request const [operation] = await domainsClient.configureContactSettings(request); const [response] = await operation.promise(); console.log(response); } callConfigureContactSettings(); // [END domains_v1_generated_Domains_ConfigureContactSettings_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
{ "content_hash": "a0f2e3107e9dd1826538964d7c61825d", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 98, "avg_line_length": 33.86746987951807, "alnum_prop": 0.7061543934542868, "repo_name": "googleapis/google-cloud-node", "id": "3bae54ac966c2b66dd165e4677499a11c1f61ad1", "size": "2811", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "packages/google-cloud-domains/samples/generated/v1/domains.configure_contact_settings.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2789" }, { "name": "JavaScript", "bytes": "10920867" }, { "name": "Python", "bytes": "19983" }, { "name": "Shell", "bytes": "58046" }, { "name": "TypeScript", "bytes": "77312562" } ], "symlink_target": "" }
package foam.dao; import foam.core.Detachable; import foam.core.FObject; import foam.core.X; public class RemoveSink extends AbstractSink { protected X x_; protected DAO dao_; public RemoveSink(X x, DAO dao) { x_ = x; dao_ = dao; } @Override public void put(Object obj, Detachable sub) { dao_.remove_(x_, (FObject)obj); } }
{ "content_hash": "bcbab28e8df65324bccd53097799c18e", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 47, "avg_line_length": 15.083333333333334, "alnum_prop": 0.649171270718232, "repo_name": "foam-framework/foam2", "id": "cc91a7c1bad528ac54a896b962d043cb205723a0", "size": "484", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/foam/dao/RemoveSink.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20356" }, { "name": "HTML", "bytes": "10220505" }, { "name": "Java", "bytes": "977816" }, { "name": "JavaScript", "bytes": "7065731" }, { "name": "Makefile", "bytes": "7676" }, { "name": "Shell", "bytes": "5963" }, { "name": "Swift", "bytes": "19039" } ], "symlink_target": "" }
@import WowWeeMiPSDK; @interface ViewController () <MipRobotDelegate> @property (nonatomic, weak) MipRobot *mip; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self addNotificationObservers]; [MipRobotFinder sharedInstance]; } - (void)dealloc { [self removeNotificationObservers]; self.mip = nil; } - (void)viewDidAppear:(BOOL)animated { // We need to wait 1 second to make sure that bluetooth is ready //[self performSelector:@selector(scan) withObject:nil afterDelay:1]; [self scan]; } - (void)scan { [[MipRobotFinder sharedInstance] scanForAllRobots]; } - (void)addNotificationObservers { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mipFoundNotification:) name:MipRobotFinderNotificationID object:nil]; } - (void)removeNotificationObservers { [[NSNotificationCenter defaultCenter] removeObserver:self name:MipRobotFinderNotificationID object:nil]; } #pragma mark - Button Actions - (IBAction)playSoundPressed:(id)sender { NSLog(@"Playing MiP Sound"); // Distinguish different robot by mipRobotType if(self.mip.mipRobotType == MipType_MinionMip) { // Playing sound in TurboDave by kMinionMipSoundFileValue kMinionMipSoundFileValue value; switch (rand()%4) { case 0: value = kMinionMipSoundFile_SPEECH_S_DMF_MINION_HELLO; break; case 1: value = kMinionMipSoundFile_NEW_FART_WET; break; case 2: value = kMinionMipSoundFile_SCREAMS_DMF_MINION_SCREAMS_INTO_TRASH_CAN_DM2; break; default: value = kMinionMipSoundFile_HAPPY_KEVIN_DIAL_116_OH_NO_ME_LE_DO_IT; break; } [(MinionMipRobot*)self.mip minionPlaySoundWithEnum:value]; } else { // When playing a sound we need to first create a sound object, all available builtin sounds are avaialble as constants using kMipSoundFile kMipSoundFileValue value; switch (rand()%4) { case 0: value = kMipSoundFile_MIP_FIGHT; break; case 1: value = kMipSoundFile_MIP_IN_LOVE; break; case 2: value = kMipSoundFile_MIP_3; break; default: value = kMipSoundFile_MIP_MUSIC; break; } MipRobotSound *mipSound = [MipRobotSound mipRobotSoundWithFile:value]; [self.mip mipPlaySound:mipSound]; } } - (IBAction)changeChestRGBPressed:(id)sender { NSLog(@"Changing RGB colour"); // Pass a UIColor here to define what colour you want the Chest RGB to turn UIColor* ledColor; switch (rand()%7) { case 0: ledColor = [UIColor redColor]; break; case 1: ledColor = [UIColor greenColor]; break; case 2: ledColor = [UIColor yellowColor]; break; case 3: ledColor = [UIColor orangeColor]; break; case 4: ledColor = [UIColor purpleColor]; break; case 5: ledColor = [UIColor whiteColor]; break; case 6: ledColor = [UIColor blueColor]; break; } [self.mip setMipChestRGBLedWithColor:ledColor]; } - (IBAction)falloverPressed:(id)sender { NSLog(@"MiP is falling forward.... Tiiiiiimmmmmmbbeeeeer!"); // Mip can fall forward or backward, in our example we are just simply making him fall forward [self.mip mipFalloverWithStyle:kMipPositionFaceDown]; // only kMipPositionFaceDown / kMipPositionOnBack } #pragma mark - MipRobotFinder Notification - (void)mipFoundNotification:(NSNotification *)note { NSDictionary *noteDict = note.userInfo; if (!noteDict || !noteDict[@"code"]) { return; } MipRobotFinderNote noteType = (MipRobotFinderNote)[noteDict[@"code"] integerValue]; if (noteType == MipRobotFinderNote_MipFound) { MipRobot *mip = noteDict[@"data"]; // Normally you might want to add this object to an array and use a UITableView to display all the found devices for the user to select. For now we just want to print this MiP to the console NSLog(@"Found: %@", mip); self.mipStatusLabel.text = [NSString stringWithFormat:@"Found MiP: %@", mip.name]; // We have one MiP so stop scanning [[MipRobotFinder sharedInstance] stopScanForMips]; // Before connecting we want to setup which class is going to handle callbacks, for simplicity we are going to use this class for everything but normally you might use a different class mip.delegate = self; self.mipStatusLabel.text = [NSString stringWithFormat:@"Connecting: %@", mip.name]; // Lets connect [mip connect]; } else if (noteType == MipRobotFinderNote_BluetoothError) { CBCentralManagerState errorCode = (CBCentralManagerState)[noteDict[@"data"] integerValue]; if (errorCode == CBCentralManagerStateUnsupported) { NSLog(@"Bluetooth Unsupported on this device"); self.mipStatusLabel.text = @"Bluetooth Unsupported on this device"; } else if (errorCode == CBCentralManagerStatePoweredOff) { NSLog(@"Bluetooth is turned off"); self.mipStatusLabel.text = @"Bluetooth Unsupported on this device"; } } else if (noteType == MipRobotFinderNote_BluetoothIsAvailable) { //[[MipRobotFinder sharedInstance] scanForMips]; } } #pragma mark - MipRobot Callbacks - (void) MipDeviceReady:(MipRobot *)mip { self.mip = mip; // Yay we are connected and ready to talk self.mipStatusLabel.text = [NSString stringWithFormat:@"Connected: %@", mip.name]; self.playSoundButton.enabled = YES; self.changeRGBColourButton.enabled = YES; self.falloverButton.enabled = YES; self.driveButton.enabled = YES; self.weightLevel.enabled =YES; [self.mip readMipSensorWeightLevel]; [self.mip getMipClapStatus]; [self.mip getMipGestureMode]; } -(void) MipRobot:(MipRobot *)mip didReceiveNumberOfClaps:(NSUInteger)claptimes{ NSLog(@"(void) MipRobot:(MipRobot *)mip didReceiveNumberOfClaps:(NSUInteger)claptimes"); } -(void) MipRobot:(MipRobot *)mip didReceiveClapDetectionStatusIsEnabled:(bool)isEnabled withMSTiming:(NSUInteger)milliseconds{ NSLog(@"didReceiveClapDetectionStatusIsEnabled %d %lu",isEnabled, (unsigned long)milliseconds); if (!isEnabled) { [self.mip setMipClapDelayTime:1000]; [self.mip setMipClapEnable:true]; } } - (void) MipDeviceDisconnected:(MipRobot *)mip error:(NSError *)error { self.mipStatusLabel.text = [NSString stringWithFormat:@"Disconnected from MiP"]; self.playSoundButton.enabled = NO; self.changeRGBColourButton.enabled = NO; self.falloverButton.enabled = NO; self.driveButton.enabled = NO; self.weightLevel.enabled =NO; self.mip = nil; [[MipRobotFinder sharedInstance] clearFoundMipList]; [[MipRobotFinder sharedInstance] scanForMips]; } -(void) MipRobot:(MipRobot *)mip didReceiveWeightReading:(uint8_t)value learningForward:(bool)learningForward { NSLog(@"didReceiveWeightReading"); int8_t weight = value; [self.weightLevel setText:[NSString stringWithFormat:@"Level = %d !",weight]]; [self performSelector:@selector(resetLevel) withObject:nil afterDelay:2]; } -(void) MipRobot:(MipRobot *)mip didReceiveGestureMode:(kMipGestureModeValue)value { if (value == kMipGestureMode_Off) { [self.mip setMipGestureMode:kMipGestureMode_On]; [self.mip getMipGestureMode]; }else { NSLog(@"Gesture ready"); } } -(void) MipRobot:(MipRobot *)mip didReceiveGesture:(kMipGestureValue)value{ NSLog(@"didReceiveGesture %@",[MipCommandValues gestureText:value]); } -(void)resetLevel{ [self.weightLevel setText:[NSString stringWithFormat:@"Weight Level"]]; } @end
{ "content_hash": "2be217f7789ade436030d4a6396838c7", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 198, "avg_line_length": 31.62686567164179, "alnum_prop": 0.6343794242567249, "repo_name": "WowWeeLabs/MiP-iOS-SDK", "id": "f06bdadd1b54b91b9e4f1dd9098ba4d244dc1030", "size": "8647", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SampleProject/SampleProject/ViewController.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "124362" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_18) on Tue Jul 07 10:41:04 PDT 2009 --> <TITLE> TierFactory </TITLE> <META NAME="keywords" CONTENT="apollo.gui.detailviewers.sequencealigner.TierFactory class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="TierFactory"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</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;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Tier.html" title="class in apollo.gui.detailviewers.sequencealigner"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?apollo/gui/detailviewers/sequencealigner/TierFactory.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TierFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> apollo.gui.detailviewers.sequencealigner</FONT> <BR> Class TierFactory</H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>apollo.gui.detailviewers.sequencealigner.TierFactory</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierFactoryI</A></DD> </DL> <HR> <DL> <DT><PRE>public class <B>TierFactory</B><DT>extends java.lang.Object<DT>implements <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierFactoryI</A></DL> </PRE> <P> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactory.html#TierFactory(apollo.gui.detailviewers.sequencealigner.ReferenceFactoryI, apollo.gui.detailviewers.sequencealigner.Strand, apollo.gui.detailviewers.sequencealigner.ReadingFrame)">TierFactory</A></B>(<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReferenceFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner">ReferenceFactoryI</A>&nbsp;ref, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A>&nbsp;s, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A>&nbsp;rf)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactory.html#getReadingFrame()">getReadingFrame</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactory.html#getStrand()">getStrand</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierI</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactory.html#makeTier()">makeTier</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierI</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactory.html#makeTier(apollo.datamodel.SequenceI, apollo.gui.detailviewers.sequencealigner.Strand, apollo.gui.detailviewers.sequencealigner.ReadingFrame)">makeTier</A></B>(<A HREF="../../../../apollo/datamodel/SequenceI.html" title="interface in apollo.datamodel">SequenceI</A>&nbsp;reference, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A>&nbsp;s, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A>&nbsp;rf)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactory.html#setReadingFrame(apollo.gui.detailviewers.sequencealigner.ReadingFrame)">setReadingFrame</A></B>(<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A>&nbsp;rf)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactory.html#setStrand(apollo.gui.detailviewers.sequencealigner.Strand)">setStrand</A></B>(<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A>&nbsp;s)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="TierFactory(apollo.gui.detailviewers.sequencealigner.ReferenceFactoryI, apollo.gui.detailviewers.sequencealigner.Strand, apollo.gui.detailviewers.sequencealigner.ReadingFrame)"><!-- --></A><H3> TierFactory</H3> <PRE> public <B>TierFactory</B>(<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReferenceFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner">ReferenceFactoryI</A>&nbsp;ref, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A>&nbsp;s, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A>&nbsp;rf)</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="makeTier()"><!-- --></A><H3> makeTier</H3> <PRE> public <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierI</A> <B>makeTier</B>()</PRE> <DL> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html#makeTier()">makeTier</A></CODE> in interface <CODE><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierFactoryI</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="makeTier(apollo.datamodel.SequenceI, apollo.gui.detailviewers.sequencealigner.Strand, apollo.gui.detailviewers.sequencealigner.ReadingFrame)"><!-- --></A><H3> makeTier</H3> <PRE> public <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierI</A> <B>makeTier</B>(<A HREF="../../../../apollo/datamodel/SequenceI.html" title="interface in apollo.datamodel">SequenceI</A>&nbsp;reference, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A>&nbsp;s, <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A>&nbsp;rf)</PRE> <DL> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html#makeTier(apollo.datamodel.SequenceI, apollo.gui.detailviewers.sequencealigner.Strand, apollo.gui.detailviewers.sequencealigner.ReadingFrame)">makeTier</A></CODE> in interface <CODE><A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner">TierFactoryI</A></CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getStrand()"><!-- --></A><H3> getStrand</H3> <PRE> public <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A> <B>getStrand</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="setStrand(apollo.gui.detailviewers.sequencealigner.Strand)"><!-- --></A><H3> setStrand</H3> <PRE> public void <B>setStrand</B>(<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Strand.html" title="enum in apollo.gui.detailviewers.sequencealigner">Strand</A>&nbsp;s)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getReadingFrame()"><!-- --></A><H3> getReadingFrame</H3> <PRE> public <A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A> <B>getReadingFrame</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="setReadingFrame(apollo.gui.detailviewers.sequencealigner.ReadingFrame)"><!-- --></A><H3> setReadingFrame</H3> <PRE> public void <B>setReadingFrame</B>(<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/ReadingFrame.html" title="enum in apollo.gui.detailviewers.sequencealigner">ReadingFrame</A>&nbsp;rf)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</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;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/Tier.html" title="class in apollo.gui.detailviewers.sequencealigner"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../apollo/gui/detailviewers/sequencealigner/TierFactoryI.html" title="interface in apollo.gui.detailviewers.sequencealigner"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?apollo/gui/detailviewers/sequencealigner/TierFactory.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TierFactory.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "aec16835e45379e198041fe1ec187226", "timestamp": "", "source": "github", "line_count": 371, "max_line_length": 468, "avg_line_length": 48.37735849056604, "alnum_prop": 0.6667595275239581, "repo_name": "genome-vendor/apollo", "id": "dcc7b9019c7526e23e4f66ecbc0f495202634a09", "size": "17948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/apollo/gui/detailviewers/sequencealigner/TierFactory.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "11006" }, { "name": "Java", "bytes": "8207482" }, { "name": "Perl", "bytes": "41725" }, { "name": "Shell", "bytes": "15681" } ], "symlink_target": "" }
'use strict'; /* global define */ define([ "jquery", "backbone", "models/Text" ], function ($, Backbone, Text) { return Backbone.Collection.extend({ model: Text, initialize: function (options) { this.url = '/api/justtexts/page/' + options.page.replace(/\*/, '') + '/text/' + options.language; } }); });
{ "content_hash": "15925f8dac0120e4f1a05ef87a3e28ee", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 109, "avg_line_length": 23.466666666666665, "alnum_prop": 0.5539772727272727, "repo_name": "JustsoSoftware/JustTexts", "id": "5ccc181b8aa25027cc0e82da76aab8071b7791ae", "size": "518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/collections/TextCollection.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3515" }, { "name": "HTML", "bytes": "2429" }, { "name": "JavaScript", "bytes": "11822" }, { "name": "PHP", "bytes": "43957" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Michael Yeung's BLog</title> <!-- Bootstrap --> <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet"> <style> a:link { color: #4C4C4C; } /* visited link */ a:visited { color: #79796B; } /* mouse over link */ a:hover { color: #79796B; text-decoration: none; } /* selected link */ a:active { color: #79796B; } #icon { height: 2em; width: 2em; border-radius: 10px; margin-top: 10px; margin-left: 5px; } .iconrow { text-align: center; margin-top: 3em; } .menus { margin-top: 2em; margin-left: auto; margin-right: auto; text-align: center; width: 50em; } .bottom { margin-top: 10em; text-align: center; } .panel { width: 40em; } .panel-heading { font-style: bold; } #home { margin-top: 10em; } </style> </head> <body background="img/grey.jpg"> <div class="container"> <div class="iconrow"> <a href="https://twitter.com/__michaelyeung"><img id="icon" src="img/twitter.png"/></a> <a href="https://www.facebook.com/michael.yeung.140"><img id="icon" src="img/facebook.png"/></a> <a href="https://github.com/myeung58"><img id="icon" src="img/github.jpg"/></a> <a href="https://www.linkedin.com/in/michaelhkyeung"><img id="icon" src="img/linkedin.png"/></a> <a href="https://plus.google.com/108706798578664618888/about"><img id="icon" src="img/google.png"/></a> </div> <div class="menus"> <div class="col-md-6"> <div class="panel-default"> <div class="panel-heading"><h4>Technical Blog</h4></div> <div class="panel-body"> <a href="blog-posts/week8_technical.html"><h5>Brief explanation: Recursion</h5></a> <a href="blog-posts/week7_technical.html"><h5>SQL Issues</h5></a> <a href="blog-posts/week6_technical.html"><h5>Blocks, Procs and Lambdas</h5></a> <a href="blog-posts/week5_technical.html"><h5>Classes and their applications</h5></a> <a href="blog-posts/week4_technical.html"><h5>Arrays vs Hashes</h5></a> <a href="blog-posts/week3_technical.html"><h5>Why JavaScript is popular</h5></a> <a href="blog-posts/week2_technical.html"><h5>HTML: Introduction to positioning</h5></a> <a href="blog-posts/week1_technical.html"><h5>Three favorite websites</h5></a> </div> </div> </div> <div class="col-md-6"> <div class="panel-default"> <div class="panel-heading"><h4>Cultural Blog</h4></div> <div class="panel-body"> <a href="../blog-posts/week9_cultural.html"><h5>Asking questions</h5></a> <a href="blog-posts/week8_cultural.html"><h5>Dealing with conflict</h5></a> <a href="blog-posts/week7_cultural.html"><h5>Affirmation and stereotype threat</h5></a> <a href="blog-posts/week6_cultural.html"><h5>General stereotype threats</h5></a> <a href="blog-posts/week5_cultural.html"><h5>Pairing and giving feedbacks</h5></a> <a href="blog-posts/week4_cultural.html"><h5>Potential issue in tech: Compliance with local regulations</h5></a> <a href="blog-posts/week3_cultural.html"><h5>Thinking style</h5></a> <a href="blog-posts/week2_cultural.html"><h5>My biggest fears</h5></a> <a href="blog-posts/week1_cultural.html"><h5>My thoughts on DBC</h5></a> </div> </div> </div> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </div> </body> </html>
{ "content_hash": "beebf3f047e3a898b05fc6aecc412c75", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 119, "avg_line_length": 33.24576271186441, "alnum_prop": 0.6041294927351517, "repo_name": "myeung58/myeung58.github.io", "id": "43b776e443579dbf565dae8cca63b2016fe21e29", "size": "3923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "menu.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "139351" }, { "name": "HTML", "bytes": "169317" }, { "name": "JavaScript", "bytes": "1" } ], "symlink_target": "" }
Server side optical character recognition based on NPM wrap of Tesseract. Uses NPM package 'node-tesseract', version 0.2.7. #Use Exposes tesseract global object with the same NPM api. An additional method is exposed, 'syncProcess', which returns the Tesseract results synchronously using the meteorhacks:async package. This is probably desirable when returning the result to the client via a Meteor Method. See Examples folder. ```javascript return tesseract.syncProcess('/path/to/img'); // or return tesseract.syncProcess('/path/to/img', options); ``` #Config If tesseract binary is in your path, it should work, no problem. You can explicitly set your Tessdata_Prefix in your environment or Meteor.Settings. In which case, syncProcess will default to these, if they aren't explicitly defined in the options in your function call.
{ "content_hash": "941ccd578ea44ac3437f57b330578136", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 222, "avg_line_length": 36.52173913043478, "alnum_prop": 0.7880952380952381, "repo_name": "awylie199/meteor-tesseract", "id": "34dfa1562caf6ec58ac02ad124e05fab6af326bb", "size": "859", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2972" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>MadeULook Lash &amp; Beauty Bar</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta name="apple-mobile-web-app-capable" content="yes"/> <meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimal-ui"/> <meta name="apple-mobile-web-app-status-bar-style" content="yes"/> <link rel="stylesheet" href="css/app.min.css"/> <link rel="stylesheet" href="css/responsive.min.css"/> <!-- inject:js --> <script src="js/app.min.js"></script> </head> <body ng-app="WebUiMobile" ng-controller="MainController"> <!-- Sidebars --> <div ng-include="'sidebar.html'" ui-track-as-search-param='true' class="sidebar sidebar-left"></div> <div class="app"> <!-- Navbars --> <div class="navbar navbar-app navbar-absolute-top"> <div class="navbar-brand navbar-brand-center" ui-yield-to="title"> Mobile Angular UI </div> <div class="btn-group pull-left"> <div ui-toggle="uiSidebarLeft" class="btn sidebar-toggle"> <i class="fa fa-bars"></i> Menu </div> </div> <div class="btn-group pull-right" ui-yield-to="navbarAction"> <div ui-toggle="uiSidebarRight" class="btn"> <i class="fa fa-comment"></i> Chat </div> </div> </div> <div class="navbar navbar-app navbar-absolute-bottom"> <div class="btn-group justified"> <a href="http://mobileangularui.com/" class="btn btn-navbar"><i class="fa fa-home fa-navbar"></i> Docs</a> <a href="https://github.com/mcasimir/mobile-angular-ui" class="btn btn-navbar"><i class="fa fa-github fa-navbar"></i> Sources</a> <a href="https://github.com/mcasimir/mobile-angular-ui/issues" class="btn btn-navbar"><i class="fa fa-exclamation-circle fa-navbar"></i> Issues</a> </div> </div> <!-- App Body --> <div class="app-body"> <div class="app-content"> <ng-view></ng-view> </div> </div> </div><!-- ~ .app --> <div ui-yield-to="modals"></div> </body> </html>
{ "content_hash": "608dcda2c767a245837b951a810f64d9", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 112, "avg_line_length": 32.21875, "alnum_prop": 0.623666343355965, "repo_name": "madeulook/web-ui", "id": "24cc90d909d42831557df7650e8d785abc005c97", "size": "2062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/app/src/html/indexold.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "5309" }, { "name": "HTML", "bytes": "48353" }, { "name": "Java", "bytes": "1488" }, { "name": "JavaScript", "bytes": "13528" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.nifi</groupId> <artifactId>nifi-commons</artifactId> <version>1.13.0-SNAPSHOT</version> </parent> <artifactId>nifi-record</artifactId> <description> This module contains the domain model for NiFi's Record abstraction, including several interfaces for interacting with Records. This module should not depend on any external libraries. </description> </project>
{ "content_hash": "652c798525ddaeeb54bac4f1733f1dee", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 205, "avg_line_length": 48.774193548387096, "alnum_prop": 0.7321428571428571, "repo_name": "mattyb149/nifi", "id": "8d27c07c66f19e170829b806b38b06d88b12a2b3", "size": "1512", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "nifi-commons/nifi-record/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "21394" }, { "name": "C++", "bytes": "652" }, { "name": "CSS", "bytes": "238624" }, { "name": "Clojure", "bytes": "3993" }, { "name": "Dockerfile", "bytes": "12380" }, { "name": "GAP", "bytes": "30848" }, { "name": "Groovy", "bytes": "2169474" }, { "name": "HTML", "bytes": "723161" }, { "name": "Java", "bytes": "41025290" }, { "name": "JavaScript", "bytes": "3090492" }, { "name": "Lua", "bytes": "983" }, { "name": "Python", "bytes": "20318" }, { "name": "Ruby", "bytes": "8028" }, { "name": "Shell", "bytes": "82171" }, { "name": "XSLT", "bytes": "5681" } ], "symlink_target": "" }
package carte; import java.util.concurrent.ThreadLocalRandom; import operateur.Operateur; public class Carte { private static final int nbrOpInit = 128; // une chance sur 4 de trouver un // opérateur sur une cellule private static final int largeur = 32; private static final int hauteur = 16; public static final Cellule[][] carte = new Cellule[hauteur][largeur]; public Carte() { for (int i = 0; i < hauteur; i++) { for (int j = 0; j < largeur; j++) { carte[i][j] = new Cellule(i, j); } } } public static void initCarte() { int randomLine; int randomColumn; int i = 0; while (i < nbrOpInit) { randomLine = ThreadLocalRandom.current().nextInt(0, hauteur); randomColumn = ThreadLocalRandom.current().nextInt(0, largeur); if (carte[randomLine][randomColumn].isEmpty()) { carte[randomLine][randomColumn].setEntite(Operateur.randomOp()); i++; } } } public boolean isEmpty() { boolean mon_bool = true; for (int i = 0; i < hauteur && mon_bool; i++) { for (int j = 0; j < largeur && mon_bool; j++) { mon_bool = carte[i][j].isEmpty(); } } return mon_bool; } }
{ "content_hash": "9d7a49a736797250f02841f7f430b270", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 76, "avg_line_length": 23.875, "alnum_prop": 0.6387434554973822, "repo_name": "EnzoMolion/Projet-PLA", "id": "3a00a81233d4800a0aacc15a15ca881c38826d19", "size": "1147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/carte/Carte.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "14002" } ], "symlink_target": "" }
""" Demo of a function to create Hinton diagrams. Hinton diagrams are useful for visualizing the values of a 2D array (e.g. a weight matrix): Positive and negative values are represented by white and black squares, respectively, and the size of each square represents the magnitude of each value. Initial idea from David Warde-Farley on the SciPy Cookbook Copy paste from http://matplotlib.org/examples/specialty_plots/hinton_demo.html """ import numpy as np import matplotlib.pyplot as plt def hinton(matrix, max_weight=None, ax=None): """ Draw Hinton diagram for visualizing a weight matrix. """ ax = ax if ax is not None else plt.gca() if max_weight is None: max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x,y),w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w)) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() if __name__ == '__main__': hinton(np.random.rand(20, 20) - 0.5) plt.show()
{ "content_hash": "dfec61e7c4e9ad7b07c931fa7535ebbb", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 75, "avg_line_length": 30.59090909090909, "alnum_prop": 0.6560178306092125, "repo_name": "LevinJ/Pedestrian-detection-and-tracking", "id": "831ad6e230d16a9ddd8ce2f5fee38b406071fb2c", "size": "1346", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/doppia/tools/helpers/hinton_diagram.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "10112" }, { "name": "C", "bytes": "9241106" }, { "name": "C++", "bytes": "17667301" }, { "name": "Cuda", "bytes": "268238" }, { "name": "M", "bytes": "2374" }, { "name": "Makefile", "bytes": "2488" }, { "name": "Matlab", "bytes": "55886" }, { "name": "Objective-C", "bytes": "176" }, { "name": "Perl", "bytes": "1417" }, { "name": "Python", "bytes": "482759" }, { "name": "Shell", "bytes": "2863" }, { "name": "Tcl", "bytes": "1739" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en" class="html--no-js"> <head> {% include head--common.html %} <!--production version of prebid.js--> <script async src="//cdn.jsdelivr.net/npm/prebid.js@latest/dist/not-for-prod/prebid.js"></script> <script type="text/javascript" src="//services.brid.tv/player/build/brid.min.js"></script> <script type="text/javascript"> var videoType = "{{page.videoType}}"; if (videoType == "pb-is-jw-01") { var pbjs = pbjs || {}; pbjs.que = pbjs.que || []; // define invokeVideoPlayer in advance in case we get the bids back from prebid before the entire page loads var tempTag = false; var invokeVideoPlayer = function(url){ tempTag = url; } /* Prebid Video adUnit */ var videoAdUnit = { code: 'video1', sizes: [640,480], mediaTypes: { video: { context: "instream" } }, bids: [ { bidder: 'appnexusAst', params: { placementId: '13232361', // Add your own placement id here video: { skipppable: true, playback_method: ['auto_play_sound_off'] } } } ] }; pbjs.que.push(function(){ pbjs.addAdUnits(videoAdUnit); // add your ad units to the bid request pbjs.setConfig({ usePrebidCache: true }); pbjs.requestBids({ bidsBackHandler: function(bids) { var videoUrl = pbjs.adServers.dfp.buildVideoUrl({ adUnit: videoAdUnit, params: { iu: '/19968336/prebid_cache_video_adunit', cust_params: { section: "blog", anotherKey: "anotherValue" }, output: "vast" } }); invokeVideoPlayer(videoUrl); } }); }); pbjs.bidderSettings = { standard: { adserverTargeting: [ { key: "hb_bidder", val: function (bidResponse) { return bidResponse.bidderCode; } }, { key: "hb_adid", val: function (bidResponse) { return bidResponse.adId; } }, { key: "hb_pb", val: function (bidResponse) { return "10.00"; } }, { key: "hb_size", val: function (bidResponse) { return bidResponse.size; } } ] } }; } </script> </head> <body>
{ "content_hash": "9cef2dab0c1177ace28f5b3fc8efd80d", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 111, "avg_line_length": 24.873873873873872, "alnum_prop": 0.4505613908004346, "repo_name": "prebid/prebid.github.io", "id": "ca70580114603df5015c3fb982c0c0edc5783a2b", "size": "2761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/video/head.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "37173" }, { "name": "HTML", "bytes": "292883" }, { "name": "JavaScript", "bytes": "211916" }, { "name": "Ruby", "bytes": "83" }, { "name": "SCSS", "bytes": "29620" } ], "symlink_target": "" }
@interface BSJSONDeserializer : BaseJSONDeserializer @end
{ "content_hash": "8b3dcae82bfcd3b5047379180e08c868", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 52, "avg_line_length": 19.666666666666668, "alnum_prop": 0.847457627118644, "repo_name": "akosma/iPhoneWebServicesClient", "id": "78b38d76834ee5cd8009e13a9192ab39d3444485", "size": "1926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Client/Classes/Helpers/Deserializers/BSJSONDeserializer.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "58188" }, { "name": "C++", "bytes": "152068" }, { "name": "Objective-C", "bytes": "2540534" }, { "name": "PHP", "bytes": "928374" }, { "name": "Shell", "bytes": "4699" } ], "symlink_target": "" }
<?php namespace refiche\UserBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use refiche\UserBundle\Entity\Etablissement; class EtablissementType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('nom', 'text') ->add('adresse', 'textarea') ->add('niveauxEnseignements', 'entity', array('class' => 'reficheUserBundle:NiveauEnseignement', 'property' => 'nom', 'multiple' => true, 'expanded' => true)) ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'refiche\UserBundle\Entity\Etablissement', 'csrf_protection' => true )); } /** * @return string */ public function getName() { return 'refiche_userbundle_etablissement'; } }
{ "content_hash": "c12ab0ffd8f789d1c16252f637bed003", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 76, "avg_line_length": 26.66, "alnum_prop": 0.5701425356339085, "repo_name": "ingegus/refiche", "id": "86c696e435e2e4d874142abe7892c7cbc92fc322", "size": "1333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/refiche/UserBundle/Form/EtablissementType.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2907" }, { "name": "CSS", "bytes": "4551" }, { "name": "HTML", "bytes": "8287" }, { "name": "PHP", "bytes": "112300" }, { "name": "Shell", "bytes": "899" } ], "symlink_target": "" }
package org.apache.causeway.core.metamodel.commons; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; class StringUtils_NaturalizeTest { @Test public void shouldNaturalizeMultipleCamelCase() { assertThat(StringExtensions.asNaturalized("thisIsACamelCasePhrase"), is("This Is A Camel Case Phrase")); } @Test public void shouldNaturalizeMultiplePascalCase() { assertThat(StringExtensions.asNaturalized("ThisIsAPascalCasePhrase"), is("This Is A Pascal Case Phrase")); } @Test public void shouldNaturalizeSingleWordStartingWithLowerCase() { assertThat(StringExtensions.asNaturalized("foo"), is("Foo")); } @Test public void shouldNaturalizeSingleWordStartingWithUpperCase() { assertThat(StringExtensions.asNaturalized("Foo"), is("Foo")); } }
{ "content_hash": "227b628a3f00556b734470798045b93f", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 114, "avg_line_length": 29.258064516129032, "alnum_prop": 0.7364939360529217, "repo_name": "apache/isis", "id": "1bbe154310e31937b0f0b7171ae7ff2b63cb45b6", "size": "1732", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/metamodel/src/test/java/org/apache/causeway/core/metamodel/commons/StringUtils_NaturalizeTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "152495" }, { "name": "Clean", "bytes": "8063" }, { "name": "Gherkin", "bytes": "412" }, { "name": "Groovy", "bytes": "15585" }, { "name": "HTML", "bytes": "268010" }, { "name": "Handlebars", "bytes": "337" }, { "name": "Java", "bytes": "17242597" }, { "name": "JavaScript", "bytes": "271368" }, { "name": "Kotlin", "bytes": "1913258" }, { "name": "Rich Text Format", "bytes": "2150674" }, { "name": "Shell", "bytes": "102821" }, { "name": "TypeScript", "bytes": "275" } ], "symlink_target": "" }
package # Date::Manip::Offset::off377; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 11:03:46 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.orgtz use strict; use warnings; require 5.010000; our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } our ($Offset,%Offset); END { undef $Offset; undef %Offset; } $Offset = '-06:40:00'; %Offset = ( 0 => [ 'america/matamoros', ], ); 1;
{ "content_hash": "691ed66304aa97518c97ec2677069a50", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 79, "avg_line_length": 21.923076923076923, "alnum_prop": 0.6690058479532164, "repo_name": "nriley/Pester", "id": "8b2f596e85726009220d99d06c2c4f6ee293818c", "size": "855", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/Manip/Offset/off377.pm", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "14557" }, { "name": "JavaScript", "bytes": "34030" }, { "name": "Objective-C", "bytes": "484994" }, { "name": "Shell", "bytes": "4127" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Lecidea floridensis Nyl. ### Remarks null
{ "content_hash": "5455b91e5a00c9c507eca01424ea3119", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 24, "avg_line_length": 9.923076923076923, "alnum_prop": 0.7054263565891473, "repo_name": "mdoering/backbone", "id": "a293c41e7cea1b1f6c3b4bffc7858d3e5e655453", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Lecideaceae/Lecidea/Lecidea floridensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
 #pragma once #include <aws/quicksight/QuickSight_EXPORTS.h> #include <aws/quicksight/QuickSightRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/quicksight/model/DataSetImportMode.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/quicksight/model/RowLevelPermissionDataSet.h> #include <aws/quicksight/model/RowLevelPermissionTagConfiguration.h> #include <aws/quicksight/model/DataSetUsageConfiguration.h> #include <aws/quicksight/model/PhysicalTable.h> #include <aws/quicksight/model/LogicalTable.h> #include <aws/quicksight/model/ColumnGroup.h> #include <aws/quicksight/model/FieldFolder.h> #include <aws/quicksight/model/ColumnLevelPermissionRule.h> #include <utility> namespace Aws { namespace QuickSight { namespace Model { /** */ class AWS_QUICKSIGHT_API UpdateDataSetRequest : public QuickSightRequest { public: UpdateDataSetRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "UpdateDataSet"; } Aws::String SerializePayload() const override; /** * <p>The Amazon Web Services account ID.</p> */ inline const Aws::String& GetAwsAccountId() const{ return m_awsAccountId; } /** * <p>The Amazon Web Services account ID.</p> */ inline bool AwsAccountIdHasBeenSet() const { return m_awsAccountIdHasBeenSet; } /** * <p>The Amazon Web Services account ID.</p> */ inline void SetAwsAccountId(const Aws::String& value) { m_awsAccountIdHasBeenSet = true; m_awsAccountId = value; } /** * <p>The Amazon Web Services account ID.</p> */ inline void SetAwsAccountId(Aws::String&& value) { m_awsAccountIdHasBeenSet = true; m_awsAccountId = std::move(value); } /** * <p>The Amazon Web Services account ID.</p> */ inline void SetAwsAccountId(const char* value) { m_awsAccountIdHasBeenSet = true; m_awsAccountId.assign(value); } /** * <p>The Amazon Web Services account ID.</p> */ inline UpdateDataSetRequest& WithAwsAccountId(const Aws::String& value) { SetAwsAccountId(value); return *this;} /** * <p>The Amazon Web Services account ID.</p> */ inline UpdateDataSetRequest& WithAwsAccountId(Aws::String&& value) { SetAwsAccountId(std::move(value)); return *this;} /** * <p>The Amazon Web Services account ID.</p> */ inline UpdateDataSetRequest& WithAwsAccountId(const char* value) { SetAwsAccountId(value); return *this;} /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline const Aws::String& GetDataSetId() const{ return m_dataSetId; } /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline bool DataSetIdHasBeenSet() const { return m_dataSetIdHasBeenSet; } /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline void SetDataSetId(const Aws::String& value) { m_dataSetIdHasBeenSet = true; m_dataSetId = value; } /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline void SetDataSetId(Aws::String&& value) { m_dataSetIdHasBeenSet = true; m_dataSetId = std::move(value); } /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline void SetDataSetId(const char* value) { m_dataSetIdHasBeenSet = true; m_dataSetId.assign(value); } /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline UpdateDataSetRequest& WithDataSetId(const Aws::String& value) { SetDataSetId(value); return *this;} /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline UpdateDataSetRequest& WithDataSetId(Aws::String&& value) { SetDataSetId(std::move(value)); return *this;} /** * <p>The ID for the dataset that you want to update. This ID is unique per Amazon * Web Services Region for each Amazon Web Services account.</p> */ inline UpdateDataSetRequest& WithDataSetId(const char* value) { SetDataSetId(value); return *this;} /** * <p>The display name for the dataset.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The display name for the dataset.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The display name for the dataset.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The display name for the dataset.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The display name for the dataset.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The display name for the dataset.</p> */ inline UpdateDataSetRequest& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The display name for the dataset.</p> */ inline UpdateDataSetRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The display name for the dataset.</p> */ inline UpdateDataSetRequest& WithName(const char* value) { SetName(value); return *this;} /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline const Aws::Map<Aws::String, PhysicalTable>& GetPhysicalTableMap() const{ return m_physicalTableMap; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline bool PhysicalTableMapHasBeenSet() const { return m_physicalTableMapHasBeenSet; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline void SetPhysicalTableMap(const Aws::Map<Aws::String, PhysicalTable>& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap = value; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline void SetPhysicalTableMap(Aws::Map<Aws::String, PhysicalTable>&& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap = std::move(value); } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& WithPhysicalTableMap(const Aws::Map<Aws::String, PhysicalTable>& value) { SetPhysicalTableMap(value); return *this;} /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& WithPhysicalTableMap(Aws::Map<Aws::String, PhysicalTable>&& value) { SetPhysicalTableMap(std::move(value)); return *this;} /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& AddPhysicalTableMap(const Aws::String& key, const PhysicalTable& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap.emplace(key, value); return *this; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& AddPhysicalTableMap(Aws::String&& key, const PhysicalTable& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap.emplace(std::move(key), value); return *this; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& AddPhysicalTableMap(const Aws::String& key, PhysicalTable&& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap.emplace(key, std::move(value)); return *this; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& AddPhysicalTableMap(Aws::String&& key, PhysicalTable&& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap.emplace(std::move(key), std::move(value)); return *this; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& AddPhysicalTableMap(const char* key, PhysicalTable&& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap.emplace(key, std::move(value)); return *this; } /** * <p>Declares the physical tables that are available in the underlying data * sources.</p> */ inline UpdateDataSetRequest& AddPhysicalTableMap(const char* key, const PhysicalTable& value) { m_physicalTableMapHasBeenSet = true; m_physicalTableMap.emplace(key, value); return *this; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline const Aws::Map<Aws::String, LogicalTable>& GetLogicalTableMap() const{ return m_logicalTableMap; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline bool LogicalTableMapHasBeenSet() const { return m_logicalTableMapHasBeenSet; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline void SetLogicalTableMap(const Aws::Map<Aws::String, LogicalTable>& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap = value; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline void SetLogicalTableMap(Aws::Map<Aws::String, LogicalTable>&& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap = std::move(value); } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& WithLogicalTableMap(const Aws::Map<Aws::String, LogicalTable>& value) { SetLogicalTableMap(value); return *this;} /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& WithLogicalTableMap(Aws::Map<Aws::String, LogicalTable>&& value) { SetLogicalTableMap(std::move(value)); return *this;} /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& AddLogicalTableMap(const Aws::String& key, const LogicalTable& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap.emplace(key, value); return *this; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& AddLogicalTableMap(Aws::String&& key, const LogicalTable& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap.emplace(std::move(key), value); return *this; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& AddLogicalTableMap(const Aws::String& key, LogicalTable&& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap.emplace(key, std::move(value)); return *this; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& AddLogicalTableMap(Aws::String&& key, LogicalTable&& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap.emplace(std::move(key), std::move(value)); return *this; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& AddLogicalTableMap(const char* key, LogicalTable&& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap.emplace(key, std::move(value)); return *this; } /** * <p>Configures the combination and transformation of the data from the physical * tables.</p> */ inline UpdateDataSetRequest& AddLogicalTableMap(const char* key, const LogicalTable& value) { m_logicalTableMapHasBeenSet = true; m_logicalTableMap.emplace(key, value); return *this; } /** * <p>Indicates whether you want to import the data into SPICE.</p> */ inline const DataSetImportMode& GetImportMode() const{ return m_importMode; } /** * <p>Indicates whether you want to import the data into SPICE.</p> */ inline bool ImportModeHasBeenSet() const { return m_importModeHasBeenSet; } /** * <p>Indicates whether you want to import the data into SPICE.</p> */ inline void SetImportMode(const DataSetImportMode& value) { m_importModeHasBeenSet = true; m_importMode = value; } /** * <p>Indicates whether you want to import the data into SPICE.</p> */ inline void SetImportMode(DataSetImportMode&& value) { m_importModeHasBeenSet = true; m_importMode = std::move(value); } /** * <p>Indicates whether you want to import the data into SPICE.</p> */ inline UpdateDataSetRequest& WithImportMode(const DataSetImportMode& value) { SetImportMode(value); return *this;} /** * <p>Indicates whether you want to import the data into SPICE.</p> */ inline UpdateDataSetRequest& WithImportMode(DataSetImportMode&& value) { SetImportMode(std::move(value)); return *this;} /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline const Aws::Vector<ColumnGroup>& GetColumnGroups() const{ return m_columnGroups; } /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline bool ColumnGroupsHasBeenSet() const { return m_columnGroupsHasBeenSet; } /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline void SetColumnGroups(const Aws::Vector<ColumnGroup>& value) { m_columnGroupsHasBeenSet = true; m_columnGroups = value; } /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline void SetColumnGroups(Aws::Vector<ColumnGroup>&& value) { m_columnGroupsHasBeenSet = true; m_columnGroups = std::move(value); } /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline UpdateDataSetRequest& WithColumnGroups(const Aws::Vector<ColumnGroup>& value) { SetColumnGroups(value); return *this;} /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline UpdateDataSetRequest& WithColumnGroups(Aws::Vector<ColumnGroup>&& value) { SetColumnGroups(std::move(value)); return *this;} /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline UpdateDataSetRequest& AddColumnGroups(const ColumnGroup& value) { m_columnGroupsHasBeenSet = true; m_columnGroups.push_back(value); return *this; } /** * <p>Groupings of columns that work together in certain Amazon QuickSight * features. Currently, only geospatial hierarchy is supported.</p> */ inline UpdateDataSetRequest& AddColumnGroups(ColumnGroup&& value) { m_columnGroupsHasBeenSet = true; m_columnGroups.push_back(std::move(value)); return *this; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline const Aws::Map<Aws::String, FieldFolder>& GetFieldFolders() const{ return m_fieldFolders; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline bool FieldFoldersHasBeenSet() const { return m_fieldFoldersHasBeenSet; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline void SetFieldFolders(const Aws::Map<Aws::String, FieldFolder>& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders = value; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline void SetFieldFolders(Aws::Map<Aws::String, FieldFolder>&& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders = std::move(value); } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& WithFieldFolders(const Aws::Map<Aws::String, FieldFolder>& value) { SetFieldFolders(value); return *this;} /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& WithFieldFolders(Aws::Map<Aws::String, FieldFolder>&& value) { SetFieldFolders(std::move(value)); return *this;} /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& AddFieldFolders(const Aws::String& key, const FieldFolder& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders.emplace(key, value); return *this; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& AddFieldFolders(Aws::String&& key, const FieldFolder& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders.emplace(std::move(key), value); return *this; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& AddFieldFolders(const Aws::String& key, FieldFolder&& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders.emplace(key, std::move(value)); return *this; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& AddFieldFolders(Aws::String&& key, FieldFolder&& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& AddFieldFolders(const char* key, FieldFolder&& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders.emplace(key, std::move(value)); return *this; } /** * <p>The folder that contains fields and nested subfolders for your dataset.</p> */ inline UpdateDataSetRequest& AddFieldFolders(const char* key, const FieldFolder& value) { m_fieldFoldersHasBeenSet = true; m_fieldFolders.emplace(key, value); return *this; } /** * <p>The row-level security configuration for the data you want to create.</p> */ inline const RowLevelPermissionDataSet& GetRowLevelPermissionDataSet() const{ return m_rowLevelPermissionDataSet; } /** * <p>The row-level security configuration for the data you want to create.</p> */ inline bool RowLevelPermissionDataSetHasBeenSet() const { return m_rowLevelPermissionDataSetHasBeenSet; } /** * <p>The row-level security configuration for the data you want to create.</p> */ inline void SetRowLevelPermissionDataSet(const RowLevelPermissionDataSet& value) { m_rowLevelPermissionDataSetHasBeenSet = true; m_rowLevelPermissionDataSet = value; } /** * <p>The row-level security configuration for the data you want to create.</p> */ inline void SetRowLevelPermissionDataSet(RowLevelPermissionDataSet&& value) { m_rowLevelPermissionDataSetHasBeenSet = true; m_rowLevelPermissionDataSet = std::move(value); } /** * <p>The row-level security configuration for the data you want to create.</p> */ inline UpdateDataSetRequest& WithRowLevelPermissionDataSet(const RowLevelPermissionDataSet& value) { SetRowLevelPermissionDataSet(value); return *this;} /** * <p>The row-level security configuration for the data you want to create.</p> */ inline UpdateDataSetRequest& WithRowLevelPermissionDataSet(RowLevelPermissionDataSet&& value) { SetRowLevelPermissionDataSet(std::move(value)); return *this;} /** * <p>The configuration of tags on a dataset to set row-level security. Row-level * security tags are currently supported for anonymous embedding only.</p> */ inline const RowLevelPermissionTagConfiguration& GetRowLevelPermissionTagConfiguration() const{ return m_rowLevelPermissionTagConfiguration; } /** * <p>The configuration of tags on a dataset to set row-level security. Row-level * security tags are currently supported for anonymous embedding only.</p> */ inline bool RowLevelPermissionTagConfigurationHasBeenSet() const { return m_rowLevelPermissionTagConfigurationHasBeenSet; } /** * <p>The configuration of tags on a dataset to set row-level security. Row-level * security tags are currently supported for anonymous embedding only.</p> */ inline void SetRowLevelPermissionTagConfiguration(const RowLevelPermissionTagConfiguration& value) { m_rowLevelPermissionTagConfigurationHasBeenSet = true; m_rowLevelPermissionTagConfiguration = value; } /** * <p>The configuration of tags on a dataset to set row-level security. Row-level * security tags are currently supported for anonymous embedding only.</p> */ inline void SetRowLevelPermissionTagConfiguration(RowLevelPermissionTagConfiguration&& value) { m_rowLevelPermissionTagConfigurationHasBeenSet = true; m_rowLevelPermissionTagConfiguration = std::move(value); } /** * <p>The configuration of tags on a dataset to set row-level security. Row-level * security tags are currently supported for anonymous embedding only.</p> */ inline UpdateDataSetRequest& WithRowLevelPermissionTagConfiguration(const RowLevelPermissionTagConfiguration& value) { SetRowLevelPermissionTagConfiguration(value); return *this;} /** * <p>The configuration of tags on a dataset to set row-level security. Row-level * security tags are currently supported for anonymous embedding only.</p> */ inline UpdateDataSetRequest& WithRowLevelPermissionTagConfiguration(RowLevelPermissionTagConfiguration&& value) { SetRowLevelPermissionTagConfiguration(std::move(value)); return *this;} /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline const Aws::Vector<ColumnLevelPermissionRule>& GetColumnLevelPermissionRules() const{ return m_columnLevelPermissionRules; } /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline bool ColumnLevelPermissionRulesHasBeenSet() const { return m_columnLevelPermissionRulesHasBeenSet; } /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline void SetColumnLevelPermissionRules(const Aws::Vector<ColumnLevelPermissionRule>& value) { m_columnLevelPermissionRulesHasBeenSet = true; m_columnLevelPermissionRules = value; } /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline void SetColumnLevelPermissionRules(Aws::Vector<ColumnLevelPermissionRule>&& value) { m_columnLevelPermissionRulesHasBeenSet = true; m_columnLevelPermissionRules = std::move(value); } /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline UpdateDataSetRequest& WithColumnLevelPermissionRules(const Aws::Vector<ColumnLevelPermissionRule>& value) { SetColumnLevelPermissionRules(value); return *this;} /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline UpdateDataSetRequest& WithColumnLevelPermissionRules(Aws::Vector<ColumnLevelPermissionRule>&& value) { SetColumnLevelPermissionRules(std::move(value)); return *this;} /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline UpdateDataSetRequest& AddColumnLevelPermissionRules(const ColumnLevelPermissionRule& value) { m_columnLevelPermissionRulesHasBeenSet = true; m_columnLevelPermissionRules.push_back(value); return *this; } /** * <p>A set of one or more definitions of a <code> <a * href="https://docs.aws.amazon.com/quicksight/latest/APIReference/API_ColumnLevelPermissionRule.html">ColumnLevelPermissionRule</a> * </code>.</p> */ inline UpdateDataSetRequest& AddColumnLevelPermissionRules(ColumnLevelPermissionRule&& value) { m_columnLevelPermissionRulesHasBeenSet = true; m_columnLevelPermissionRules.push_back(std::move(value)); return *this; } inline const DataSetUsageConfiguration& GetDataSetUsageConfiguration() const{ return m_dataSetUsageConfiguration; } inline bool DataSetUsageConfigurationHasBeenSet() const { return m_dataSetUsageConfigurationHasBeenSet; } inline void SetDataSetUsageConfiguration(const DataSetUsageConfiguration& value) { m_dataSetUsageConfigurationHasBeenSet = true; m_dataSetUsageConfiguration = value; } inline void SetDataSetUsageConfiguration(DataSetUsageConfiguration&& value) { m_dataSetUsageConfigurationHasBeenSet = true; m_dataSetUsageConfiguration = std::move(value); } inline UpdateDataSetRequest& WithDataSetUsageConfiguration(const DataSetUsageConfiguration& value) { SetDataSetUsageConfiguration(value); return *this;} inline UpdateDataSetRequest& WithDataSetUsageConfiguration(DataSetUsageConfiguration&& value) { SetDataSetUsageConfiguration(std::move(value)); return *this;} private: Aws::String m_awsAccountId; bool m_awsAccountIdHasBeenSet; Aws::String m_dataSetId; bool m_dataSetIdHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; Aws::Map<Aws::String, PhysicalTable> m_physicalTableMap; bool m_physicalTableMapHasBeenSet; Aws::Map<Aws::String, LogicalTable> m_logicalTableMap; bool m_logicalTableMapHasBeenSet; DataSetImportMode m_importMode; bool m_importModeHasBeenSet; Aws::Vector<ColumnGroup> m_columnGroups; bool m_columnGroupsHasBeenSet; Aws::Map<Aws::String, FieldFolder> m_fieldFolders; bool m_fieldFoldersHasBeenSet; RowLevelPermissionDataSet m_rowLevelPermissionDataSet; bool m_rowLevelPermissionDataSetHasBeenSet; RowLevelPermissionTagConfiguration m_rowLevelPermissionTagConfiguration; bool m_rowLevelPermissionTagConfigurationHasBeenSet; Aws::Vector<ColumnLevelPermissionRule> m_columnLevelPermissionRules; bool m_columnLevelPermissionRulesHasBeenSet; DataSetUsageConfiguration m_dataSetUsageConfiguration; bool m_dataSetUsageConfigurationHasBeenSet; }; } // namespace Model } // namespace QuickSight } // namespace Aws
{ "content_hash": "1a1738423a6b400d6ea8271791a63173", "timestamp": "", "source": "github", "line_count": 645, "max_line_length": 220, "avg_line_length": 44.968992248062015, "alnum_prop": 0.7090846405792105, "repo_name": "cedral/aws-sdk-cpp", "id": "77ff9a0218b72ceb0660c1af516b324cb144842f", "size": "29124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-quicksight/include/aws/quicksight/model/UpdateDataSetRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SpirvNet.Spirv.Enums; // This file is auto-generated and should not be modified manually. namespace SpirvNet.Spirv.Ops.Conversion { /// <summary> /// OpBitcast /// /// Bit-pattern preserving type conversion for Numerical-type or pointer-type vectors and scalars. /// /// Operand is the bit pattern whose type will change. /// /// Result Type must be different than the type of Operand. Both Result Type and the type of Operand must be Numerical-types or pointer types. The components of Operand and Result Type must be same bit width. /// /// Results are computed per component. The operand&#8217;s type and Result Type must have the same number of components. /// </summary> public sealed class OpBitcast : ConversionInstruction { public override bool IsConversion => true; public override OpCode OpCode => OpCode.Bitcast; public override ID? ResultID => Result; public override ID? ResultTypeID => ResultType; public ID ResultType; public ID Result; public ID Operand; #region Code public override string ToString() => "(" + OpCode + "(" + (int)OpCode + ")" + ", " + StrOf(ResultType) + ", " + StrOf(Result) + ", " + StrOf(Operand) + ")"; public override string ArgString => "Operand: " + StrOf(Operand); protected override void FromCode(uint[] codes, int start) { System.Diagnostics.Debug.Assert((codes[start] & 0x0000FFFF) == (uint)OpCode.Bitcast); var i = start + 1; ResultType = new ID(codes[i++]); Result = new ID(codes[i++]); Operand = new ID(codes[i++]); } protected override void WriteCode(List<uint> code) { code.Add(ResultType.Value); code.Add(Result.Value); code.Add(Operand.Value); } public override IEnumerable<ID> AllIDs { get { yield return ResultType; yield return Result; yield return Operand; } } #endregion } }
{ "content_hash": "c04b735fafeba121de0e8fa20096a760", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 214, "avg_line_length": 34.89230769230769, "alnum_prop": 0.6009700176366843, "repo_name": "Philip-Trettner/SpirvNet", "id": "cde97a69f9028cea6cc8795572e7864364eb4cae", "size": "2268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SpirvNet/SpirvNet/Spirv/Ops/Conversion/OpBitcast.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1027195" } ], "symlink_target": "" }
require 'util/repo_util' module Pod class Command class RepoArt class Add < RepoArt UTIL = Pod::RepoArt::RepoUtil self.summary = 'Add a Specs repo from Artifactory.' self.description = <<-DESC Retrieves the index from an Artifactory instance at 'URL' to the local spec repos-art directory at `~/.cocoapods/repos-art/'NAME'`. DESC self.arguments = [ CLAide::Argument.new('NAME', true), CLAide::Argument.new('URL', true) ] def initialize(argv) init @name, @url = argv.shift_argument, argv.shift_argument @silent = argv.flag?('silent', false) super end def validate! super unless @name && @url help! 'This command requires both a repo name and a url.' end end def run UI.section("Retrieving index from `#{@url}` into local spec repo `#{@name}`") do # Check if a repo with the same name under repos/ already exists repos_path = "#{Pod::Config.instance.home_dir}/repos" raise Informative, "Path #{repos_path}/#{@name} already exists - remove it first, "\ "or run 'pod repo-art update #{@name}' to update it" if File.exist?("#{repos_path}/#{@name}") && !@silent # Check if a repo with the same name under repo-art/ already exists repo_dir_root = "#{@repos_art_dir}/#{@name}" raise Informative, "Path #{repo_dir_root} already exists - remove it first, "\ "or run 'pod repo-art update #{@name}' to update it" if File.exist?(repo_dir_root) && !@silent FileUtils::mkdir_p repo_dir_root repo_dir_specs = "#{repo_dir_root}/Specs" begin downloader = Pod::Downloader::Http.new(repo_dir_specs, "#{@url}/index/fetchIndex", :type => 'tgz', :indexDownload => true) downloader.download rescue => e FileUtils.remove_entry_secure(repo_dir_root, :force => true) raise Informative, "Error getting the index from Artifactory at: '#{@url}' : #{e.message}" end begin UTIL.cleanup_index_download(repo_dir_specs) UTIL.del_redundant_spec_dir("#{repo_dir_specs}/Specs") rescue => e UI.warn("Failed cleaning up temp files in #{repo_dir_specs}") end begin artpodrc_path = create_artpodrc_file(repo_dir_root) rescue => e raise Informative, "Cannot create file '#{artpodrc_path}' because : #{e.message}."\ '- your Artifactory-backed Specs repo will not work correctly without it!' end # Create a local git repository in the newly added Artifactory local repo system "cd '#{repo_dir_root}' && git init && git add . && git commit -m 'Artifactory repo init'" # Create local repo under repos/ which is a remote for the new local git repository system "cd '#{repos_path}' && git clone file://#{repo_dir_root}" end UI.puts "Successfully added repo #{@name}".green unless @silent end # Creates the .artpodrc file which contains the repository's url in the root of the Spec repo # # @param [String] repo_dir_root root of the Spec repo # def create_artpodrc_file(repo_dir_root) artpodrc_path = "#{repo_dir_root}/.artpodrc" artpodrc = File.new(artpodrc_path, "wb") artpodrc << @url artpodrc.close artpodrc_path end end end end end
{ "content_hash": "7519751ccea60d417c16ef13a36ff4ce", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 136, "avg_line_length": 39.03157894736842, "alnum_prop": 0.5622977346278317, "repo_name": "JFrogDev/cocoapods-art", "id": "f87043d1afe24e29857090eb438f43cfe7a6d8cb", "size": "3708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/pod/command/repo_art/add.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "29397" } ], "symlink_target": "" }
package org.orekit.models.earth; import org.hipparchus.util.FastMath; import org.orekit.models.AtmosphericRefractionModel; /** Implementation of refraction model for Earth standard atmosphere. * <p>Refraction angle is 0 at zenith, about 1 arcminute at 45°, and 34 arcminutes at the * horizon for optical wavelengths.</p> * <p>Refraction angle is computed according to Saemundssen formula quoted by Meeus. * For reference, see <b>Astronomical Algorithms</b> (1998), 2nd ed, * (ISBN 0-943396-61-1), chap. 15.</p> * <p>This formula is about 30 arcseconds of accuracy very close to the horizon, as * variable atmospheric effects become very important.</p> * <p>Local pressure and temperature can be set to correct refraction at the viewpoint.</p> * @since 6.1 */ public class EarthStandardAtmosphereRefraction implements AtmosphericRefractionModel { /** Default correction factor value. */ public static final double DEFAULT_CORRECTION_FACTOR = 1.0; /** Default local pressure at viewpoint (Pa). */ public static final double DEFAULT_PRESSURE = 101000.0; /** Default local temperature at viewpoint (K). */ public static final double DEFAULT_TEMPERATURE = 283.0; /** NIST standard atmospheric pressure (Pa). */ public static final double STANDARD_ATM_PRESSURE = 101325.0; /** NIST standard atmospheric temperature (K). */ public static final double STANDARD_ATM_TEMPERATURE = 293.15; /** Elevation min value to compute refraction (under the horizon). */ private static final double MIN_ELEVATION = -2.0; /** Elevation max value to compute refraction (zenithal). */ private static final double MAX_ELEVATION = 89.89; /** Serializable UID. */ private static final long serialVersionUID = 6001744143210742620L; /** Refraction correction from local pressure and temperature. */ private double correfrac; /** Local pressure. */ private double pressure; /** Local temperature. */ private double temperature; /** * Creates a new default instance. */ public EarthStandardAtmosphereRefraction() { correfrac = DEFAULT_CORRECTION_FACTOR; pressure = DEFAULT_PRESSURE; temperature = DEFAULT_TEMPERATURE; } /** * Creates an instance given a specific pressure and temperature. * @param pressure in Pascals (Pa) * @param temperature in Kelvin (K) */ public EarthStandardAtmosphereRefraction(final double pressure, final double temperature) { setTemperature(temperature); setPressure(pressure); } /** Get the local pressure at the evaluation location. * @return the pressure (Pa) */ public double getPressure() { return pressure; } /** Set the local pressure at the evaluation location * <p>Otherwise the default value for the local pressure is set to {@link #DEFAULT_PRESSURE}.</p> * @param pressure the pressure to set (Pa) */ public void setPressure(final double pressure) { this.pressure = pressure; this.correfrac = (pressure / DEFAULT_PRESSURE) * (DEFAULT_TEMPERATURE / temperature); } /** Get the local temperature at the evaluation location. * @return the temperature (K) */ public double getTemperature() { return temperature; } /** Set the local temperature at the evaluation location * <p>Otherwise the default value for the local temperature is set to {@link #DEFAULT_TEMPERATURE}.</p> * @param temperature the temperature to set (K) */ public void setTemperature(final double temperature) { this.temperature = temperature; this.correfrac = (pressure / DEFAULT_PRESSURE) * (DEFAULT_TEMPERATURE / temperature); } @Override /** {@inheritDoc} */ public double getRefraction(final double trueElevation) { double refraction = 0.0; final double eld = FastMath.toDegrees(trueElevation); if (eld > MIN_ELEVATION && eld < MAX_ELEVATION) { final double tmp = eld + 10.3 / (eld + 5.11); final double ref = 1.02 / FastMath.tan(FastMath.toRadians(tmp)) / 60.; refraction = FastMath.toRadians(correfrac * ref); } return refraction; } }
{ "content_hash": "5c65df103d510aa06c29e9aac8ff9463", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 107, "avg_line_length": 36.52136752136752, "alnum_prop": 0.6770418909431313, "repo_name": "CS-SI/Orekit", "id": "2be17bdca94afac26f536a10e912ee9daec7e14e", "size": "5112", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/main/java/org/orekit/models/earth/EarthStandardAtmosphereRefraction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Fortran", "bytes": "7408" }, { "name": "HTML", "bytes": "19673" }, { "name": "Java", "bytes": "25367949" }, { "name": "Roff", "bytes": "31072" }, { "name": "XSLT", "bytes": "734" } ], "symlink_target": "" }
bash my_print.sh "STARTING: Installing Q-ML dependencies" sudo apt-get install python3-pip -y sudo pip3 install numpy sudo pip3 install pandas sudo apt-get install build-essential -y sudo apt-get install python3-dev -y sudo apt-get install python3-setuptools -y sudo apt-get install python3-numpy -y sudo apt-get install python3-scipy -y sudo apt-get install python3-pip -y sudo apt-get install libatlas-dev -y sudo apt-get install libatlas3gf-base -y sudo pip3 install scikit-learn bash my_print.sh "COMPLETED: Installing Q-ML dependencies"
{ "content_hash": "cc1e0487c994f6acf4536612daabdcf9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 41, "alnum_prop": 0.7543554006968641, "repo_name": "NerdWalletOSS/Q", "id": "73feaec52a3605010fce500efda99f29222d89be", "size": "607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GUIDING_PRINCIPLES/q_ml_dependencies.sh", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1528854" }, { "name": "C++", "bytes": "11900" }, { "name": "CMake", "bytes": "414" }, { "name": "CSS", "bytes": "651" }, { "name": "Cuda", "bytes": "4192" }, { "name": "HTML", "bytes": "184009" }, { "name": "JavaScript", "bytes": "12282" }, { "name": "Jupyter Notebook", "bytes": "60539" }, { "name": "Lex", "bytes": "5777" }, { "name": "Logos", "bytes": "18046" }, { "name": "Lua", "bytes": "2273456" }, { "name": "Makefile", "bytes": "72536" }, { "name": "Perl", "bytes": "3421" }, { "name": "Python", "bytes": "121910" }, { "name": "R", "bytes": "1071" }, { "name": "RPC", "bytes": "5973" }, { "name": "Shell", "bytes": "128156" }, { "name": "TeX", "bytes": "819194" }, { "name": "Terra", "bytes": "3360" }, { "name": "Vim script", "bytes": "5911" }, { "name": "Yacc", "bytes": "52645" } ], "symlink_target": "" }
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/netwerk/cache/nsICacheVisitor.idl */ #ifndef __gen_nsICacheVisitor_h__ #define __gen_nsICacheVisitor_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsICacheDeviceInfo; /* forward declaration */ class nsICacheEntryInfo; /* forward declaration */ /* starting interface: nsICacheVisitor */ #define NS_ICACHEVISITOR_IID_STR "f8c08c4b-d778-49d1-a59b-866fdc500d95" #define NS_ICACHEVISITOR_IID \ {0xf8c08c4b, 0xd778, 0x49d1, \ { 0xa5, 0x9b, 0x86, 0x6f, 0xdc, 0x50, 0x0d, 0x95 }} class NS_NO_VTABLE NS_SCRIPTABLE nsICacheVisitor : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICACHEVISITOR_IID) /* boolean visitDevice (in string deviceID, in nsICacheDeviceInfo deviceInfo); */ NS_SCRIPTABLE NS_IMETHOD VisitDevice(const char * deviceID, nsICacheDeviceInfo *deviceInfo, bool *_retval NS_OUTPARAM) = 0; /* boolean visitEntry (in string deviceID, in nsICacheEntryInfo entryInfo); */ NS_SCRIPTABLE NS_IMETHOD VisitEntry(const char * deviceID, nsICacheEntryInfo *entryInfo, bool *_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsICacheVisitor, NS_ICACHEVISITOR_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSICACHEVISITOR \ NS_SCRIPTABLE NS_IMETHOD VisitDevice(const char * deviceID, nsICacheDeviceInfo *deviceInfo, bool *_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD VisitEntry(const char * deviceID, nsICacheEntryInfo *entryInfo, bool *_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSICACHEVISITOR(_to) \ NS_SCRIPTABLE NS_IMETHOD VisitDevice(const char * deviceID, nsICacheDeviceInfo *deviceInfo, bool *_retval NS_OUTPARAM) { return _to VisitDevice(deviceID, deviceInfo, _retval); } \ NS_SCRIPTABLE NS_IMETHOD VisitEntry(const char * deviceID, nsICacheEntryInfo *entryInfo, bool *_retval NS_OUTPARAM) { return _to VisitEntry(deviceID, entryInfo, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSICACHEVISITOR(_to) \ NS_SCRIPTABLE NS_IMETHOD VisitDevice(const char * deviceID, nsICacheDeviceInfo *deviceInfo, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->VisitDevice(deviceID, deviceInfo, _retval); } \ NS_SCRIPTABLE NS_IMETHOD VisitEntry(const char * deviceID, nsICacheEntryInfo *entryInfo, bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->VisitEntry(deviceID, entryInfo, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsCacheVisitor : public nsICacheVisitor { public: NS_DECL_ISUPPORTS NS_DECL_NSICACHEVISITOR nsCacheVisitor(); private: ~nsCacheVisitor(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsCacheVisitor, nsICacheVisitor) nsCacheVisitor::nsCacheVisitor() { /* member initializers and constructor code */ } nsCacheVisitor::~nsCacheVisitor() { /* destructor code */ } /* boolean visitDevice (in string deviceID, in nsICacheDeviceInfo deviceInfo); */ NS_IMETHODIMP nsCacheVisitor::VisitDevice(const char * deviceID, nsICacheDeviceInfo *deviceInfo, bool *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean visitEntry (in string deviceID, in nsICacheEntryInfo entryInfo); */ NS_IMETHODIMP nsCacheVisitor::VisitEntry(const char * deviceID, nsICacheEntryInfo *entryInfo, bool *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsICacheDeviceInfo */ #define NS_ICACHEDEVICEINFO_IID_STR "31d1c294-1dd2-11b2-be3a-c79230dca297" #define NS_ICACHEDEVICEINFO_IID \ {0x31d1c294, 0x1dd2, 0x11b2, \ { 0xbe, 0x3a, 0xc7, 0x92, 0x30, 0xdc, 0xa2, 0x97 }} class NS_NO_VTABLE NS_SCRIPTABLE nsICacheDeviceInfo : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICACHEDEVICEINFO_IID) /* readonly attribute string description; */ NS_SCRIPTABLE NS_IMETHOD GetDescription(char * *aDescription) = 0; /* readonly attribute string usageReport; */ NS_SCRIPTABLE NS_IMETHOD GetUsageReport(char * *aUsageReport) = 0; /* readonly attribute unsigned long entryCount; */ NS_SCRIPTABLE NS_IMETHOD GetEntryCount(PRUint32 *aEntryCount) = 0; /* readonly attribute unsigned long totalSize; */ NS_SCRIPTABLE NS_IMETHOD GetTotalSize(PRUint32 *aTotalSize) = 0; /* readonly attribute unsigned long maximumSize; */ NS_SCRIPTABLE NS_IMETHOD GetMaximumSize(PRUint32 *aMaximumSize) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsICacheDeviceInfo, NS_ICACHEDEVICEINFO_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSICACHEDEVICEINFO \ NS_SCRIPTABLE NS_IMETHOD GetDescription(char * *aDescription); \ NS_SCRIPTABLE NS_IMETHOD GetUsageReport(char * *aUsageReport); \ NS_SCRIPTABLE NS_IMETHOD GetEntryCount(PRUint32 *aEntryCount); \ NS_SCRIPTABLE NS_IMETHOD GetTotalSize(PRUint32 *aTotalSize); \ NS_SCRIPTABLE NS_IMETHOD GetMaximumSize(PRUint32 *aMaximumSize); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSICACHEDEVICEINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetDescription(char * *aDescription) { return _to GetDescription(aDescription); } \ NS_SCRIPTABLE NS_IMETHOD GetUsageReport(char * *aUsageReport) { return _to GetUsageReport(aUsageReport); } \ NS_SCRIPTABLE NS_IMETHOD GetEntryCount(PRUint32 *aEntryCount) { return _to GetEntryCount(aEntryCount); } \ NS_SCRIPTABLE NS_IMETHOD GetTotalSize(PRUint32 *aTotalSize) { return _to GetTotalSize(aTotalSize); } \ NS_SCRIPTABLE NS_IMETHOD GetMaximumSize(PRUint32 *aMaximumSize) { return _to GetMaximumSize(aMaximumSize); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSICACHEDEVICEINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetDescription(char * *aDescription) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDescription(aDescription); } \ NS_SCRIPTABLE NS_IMETHOD GetUsageReport(char * *aUsageReport) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUsageReport(aUsageReport); } \ NS_SCRIPTABLE NS_IMETHOD GetEntryCount(PRUint32 *aEntryCount) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetEntryCount(aEntryCount); } \ NS_SCRIPTABLE NS_IMETHOD GetTotalSize(PRUint32 *aTotalSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTotalSize(aTotalSize); } \ NS_SCRIPTABLE NS_IMETHOD GetMaximumSize(PRUint32 *aMaximumSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetMaximumSize(aMaximumSize); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsCacheDeviceInfo : public nsICacheDeviceInfo { public: NS_DECL_ISUPPORTS NS_DECL_NSICACHEDEVICEINFO nsCacheDeviceInfo(); private: ~nsCacheDeviceInfo(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsCacheDeviceInfo, nsICacheDeviceInfo) nsCacheDeviceInfo::nsCacheDeviceInfo() { /* member initializers and constructor code */ } nsCacheDeviceInfo::~nsCacheDeviceInfo() { /* destructor code */ } /* readonly attribute string description; */ NS_IMETHODIMP nsCacheDeviceInfo::GetDescription(char * *aDescription) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute string usageReport; */ NS_IMETHODIMP nsCacheDeviceInfo::GetUsageReport(char * *aUsageReport) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long entryCount; */ NS_IMETHODIMP nsCacheDeviceInfo::GetEntryCount(PRUint32 *aEntryCount) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long totalSize; */ NS_IMETHODIMP nsCacheDeviceInfo::GetTotalSize(PRUint32 *aTotalSize) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long maximumSize; */ NS_IMETHODIMP nsCacheDeviceInfo::GetMaximumSize(PRUint32 *aMaximumSize) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsICacheEntryInfo */ #define NS_ICACHEENTRYINFO_IID_STR "fab51c92-95c3-4468-b317-7de4d7588254" #define NS_ICACHEENTRYINFO_IID \ {0xfab51c92, 0x95c3, 0x4468, \ { 0xb3, 0x17, 0x7d, 0xe4, 0xd7, 0x58, 0x82, 0x54 }} class NS_NO_VTABLE NS_SCRIPTABLE nsICacheEntryInfo : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICACHEENTRYINFO_IID) /* readonly attribute string clientID; */ NS_SCRIPTABLE NS_IMETHOD GetClientID(char * *aClientID) = 0; /* readonly attribute string deviceID; */ NS_SCRIPTABLE NS_IMETHOD GetDeviceID(char * *aDeviceID) = 0; /* readonly attribute ACString key; */ NS_SCRIPTABLE NS_IMETHOD GetKey(nsACString & aKey) = 0; /* readonly attribute long fetchCount; */ NS_SCRIPTABLE NS_IMETHOD GetFetchCount(PRInt32 *aFetchCount) = 0; /* readonly attribute PRUint32 lastFetched; */ NS_SCRIPTABLE NS_IMETHOD GetLastFetched(PRUint32 *aLastFetched) = 0; /* readonly attribute PRUint32 lastModified; */ NS_SCRIPTABLE NS_IMETHOD GetLastModified(PRUint32 *aLastModified) = 0; /* readonly attribute PRUint32 expirationTime; */ NS_SCRIPTABLE NS_IMETHOD GetExpirationTime(PRUint32 *aExpirationTime) = 0; /* readonly attribute unsigned long dataSize; */ NS_SCRIPTABLE NS_IMETHOD GetDataSize(PRUint32 *aDataSize) = 0; /* boolean isStreamBased (); */ NS_SCRIPTABLE NS_IMETHOD IsStreamBased(bool *_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsICacheEntryInfo, NS_ICACHEENTRYINFO_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSICACHEENTRYINFO \ NS_SCRIPTABLE NS_IMETHOD GetClientID(char * *aClientID); \ NS_SCRIPTABLE NS_IMETHOD GetDeviceID(char * *aDeviceID); \ NS_SCRIPTABLE NS_IMETHOD GetKey(nsACString & aKey); \ NS_SCRIPTABLE NS_IMETHOD GetFetchCount(PRInt32 *aFetchCount); \ NS_SCRIPTABLE NS_IMETHOD GetLastFetched(PRUint32 *aLastFetched); \ NS_SCRIPTABLE NS_IMETHOD GetLastModified(PRUint32 *aLastModified); \ NS_SCRIPTABLE NS_IMETHOD GetExpirationTime(PRUint32 *aExpirationTime); \ NS_SCRIPTABLE NS_IMETHOD GetDataSize(PRUint32 *aDataSize); \ NS_SCRIPTABLE NS_IMETHOD IsStreamBased(bool *_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSICACHEENTRYINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetClientID(char * *aClientID) { return _to GetClientID(aClientID); } \ NS_SCRIPTABLE NS_IMETHOD GetDeviceID(char * *aDeviceID) { return _to GetDeviceID(aDeviceID); } \ NS_SCRIPTABLE NS_IMETHOD GetKey(nsACString & aKey) { return _to GetKey(aKey); } \ NS_SCRIPTABLE NS_IMETHOD GetFetchCount(PRInt32 *aFetchCount) { return _to GetFetchCount(aFetchCount); } \ NS_SCRIPTABLE NS_IMETHOD GetLastFetched(PRUint32 *aLastFetched) { return _to GetLastFetched(aLastFetched); } \ NS_SCRIPTABLE NS_IMETHOD GetLastModified(PRUint32 *aLastModified) { return _to GetLastModified(aLastModified); } \ NS_SCRIPTABLE NS_IMETHOD GetExpirationTime(PRUint32 *aExpirationTime) { return _to GetExpirationTime(aExpirationTime); } \ NS_SCRIPTABLE NS_IMETHOD GetDataSize(PRUint32 *aDataSize) { return _to GetDataSize(aDataSize); } \ NS_SCRIPTABLE NS_IMETHOD IsStreamBased(bool *_retval NS_OUTPARAM) { return _to IsStreamBased(_retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSICACHEENTRYINFO(_to) \ NS_SCRIPTABLE NS_IMETHOD GetClientID(char * *aClientID) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetClientID(aClientID); } \ NS_SCRIPTABLE NS_IMETHOD GetDeviceID(char * *aDeviceID) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDeviceID(aDeviceID); } \ NS_SCRIPTABLE NS_IMETHOD GetKey(nsACString & aKey) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetKey(aKey); } \ NS_SCRIPTABLE NS_IMETHOD GetFetchCount(PRInt32 *aFetchCount) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFetchCount(aFetchCount); } \ NS_SCRIPTABLE NS_IMETHOD GetLastFetched(PRUint32 *aLastFetched) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLastFetched(aLastFetched); } \ NS_SCRIPTABLE NS_IMETHOD GetLastModified(PRUint32 *aLastModified) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLastModified(aLastModified); } \ NS_SCRIPTABLE NS_IMETHOD GetExpirationTime(PRUint32 *aExpirationTime) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetExpirationTime(aExpirationTime); } \ NS_SCRIPTABLE NS_IMETHOD GetDataSize(PRUint32 *aDataSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDataSize(aDataSize); } \ NS_SCRIPTABLE NS_IMETHOD IsStreamBased(bool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsStreamBased(_retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsCacheEntryInfo : public nsICacheEntryInfo { public: NS_DECL_ISUPPORTS NS_DECL_NSICACHEENTRYINFO nsCacheEntryInfo(); private: ~nsCacheEntryInfo(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsCacheEntryInfo, nsICacheEntryInfo) nsCacheEntryInfo::nsCacheEntryInfo() { /* member initializers and constructor code */ } nsCacheEntryInfo::~nsCacheEntryInfo() { /* destructor code */ } /* readonly attribute string clientID; */ NS_IMETHODIMP nsCacheEntryInfo::GetClientID(char * *aClientID) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute string deviceID; */ NS_IMETHODIMP nsCacheEntryInfo::GetDeviceID(char * *aDeviceID) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute ACString key; */ NS_IMETHODIMP nsCacheEntryInfo::GetKey(nsACString & aKey) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long fetchCount; */ NS_IMETHODIMP nsCacheEntryInfo::GetFetchCount(PRInt32 *aFetchCount) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute PRUint32 lastFetched; */ NS_IMETHODIMP nsCacheEntryInfo::GetLastFetched(PRUint32 *aLastFetched) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute PRUint32 lastModified; */ NS_IMETHODIMP nsCacheEntryInfo::GetLastModified(PRUint32 *aLastModified) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute PRUint32 expirationTime; */ NS_IMETHODIMP nsCacheEntryInfo::GetExpirationTime(PRUint32 *aExpirationTime) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long dataSize; */ NS_IMETHODIMP nsCacheEntryInfo::GetDataSize(PRUint32 *aDataSize) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isStreamBased (); */ NS_IMETHODIMP nsCacheEntryInfo::IsStreamBased(bool *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsICacheVisitor_h__ */
{ "content_hash": "80d6dfdc800e6e76d951f36fed9c2b5c", "timestamp": "", "source": "github", "line_count": 397, "max_line_length": 213, "avg_line_length": 38.2015113350126, "alnum_prop": 0.7539232493735989, "repo_name": "bwp/SeleniumWebDriver", "id": "248889565c9a84612b3c5626e3d272e9f3fb05b3", "size": "15166", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "third_party/gecko-15/win32/include/nsICacheVisitor.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "22162" }, { "name": "C", "bytes": "302788" }, { "name": "C#", "bytes": "2090580" }, { "name": "C++", "bytes": "771128" }, { "name": "Java", "bytes": "7874195" }, { "name": "JavaScript", "bytes": "14218193" }, { "name": "Objective-C", "bytes": "368823" }, { "name": "Python", "bytes": "634315" }, { "name": "Ruby", "bytes": "757466" }, { "name": "Shell", "bytes": "6429" } ], "symlink_target": "" }
package org.apache.flink.table.runtime.stream.table import java.math.BigDecimal import org.apache.flink.api.common.time.Time import org.apache.flink.api.scala._ import org.apache.flink.table.api.scala._ import org.apache.flink.table.api.{StreamQueryConfig, TableEnvironment} import org.apache.flink.streaming.api.TimeCharacteristic import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment import org.apache.flink.streaming.api.watermark.Watermark import org.apache.flink.streaming.util.StreamingMultipleProgramsTestBase import org.apache.flink.table.runtime.utils.JavaUserDefinedAggFunctions.{WeightedAvg, WeightedAvgWithMerge} import org.apache.flink.table.functions.aggfunctions.CountAggFunction import org.apache.flink.table.runtime.stream.table.GroupWindowITCase._ import org.apache.flink.table.runtime.utils.StreamITCase import org.apache.flink.types.Row import org.junit.Assert._ import org.junit.Test import scala.collection.mutable /** * We only test some aggregations until better testing of constructed DataStream * programs is possible. */ class GroupWindowITCase extends StreamingMultipleProgramsTestBase { private val queryConfig = new StreamQueryConfig() queryConfig.withIdleStateRetentionTime(Time.hours(1), Time.hours(2)) val data = List( (1L, 1, "Hi"), (2L, 2, "Hello"), (4L, 2, "Hello"), (8L, 3, "Hello world"), (16L, 3, "Hello world")) val data2 = List( (1L, 1, 1d, 1f, new BigDecimal("1"), "Hi"), (2L, 2, 2d, 2f, new BigDecimal("2"), "Hallo"), (3L, 2, 2d, 2f, new BigDecimal("2"), "Hello"), (4L, 5, 5d, 5f, new BigDecimal("5"), "Hello"), (7L, 3, 3d, 3f, new BigDecimal("3"), "Hello"), (8L, 3, 3d, 3f, new BigDecimal("3"), "Hello world"), (16L, 4, 4d, 4f, new BigDecimal("4"), "Hello world")) @Test def testProcessingTimeSlidingGroupWindowOverCount(): Unit = { val env = StreamExecutionEnvironment.getExecutionEnvironment env.setParallelism(1) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env.fromCollection(data) val table = stream.toTable(tEnv, 'long, 'int, 'string, 'proctime.proctime) val countFun = new CountAggFunction val weightAvgFun = new WeightedAvg val windowedTable = table .window(Slide over 2.rows every 1.rows on 'proctime as 'w) .groupBy('w, 'string) .select('string, countFun('int), 'int.avg, weightAvgFun('long, 'int), weightAvgFun('int, 'int)) val results = windowedTable.toAppendStream[Row](queryConfig) results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq("Hello world,1,3,8,3", "Hello world,2,3,12,3", "Hello,1,2,2,2", "Hello,2,2,3,2", "Hi,1,1,1,1") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testEventTimeSessionGroupWindowOverTime(): Unit = { //To verify the "merge" functionality, we create this test with the following characteristics: // 1. set the Parallelism to 1, and have the test data out of order // 2. create a waterMark with 10ms offset to delay the window emission by 10ms val sessionWindowTestdata = List( (1L, 1, "Hello"), (2L, 2, "Hello"), (8L, 8, "Hello"), (9L, 9, "Hello World"), (4L, 4, "Hello"), (16L, 16, "Hello")) val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) env.setParallelism(1) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val countFun = new CountAggFunction val weightAvgFun = new WeightedAvgWithMerge val stream = env .fromCollection(sessionWindowTestdata) .assignTimestampsAndWatermarks(new TimestampAndWatermarkWithOffset[(Long, Int, String)](10L)) val table = stream.toTable(tEnv, 'long, 'int, 'string, 'rowtime.rowtime) val windowedTable = table .window(Session withGap 5.milli on 'rowtime as 'w) .groupBy('w, 'string) .select('string, countFun('int), 'int.avg, weightAvgFun('long, 'int), weightAvgFun('int, 'int)) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq("Hello World,1,9,9,9", "Hello,1,16,16,16", "Hello,4,3,5,5") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testAllProcessingTimeTumblingGroupWindowOverCount(): Unit = { val env = StreamExecutionEnvironment.getExecutionEnvironment env.setParallelism(1) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env.fromCollection(data) val table = stream.toTable(tEnv, 'long, 'int, 'string, 'proctime.proctime) val countFun = new CountAggFunction val weightAvgFun = new WeightedAvg val windowedTable = table .window(Tumble over 2.rows on 'proctime as 'w) .groupBy('w) .select(countFun('string), 'int.avg, weightAvgFun('long, 'int), weightAvgFun('int, 'int)) val results = windowedTable.toAppendStream[Row](queryConfig) results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq("2,1,1,1", "2,2,6,2") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testEventTimeTumblingWindow(): Unit = { val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env .fromCollection(data) .assignTimestampsAndWatermarks(new TimestampAndWatermarkWithOffset[(Long, Int, String)](0L)) val table = stream.toTable(tEnv, 'long, 'int, 'string, 'rowtime.rowtime) val countFun = new CountAggFunction val weightAvgFun = new WeightedAvg val windowedTable = table .window(Tumble over 5.milli on 'rowtime as 'w) .groupBy('w, 'string) .select('string, countFun('string), 'int.avg, weightAvgFun('long, 'int), weightAvgFun('int, 'int), 'int.min, 'int.max, 'int.sum, 'w.start, 'w.end) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq( "Hello world,1,3,8,3,3,3,3,1970-01-01 00:00:00.005,1970-01-01 00:00:00.01", "Hello world,1,3,16,3,3,3,3,1970-01-01 00:00:00.015,1970-01-01 00:00:00.02", "Hello,2,2,3,2,2,2,4,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005", "Hi,1,1,1,1,1,1,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testGroupWindowWithoutKeyInProjection(): Unit = { val data = List( (1L, 1, "Hi", 1, 1), (2L, 2, "Hello", 2, 2), (4L, 2, "Hello", 2, 2), (8L, 3, "Hello world", 3, 3), (16L, 3, "Hello world", 3, 3)) val env = StreamExecutionEnvironment.getExecutionEnvironment env.setParallelism(1) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env.fromCollection(data) val table = stream.toTable(tEnv, 'long, 'int, 'string, 'int2, 'int3, 'proctime.proctime) val weightAvgFun = new WeightedAvg val windowedTable = table .window(Slide over 2.rows every 1.rows on 'proctime as 'w) .groupBy('w, 'int2, 'int3, 'string) .select(weightAvgFun('long, 'int)) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq("12", "8", "2", "3", "1") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } // ---------------------------------------------------------------------------------------------- // Sliding windows // ---------------------------------------------------------------------------------------------- @Test def testAllEventTimeSlidingGroupWindowOverTime(): Unit = { // please keep this test in sync with the DataSet variant val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env .fromCollection(data2) .assignTimestampsAndWatermarks( new TimestampAndWatermarkWithOffset[(Long, Int, Double, Float, BigDecimal, String)](0L)) val table = stream.toTable(tEnv, 'long.rowtime, 'int, 'double, 'float, 'bigdec, 'string) val windowedTable = table .window(Slide over 5.milli every 2.milli on 'long as 'w) .groupBy('w) .select('int.count, 'w.start, 'w.end) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq( "1,1970-01-01 00:00:00.008,1970-01-01 00:00:00.013", "1,1970-01-01 00:00:00.012,1970-01-01 00:00:00.017", "1,1970-01-01 00:00:00.014,1970-01-01 00:00:00.019", "1,1970-01-01 00:00:00.016,1970-01-01 00:00:00.021", "2,1969-12-31 23:59:59.998,1970-01-01 00:00:00.003", "2,1970-01-01 00:00:00.006,1970-01-01 00:00:00.011", "3,1970-01-01 00:00:00.002,1970-01-01 00:00:00.007", "3,1970-01-01 00:00:00.004,1970-01-01 00:00:00.009", "4,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testEventTimeSlidingGroupWindowOverTimeOverlappingFullPane(): Unit = { // please keep this test in sync with the DataSet variant val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env .fromCollection(data2) .assignTimestampsAndWatermarks( new TimestampAndWatermarkWithOffset[(Long, Int, Double, Float, BigDecimal, String)](0L)) val table = stream.toTable(tEnv, 'long.rowtime, 'int, 'double, 'float, 'bigdec, 'string) val windowedTable = table .window(Slide over 10.milli every 5.milli on 'long as 'w) .groupBy('w, 'string) .select('string, 'int.count, 'w.start, 'w.end) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq( "Hallo,1,1969-12-31 23:59:59.995,1970-01-01 00:00:00.005", "Hallo,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.01", "Hello world,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.01", "Hello world,1,1970-01-01 00:00:00.005,1970-01-01 00:00:00.015", "Hello world,1,1970-01-01 00:00:00.01,1970-01-01 00:00:00.02", "Hello world,1,1970-01-01 00:00:00.015,1970-01-01 00:00:00.025", "Hello,1,1970-01-01 00:00:00.005,1970-01-01 00:00:00.015", "Hello,2,1969-12-31 23:59:59.995,1970-01-01 00:00:00.005", "Hello,3,1970-01-01 00:00:00.0,1970-01-01 00:00:00.01", "Hi,1,1969-12-31 23:59:59.995,1970-01-01 00:00:00.005", "Hi,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.01") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testEventTimeSlidingGroupWindowOverTimeOverlappingSplitPane(): Unit = { // please keep this test in sync with the DataSet variant val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env .fromCollection(data2) .assignTimestampsAndWatermarks( new TimestampAndWatermarkWithOffset[(Long, Int, Double, Float, BigDecimal, String)](0L)) val table = stream.toTable(tEnv, 'long.rowtime, 'int, 'double, 'float, 'bigdec, 'string) val windowedTable = table .window(Slide over 5.milli every 4.milli on 'long as 'w) .groupBy('w, 'string) .select('string, 'int.count, 'w.start, 'w.end) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq( "Hallo,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005", "Hello world,1,1970-01-01 00:00:00.004,1970-01-01 00:00:00.009", "Hello world,1,1970-01-01 00:00:00.008,1970-01-01 00:00:00.013", "Hello world,1,1970-01-01 00:00:00.012,1970-01-01 00:00:00.017", "Hello world,1,1970-01-01 00:00:00.016,1970-01-01 00:00:00.021", "Hello,2,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005", "Hello,2,1970-01-01 00:00:00.004,1970-01-01 00:00:00.009", "Hi,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testEventTimeSlidingGroupWindowOverTimeNonOverlappingFullPane(): Unit = { // please keep this test in sync with the DataSet variant val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env .fromCollection(data2) .assignTimestampsAndWatermarks( new TimestampAndWatermarkWithOffset[(Long, Int, Double, Float, BigDecimal, String)](0L)) val table = stream.toTable(tEnv, 'long.rowtime, 'int, 'double, 'float, 'bigdec, 'string) val windowedTable = table .window(Slide over 5.milli every 10.milli on 'long as 'w) .groupBy('w, 'string) .select('string, 'int.count, 'w.start, 'w.end) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq( "Hallo,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005", "Hello,2,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005", "Hi,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.005") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testEventTimeSlidingGroupWindowOverTimeNonOverlappingSplitPane(): Unit = { // please keep this test in sync with the DataSet variant val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env .fromCollection(data2) .assignTimestampsAndWatermarks( new TimestampAndWatermarkWithOffset[(Long, Int, Double, Float, BigDecimal, String)](0L)) val table = stream.toTable(tEnv, 'long.rowtime, 'int, 'double, 'float, 'bigdec, 'string) val windowedTable = table .window(Slide over 3.milli every 10.milli on 'long as 'w) .groupBy('w, 'string) .select('string, 'int.count, 'w.start, 'w.end) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq( "Hallo,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.003", "Hi,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.003") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } @Test def testEventTimeGroupWindowWithoutExplicitTimeField(): Unit = { val env = StreamExecutionEnvironment.getExecutionEnvironment env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime) val tEnv = TableEnvironment.getTableEnvironment(env) StreamITCase.testResults = mutable.MutableList() val stream = env .fromCollection(data2) .assignTimestampsAndWatermarks( new TimestampAndWatermarkWithOffset[(Long, Int, Double, Float, BigDecimal, String)](0L)) .map(t => (t._2, t._6)) val table = stream.toTable(tEnv, 'int, 'string, 'rowtime.rowtime) val windowedTable = table .window(Slide over 3.milli every 10.milli on 'rowtime as 'w) .groupBy('w, 'string) .select('string, 'int.count, 'w.start, 'w.end) val results = windowedTable.toAppendStream[Row] results.addSink(new StreamITCase.StringSink[Row]) env.execute() val expected = Seq( "Hallo,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.003", "Hi,1,1970-01-01 00:00:00.0,1970-01-01 00:00:00.003") assertEquals(expected.sorted, StreamITCase.testResults.sorted) } } object GroupWindowITCase { class TimestampAndWatermarkWithOffset[T <: Product]( offset: Long) extends AssignerWithPunctuatedWatermarks[T] { override def checkAndGetNextWatermark( lastElement: T, extractedTimestamp: Long): Watermark = { new Watermark(extractedTimestamp - offset) } override def extractTimestamp( element: T, previousElementTimestamp: Long): Long = { element.productElement(0).asInstanceOf[Long] } } }
{ "content_hash": "8ddfa81c14e162b784c5af378097a8a6", "timestamp": "", "source": "github", "line_count": 429, "max_line_length": 107, "avg_line_length": 40.107226107226104, "alnum_prop": 0.6853423224456585, "repo_name": "mtunique/flink", "id": "1561da0417edb3f0181133736b8e00839fe0c311", "size": "18011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-libraries/flink-table/src/test/scala/org/apache/flink/table/runtime/stream/table/GroupWindowITCase.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4792" }, { "name": "CSS", "bytes": "18100" }, { "name": "CoffeeScript", "bytes": "89007" }, { "name": "HTML", "bytes": "86524" }, { "name": "Java", "bytes": "31693932" }, { "name": "JavaScript", "bytes": "8267" }, { "name": "Python", "bytes": "166860" }, { "name": "Scala", "bytes": "5808062" }, { "name": "Shell", "bytes": "86444" } ], "symlink_target": "" }
package techreborn.client.gui; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.player.PlayerEntity; import reborncore.client.gui.builder.GuiBase; import reborncore.client.gui.guibuilder.GuiBuilder; import reborncore.common.screen.BuiltScreenHandler; import techreborn.blockentity.machine.tier1.ExtractorBlockEntity; public class GuiExtractor extends GuiBase<BuiltScreenHandler> { ExtractorBlockEntity blockEntity; public GuiExtractor(int syncID, final PlayerEntity player, final ExtractorBlockEntity blockEntity) { super(player, blockEntity, blockEntity.createScreenHandler(syncID, player)); this.blockEntity = blockEntity; } @Override protected void drawBackground(MatrixStack matrixStack, final float f, final int mouseX, final int mouseY) { super.drawBackground(matrixStack, f, mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.BACKGROUND; drawSlot(matrixStack, 8, 72, layer); drawSlot(matrixStack, 55, 45, layer); drawOutputSlot(matrixStack, 101, 45, layer); builder.drawJEIButton(matrixStack, this, 158, 5, layer); } @Override protected void drawForeground(MatrixStack matrixStack, final int mouseX, final int mouseY) { super.drawForeground(matrixStack, mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.FOREGROUND; builder.drawProgressBar(matrixStack, this, blockEntity.getProgressScaled(100), 100, 76, 48, mouseX, mouseY, GuiBuilder.ProgressDirection.RIGHT, layer); builder.drawMultiEnergyBar(matrixStack, this, 9, 19, (int) blockEntity.getEnergy(), (int) blockEntity.getMaxStoredPower(), mouseX, mouseY, 0, layer); } }
{ "content_hash": "e6d2a8ff6d13d68ac46d109f98a70b87", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 153, "avg_line_length": 38.595238095238095, "alnum_prop": 0.7951881554595929, "repo_name": "TechReborn/TechReborn", "id": "7e3a6188a8dd80531a07d66da32e54cd76a5d7ff", "size": "2812", "binary": false, "copies": "1", "ref": "refs/heads/1.19", "path": "src/client/java/techreborn/client/gui/GuiExtractor.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "145055" }, { "name": "Java", "bytes": "2134577" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.openid4java</groupId> <artifactId>openid4java-parent</artifactId> <version>0.9.4</version> </parent> <artifactId>openid4java-server-JdbcServerAssociationStore</artifactId> <packaging>jar</packaging> <name>OpenID4Java Server JdbcServerAssociationStore</name> <build> <sourceDirectory>../../src</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <includes> <include>org/openid4java/server/JdbcServerAssociationStore.java</include> </includes> </configuration> </plugin> </plugins> </build> <reporting> <outputDirectory>../target/site/${project.artifactId}/</outputDirectory> </reporting> <dependencies> <dependency> <groupId>${groupId}</groupId> <artifactId>openid4java-server</artifactId> <version>${version}</version> </dependency> <!-- JdbcServerAssociationStore --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> </dependencies> </project>
{ "content_hash": "16194103cdcf975e7d00a4c49eb058c5", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 85, "avg_line_length": 31.02127659574468, "alnum_prop": 0.6625514403292181, "repo_name": "yorkie1/openid4java", "id": "d0c0a6f42dbaa3896374e23c6873a2b8779bc183", "size": "1458", "binary": false, "copies": "1", "ref": "refs/heads/openid4java-0.9.4", "path": "maven2/openid4java-server-JdbcServerAssociationStore/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "38835" }, { "name": "Java", "bytes": "688584" } ], "symlink_target": "" }
import errno import json from contextlib import contextmanager from hashlib import md5 import unittest import uuid import shutil import random from collections import defaultdict import os from test.probe.common import ECProbeTest from swift.common import direct_client from swift.common.storage_policy import EC_POLICY from swift.common.manager import Manager from swift.obj.reconstructor import _get_partners from swiftclient import client, ClientException class Body(object): def __init__(self, total=3.5 * 2 ** 20): self.total = total self.hasher = md5() self.size = 0 self.chunk = 'test' * 16 * 2 ** 10 @property def etag(self): return self.hasher.hexdigest() def __iter__(self): return self def next(self): if self.size > self.total: raise StopIteration() self.size += len(self.chunk) self.hasher.update(self.chunk) return self.chunk def __next__(self): return next(self) class TestReconstructorRebuild(ECProbeTest): def setUp(self): super(TestReconstructorRebuild, self).setUp() self.container_name = 'container-%s' % uuid.uuid4() self.object_name = 'object-%s' % uuid.uuid4() # sanity self.assertEqual(self.policy.policy_type, EC_POLICY) self.reconstructor = Manager(["object-reconstructor"]) # create EC container headers = {'X-Storage-Policy': self.policy.name} client.put_container(self.url, self.token, self.container_name, headers=headers) # PUT object and POST some metadata contents = Body() headers = {'x-object-meta-foo': 'meta-foo'} self.headers_post = {'x-object-meta-bar': 'meta-bar'} self.etag = client.put_object(self.url, self.token, self.container_name, self.object_name, contents=contents, headers=headers) client.post_object(self.url, self.token, self.container_name, self.object_name, headers=dict(self.headers_post)) self.opart, self.onodes = self.object_ring.get_nodes( self.account, self.container_name, self.object_name) # stash frag etags and metadata for later comparison self.frag_headers, self.frag_etags = self._assert_all_nodes_have_frag() for node_index, hdrs in self.frag_headers.items(): # sanity check self.assertIn( 'X-Backend-Durable-Timestamp', hdrs, 'Missing durable timestamp in %r' % self.frag_headers) def proxy_get(self): # GET object headers, body = client.get_object(self.url, self.token, self.container_name, self.object_name, resp_chunk_size=64 * 2 ** 10) resp_checksum = md5() for chunk in body: resp_checksum.update(chunk) return headers, resp_checksum.hexdigest() def direct_get(self, node, part, require_durable=True): req_headers = {'X-Backend-Storage-Policy-Index': int(self.policy)} if not require_durable: req_headers.update( {'X-Backend-Fragment-Preferences': json.dumps([])}) headers, data = direct_client.direct_get_object( node, part, self.account, self.container_name, self.object_name, headers=req_headers, resp_chunk_size=64 * 2 ** 20) hasher = md5() for chunk in data: hasher.update(chunk) return headers, hasher.hexdigest() def _break_nodes(self, failed, non_durable): # delete partitions on the failed nodes and remove durable marker from # non-durable nodes for i, node in enumerate(self.onodes): part_dir = self.storage_dir('object', node, part=self.opart) if i in failed: shutil.rmtree(part_dir, True) try: self.direct_get(node, self.opart) except direct_client.DirectClientException as err: self.assertEqual(err.http_status, 404) elif i in non_durable: for dirs, subdirs, files in os.walk(part_dir): for fname in files: if fname.endswith('.data'): non_durable_fname = fname.replace('#d', '') os.rename(os.path.join(dirs, fname), os.path.join(dirs, non_durable_fname)) break headers, etag = self.direct_get(node, self.opart, require_durable=False) self.assertNotIn('X-Backend-Durable-Timestamp', headers) try: os.remove(os.path.join(part_dir, 'hashes.pkl')) except OSError as e: if e.errno != errno.ENOENT: raise def _format_node(self, node): return '%s#%s' % (node['device'], node['index']) def _assert_all_nodes_have_frag(self): # check all frags are in place failures = [] frag_etags = {} frag_headers = {} for node in self.onodes: try: headers, etag = self.direct_get(node, self.opart) frag_etags[node['index']] = etag del headers['Date'] # Date header will vary so remove it frag_headers[node['index']] = headers except direct_client.DirectClientException as err: failures.append((node, err)) if failures: self.fail('\n'.join([' Node %r raised %r' % (self._format_node(node), exc) for (node, exc) in failures])) return frag_headers, frag_etags @contextmanager def _annotate_failure_with_scenario(self, failed, non_durable): try: yield except (AssertionError, ClientException) as err: self.fail( 'Scenario with failed nodes: %r, non-durable nodes: %r\n' ' failed with:\n%s' % ([self._format_node(self.onodes[n]) for n in failed], [self._format_node(self.onodes[n]) for n in non_durable], err) ) def _test_rebuild_scenario(self, failed, non_durable, reconstructor_cycles): # helper method to test a scenario with some nodes missing their # fragment and some nodes having non-durable fragments with self._annotate_failure_with_scenario(failed, non_durable): self._break_nodes(failed, non_durable) # make sure we can still GET the object and it is correct; the # proxy is doing decode on remaining fragments to get the obj with self._annotate_failure_with_scenario(failed, non_durable): headers, etag = self.proxy_get() self.assertEqual(self.etag, etag) for key in self.headers_post: self.assertIn(key, headers) self.assertEqual(self.headers_post[key], headers[key]) # fire up reconstructor for i in range(reconstructor_cycles): self.reconstructor.once() # check GET via proxy returns expected data and metadata with self._annotate_failure_with_scenario(failed, non_durable): headers, etag = self.proxy_get() self.assertEqual(self.etag, etag) for key in self.headers_post: self.assertIn(key, headers) self.assertEqual(self.headers_post[key], headers[key]) # check all frags are intact, durable and have expected metadata with self._annotate_failure_with_scenario(failed, non_durable): frag_headers, frag_etags = self._assert_all_nodes_have_frag() self.assertEqual(self.frag_etags, frag_etags) # self._frag_headers include X-Backend-Durable-Timestamp so this # assertion confirms that the rebuilt frags are all durable self.assertEqual(self.frag_headers, frag_headers) def test_rebuild_missing_frags(self): # build up a list of node lists to kill data from, # first try a single node # then adjacent nodes and then nodes >1 node apart single_node = (random.randint(0, 5),) adj_nodes = (0, 5) far_nodes = (0, 4) for failed_nodes in [single_node, adj_nodes, far_nodes]: self._test_rebuild_scenario(failed_nodes, [], 1) def test_rebuild_non_durable_frags(self): # build up a list of node lists to make non-durable, # first try a single node # then adjacent nodes and then nodes >1 node apart single_node = (random.randint(0, 5),) adj_nodes = (0, 5) far_nodes = (0, 4) for non_durable_nodes in [single_node, adj_nodes, far_nodes]: self._test_rebuild_scenario([], non_durable_nodes, 1) def test_rebuild_with_missing_frags_and_non_durable_frags(self): # pick some nodes with parts deleted, some with non-durable fragments scenarios = [ # failed, non-durable ((0, 2), (4,)), ((0, 4), (2,)), ] for failed, non_durable in scenarios: self._test_rebuild_scenario(failed, non_durable, 3) scenarios = [ # failed, non-durable ((0, 1), (2,)), ((0, 2), (1,)), ] for failed, non_durable in scenarios: # why 2 repeats? consider missing fragment on nodes 0, 1 and # missing durable on node 2: first reconstructor cycle on node 3 # will make node 2 durable, first cycle on node 5 will rebuild on # node 0; second cycle on node 0 or 2 will rebuild on node 1. Note # that it is possible, that reconstructor processes on each node # run in order such that all rebuild complete in once cycle, but # that is not guaranteed, we allow 2 cycles to be sure. self._test_rebuild_scenario(failed, non_durable, 2) scenarios = [ # failed, non-durable ((0, 2), (1, 3, 5)), ((0,), (1, 2, 4, 5)), ] for failed, non_durable in scenarios: # why 3 repeats? consider missing fragment on node 0 and single # durable on node 3: first reconstructor cycle on node 3 will make # nodes 2 and 4 durable, second cycle on nodes 2 and 4 will make # node 1 and 5 durable, third cycle on nodes 1 or 5 will # reconstruct the missing fragment on node 0. self._test_rebuild_scenario(failed, non_durable, 3) def test_rebuild_partner_down(self): # find a primary server that only has one of it's devices in the # primary node list group_nodes_by_config = defaultdict(list) for n in self.onodes: group_nodes_by_config[self.config_number(n)].append(n) for config_number, node_list in group_nodes_by_config.items(): if len(node_list) == 1: break else: self.fail('ring balancing did not use all available nodes') primary_node = node_list[0] # pick one it's partners to fail randomly partner_node = random.choice(_get_partners( primary_node['index'], self.onodes)) # 507 the partner device device_path = self.device_dir('object', partner_node) self.kill_drive(device_path) # select another primary sync_to node to fail failed_primary = [n for n in self.onodes if n['id'] not in (primary_node['id'], partner_node['id'])][0] # ... capture it's fragment etag failed_primary_meta, failed_primary_etag = self.direct_get( failed_primary, self.opart) # ... and delete it part_dir = self.storage_dir('object', failed_primary, part=self.opart) shutil.rmtree(part_dir, True) # reconstruct from the primary, while one of it's partners is 507'd self.reconstructor.once(number=self.config_number(primary_node)) # the other failed primary will get it's fragment rebuilt instead failed_primary_meta_new, failed_primary_etag_new = self.direct_get( failed_primary, self.opart) del failed_primary_meta['Date'] del failed_primary_meta_new['Date'] self.assertEqual(failed_primary_etag, failed_primary_etag_new) self.assertEqual(failed_primary_meta, failed_primary_meta_new) # just to be nice self.revive_drive(device_path) if __name__ == "__main__": unittest.main()
{ "content_hash": "79b4cc338c5ae6cfdd71023a4e06eb02", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 79, "avg_line_length": 41.284345047923324, "alnum_prop": 0.5758396533044421, "repo_name": "hurricanerix/swift", "id": "ed640939a343dc9219d2c5ed25efceb96e148ab4", "size": "13538", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/probe/test_reconstructor_rebuild.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "248" }, { "name": "PHP", "bytes": "377" }, { "name": "Python", "bytes": "8216497" }, { "name": "Shell", "bytes": "1804" } ], "symlink_target": "" }