hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
4e7486e8086b7a35a7d01a8696ccb134ffcac371
1,224
package com.bluecove.emu.gui.graph; import org.jgraph.graph.AttributeMap; import org.jgraph.graph.ConnectionSet; import org.jgraph.graph.DefaultEdge; import org.jgraph.graph.DefaultGraphCell; import org.jgraph.graph.GraphConstants; public class ConnectionEdge extends DefaultEdge { private static final long serialVersionUID = 1L; private ConnectionSet connectionSet; public ConnectionEdge(String name, DefaultGraphCell source, DefaultGraphCell target) { super(name); attributes = new AttributeMap(); GraphConstants.setLineBegin(attributes, GraphConstants.ARROW_CLASSIC); GraphConstants.setBeginSize(attributes, 10); GraphConstants.setBeginFill(attributes, true); if (GraphConstants.DEFAULTFONT != null) { GraphConstants.setFont(attributes, GraphConstants.DEFAULTFONT .deriveFont(10)); } GraphConstants.setBendable(attributes,false); GraphConstants.setEditable(attributes,false); GraphConstants.setSizeable(attributes,false); GraphConstants.setDisconnectable(attributes,false); connectionSet = new ConnectionSet(); connectionSet.connect(this, source.getChildAt(0), target.getChildAt(0)); } public ConnectionSet getConnectionSet() { return connectionSet; } }
27.818182
88
0.789216
b8d7653ec73baa92c63984be1e96f6340ce51a13
6,387
/* * The MIT License * * Copyright 2013 Jakub Jirutka <[email protected]>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package cz.jirutka.rsql.hibernate; import java.util.ArrayList; import java.util.List; import cz.jirutka.rsql.hibernate.builder.*; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.DetachedCriteria; /** * Factory for creating {@link RSQL2CriteriaConverter} instances. This may be used * in application's context for obtaining preconfigured Criteria Converters. * * @author Jakub Jirutka <[email protected]> */ public class RSQL2HibernateFactory { private static RSQL2HibernateFactory instance; private SessionFactory sessionFactory; private ArgumentParser argumentParser = new DefaultArgumentParser(); //default private List<AbstractCriterionBuilder> criterionBuilders = new ArrayList<AbstractCriterionBuilder>(4); private int associationsLimit = -1; // default private Mapper mapper = new SimpleMapper(); // default /** * Factory method for obtaining singleton instance of * <tt>RSQL2HibernateFactory</tt>. * * @return Singleton instance of <tt>RSQL2HibernateFactory</tt>. */ public static RSQL2HibernateFactory getInstance() { if (instance == null) { instance = new RSQL2HibernateFactory(); } return instance; } private RSQL2HibernateFactory() { criterionBuilders.add(new AssociationsCriterionBuilder()); criterionBuilders.add(new NaturalIdCriterionBuilder()); criterionBuilders.add(new IdentifierCriterionBuilder()); criterionBuilders.add(new DefaultCriterionBuilder()); } /** * Create new {@link RSQL2CriteriaConverter} that can parse a RSQL expressions * and convert it to Hibernate {@link Criteria} or {@link DetachedCriteria}. * * @return RSQL2CriteriaConverter */ public RSQL2CriteriaConverter createConverter() { RSQL2CriteriaConverterImpl converter = new RSQL2CriteriaConverterImpl(sessionFactory); // copy defaults converter.setArgumentParser(argumentParser); converter.setAssociationsLimit(associationsLimit); converter.setMapper(mapper); converter.getCriterionBuilders().addAll(criterionBuilders); return converter; } /** * Set default Argument Parser. If you don't set any, the * {@link DefaultArgumentParser} will be used. * * @see RSQL2CriteriaConverter#getArgumentParser() * @param argumentParser An <tt>ArgumentParser</tt> instance, * must not be <tt>null</tt>. */ public void setArgumentParser(ArgumentParser argumentParser) { this.argumentParser = argumentParser; } /** * Set default stack of {@linkplain AbstractCriterionBuilder Criterion * Builders} that will be copied to all new RSQL2CriteriaConverter instances. * * If you dont't set any, these will by used: <ul> * <li>{@link AssociationsCriterionBuilder} - Handles association "dereference". * That means you can specify constraints upon related entities by navigating * associations using dot-notation.</li> * <li>{@link NaturalIdCriterionBuilder} - Creates Criterion for a property * representing an association, and an argument containing NaturalID of the * associated entity.</li> * <li>{@link IdentifierCriterionBuilder} - Creates Criterion for a property * representing an association, and an argument containing ID of the * associated entity.</li> * <li>{@link DefaultCriterionBuilder} - Default implementation, simply * creates Criterion for a basic property (not association).</li> * </ul> * * @param criterionBuilders List of Criterion Builders to use as default in * new instances of Criteria Builder. */ public void setCriterionBuilders(List<AbstractCriterionBuilder> criterionBuilders) { assert !criterionBuilders.isEmpty(); this.criterionBuilders = criterionBuilders; } /** * Set default associations limit. Default value is -1 (e.g. none limit). * * @see RSQL2CriteriaConverter#getAssociationsLimit() * @param limit Upper limit of associations that can be handled. Must be * greater or equal -1. */ public void setAssociationsLimit(int limit) { assert limit >= -1 : "must be greater or equal -1"; this.associationsLimit = limit; } /** * Set default <tt>Mapper</tt> for new instances. If you don't set any, * the {@link SimpleMapper} will be used. * * @see RSQL2CriteriaConverter#getMapper() * @param mapping A <tt>Mapper</tt> instance, must not be <tt>null</tt>. */ public void setMapper(Mapper mapping) { this.mapper = mapping; } /** * Set Hibernate <tt>SessionFactory</tt> that will be used to obtain * <tt>ClassMetadata</tt>. * * <b>This si required and must not be null!</b> * * @param sessionFactory Hibernate <tt>SessionFactory</tt>, must not be * <tt>null.</tt>. */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
38.475904
106
0.690465
f1ac5e34cb69233e41766cc1d23567050f8c9c6d
3,828
package org.rapidpm.vaadin.server; import static io.undertow.Handlers.redirect; import static io.undertow.servlet.Servlets.servlet; import static javax.servlet.DispatcherType.ERROR; import static javax.servlet.DispatcherType.FORWARD; import static javax.servlet.DispatcherType.INCLUDE; import static javax.servlet.DispatcherType.REQUEST; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Supplier; import javax.servlet.Servlet; import javax.servlet.ServletException; import org.apache.shiro.web.env.EnvironmentLoaderListener; import org.apache.shiro.web.servlet.ShiroFilter; import org.rapidpm.frp.functions.TriFunction; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.ListenerInfo; /** * */ public interface InfrastructureFunctions { String DEFAULT_SHIRO_FILTER = "ShiroFilter"; String DEFAULT_SHIRO_FILTER_MAPPING = "/*"; String DEFAULT_DEPLOYMENT_NAME = "ROOT.war"; static BiFunction<ClassLoader, String, DeploymentInfo> baseDeploymentInfo() { return (classLoader, contextpath) -> Servlets.deployment() .setDefaultEncoding("UTF-8") .setClassLoader(classLoader) .setContextPath(contextpath); } static TriFunction<DeploymentInfo, String, String, DeploymentInfo> shiroFilter() { return (deploymentInfo, filterName, filterMapping) -> deploymentInfo .addListener(new ListenerInfo(EnvironmentLoaderListener.class)) .addFilter(new FilterInfo(filterName, ShiroFilter.class)) .addFilterUrlMapping(filterName, filterMapping, REQUEST) .addFilterUrlMapping(filterName, filterMapping, FORWARD) .addFilterUrlMapping(filterName, filterMapping, INCLUDE) .addFilterUrlMapping(filterName, filterMapping, ERROR); } static Supplier<Integer> httpPort(){ return ()->8080; } static TriFunction<Class<? extends Servlet>, ClassLoader, String, Optional<Undertow>> undertowOneServlet() { return (servlet, classLoader, contextpath) -> { DeploymentInfo servletBuilder = baseDeploymentInfo().apply(classLoader, contextpath) .setDeploymentName(DEFAULT_DEPLOYMENT_NAME) .addServlets( servlet(servlet.getSimpleName(), servlet, new ServletInstanceFactory(servlet)) .addMapping("/*") ); DeploymentManager manager = Servlets .defaultContainer() .addDeployment(servletBuilder); manager.deploy(); try { HttpHandler httpHandler = manager.start(); PathHandler path = Handlers.path(redirect(contextpath)) .addPrefixPath(contextpath, httpHandler); Undertow undertowServer = Undertow.builder() .addHttpListener(httpPort().get(), "0.0.0.0") .setHandler(path) .build(); undertowServer.start(); undertowServer.getListenerInfo().forEach(System.out::println); return Optional.of(undertowServer); } catch (ServletException e) { e.printStackTrace(); return Optional.empty(); } }; } }
35.775701
110
0.636102
30b9387ffa9f2e6829eb9f7caa6b11ffa87e3c91
168
package output.animation; import common.AbstractLaneGroup; public interface InterfaceLinkInfo { AbstractLaneGroupInfo newLaneGroupInfo(AbstractLaneGroup lg); }
16.8
65
0.827381
c01f7cb9e3724e17eea37fd1e3e42f93c1004d7c
787
package com.stackroute.freelancerprofile.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.stereotype.Component; import java.util.*; @Document @Data @NoArgsConstructor @AllArgsConstructor @Component @Builder public class Skill { // private Map<String, List<Freelancer>> hm=new HashMap<String, List<Freelancer>>(); @Id private String id; private String skill; private List<Freelancer> list; }
27.137931
87
0.817027
9bbc7872b3f47ae100023a73390c8315579f2b0b
4,632
package io.wkm.jcartstoreback.controller; import at.favre.lib.crypto.bcrypt.BCrypt; import com.sun.xml.internal.ws.client.ClientTransportException; import io.wkm.jcartstoreback.constant.ClientExceptionConstant; import io.wkm.jcartstoreback.dto.in.*; import io.wkm.jcartstoreback.dto.out.CustomerLoginOutDTO; import io.wkm.jcartstoreback.dto.out.CustomerProfileOutDTO; import io.wkm.jcartstoreback.exception.ClientException; import io.wkm.jcartstoreback.pojo.Customer; import io.wkm.jcartstoreback.service.CustomerService; import io.wkm.jcartstoreback.util.JWTUtil; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @RestController @RequestMapping("/customer") @CrossOrigin public class CustomerController { @Resource private CustomerService customerService; @Resource private JWTUtil jwtUtil; @PostMapping("/register") public Integer register(@RequestBody CustomerRegisterInDTO customerRegisterInDTO){ return customerService.register(customerRegisterInDTO); } @GetMapping("/login") public CustomerLoginOutDTO login(CustomerLoginInDTO customerLoginInDTO) throws ClientException { Customer customer = customerService.getByUserName(customerLoginInDTO.getUsername()); if (customer == null){ throw new ClientException(ClientExceptionConstant.CUSTOMER_USERNAME_NOT_EXIST_ERRCODE,ClientExceptionConstant.CUSTOMER_USERNAME_NOT_EXIST_ERRMSG); } String encryptedPassword = customer.getEncryptedPassword(); BCrypt.Result result = BCrypt.verifyer().verify(customerLoginInDTO.getPassword().toCharArray(), encryptedPassword); if (result.verified){ return jwtUtil.issueToken(customer); }else { throw new ClientException(ClientExceptionConstant.CUSTOMER_PASSWORD_INVALID_ERRCODE,ClientExceptionConstant.CUSTOMER_PASSWORD_INVALID_ERRMSG); } } @GetMapping("/getProfile") public CustomerProfileOutDTO getProfile(@RequestAttribute Integer customerId){ Customer customer = customerService.getById(customerId); CustomerProfileOutDTO customerGetProfileOutDTO = new CustomerProfileOutDTO(); customerGetProfileOutDTO.setUsername(customer.getUsername()); customerGetProfileOutDTO.setRealName(customer.getRealName()); customerGetProfileOutDTO.setMobile(customer.getMobile()); customerGetProfileOutDTO.setMobileVerified(customer.getMobileVerified()); customerGetProfileOutDTO.setEmail(customer.getEmail()); customerGetProfileOutDTO.setEmailVerified(customer.getEmailVerified()); return customerGetProfileOutDTO; } @PostMapping("/updateProfile") public void updateProfile(@RequestBody CustomerUpdateProfileInDTO customerUpdateProfileInDTO,@RequestAttribute Integer customerId){ Customer customer = new Customer(); customer.setCustomerId(customerId); customer.setRealName(customerUpdateProfileInDTO.getRealName()); customer.setMobile(customerUpdateProfileInDTO.getMobile()); customer.setEmail(customerUpdateProfileInDTO.getEmail()); customerService.update(customer); } @PostMapping("/changePassword") public void changePassword(@RequestBody CustomerChangePasswordInDTO customerChangePasswordInDTO,@RequestAttribute Integer customerId) throws ClientException { Customer customer = customerService.getById(customerId); String encryptedPassword = customer.getEncryptedPassword(); BCrypt.Result result = BCrypt.verifyer().verify(customerChangePasswordInDTO.getOriginPwd().toCharArray(), encryptedPassword); if (result.verified){ String s = BCrypt.withDefaults().hashToString(12, customerChangePasswordInDTO.getNewPwd().toCharArray()); customer.setEncryptedPassword(s); customerService.update(customer); }else { throw new ClientException(ClientExceptionConstant.CUSTOMER_PASSWORD_INVALID_ERRCODE , ClientExceptionConstant.CUSTOMER_PASSWORD_INVALID_ERRMSG); } } @GetMapping("/getPwdResetCode") public String getPwdResetCode(@RequestParam String email) throws ClientException { Customer customer = customerService.getByEmail(email); if (customer == null){ throw new ClientException(ClientExceptionConstant.CUSTOMER_USERNAME_NOT_EXIST_ERRCODE, ClientExceptionConstant.CUSTOMER_USERNAME_NOT_EXIST_ERRMSG); } return null; } @PostMapping("/resetPwd") public void resetPwd(@RequestBody CustomerResetPwdInDTO customerResetPwdInDTO){ } }
45.411765
162
0.761658
c57eebd5d84751dd0b811bd5e337aa52b9885e02
448
package org.springframework.test.util.subpackage; /** * Interface representing a <em>person</em> entity; intended for use in unit tests. * * The introduction of an interface is necessary in order to test support for * JDK dynamic proxies. * * @author Sam Brannen * @since 4.3 */ public interface Person { long getId(); String getName(); int getAge(); String getEyeColor(); boolean likesPets(); Number getFavoriteNumber(); }
15.448276
83
0.705357
014f001ff928695cac953bcf4321052f70ae4aa7
450
package com.accenture.airpoll.averages; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; public interface AverageRepository extends PagingAndSortingRepository<Average, String> { Page<Average> findByCountry(String country, Pageable pageable); Page<Average> findByCountryAndCity(String country, String city, Pageable pageable); }
40.909091
88
0.842222
46e9a5a7217f52b712268b26a5de526fcdbdb1f6
9,972
// ********************************************************************** // This file was generated by a TAF parser! // TAF version 3.0.0.34 by WSRD Tencent. // Generated from `/usr/local/resin_system.mqq.com/webapps/communication/taf/upload/noahyang/dock.jce' // ********************************************************************** package com.qq.jce.WCS; public final class ModifyDockInfoRequest extends com.qq.taf.jce.JceStruct implements java.lang.Cloneable { public String className() { return "WCS.ModifyDockInfoRequest"; } public String fullClassName() { return "com.qq.jce.WCS.ModifyDockInfoRequest"; } public com.qq.jce.WCS.AdminRequest stAdminRequestInfo = null; public java.util.Map<String, java.util.ArrayList<String>> mapUnit = null; public java.util.ArrayList<com.qq.jce.WCS.DockInfoElem> vecInfos = null; public long lReleaseTime = 0; public long lUpdateLimit = 0; public int nEnablePeriod = 0; public int eDockInfoStatus = 0; public String sDockDesc = ""; public String sDockInvalidDesc = ""; public boolean bRollBack = false; public String sTargetVersion = ""; public com.qq.jce.WCS.AdminRequest getStAdminRequestInfo() { return stAdminRequestInfo; } public void setStAdminRequestInfo(com.qq.jce.WCS.AdminRequest stAdminRequestInfo) { this.stAdminRequestInfo = stAdminRequestInfo; } public java.util.Map<String, java.util.ArrayList<String>> getMapUnit() { return mapUnit; } public void setMapUnit(java.util.Map<String, java.util.ArrayList<String>> mapUnit) { this.mapUnit = mapUnit; } public java.util.ArrayList<com.qq.jce.WCS.DockInfoElem> getVecInfos() { return vecInfos; } public void setVecInfos(java.util.ArrayList<com.qq.jce.WCS.DockInfoElem> vecInfos) { this.vecInfos = vecInfos; } public long getLReleaseTime() { return lReleaseTime; } public void setLReleaseTime(long lReleaseTime) { this.lReleaseTime = lReleaseTime; } public long getLUpdateLimit() { return lUpdateLimit; } public void setLUpdateLimit(long lUpdateLimit) { this.lUpdateLimit = lUpdateLimit; } public int getNEnablePeriod() { return nEnablePeriod; } public void setNEnablePeriod(int nEnablePeriod) { this.nEnablePeriod = nEnablePeriod; } public int getEDockInfoStatus() { return eDockInfoStatus; } public void setEDockInfoStatus(int eDockInfoStatus) { this.eDockInfoStatus = eDockInfoStatus; } public String getSDockDesc() { return sDockDesc; } public void setSDockDesc(String sDockDesc) { this.sDockDesc = sDockDesc; } public String getSDockInvalidDesc() { return sDockInvalidDesc; } public void setSDockInvalidDesc(String sDockInvalidDesc) { this.sDockInvalidDesc = sDockInvalidDesc; } public boolean getBRollBack() { return bRollBack; } public void setBRollBack(boolean bRollBack) { this.bRollBack = bRollBack; } public String getSTargetVersion() { return sTargetVersion; } public void setSTargetVersion(String sTargetVersion) { this.sTargetVersion = sTargetVersion; } public ModifyDockInfoRequest() { } public ModifyDockInfoRequest(com.qq.jce.WCS.AdminRequest stAdminRequestInfo, java.util.Map<String, java.util.ArrayList<String>> mapUnit, java.util.ArrayList<com.qq.jce.WCS.DockInfoElem> vecInfos, long lReleaseTime, long lUpdateLimit, int nEnablePeriod, int eDockInfoStatus, String sDockDesc, String sDockInvalidDesc, boolean bRollBack, String sTargetVersion) { this.stAdminRequestInfo = stAdminRequestInfo; this.mapUnit = mapUnit; this.vecInfos = vecInfos; this.lReleaseTime = lReleaseTime; this.lUpdateLimit = lUpdateLimit; this.nEnablePeriod = nEnablePeriod; this.eDockInfoStatus = eDockInfoStatus; this.sDockDesc = sDockDesc; this.sDockInvalidDesc = sDockInvalidDesc; this.bRollBack = bRollBack; this.sTargetVersion = sTargetVersion; } public boolean equals(Object o) { if(o == null) { return false; } ModifyDockInfoRequest t = (ModifyDockInfoRequest) o; return ( com.qq.taf.jce.JceUtil.equals(stAdminRequestInfo, t.stAdminRequestInfo) && com.qq.taf.jce.JceUtil.equals(mapUnit, t.mapUnit) && com.qq.taf.jce.JceUtil.equals(vecInfos, t.vecInfos) && com.qq.taf.jce.JceUtil.equals(lReleaseTime, t.lReleaseTime) && com.qq.taf.jce.JceUtil.equals(lUpdateLimit, t.lUpdateLimit) && com.qq.taf.jce.JceUtil.equals(nEnablePeriod, t.nEnablePeriod) && com.qq.taf.jce.JceUtil.equals(eDockInfoStatus, t.eDockInfoStatus) && com.qq.taf.jce.JceUtil.equals(sDockDesc, t.sDockDesc) && com.qq.taf.jce.JceUtil.equals(sDockInvalidDesc, t.sDockInvalidDesc) && com.qq.taf.jce.JceUtil.equals(bRollBack, t.bRollBack) && com.qq.taf.jce.JceUtil.equals(sTargetVersion, t.sTargetVersion) ); } public int hashCode() { try { throw new Exception("Need define key first!"); } catch(Exception ex) { ex.printStackTrace(); } return 0; } public java.lang.Object clone() { java.lang.Object o = null; try { o = super.clone(); } catch(CloneNotSupportedException ex) { assert false; // impossible } return o; } public void writeTo(com.qq.taf.jce.JceOutputStream _os) { _os.write(stAdminRequestInfo, 0); _os.write(mapUnit, 1); _os.write(vecInfos, 2); _os.write(lReleaseTime, 3); _os.write(lUpdateLimit, 4); _os.write(nEnablePeriod, 5); _os.write(eDockInfoStatus, 6); if (null != sDockDesc) { _os.write(sDockDesc, 7); } if (null != sDockInvalidDesc) { _os.write(sDockInvalidDesc, 8); } _os.write(bRollBack, 9); if (null != sTargetVersion) { _os.write(sTargetVersion, 10); } } static com.qq.jce.WCS.AdminRequest cache_stAdminRequestInfo; static java.util.Map<String, java.util.ArrayList<String>> cache_mapUnit; static java.util.ArrayList<com.qq.jce.WCS.DockInfoElem> cache_vecInfos; static int cache_eDockInfoStatus; public void readFrom(com.qq.taf.jce.JceInputStream _is) { if(null == cache_stAdminRequestInfo) { cache_stAdminRequestInfo = new com.qq.jce.WCS.AdminRequest(); } this.stAdminRequestInfo = (com.qq.jce.WCS.AdminRequest) _is.read(cache_stAdminRequestInfo, 0, true); if(null == cache_mapUnit) { cache_mapUnit = new java.util.HashMap<String, java.util.ArrayList<String>>(); String __var_3 = ""; java.util.ArrayList<String> __var_4 = new java.util.ArrayList<String>(); String __var_5 = ""; ((java.util.ArrayList<String>)__var_4).add(__var_5); cache_mapUnit.put(__var_3, __var_4); } this.mapUnit = (java.util.Map<String, java.util.ArrayList<String>>) _is.read(cache_mapUnit, 1, true); if(null == cache_vecInfos) { cache_vecInfos = new java.util.ArrayList<com.qq.jce.WCS.DockInfoElem>(); com.qq.jce.WCS.DockInfoElem __var_6 = new com.qq.jce.WCS.DockInfoElem(); ((java.util.ArrayList<com.qq.jce.WCS.DockInfoElem>)cache_vecInfos).add(__var_6); } this.vecInfos = (java.util.ArrayList<com.qq.jce.WCS.DockInfoElem>) _is.read(cache_vecInfos, 2, true); this.lReleaseTime = (long) _is.read(lReleaseTime, 3, false); this.lUpdateLimit = (long) _is.read(lUpdateLimit, 4, false); this.nEnablePeriod = (int) _is.read(nEnablePeriod, 5, false); this.eDockInfoStatus = (int) _is.read(eDockInfoStatus, 6, false); this.sDockDesc = _is.readString(7, false); this.sDockInvalidDesc = _is.readString(8, false); this.bRollBack = (boolean) _is.read(bRollBack, 9, false); this.sTargetVersion = _is.readString(10, false); } public void display(java.lang.StringBuilder _os, int _level) { com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level); _ds.display(stAdminRequestInfo, "stAdminRequestInfo"); _ds.display(mapUnit, "mapUnit"); _ds.display(vecInfos, "vecInfos"); _ds.display(lReleaseTime, "lReleaseTime"); _ds.display(lUpdateLimit, "lUpdateLimit"); _ds.display(nEnablePeriod, "nEnablePeriod"); _ds.display(eDockInfoStatus, "eDockInfoStatus"); _ds.display(sDockDesc, "sDockDesc"); _ds.display(sDockInvalidDesc, "sDockInvalidDesc"); _ds.display(bRollBack, "bRollBack"); _ds.display(sTargetVersion, "sTargetVersion"); } public void displaySimple(java.lang.StringBuilder _os, int _level) { com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level); _ds.displaySimple(stAdminRequestInfo, true); _ds.displaySimple(mapUnit, true); _ds.displaySimple(vecInfos, true); _ds.displaySimple(lReleaseTime, true); _ds.displaySimple(lUpdateLimit, true); _ds.displaySimple(nEnablePeriod, true); _ds.displaySimple(eDockInfoStatus, true); _ds.displaySimple(sDockDesc, true); _ds.displaySimple(sDockInvalidDesc, true); _ds.displaySimple(bRollBack, true); _ds.displaySimple(sTargetVersion, false); } }
31.457413
362
0.628961
0458dc0fb26b00a60fe706f7c7e034e526fe5477
2,028
package test.boulder.dmesh; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.jme3.scene.Node; import com.simsilica.lemur.Container; import com.simsilica.lemur.Label; import com.simsilica.lemur.core.VersionedReference; import com.simsilica.lemur.geom.Deformation; import com.simsilica.lemur.props.PropertyPanel; import com.simsilica.lemur.style.BaseStyles; import com.simsilica.lemur.style.ElementId; final class StDeformGui extends BaseAppState { private final Node scene = new Node("scene"); private VersionedReference<PropertyPanel> propsRef; public StDeformGui(Node guiNode) { guiNode.attachChild(scene); } @Override protected void initialize(Application app) { Container container = new Container(); container.addChild(new Label("Cylindrical deformation", new ElementId("window.title.label"))); PropertyPanel props = new PropertyPanel(BaseStyles.GLASS); // props.addIntProperty("major axis", getState(StBoulder.class).cylindricalDeform(), "majorAxis", 0, 2, 1); // props.addIntProperty("minor axis", getState(StBoulder.class).cylindricalDeform(), "minorAxis", 0, 2, 1); props.addFloatProperty("radius", getState(StBoulder.class).cylindricalDeform(), "radius", 0, 64, 0.25f); props.addFloatProperty("start", getState(StBoulder.class).cylindricalDeform(), "start", 0, 64, 0.25f); props.addFloatProperty("limit", getState(StBoulder.class).cylindricalDeform(), "limit", 0, 64, 0.25f); propsRef = props.createReference(); container.addChild(props); // major axis // minor axis // vector3f origin // float radius // float start // float limit scene.attachChild(container); container.setLocalTranslation(5, app.getCamera().getHeight() - 5, 0); } @Override public void update(float tpf) { super.update(tpf); if (propsRef.update()) { getState(StBoulder.class).updateMesh(); } } @Override protected void cleanup(Application app) { } @Override protected void onEnable() { } @Override protected void onDisable() { } }
27.780822
109
0.744083
3b1744a9861a52d2cbf91d923c8c583e0421a7ac
3,190
package com.liang.controller; import com.liang.bean.PhotoPro; import com.liang.code.ReturnT; import com.liang.service.PhotoProService; import com.liang.service.TbPhotoService; import com.liang.utils.UUIDUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; @RequestMapping("/api/rest/nanshengbbs/v3.0/photoPro") @Controller public class PhotoProController { @Autowired PhotoProService photoProService; @Autowired TbPhotoService tbPhotoService; /** * 创建相册 * @param photoPro * @param session * @return */ @PostMapping("/setPhotoPro") @ResponseBody public ReturnT<?> setPhotoPro(PhotoPro photoPro, HttpSession session) { try { photoPro.setUserid((String) session.getAttribute("userid")); if (photoProService.selectByName(photoPro).size() == 0){ // 不存在该相册名 photoPro.setFid(UUIDUtil.getRandomUUID()); photoProService.setPhotoPro(photoPro); return ReturnT.success("创建相册成功"); } else { return ReturnT.fail(HttpStatus.NOT_FOUND, "该相册已存在!"); } } catch (Exception e) { e.printStackTrace(); return ReturnT.fail("创建相册失败"); } } /** * 删除相册 * @return */ @DeleteMapping("/deletePhotoPro") @ResponseBody public ReturnT<?> deletePhotoPro(HttpServletRequest request) { try { String fid = request.getParameter("fid"); // 删除相册 photoProService.deletePhotoPro(fid); return ReturnT.success("删除相册成功"); } catch (Exception e) { e.printStackTrace(); return ReturnT.fail("删除相册失败"); } } /** * 编辑相册 * @return */ @PutMapping("/updatePhotoPro") @ResponseBody public ReturnT<?> updatePhotoPro(PhotoPro photoPro, HttpSession session) { try { photoPro.setUserid((String) session.getAttribute("userid")); if (photoProService.selectByName(photoPro).size() == 0) { // 不存在该相册名 photoProService.updateName(photoPro); return ReturnT.success("修改相册成功"); } else { return ReturnT.fail(HttpStatus.NOT_FOUND, "该相册已存在!"); } } catch (Exception e) { e.printStackTrace(); return ReturnT.fail("修改相册失败"); } } /** * 获取相册信息 * @return */ @GetMapping("/getPhoto") @ResponseBody public ReturnT<?> getPhoto(HttpSession session) { Map<String, Object> map = new HashMap<>(); try { //获取相册分类信息(按userid) map.put("listPhotoPros", photoProService.getPhotoPro((String) session.getAttribute("userid"))); return new ReturnT<>(HttpStatus.OK, "获取相册数据成功", map); } catch (Exception e) { e.printStackTrace(); return ReturnT.fail("获取相册数据失败"); } } /** * 按fid(相册id)获取相册信息 * @return */ @GetMapping("/getPhotoProFid/{fid}") @ResponseBody public ReturnT<?> selectByPrimaryKey(@PathVariable String fid) { Map<String, Object> map = new HashMap<>(); try { //查询相册 map.put("photoPro", photoProService.selectByPrimaryKey(fid)); return new ReturnT<>(HttpStatus.OK, "获取相册数据成功", map); } catch (Exception e) { e.printStackTrace(); return ReturnT.fail("获取相册数据失败"); } } }
25.52
98
0.705016
a34aed221cb16c47c2d96d7d51390996d91d1147
24,441
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.database; import java.io.File; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.management.JMException; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.MemoryMetrics; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.DataPageEvictionMode; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.MemoryPolicyConfiguration; import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.mem.DirectMemoryProvider; import org.apache.ignite.internal.mem.file.MappedFileMemoryProvider; import org.apache.ignite.internal.mem.unsafe.UnsafeMemoryProvider; import org.apache.ignite.internal.pagemem.PageMemory; import org.apache.ignite.internal.pagemem.snapshot.StartFullSnapshotAckDiscoveryMessage; import org.apache.ignite.internal.pagemem.impl.PageMemoryNoStoreImpl; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheMapEntry; import org.apache.ignite.internal.processors.cache.GridCacheSharedManagerAdapter; import org.apache.ignite.internal.processors.cache.database.evict.FairFifoPageEvictionTracker; import org.apache.ignite.internal.processors.cache.database.evict.NoOpPageEvictionTracker; import org.apache.ignite.internal.processors.cache.database.evict.PageEvictionTracker; import org.apache.ignite.internal.processors.cache.database.evict.Random2LruPageEvictionTracker; import org.apache.ignite.internal.processors.cache.database.evict.RandomLruPageEvictionTracker; import org.apache.ignite.internal.processors.cache.database.freelist.FreeList; import org.apache.ignite.internal.processors.cache.database.freelist.FreeListImpl; import org.apache.ignite.internal.processors.cache.database.tree.reuse.ReuseList; import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.processors.cluster.IgniteChangeGlobalStateSupport; import org.apache.ignite.mxbean.MemoryMetricsMXBean; import org.jetbrains.annotations.Nullable; /** * */ public class IgniteCacheDatabaseSharedManager extends GridCacheSharedManagerAdapter implements IgniteChangeGlobalStateSupport { /** MemoryPolicyConfiguration name reserved for internal caches. */ private static final String SYSTEM_MEMORY_POLICY_NAME = "sysMemPlc"; /** Minimum size of memory chunk */ private static final long MIN_PAGE_MEMORY_SIZE = 1024 * 1024; /** */ protected Map<String, MemoryPolicy> memPlcMap; /** */ protected Map<String, MemoryMetrics> memMetricsMap; /** */ protected MemoryPolicy dfltMemPlc; /** */ private Map<String, FreeListImpl> freeListMap; /** */ private FreeListImpl dfltFreeList; /** */ private int pageSize; /** {@inheritDoc} */ @Override protected void start0() throws IgniteCheckedException { if (cctx.kernalContext().clientNode() && cctx.kernalContext().config().getMemoryConfiguration() == null) return; init(); } /** * @throws IgniteCheckedException If failed. */ public void init() throws IgniteCheckedException { if (memPlcMap == null) { MemoryConfiguration memCfg = cctx.kernalContext().config().getMemoryConfiguration(); if (memCfg == null) memCfg = new MemoryConfiguration(); validateConfiguration(memCfg); pageSize = memCfg.getPageSize(); initPageMemoryPolicies(memCfg); startMemoryPolicies(); initPageMemoryDataStructures(memCfg); } } /** * @param dbCfg Database config. */ protected void initPageMemoryDataStructures(MemoryConfiguration dbCfg) throws IgniteCheckedException { freeListMap = U.newHashMap(memPlcMap.size()); String dfltMemPlcName = dbCfg.getDefaultMemoryPolicyName(); for (MemoryPolicy memPlc : memPlcMap.values()) { MemoryPolicyConfiguration memPlcCfg = memPlc.config(); MemoryMetricsImpl memMetrics = (MemoryMetricsImpl) memMetricsMap.get(memPlcCfg.getName()); FreeListImpl freeList = new FreeListImpl(0, cctx.igniteInstanceName(), memMetrics, memPlc, null, cctx.wal(), 0L, true); memMetrics.freeList(freeList); freeListMap.put(memPlcCfg.getName(), freeList); } dfltFreeList = freeListMap.get(dfltMemPlcName); } /** * @return Size of page used for PageMemory regions. */ public int pageSize() { return pageSize; } /** * */ private void startMemoryPolicies() { for (MemoryPolicy memPlc : memPlcMap.values()) { memPlc.pageMemory().start(); memPlc.evictionTracker().start(); } } /** * @param dbCfg Database config. */ protected void initPageMemoryPolicies(MemoryConfiguration dbCfg) { MemoryPolicyConfiguration[] memPlcsCfgs = dbCfg.getMemoryPolicies(); if (memPlcsCfgs == null) { //reserve place for default and system memory policies memPlcMap = U.newHashMap(2); memMetricsMap = U.newHashMap(2); MemoryPolicyConfiguration dfltPlcCfg = dbCfg.createDefaultPolicyConfig(); MemoryMetricsImpl memMetrics = new MemoryMetricsImpl(dfltPlcCfg); registerMetricsMBean(memMetrics); dfltMemPlc = createDefaultMemoryPolicy(dbCfg, dfltPlcCfg, memMetrics); memPlcMap.put(null, dfltMemPlc); memMetricsMap.put(null, memMetrics); log.warning("No user-defined default MemoryPolicy found; system default of 1GB size will be used."); } else { String dfltMemPlcName = dbCfg.getDefaultMemoryPolicyName(); if (dfltMemPlcName == null) { //reserve additional place for default and system memory policies memPlcMap = U.newHashMap(memPlcsCfgs.length + 2); memMetricsMap = U.newHashMap(memPlcsCfgs.length + 2); MemoryPolicyConfiguration dfltPlcCfg = dbCfg.createDefaultPolicyConfig(); MemoryMetricsImpl memMetrics = new MemoryMetricsImpl(dfltPlcCfg); dfltMemPlc = createDefaultMemoryPolicy(dbCfg, dfltPlcCfg, memMetrics); memPlcMap.put(null, dfltMemPlc); memMetricsMap.put(null, memMetrics); log.warning("No user-defined default MemoryPolicy found; system default of 1GB size will be used."); } else { //reserve additional place for system memory policy only memPlcMap = U.newHashMap(memPlcsCfgs.length + 1); memMetricsMap = U.newHashMap(memPlcsCfgs.length + 1);; } for (MemoryPolicyConfiguration memPlcCfg : memPlcsCfgs) { MemoryMetricsImpl memMetrics = new MemoryMetricsImpl(memPlcCfg); MemoryPolicy memPlc = initMemory(dbCfg, memPlcCfg, memMetrics); memPlcMap.put(memPlcCfg.getName(), memPlc); memMetricsMap.put(memPlcCfg.getName(), memMetrics); if (memPlcCfg.getName().equals(dfltMemPlcName)) dfltMemPlc = memPlc; } } MemoryPolicyConfiguration sysPlcCfg = createSystemMemoryPolicy(dbCfg.getSystemCacheMemorySize()); MemoryMetricsImpl sysMemMetrics = new MemoryMetricsImpl(sysPlcCfg); memPlcMap.put(SYSTEM_MEMORY_POLICY_NAME, initMemory(dbCfg, sysPlcCfg, sysMemMetrics)); memMetricsMap.put(SYSTEM_MEMORY_POLICY_NAME, sysMemMetrics); } /** * @param memMetrics Mem metrics. */ private void registerMetricsMBean(MemoryMetricsImpl memMetrics) { IgniteConfiguration cfg = cctx.gridConfig(); try { U.registerMBean( cfg.getMBeanServer(), cfg.getIgniteInstanceName(), "MemoryMetrics", memMetrics.getName(), memMetrics, MemoryMetricsMXBean.class); } catch (JMException e) { log.warning("Failed to register MBean for MemoryMetrics with name: '" + memMetrics.getName() + "'"); } } /** * @param dbCfg Database configuration. * @param memPlcCfg MemoryPolicy configuration. * @param memMetrics MemoryMetrics instance. */ private MemoryPolicy createDefaultMemoryPolicy(MemoryConfiguration dbCfg, MemoryPolicyConfiguration memPlcCfg, MemoryMetricsImpl memMetrics) { return initMemory(dbCfg, memPlcCfg, memMetrics); } /** * @param sysCacheMemSize size of PageMemory to be created for system cache. */ private MemoryPolicyConfiguration createSystemMemoryPolicy(long sysCacheMemSize) { MemoryPolicyConfiguration res = new MemoryPolicyConfiguration(); res.setName(SYSTEM_MEMORY_POLICY_NAME); res.setSize(sysCacheMemSize); return res; } /** * @param dbCfg configuration to validate. */ private void validateConfiguration(MemoryConfiguration dbCfg) throws IgniteCheckedException { MemoryPolicyConfiguration[] plcCfgs = dbCfg.getMemoryPolicies(); Set<String> plcNames = (plcCfgs != null) ? U.<String>newHashSet(plcCfgs.length) : new HashSet<String>(0); if (plcCfgs != null) { for (MemoryPolicyConfiguration plcCfg : plcCfgs) { assert plcCfg != null; checkPolicyName(plcCfg.getName(), plcNames); checkPolicySize(plcCfg); checkPolicyEvictionProperties(plcCfg, dbCfg); } } checkDefaultPolicyConfiguration(dbCfg.getDefaultMemoryPolicyName(), plcNames); } /** * @param dfltPlcName Default MemoryPolicy name. * @param plcNames All MemoryPolicy names. * @throws IgniteCheckedException In case of validation violation. */ private static void checkDefaultPolicyConfiguration(String dfltPlcName, Set<String> plcNames) throws IgniteCheckedException { if (dfltPlcName != null) { if (dfltPlcName.isEmpty()) throw new IgniteCheckedException("User-defined default MemoryPolicy name must be non-empty"); if (!plcNames.contains(dfltPlcName)) throw new IgniteCheckedException("User-defined default MemoryPolicy name must be presented among configured MemoryPolices: " + dfltPlcName); } } /** * @param plcCfg MemoryPolicyConfiguration to validate. * @throws IgniteCheckedException If config is invalid. */ private static void checkPolicySize(MemoryPolicyConfiguration plcCfg) throws IgniteCheckedException { if (plcCfg.getSize() < MIN_PAGE_MEMORY_SIZE) throw new IgniteCheckedException("MemoryPolicy must have size more than 1MB: " + plcCfg.getName()); } /** * @param plcCfg MemoryPolicyConfiguration to validate. * @param dbCfg Memory configuration. * @throws IgniteCheckedException If config is invalid. */ protected void checkPolicyEvictionProperties(MemoryPolicyConfiguration plcCfg, MemoryConfiguration dbCfg) throws IgniteCheckedException { if (plcCfg.getPageEvictionMode() == DataPageEvictionMode.DISABLED) return; if (plcCfg.getEvictionThreshold() < 0.5 || plcCfg.getEvictionThreshold() > 0.999) { throw new IgniteCheckedException("Page eviction threshold must be between 0.5 and 0.999: " + plcCfg.getName()); } if (plcCfg.getEmptyPagesPoolSize() <= 10) throw new IgniteCheckedException("Evicted pages pool size should be greater than 10: " + plcCfg.getName()); long maxPoolSize = plcCfg.getSize() / dbCfg.getPageSize() / 10; if (plcCfg.getEmptyPagesPoolSize() >= maxPoolSize) { throw new IgniteCheckedException("Evicted pages pool size should be lesser than " + maxPoolSize + ": " + plcCfg.getName()); } } /** * @param plcName MemoryPolicy name to validate. * @param observedNames Names of MemoryPolicies observed before. * @throws IgniteCheckedException If config is invalid. */ private static void checkPolicyName(String plcName, Set<String> observedNames) throws IgniteCheckedException { if (plcName == null || plcName.isEmpty()) throw new IgniteCheckedException("User-defined MemoryPolicyConfiguration must have non-null and non-empty name."); if (observedNames.contains(plcName)) throw new IgniteCheckedException("Two MemoryPolicies have the same name: " + plcName); if (SYSTEM_MEMORY_POLICY_NAME.equals(plcName)) throw new IgniteCheckedException("'sysMemPlc' policy name is reserved for internal use."); observedNames.add(plcName); } /** * @param log Logger. */ public void dumpStatistics(IgniteLogger log) { if (freeListMap != null) { for (FreeListImpl freeList : freeListMap.values()) freeList.dumpStatistics(log); } } /** * @throws IgniteCheckedException If failed. */ public void initDataBase() throws IgniteCheckedException{ // No-op. } /** * @return collection of all configured {@link MemoryPolicy policies}. */ public Collection<MemoryPolicy> memoryPolicies() { return memPlcMap != null ? memPlcMap.values() : null; } /** * @return MemoryMetrics for all MemoryPolicies configured in Ignite instance. */ public Collection<MemoryMetrics> memoryMetrics() { return memMetricsMap != null ? memMetricsMap.values() : null; } /** * @param memPlcName Memory policy name. * @return {@link MemoryPolicy} instance associated with a given {@link MemoryPolicyConfiguration}. * @throws IgniteCheckedException in case of request for unknown MemoryPolicy. */ public MemoryPolicy memoryPolicy(String memPlcName) throws IgniteCheckedException { if (memPlcName == null) return dfltMemPlc; if (memPlcMap == null) return null; MemoryPolicy plc; if ((plc = memPlcMap.get(memPlcName)) == null) throw new IgniteCheckedException("Requested MemoryPolicy is not configured: " + memPlcName); return plc; } /** * @param memPlcName MemoryPolicyConfiguration name. * @return {@link FreeList} instance associated with a given {@link MemoryPolicyConfiguration}. */ public FreeList freeList(String memPlcName) { if (memPlcName == null) return dfltFreeList; return freeListMap != null ? freeListMap.get(memPlcName) : null; } /** * @param memPlcName MemoryPolicyConfiguration name. * @return {@link ReuseList} instance associated with a given {@link MemoryPolicyConfiguration}. */ public ReuseList reuseList(String memPlcName) { if (memPlcName == null) return dfltFreeList; return freeListMap != null ? freeListMap.get(memPlcName) : null; } /** {@inheritDoc} */ @Override protected void stop0(boolean cancel) { if (memPlcMap != null) { for (MemoryPolicy memPlc : memPlcMap.values()) { memPlc.pageMemory().stop(); memPlc.evictionTracker().stop(); } } } /** * */ public boolean persistenceEnabled() { return false; } /** * */ public void lock() throws IgniteCheckedException { } /** * */ public void unLock(){ } /** * No-op for non-persistent storage. */ public void checkpointReadLock() { // No-op. } /** * No-op for non-persistent storage. */ public void checkpointReadUnlock() { // No-op. } /** * */ @Nullable public IgniteInternalFuture wakeupForCheckpoint(String reason) { return null; } /** * Waits until current state is checkpointed. * * @throws IgniteCheckedException If failed. */ public void waitForCheckpoint(String reason) throws IgniteCheckedException { // No-op } /** * */ @Nullable public IgniteInternalFuture wakeupForSnapshot(long snapshotId, UUID snapshotNodeId, Collection<String> cacheNames) { return null; } /** * @param discoEvt Before exchange for the given discovery event. */ public void beforeExchange(GridDhtPartitionsExchangeFuture discoEvt) throws IgniteCheckedException { // No-op. } /** * @throws IgniteCheckedException If failed. */ public void beforeCachesStop() throws IgniteCheckedException { // No-op. } /** * @param cctx Stopped cache context. */ public void onCacheStop(GridCacheContext cctx) { // No-op } /** * @param snapshotMsg Snapshot message. * @param initiator Initiator node. * @param msg message to log * @return Snapshot creation init future or {@code null} if snapshot is not available. * @throws IgniteCheckedException If failed. */ @Nullable public IgniteInternalFuture startLocalSnapshotCreation(StartFullSnapshotAckDiscoveryMessage snapshotMsg, ClusterNode initiator, String msg) throws IgniteCheckedException { return null; } /** * @return Future that will be completed when indexes for given cache are restored. */ @Nullable public IgniteInternalFuture indexRebuildFuture(int cacheId) { return null; } /** * See {@link GridCacheMapEntry#ensureFreeSpace()} * * @param memPlc Memory policy. */ public void ensureFreeSpace(MemoryPolicy memPlc) throws IgniteCheckedException { if (memPlc == null) return; MemoryPolicyConfiguration plcCfg = memPlc.config(); if (plcCfg.getPageEvictionMode() == DataPageEvictionMode.DISABLED) return; long memorySize = plcCfg.getSize(); PageMemory pageMem = memPlc.pageMemory(); int sysPageSize = pageMem.systemPageSize(); FreeListImpl freeListImpl = freeListMap.get(plcCfg.getName()); for (;;) { long allocatedPagesCnt = pageMem.loadedPages(); int emptyDataPagesCnt = freeListImpl.emptyDataPages(); boolean shouldEvict = allocatedPagesCnt > (memorySize / sysPageSize * plcCfg.getEvictionThreshold()) && emptyDataPagesCnt < plcCfg.getEmptyPagesPoolSize(); if (shouldEvict) memPlc.evictionTracker().evictDataPage(); else break; } } /** * @param dbCfg memory configuration with common parameters. * @param plc memory policy with PageMemory specific parameters. * @param memMetrics {@link MemoryMetrics} object to collect memory usage metrics. * @return Memory policy instance. */ private MemoryPolicy initMemory(MemoryConfiguration dbCfg, MemoryPolicyConfiguration plc, MemoryMetricsImpl memMetrics) { long[] sizes = calculateFragmentSizes( dbCfg.getConcurrencyLevel(), plc.getSize()); File allocPath = buildAllocPath(plc); DirectMemoryProvider memProvider = allocPath == null ? new UnsafeMemoryProvider(sizes) : new MappedFileMemoryProvider( log, allocPath, true, sizes); PageMemory pageMem = createPageMemory(memProvider, dbCfg.getPageSize(), memMetrics); return new MemoryPolicy(pageMem, plc, memMetrics, createPageEvictionTracker(plc, pageMem)); } /** * @param plc Memory Policy Configuration. * @param pageMem Page memory. */ private PageEvictionTracker createPageEvictionTracker(MemoryPolicyConfiguration plc, PageMemory pageMem) { if (Boolean.getBoolean("override.fair.fifo.page.eviction.tracker")) return new FairFifoPageEvictionTracker(pageMem, plc, cctx); switch (plc.getPageEvictionMode()) { case RANDOM_LRU: return new RandomLruPageEvictionTracker(pageMem, plc, cctx); case RANDOM_2_LRU: return new Random2LruPageEvictionTracker(pageMem, plc, cctx); default: return new NoOpPageEvictionTracker(); } } /** * Calculate fragment sizes for a cache with given size and concurrency level. * @param concLvl Concurrency level. * @param cacheSize Cache size. */ protected long[] calculateFragmentSizes(int concLvl, long cacheSize) { if (concLvl < 1) concLvl = Runtime.getRuntime().availableProcessors(); long fragmentSize = cacheSize / concLvl; if (fragmentSize < 1024 * 1024) fragmentSize = 1024 * 1024; long[] sizes = new long[concLvl]; for (int i = 0; i < concLvl; i++) sizes[i] = fragmentSize; return sizes; } /** * Builds allocation path for memory mapped file to be used with PageMemory. * * @param plc MemoryPolicyConfiguration. */ @Nullable protected File buildAllocPath(MemoryPolicyConfiguration plc) { String path = plc.getSwapFilePath(); if (path == null) return null; String consId = String.valueOf(cctx.discovery().consistentId()); consId = consId.replaceAll("[:,\\.]", "_"); return buildPath(path, consId); } /** * Creates PageMemory with given size and memory provider. * * @param memProvider Memory provider. * @param pageSize Page size. * @param memMetrics MemoryMetrics to collect memory usage metrics. * @return PageMemory instance. */ protected PageMemory createPageMemory(DirectMemoryProvider memProvider, int pageSize, MemoryMetricsImpl memMetrics) { return new PageMemoryNoStoreImpl(log, memProvider, cctx, pageSize, memMetrics, false); } /** * @param path Path to the working directory. * @param consId Consistent ID of the local node. * @return DB storage path. */ protected File buildPath(String path, String consId) { String igniteHomeStr = U.getIgniteHome(); File igniteHome = igniteHomeStr != null ? new File(igniteHomeStr) : null; File workDir = igniteHome == null ? new File(path) : new File(igniteHome, path); return new File(workDir, consId); } /** {@inheritDoc} */ @Override public void onActivate(GridKernalContext kctx) throws IgniteCheckedException { } /** {@inheritDoc} */ @Override public void onDeActivate(GridKernalContext kctx) throws IgniteCheckedException { } /** * @return Name of MemoryPolicyConfiguration for internal caches. */ public String systemMemoryPolicyName() { return SYSTEM_MEMORY_POLICY_NAME; } }
34.04039
156
0.659711
3a18db64e6aa861908905aebc10a31ee3f6c4593
1,155
package com.intkr.saas.manager.opa.impl; import javax.annotation.Resource; import org.springframework.stereotype.Repository; import com.intkr.saas.dao.BaseDAO; import com.intkr.saas.dao.opa.ApiExtDAO; import com.intkr.saas.domain.bo.opa.ApiBO; import com.intkr.saas.domain.bo.opa.ApiExtBO; import com.intkr.saas.domain.dbo.opa.ApiExtDO; import com.intkr.saas.manager.BaseManagerImpl; import com.intkr.saas.manager.opa.ApiExtManager; /** * * * @table api_ext_tab * * @author Beiden * @date 2020-07-23 22:57:32 * @version 1.0 */ @Repository("opa.ApiExtManager") public class ApiExtManagerImpl extends BaseManagerImpl<ApiExtBO, ApiExtDO> implements ApiExtManager { @Resource private ApiExtDAO apiExtDAO; public BaseDAO<ApiExtDO> getBaseDAO() { return apiExtDAO; } public ApiBO fill(ApiBO api) { if (api == null) { return null; } ApiExtBO query = new ApiExtBO(); query.setApiId(api.getId()); api.setApiExt(selectOne(query)); return api; } public ApiExtBO getByApiId(Long apiId) { if (apiId == null) { return null; } ApiExtBO query = new ApiExtBO(); query.setApiId(apiId); return selectOne(query); } }
21.388889
101
0.730736
1e5b1c835bfd432d97c27ccbe612596e39ed03ee
4,291
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: grpcKotlin.proto package br.com.zup; public final class GrpcKotlin { private GrpcKotlin() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_br_com_zup_FuncionarioRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_br_com_zup_FuncionarioRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_br_com_zup_FuncionarioRequest_Endereco_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_br_com_zup_FuncionarioRequest_Endereco_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_br_com_zup_FuncionarioResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_br_com_zup_FuncionarioResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\020grpcKotlin.proto\022\nbr.com.zup\032\037google/p" + "rotobuf/timestamp.proto\"\376\001\n\022FuncionarioR" + "equest\022\014\n\004nome\030\001 \001(\t\022\013\n\003cpf\030\002 \001(\t\022\r\n\005ida" + "de\030\003 \001(\005\022\017\n\007salario\030\004 \001(\001\022\r\n\005ativo\030\005 \001(\010" + "\022 \n\005cargo\030\006 \001(\0162\021.br.com.zup.Cargo\022:\n\ten" + "derecos\030\007 \003(\0132\'.br.com.zup.FuncionarioRe" + "quest.Endereco\032@\n\010Endereco\022\022\n\nlogradouro" + "\030\001 \001(\t\022\013\n\003cep\030\002 \001(\t\022\023\n\013complemento\030\003 \001(\t" + "\"Q\n\023FuncionarioResponse\022\014\n\004nome\030\001 \001(\t\022,\n" + "\010criadoEm\030\002 \001(\0132\032.google.protobuf.Timest" + "amp*%\n\005Cargo\022\007\n\003DEV\020\000\022\006\n\002QA\020\001\022\013\n\007GERENTE" + "\020\0022d\n\022FuncionarioService\022N\n\tcadastrar\022\036." + "br.com.zup.FuncionarioRequest\032\037.br.com.z" + "up.FuncionarioResponse\"\000B\032\n\nbr.com.zupB\n" + "GrpcKotlinP\001b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.protobuf.TimestampProto.getDescriptor(), }); internal_static_br_com_zup_FuncionarioRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_br_com_zup_FuncionarioRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_br_com_zup_FuncionarioRequest_descriptor, new java.lang.String[] { "Nome", "Cpf", "Idade", "Salario", "Ativo", "Cargo", "Enderecos", }); internal_static_br_com_zup_FuncionarioRequest_Endereco_descriptor = internal_static_br_com_zup_FuncionarioRequest_descriptor.getNestedTypes().get(0); internal_static_br_com_zup_FuncionarioRequest_Endereco_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_br_com_zup_FuncionarioRequest_Endereco_descriptor, new java.lang.String[] { "Logradouro", "Cep", "Complemento", }); internal_static_br_com_zup_FuncionarioResponse_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_br_com_zup_FuncionarioResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_br_com_zup_FuncionarioResponse_descriptor, new java.lang.String[] { "Nome", "CriadoEm", }); com.google.protobuf.TimestampProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
50.482353
104
0.7567
32d02515d5c9d5f16e011184d133b868f93d595e
4,713
/* * Copyright 2004-2010 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.doma.internal.apt.meta; /** * @author taedium * */ public interface CallableSqlParameterMetaVisitor<R, P> { R visitBasicInParameterMeta(BasicInParameterMeta m, P p); R visitBasicOutParameterMeta(BasicOutParameterMeta m, P p); R visitBasicInOutParameterMeta(BasicInOutParameterMeta m, P p); R visitBasicListParameterMeta(BasicListParameterMeta m, P p); R visitBasicSingleResultParameterMeta(BasicSingleResultParameterMeta m, P p); R visitBasicResultListParameterMeta(BasicResultListParameterMeta m, P p); R visitDomainInParameterMeta(DomainInParameterMeta m, P p); R visitDomainOutParameterMeta(DomainOutParameterMeta m, P p); R visitDomainInOutParameterMeta(DomainInOutParameterMeta m, P p); R visitDomainListParameterMeta(DomainListParameterMeta m, P p); R visitDomainSingleResultParameterMeta(DomainSingleResultParameterMeta m, P p); R visitDomainResultListParameterMeta(DomainResultListParameterMeta m, P p); R visitEntityListParameterMeta(EntityListParameterMeta m, P p); R visitEntityResultListParameterMeta(EntityResultListParameterMeta m, P p); R visitMapListParameterMeta(MapListParameterMeta m, P p); R visitMapResultListParameterMeta(MapResultListParameterMeta m, P p); R visitOptionalBasicInParameterMeta(OptionalBasicInParameterMeta m, P p); R visitOptionalBasicOutParameterMeta(OptionalBasicOutParameterMeta m, P p); R visitOptionalBasicInOutParameterMeta(OptionalBasicInOutParameterMeta m, P p); R visitOptionalBasicListParameterMeta(OptionalBasicListParameterMeta m, P p); R visitOptionalBasicSingleResultParameterMeta( OptionalBasicSingleResultParameterMeta m, P p); R visitOptionalBasicResultListParameterMeta( OptionalBasicResultListParameterMeta m, P p); R visitOptionalDomainInParameterMeta(OptionalDomainInParameterMeta m, P p); R visitOptionalDomainOutParameterMeta(OptionalDomainOutParameterMeta m, P p); R visitOptionalDomainInOutParameterMeta(OptionalDomainInOutParameterMeta m, P p); R visitOptionalDomainListParameterMeta(OptionalDomainListParameterMeta m, P p); R visitOptionalDomainSingleResultParameterMeta( OptionalDomainSingleResultParameterMeta m, P p); R visitOptionalDomainResultListParameterMeta( OptionalDomainResultListParameterMeta m, P p); R visitOptionalIntInParameterMeta(OptionalIntInParameterMeta m, P p); R visitOptionalIntOutParameterMeta(OptionalIntOutParameterMeta m, P p); R visitOptionalIntInOutParameterMeta(OptionalIntInOutParameterMeta m, P p); R visitOptionalIntListParameterMeta(OptionalIntListParameterMeta m, P p); R visitOptionalIntSingleResultParameterMeta( OptionalIntSingleResultParameterMeta m, P p); R visitOptionalIntResultListParameterMeta( OptionalIntResultListParameterMeta m, P p); R visitOptionalLongInParameterMeta(OptionalLongInParameterMeta m, P p); R visitOptionalLongOutParameterMeta(OptionalLongOutParameterMeta m, P p); R visitOptionalLongInOutParameterMeta(OptionalLongInOutParameterMeta m, P p); R visitOptionalLongListParameterMeta(OptionalLongListParameterMeta m, P p); R visitOptionalLongSingleResultParameterMeta( OptionalLongSingleResultParameterMeta m, P p); R visitOptionalLongResultListParameterMeta( OptionalLongResultListParameterMeta m, P p); R visitOptionalDoubleInParameterMeta(OptionalDoubleInParameterMeta m, P p); R visitOptionalDoubleOutParameterMeta(OptionalDoubleOutParameterMeta m, P p); R visitOptionalDoubleInOutParameterMeta(OptionalDoubleInOutParameterMeta m, P p); R visitOptionalDoubleListParameterMeta(OptionalDoubleListParameterMeta m, P p); R visitOptionalDoubleSingleResultParameterMeta( OptionalDoubleSingleResultParameterMeta m, P p); R visitOptionalDoubleResultListParameterMeta( OptionalDoubleResultListParameterMeta m, P p); }
35.43609
81
0.777849
1769fb130457a0786eee0d0f4a0d4364a7446859
279
package timerx; /** * Exception thrown when input format does not contain any special symbols like "H", "M", * "S" or "L" */ public class NoNecessarySymbolsException extends RuntimeException { public NoNecessarySymbolsException(String message) { super(message); } }
21.461538
89
0.727599
dd9c10c8fd45641c9a60088a92a685d409542dc2
5,149
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.testing.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Load classes as File from File[] dirs or URL[] jars. */ public class TestClassLoader extends URLClassLoader { /** seek classes in dirs first */ List /*File*/ dirs; /** save URL[] only for toString */ private URL[] urlsForDebugString; public TestClassLoader(URL[] urls, File[] dirs) { super(urls); this.urlsForDebugString = urls; LangUtil.throwIaxIfComponentsBad(dirs, "dirs", null); ArrayList dcopy = new ArrayList(); if (!LangUtil.isEmpty(dirs)) { dcopy.addAll(Arrays.asList(dirs)); } this.dirs = Collections.unmodifiableList(dcopy); } public URL getResource(String name) { return ClassLoader.getSystemResource(name); } public InputStream getResourceAsStream(String name) { return ClassLoader.getSystemResourceAsStream(name); } /** We don't expect test classes to have prefixes java, org, or com */ protected boolean maybeTestClassName(String name) { return (null != name) && !name.startsWith("java") && !name.startsWith("org.") && !name.startsWith("com."); } public synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // search the cache, our dirs (if maybe test), // the system, the superclass (URL[]), // and our dirs again (if not maybe test) ClassNotFoundException thrown = null; final boolean maybeTestClass = maybeTestClassName(name); Class result = findLoadedClass(name); if (null != result) { resolve = false; } else if (maybeTestClass) { // subvert the dominant paradigm... byte[] data = readClass(name); if (data != null) { result = defineClass(name, data, 0, data.length); } // handle ClassFormatError? } if (null == result) { try { result = findSystemClass(name); } catch (ClassNotFoundException e) { thrown = e; } } if (null == result) { try { result = super.loadClass(name, resolve); } catch (ClassNotFoundException e) { thrown = e; } if (null != result) { // resolved by superclass return result; } } if ((null == result) && !maybeTestClass) { byte[] data = readClass(name); if (data != null) { result = defineClass(name, data, 0, data.length); } // handle ClassFormatError? } if (null == result) { throw (null != thrown ? thrown : new ClassNotFoundException(name)); } if (resolve) { resolveClass(result); } return result; } /** @return null if class not found or byte[] of class otherwise */ private byte[] readClass(String className) throws ClassNotFoundException { final String fileName = className.replace('.', '/')+".class"; for (Iterator iter = dirs.iterator(); iter.hasNext();) { File file = new File((File) iter.next(), fileName); if (file.canRead()) { return getClassData(file); } } return null; } private byte[] getClassData(File f) { try { FileInputStream stream= new FileInputStream(f); ByteArrayOutputStream out= new ByteArrayOutputStream(1000); byte[] b= new byte[4096]; int n; while ((n= stream.read(b)) != -1) { out.write(b, 0, n); } stream.close(); out.close(); return out.toByteArray(); } catch (IOException e) { } return null; } /** @return String with debug info: urls and classes used */ public String toString() { return "TestClassLoader(urls=" + Arrays.asList(urlsForDebugString) + ", dirs=" + dirs + ")"; } }
32.588608
79
0.546514
65ffb50503db248943556a6d3690e1b3eb3a200f
1,426
/* * Bach - Java Shell Builder * Copyright (C) 2020 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach.project; import java.util.Set; /** A feature flag on a main code space. */ public enum Feature { /** Generate HTML pages of API documentation from main source files. */ CREATE_API_DOCUMENTATION, /** Assemble and optimize main modules and their dependencies into a custom runtime image. */ CREATE_CUSTOM_RUNTIME_IMAGE, /** Include {@code *.java} files alongside with {@code *.class} files into each modular JAR. */ INCLUDE_SOURCES_IN_MODULAR_JAR, /** Include all resource files alongside with {@code *.java} files into each sources JAR. */ INCLUDE_RESOURCES_IN_SOURCES_JAR; /** The default feature set on a main code space. */ public static final Set<Feature> DEFAULTS = Set.of(CREATE_API_DOCUMENTATION, CREATE_CUSTOM_RUNTIME_IMAGE); }
35.65
97
0.73913
937f60db86bfff10c2a756914c5f876a9fb1b373
2,621
package io.fdlessard.codesamples.order.services; import io.fdlessard.codebites.order.services.SalesOrderService; import io.fdlessard.codesamples.order.configurations.PersistenceItTestConfiguration; import io.fdlessard.codesamples.order.configurations.WebMvcItTestConfiguration; import io.fdlessard.codebites.order.domain.SalesOrder; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @ContextConfiguration(classes = {PersistenceItTestConfiguration.class, WebMvcItTestConfiguration.class}) @WebAppConfiguration @Transactional @RunWith(SpringJUnit4ClassRunner.class) public class SalesOrderServiceIT { @Autowired private SalesOrderService salesOrderService; @Before public void setup() { } @Test public void testGetAllSalesOrder() throws Exception { Iterable<SalesOrder> it = salesOrderService.getAllSalesOrder(); Iterator<SalesOrder> iterator = it.iterator(); List<SalesOrder> list = new ArrayList<SalesOrder>(); iterator.forEachRemaining(list::add); Assert.assertEquals(3, list.size()); } @Test public void testGetSalesOrder() throws Exception { SalesOrder salesOrder = salesOrderService.getSalesOrder(100l); Assert.assertNotNull(salesOrder); Assert.assertEquals(Long.valueOf(100), salesOrder.getId()); Assert.assertEquals(Long.valueOf(1), salesOrder.getVersion()); Assert.assertEquals("SalesOrder 0", salesOrder.getDescription()); //Assert. "2016-08-01 12:00:00", salesOrder.getDate()); Assert.assertEquals(new BigDecimal(10.00), salesOrder.getTotal()); } @Test(expected = IllegalArgumentException.class) public void testGetSalesOrderWithNullId() throws Exception { SalesOrder salesOrder = salesOrderService.getSalesOrder(null); } @Test(expected = IllegalArgumentException.class) public void testDeleteSalesOrderWithNullId() throws Exception { salesOrderService.deleteSalesOrder(null); } @Test public void testDeleteSalesOrderWithNonExistingId() throws Exception { salesOrderService.deleteSalesOrder(null); } }
32.7625
104
0.764212
b53894933a5617746f070e6602846f7c48db454c
4,726
package org.tokalac.logging.modules.output.handler; /** * Created by Erol TOKALACOGLU on 31/05/15. * Version 1.0 * Param <V> */ import org.tokalac.logging.core.Level; import org.tokalac.logging.core.LogManager; import org.tokalac.logging.modules.config.Key; import org.tokalac.logging.modules.output.formatter.Formatter; import org.elasticsearch.common.transport.*; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import java.util.Properties; public class ESHandler extends AbstractHandler { private String essAddress; private Integer essPort; private Client client; private String loggerAlias; private Properties settings = LogManager.config.getSettings(); private Printer printer = new Printer(); public ESHandler() { this.setESSddress(null); this.setESSPort(null); this.setClient(); } public ESHandler(String address, Integer port) { this.setESSddress(address); this.setESSPort(port); this.setClient(); } @Override public void log(String appName, Level level, String message, String fqcn, String handler, Formatter formatter) { this.setLoggerAlias(fqcn); if(this.getClass().getName().equals(handler)) { //Send to Elastic Search Server printer.write(appName, level, message, fqcn, FileHandler.class.getName(), formatter, this.client); } } @Override public void log(String appName, Level level, String userId, String sessionId, String cartId, String productId, String price, String qty, String onSale, String process, String categoryId, String message, String fqcn, String handler, Formatter formatter) { this.log(appName, level, message, fqcn, handler, formatter); } @Override public void log(String appName, Level level, String message, String fqcn, String handler, Formatter formatter, Level levelFixed) { this.setLoggerAlias(fqcn); if(level == levelFixed){ if(this.getClass().getName().equals(handler)) { //Send to Elastic Search Server printer.write(appName, levelFixed, message, fqcn, FileHandler.class.getName(), formatter, this.client); } } } @Override public void log(String appName, Level level, String message, String fqcn, String handler, Formatter formatter, boolean forceLogging) { this.setLoggerAlias(fqcn); if(forceLogging){ if(this.getClass().getName().equals(handler)) { //Send to Elastic Search Server printer.write(appName, level, message, fqcn, FileHandler.class.getName(), formatter, this.client); } } } public void setESSddress(String essAddress) { String key = loggerAlias + ".ESSAddress"; if(settings.containsKey(key)) { this.essAddress = (String) settings.get(key); } if (essAddress != null) { this.essAddress = essAddress; } if (this.essAddress == null || this.essAddress.isEmpty()) { this.essAddress = (String) settings.get(Key.ESSAddress.name()); } } public void setESSPort(Integer essPort) { String key = loggerAlias + ".ESSPort"; if(settings.containsKey(key)) { this.essPort = this.initPort((String) settings.get(key)); } if (essPort != null) { this.essPort = essPort; } if (this.essPort == null) { this.essPort = this.initPort((String)settings.get(Key.ESSPort.name())); } } private Integer initPort(String limit) { String port = limit; Integer portNum = 0; try { portNum = Integer.parseInt(port.trim()); } catch (NumberFormatException e) { System.out.print("Your ES Port is not readable, please check it => "); e.printStackTrace(); } return portNum; } public void setClient(){ this.client = new TransportClient() .addTransportAddress(new InetSocketTransportAddress(this.essAddress, this.essPort)) .addTransportAddress(new InetSocketTransportAddress(this.essAddress, this.essPort)); } private void setLoggerAlias(String fqcn) { for(String key : settings.stringPropertyNames()) { String value = settings.getProperty(key); if (value.equalsIgnoreCase(fqcn)) { this.loggerAlias = key.split("\\.")[0]; } } this.setESSddress(null); this.setESSPort(null); this.setClient(); } }
32.369863
258
0.625688
3f81208b4fc7d8c749110ba1a6d2a3f3dfdab8c4
153
package com.dawnengine.game.graphics; /** * * @author alyss */ public enum StringRenderPosition { Leading, Leading_Fixed, Center, Center_Fixed }
15.3
48
0.72549
fb736ab555d2779819879ebbed63d1e8c54384af
984
package com.lambdaschool; public class piggyBank { private double balance = 0; public double getBalance() { System.out.println("*Piggy has been smashed. This is now blood money.*"); System.out.println(balance); return balance; } public void depositCash(String currency, int amount) { switch(currency) { case "dollar": balance += (1.00 * amount); break; case "quarter": balance += (0.25 * amount); break; case "dime": balance += (0.10 * amount); break; case "nickel": balance += (0.05 * amount); break; case "penny": balance += (0.01 * amount); break; default: balance =+ (0.00); System.out.println("Fall on hard times? You didn't put any money in."); } } }
28.114286
87
0.462398
f4464c23f5f79933b2bc0a6d9b03bb9d352579ac
5,410
package org.imp.jvm.expression; import org.apache.commons.lang3.NotImplementedException; import org.imp.jvm.compiler.DescriptorFactory; import org.imp.jvm.compiler.Logger; import org.imp.jvm.domain.ImpFile; import org.imp.jvm.domain.scope.Identifier; import org.imp.jvm.domain.scope.LocalVariable; import org.imp.jvm.domain.scope.Scope; import org.imp.jvm.exception.Errors; import org.imp.jvm.statement.Block; import org.imp.jvm.statement.Return; import org.imp.jvm.statement.Statement; import org.imp.jvm.types.BuiltInType; import org.imp.jvm.types.FunctionType; import org.imp.jvm.types.Modifier; import org.imp.jvm.types.Type; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.util.List; import java.util.stream.Collectors; public class Function extends Expression { public final Block block; public final List<Identifier> parameters; public final Type returnType; public FunctionType functionType; public final Modifier modifier; public FunctionKind kind = FunctionKind.Internal; public enum FunctionKind { Internal, External, Standard } public String name; private ImpFile parent; public Function( FunctionType functionType, List<Identifier> parameters, Type returnType, Block block, Modifier modifier ) { super(); this.modifier = modifier; this.block = block; this.functionType = functionType; this.parameters = parameters; this.returnType = returnType; } public Function( Modifier modifier, String name, List<Identifier> parameters, Type returnType, Block block, ImpFile parent ) { super(); this.modifier = modifier; this.name = name; this.parameters = parameters; this.returnType = returnType; this.block = block; this.parent = parent; this.functionType = null; } public Function( FunctionType functionType, List<Identifier> parameters, Type returnType, FunctionKind kind ) { super(); this.modifier = null; this.block = null; this.functionType = functionType; this.parameters = parameters; this.kind = kind; this.returnType = returnType; } @Override public List<Statement> getChildren() { return List.of(block); } @SuppressWarnings("UnnecessaryLocalVariable") static public String getDescriptor(List<Identifier> identifiers) { String params = identifiers.stream().map(parameters -> parameters.type.getDescriptor()) .collect(Collectors.joining(", ")); return params; } @Override public String toString() { if (functionType != null) { return functionType.name + this.toStringRepr(); } return "null signature"; } public String toStringRepr() { String params = parameters.stream().map(parameters -> parameters.type.toString()) .collect(Collectors.joining(", ")); return "(" + String.join(", ", params) + ") " + returnType; } @Override public void generate(MethodVisitor mv, Scope scope) { throw new NotImplementedException("reeb"); } @Override public void validate(Scope scope) { assert block != null; functionType = scope.findFunctionType(name, false); // If no FunctionTypes of name exist on the current scope, if (functionType == null) { // Create a new FunctionType and add it to the scope functionType = new FunctionType(name, parent, false); scope.addFunctionType(functionType); } if (functionType.getSignatures().containsKey(Function.getDescriptor(parameters))) { Logger.syntaxError(Errors.DuplicateFunctionOverloads, this, name); return; } else { functionType.addSignature(Function.getDescriptor(parameters), this); } if (name != null && !name.equals("main")) { Scope newScope = new Scope(scope); newScope.functionType = functionType; parameters.forEach(param -> newScope.addLocalVariable(new LocalVariable(param.name, param.type))); block.scope = newScope; } } public void generate(ClassWriter cw) { String name = functionType.name; int access = Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC; if (!name.equals("main")) { if (!name.equals("closure")) { name = "invoke"; } access = Opcodes.ACC_PUBLIC; } String description = DescriptorFactory.getMethodDescriptor(this); if (this.kind == FunctionKind.Internal) { MethodVisitor mv = cw.visitMethod(access, name, description, null, null); mv.visitCode(); block.generate(mv, block.scope); appendReturn(mv, block.scope); mv.visitMaxs(-1, -1); mv.visitEnd(); } } private void appendReturn(MethodVisitor mv, Scope scope) { Return r = new Return(new EmptyExpression(BuiltInType.VOID)); r.generate(mv, scope); } }
28.031088
110
0.621811
fb253b0fa3f6327a40d10daf5e8efad640cc5f58
139
/* * 작성자 : * 작성일 : * 통계 관련 DAO * */ package com.spring.Creamy_CRM.Host_dao; public class StaticsDAOImpl implements StaticsDAO { }
11.583333
51
0.661871
5dae62817b83f2cf139daccbde6ceeeab1cee48e
1,608
package com.ashwani.family.util.response_builder.failed; import com.ashwani.family.infra.model.response.BaseResponse; import com.ashwani.family.infra.model.response.FindMemberResponse; import com.ashwani.family.infra.model.response.GetDocumentResponse; import com.ashwani.family.util.constants.ResponseConstants; import com.ashwani.family.util.response_builder.BaseFailedResponseBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MemberFailedResponseBuilder { @Autowired private BaseFailedResponseBuilder baseFailedResponseBuilder; public BaseResponse addMember() { BaseResponse resp = baseFailedResponseBuilder.baseFailResponse(); resp.setResponseDescription(ResponseConstants.ADD_MEMBER_FAILURE); return resp; } public FindMemberResponse findMember() { BaseResponse response = baseFailedResponseBuilder.baseFailResponse(); var resp = new FindMemberResponse(); resp.setHttpStatus(response.getHttpStatus()); resp.setResponseCode(response.getResponseCode()); resp.setResponseDescription(response.getResponseDescription()); return resp; } public GetDocumentResponse getDocuments() { BaseResponse response = baseFailedResponseBuilder.baseFailResponse(); var resp = new GetDocumentResponse(); resp.setHttpStatus(response.getHttpStatus()); resp.setResponseCode(response.getResponseCode()); resp.setResponseDescription(response.getResponseDescription()); return resp; } }
39.219512
78
0.774254
2028999f8122e34a2a3e251415357242e601cbd8
5,239
package com.question.answer.misc; import java.util.Scanner; public class SayingNumber { //This returns the English word for numbers 0 - 9 public static String oneDigitToStr(int num) { switch (num) { case 0 : return "zero"; case 1 : return "one"; case 2 : return "two"; case 3 : return "three"; case 4 : return "four"; case 5 : return "five"; case 6 : return "six"; case 7 : return "seven"; case 8 : return "eight"; case 9 : return "nine"; } return""; } //This returns the English words for numbers 10 - 99 public static String twoDigitToStr(int num) { //This returns the English word for numbers 10 - 19 switch(num){ case 10 : return "ten"; case 11 : return "eleven"; case 12 : return "tweleve"; case 13 : return "thirteen"; case 14 : return "fourteen"; case 15 : return "fifteen"; case 16 : return "sixteen"; case 17 : return "seventeen"; case 18 : return "eighteen"; case 19 : return "nineteen"; } //This returns the English word for multiples of 10 up until 90. String tens[] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; int onesPlace; int tensPlace; int i; i = num; onesPlace = i%10; //Finds ones place i /= 10; tensPlace = i; //Finds tens place if(tensPlace == 0) { return oneDigitToStr(onesPlace); //Calls oneDigitToStr for single digit numbers } if(onesPlace == 0) { return tens[tensPlace - 2]; //Multiples of 10 } //Returns all other two digit numbers > 20 return tens[tensPlace - 2] + " " + oneDigitToStr(onesPlace); } //Returns the English words for numbers 100-999 public static String threeDigitToStr (int num) { String hundreds = "hundred"; int hundredsPlace; int tensPlace; int onesPlace; int i; i = num; onesPlace = i % 100; hundredsPlace = i / 100; i = num; i = i - hundredsPlace; tensPlace = i / 10; if (hundredsPlace == 0) { return twoDigitToStr(tensPlace); } i = num - hundredsPlace; return oneDigitToStr(hundredsPlace) + " hundred " + twoDigitToStr(onesPlace); } //Returns the English words for numbers 1000+ (within int parameters) public static String numToStr (int num) { String userNum = Integer.toString(num); int billions; int millions; int thousands; int hundredsPlace; int tensPlace; int onesPlace; int i = num; int n = userNum.length(); if (n > 9) { if (n < 12) { n = 12 - n; while (n > 0) { userNum = "0" + userNum; n--; } } billions = Integer.parseInt(userNum.substring(0,3)); millions = Integer.parseInt(userNum.substring(3,6)); thousands = Integer.parseInt(userNum.substring(6,9)); hundredsPlace = Integer.parseInt(userNum.substring(9,12)); return threeDigitToStr(billions) + " billion " + threeDigitToStr(millions) + " million " + threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace); } else if (n > 6 && n <= 9) { if (n < 9) { n = 9 - n; while (n > 0) { userNum = "0" + userNum; n--; } } millions = Integer.parseInt(userNum.substring(0,3)); thousands = Integer.parseInt(userNum.substring(3,6)); hundredsPlace = Integer.parseInt(userNum.substring(6,9)); return threeDigitToStr(millions) + " million " + threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace); } else if (n > 3) { if (n < 6) { n = 6 - n; while (n > 0) { userNum = "0" + userNum; n--; } } thousands = Integer.parseInt(userNum.substring(0,3)); hundredsPlace = Integer.parseInt(userNum.substring(3,6)); return threeDigitToStr(thousands) + " thousand " + threeDigitToStr(hundredsPlace); } else { return threeDigitToStr(Integer.parseInt(userNum)); } } //This gets user input public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int numEntered; while(true) { System.out.print("Enter an integer to pronounce (any negative value to exit): "); numEntered = scnr.nextInt(); if (numEntered < 0) { break; } System.out.println(numEntered); String numToString = numToStr(numEntered); System.out.println(numToString); } System.out.println("kthxbye!"); } }
36.381944
178
0.516702
319327ef15522d0298bff2ee4a73887a23e206b1
730
package com.comcast.pop.endpoint.api.auth; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Collections; public class AuthorizationResponseTest { @Test public void testToString() { AuthorizationResponse authorizationResponse = new AuthorizationResponse("myUserId", "myUserName", Collections.singleton("myAccountId"), DataVisibility.authorized_account); Assert.assertNotNull(authorizationResponse.toString()); AuthorizationResponse resp = new AuthorizationResponseBuilder().withAccounts("http://myaccounturl/data/Account/3131523765|http://access.auth" + ".com/data/Account/3131523999").build(); System.out.println(resp); } }
33.181818
151
0.734247
8df9deb13425a3e3b35f4b50b9eb19c0255260dd
4,779
// Copyright (c) 2018 Imperial College London // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.graphicsfuzz.common.ast.expr; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.graphicsfuzz.common.ast.CompareAstsDuplicate; import java.util.Arrays; import java.util.List; import org.junit.Test; public class BinOpTest { @Test public void isSideEffecting() throws Exception { List<BinOp> shouldBeSideEffecting = Arrays.asList(BinOp.ASSIGN, BinOp.MUL_ASSIGN, BinOp.DIV_ASSIGN, BinOp.MOD_ASSIGN, BinOp.ADD_ASSIGN, BinOp.SUB_ASSIGN, BinOp.BAND_ASSIGN, BinOp.BOR_ASSIGN, BinOp.BXOR_ASSIGN, BinOp.SHL_ASSIGN, BinOp.SHR_ASSIGN); for (BinOp bop : shouldBeSideEffecting) { assertTrue(bop.isSideEffecting()); } for (BinOp bop : BinOp.values()) { if (!shouldBeSideEffecting.contains(bop)) { assertFalse(bop.isSideEffecting()); } } } private String choose(boolean pred, String first, String second) { return pred ? first : second; } @Test public void getText() throws Exception { String programUsingGetText = getOpTesterProgram(true); String programUsingStrings = getOpTesterProgram(true); CompareAstsDuplicate.assertEqualAsts(programUsingGetText, programUsingStrings); } private String getOpTesterProgram(boolean p) { return "void main() {" + " int a " + choose(p, BinOp.ASSIGN.getText(), "=") + "1, b " + choose(p, BinOp.ASSIGN.getText(), "=") + "2;" + " bool x " + choose(p, BinOp.ASSIGN.getText(), "=") + " true, y " + choose(p, BinOp.ASSIGN.getText(), "=") + " false;" + " " + " a = 3" + choose(p, BinOp.COMMA.getText(), ",") + " 4;" + " a = b " + choose(p, choose(p, BinOp.MOD.getText(), "X") + " a " + BinOp.MUL.getText(), "X") + " a;" + " a = b " + choose(p, BinOp.DIV.getText(), "/") + " 2 " + choose(p, BinOp.ADD.getText(), "X") + " b " + choose(p, BinOp.SUB.getText(), "-") + " 3;" + " a = a " + choose(p, BinOp.BAND.getText(), "&") + " b;" + " a = a " + choose(p, BinOp.BOR.getText(), "|") + " b;" + " a = a " + choose(p, BinOp.BXOR.getText(), "^") + " b;" + " x = x " + choose(p, BinOp.LAND.getText(), "&&") + " y;" + " x = x " + choose(p, BinOp.LOR.getText(), "||") + " y;" + " x = x " + choose(p, BinOp.LXOR.getText(), "^^") + " y;" + " a = a " + choose(p, BinOp.SHL.getText(), "<<") + " b;" + " a = a " + choose(p, BinOp.SHR.getText(), ">>") + " b;" + " x = a " + choose(p, BinOp.LT.getText(), "<") + " b;" + " x = a " + choose(p, BinOp.GT.getText(), ">") + " b;" + " x = a " + choose(p, BinOp.LE.getText(), "<=") + " b;" + " x = a " + choose(p, BinOp.GE.getText(), ">=") + " b;" + " x = a " + choose(p, BinOp.EQ.getText(), "==") + " b;" + " x = a " + choose(p, BinOp.NE.getText(), "!=") + " b;" + " a " + choose(p, BinOp.MUL_ASSIGN.getText(), "*=") + " b;" + " a " + choose(p, BinOp.DIV_ASSIGN.getText(), "/=") + " b;" + " a " + choose(p, BinOp.MOD_ASSIGN.getText(), "%=") + " b;" + " a " + choose(p, BinOp.ADD_ASSIGN.getText(), "+=") + " b;" + " a " + choose(p, BinOp.SUB_ASSIGN.getText(), "-=") + " b;" + " a " + choose(p, BinOp.BAND_ASSIGN.getText(), "&=") + " b;" + " a " + choose(p, BinOp.BOR_ASSIGN.getText(), "|=") + " b;" + " a " + choose(p, BinOp.BXOR_ASSIGN.getText(), "^=") + " b;" + " a " + choose(p, BinOp.SHL_ASSIGN.getText(), "<<=") + " b;" + " a " + choose(p, BinOp.SHR_ASSIGN.getText(), ">>=") + " b;" + "}"; } }
43.844037
158
0.575434
04906410e46160e59d4de392f77fb9e299f4cb7d
1,956
package com.example.housin.view; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import com.example.housin.R; import androidx.appcompat.app.AppCompatActivity; public class MeusAnuncios extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_meus_anuncios); ImageButton voltar = findViewById(R.id.imageButton16); ImageButton info = findViewById(R.id.infoButton1); ImageButton info2 = findViewById(R.id.infoButton2); ImageButton info3 = findViewById(R.id.infoButton3); voltar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MeusAnuncios.this, PerfilActivity.class); startActivity(intent); finish(); } }); info.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MeusAnuncios.this, DetalhesCasaActivity.class); startActivity(intent); finish(); } }); info2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MeusAnuncios.this, DetalhesCasaActivity.class); startActivity(intent); finish(); } }); info3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MeusAnuncios.this, DetalhesCasaActivity.class); startActivity(intent); finish(); } }); } }
30.5625
90
0.607873
14bc806f5b0ad508385f195901fdfa44b468af4c
10,936
package org.drip.feed.loader; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2017 Lakshmi Krishnamurthy * Copyright (C) 2016 Lakshmi Krishnamurthy * Copyright (C) 2015 Lakshmi Krishnamurthy * Copyright (C) 2014 Lakshmi Krishnamurthy * Copyright (C) 2013 Lakshmi Krishnamurthy * Copyright (C) 2012 Lakshmi Krishnamurthy * Copyright (C) 2011 Lakshmi Krishnamurthy * * This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model * libraries targeting analysts and developers * https://lakshmidrip.github.io/DRIP/ * * DRIP is composed of four main libraries: * * - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/ * - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/ * - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/ * - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/ * * - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options, * Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA * Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV * Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM * Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics. * * - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy * Incorporator, Holdings Constraint, and Transaction Costs. * * - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality. * * - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning. * * 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. */ /** * BondRefData contains functionality to load a variety of Bond Product reference data and closing * marks. It exposes the following functionality: * - Load the bond valuation-based reference data, amortization schedule and EOS * - Build the bond instance entities from the valuation-based reference data * - Load the bond non-valuation-based reference data * * BondRefData assumes the appropriate connections are available to load the data. * * @author Lakshmi Krishnamurthy */ class BondRefData { private static final boolean m_bBlog = false; private static final boolean m_bDBExec = true; private static final org.drip.product.creator.BondRefDataBuilder MakeBRDB ( final java.lang.String[] astrFODATA) { if (null == astrFODATA || 88 != astrFODATA.length) return null; org.drip.product.creator.BondRefDataBuilder brdb = new org.drip.product.creator.BondRefDataBuilder(); if (!brdb.setISIN (astrFODATA[40])) { System.out.println ("Bad ISIN " + astrFODATA[40]); return null; } if (!brdb.setCUSIP (astrFODATA[42])) { System.out.println ("Bad CUSIP " + astrFODATA[42]); return null; } brdb.setBBGID (astrFODATA[1]); brdb.setIssuerCategory (astrFODATA[2]); brdb.setTicker (astrFODATA[3]); brdb.setSeries (astrFODATA[7]); brdb.setName (astrFODATA[8]); brdb.setShortName (astrFODATA[9]); brdb.setIssuerIndustry (astrFODATA[10]); brdb.setCouponType (astrFODATA[13]); brdb.setMaturityType (astrFODATA[14]); brdb.setCalculationType (astrFODATA[15]); brdb.setDayCountCode (astrFODATA[16]); brdb.setMarketIssueType (astrFODATA[17]); brdb.setIssueCountryCode (astrFODATA[18]); brdb.setIssueCountry (astrFODATA[19]); brdb.setCollateralType (astrFODATA[20]); brdb.setIssueAmount (astrFODATA[21]); brdb.setOutstandingAmount (astrFODATA[22]); brdb.setMinimumPiece (astrFODATA[23]); brdb.setMinimumIncrement (astrFODATA[24]); brdb.setParAmount (astrFODATA[25]); brdb.setLeadManager (astrFODATA[26]); brdb.setExchangeCode (astrFODATA[27]); brdb.setRedemptionValue (astrFODATA[28]); brdb.setAnnounce (astrFODATA[29]); brdb.setFirstSettle (astrFODATA[31]); brdb.setFirstCoupon (astrFODATA[33]); brdb.setInterestAccrualStart (astrFODATA[35]); brdb.setIssue (astrFODATA[37]); brdb.setIssuePrice (astrFODATA[39]); brdb.setNextCouponDate (astrFODATA[43]); brdb.setIsCallable (astrFODATA[45]); brdb.setIsSinkable (astrFODATA[46]); brdb.setIsPutable (astrFODATA[47]); brdb.setBBGParent (astrFODATA[48]); brdb.setCountryOfIncorporation (astrFODATA[53]); brdb.setIndustrySector (astrFODATA[54]); brdb.setIndustryGroup (astrFODATA[55]); brdb.setIndustrySubgroup (astrFODATA[56]); brdb.setCountryOfGuarantor (astrFODATA[57]); brdb.setCountryOfDomicile (astrFODATA[58]); brdb.setDescription (astrFODATA[59]); brdb.setSecurityType (astrFODATA[60]); brdb.setPrevCouponDate (astrFODATA[61]); brdb.setBBGUniqueID (astrFODATA[63]); brdb.setLongCompanyName (astrFODATA[64]); brdb.setRedemptionCurrency (astrFODATA[66]); brdb.setCouponCurrency (astrFODATA[67]); brdb.setIsStructuredNote (astrFODATA[68]); brdb.setIsUnitTraded (astrFODATA[69]); brdb.setIsReversibleConvertible (astrFODATA[70]); brdb.setTradeCurrency (astrFODATA[71]); brdb.setIsBearer (astrFODATA[72]); brdb.setIsRegistered (astrFODATA[73]); brdb.setHasBeenCalled (astrFODATA[74]); brdb.setIssuer (astrFODATA[75]); brdb.setPenultimateCouponDate (astrFODATA[76]); brdb.setFloatCouponConvention (astrFODATA[77]); brdb.setCurrentCoupon (astrFODATA[78]); brdb.setIsFloater (astrFODATA[79]); brdb.setTradeStatus (astrFODATA[80]); brdb.setCDRCountryCode (astrFODATA[81]); brdb.setCDRSettleCode (astrFODATA[82]); brdb.setFinalMaturity (astrFODATA[83]); brdb.setIsPrivatePlacement (astrFODATA[85]); brdb.setIsPerpetual (astrFODATA[86]); brdb.setIsDefaulted (astrFODATA[87]); if (!brdb.validate()) return null; return brdb; } private static final org.drip.product.creator.BondProductBuilder MakeBPB ( final java.lang.String[] astrFODATA, final org.drip.param.definition.ScenarioMarketParams mpc) { if (null == astrFODATA || 88 != astrFODATA.length || null == mpc) return null; org.drip.product.creator.BondProductBuilder bpb = new org.drip.product.creator.BondProductBuilder(); if (!bpb.setISIN (astrFODATA[40])) { System.out.println ("Bad ISIN " + astrFODATA[40]); return null; } if (!bpb.setCUSIP (astrFODATA[42])) { System.out.println ("Bad CUSIP " + astrFODATA[42]); return null; } bpb.setTicker (astrFODATA[3]); bpb.setCoupon (astrFODATA[4]); if (!bpb.setMaturity (astrFODATA[5])) { System.out.println ("Bad Maturity " + astrFODATA[5]); return null; } if (!bpb.setCouponFreq (astrFODATA[12])) { System.out.println ("Bad Cpn Freq " + astrFODATA[12]); return null; } bpb.setCouponType (astrFODATA[13]); bpb.setMaturityType (astrFODATA[14]); bpb.setCalculationType (astrFODATA[15]); if (!bpb.setDayCountCode (astrFODATA[16])) { System.out.println ("Bad Day Count " + astrFODATA[40]); return null; } if (!bpb.setRedemptionValue (astrFODATA[28])) { System.out.println ("Bad Redemp Value " + astrFODATA[40]); return null; } bpb.setAnnounce (astrFODATA[29]); bpb.setFirstSettle (astrFODATA[31]); bpb.setFirstCoupon (astrFODATA[33]); bpb.setInterestAccrualStart (astrFODATA[35]); bpb.setIssue (astrFODATA[37]); bpb.setIsCallable (astrFODATA[45]); bpb.setIsSinkable (astrFODATA[46]); bpb.setIsPutable (astrFODATA[47]); if (!bpb.setRedemptionCurrency (astrFODATA[66])) { System.out.println ("Bad Redemp Ccy " + astrFODATA[66]); return null; } if (!bpb.setCouponCurrency (astrFODATA[67])) { System.out.println ("Bad Cpn Ccy " + astrFODATA[40]); return null; } if (!bpb.setTradeCurrency (astrFODATA[71])) { System.out.println ("Bad Trade ccy " + astrFODATA[40]); return null; } bpb.setHasBeenCalled (astrFODATA[74]); bpb.setFloatCouponConvention (astrFODATA[77]); bpb.setCurrentCoupon (astrFODATA[78]); bpb.setIsFloater (astrFODATA[79]); bpb.setFinalMaturity (astrFODATA[83]); bpb.setIsPerpetual (astrFODATA[86]); bpb.setIsDefaulted (astrFODATA[87]); if (!bpb.validate (mpc)) return null; return bpb; } public static final void UploadBondFromFODATA ( final java.lang.String strFODATAFile, final java.sql.Statement stmt, final org.drip.param.definition.ScenarioMarketParams mpc) throws java.lang.Exception { int iNumBonds = 0; int iNumFloaters = 0; int iNumFailedToLoad = 0; java.lang.String strBondFODATALine = ""; java.io.BufferedReader inBondFODATA = new java.io.BufferedReader (new java.io.FileReader (strFODATAFile)); while (null != (strBondFODATALine = inBondFODATA.readLine())) { ++iNumBonds; java.lang.String[] astrBondFODATARecord = strBondFODATALine.split (","); org.drip.product.creator.BondRefDataBuilder brdb = MakeBRDB (astrBondFODATARecord); if (null != brdb) { System.out.println ("Doing #" + iNumBonds + ": " + brdb._strCUSIP); java.lang.String strSQLBRDBDelete = brdb.makeSQLDelete(); if (null != strSQLBRDBDelete) { if (m_bBlog) System.out.println (strSQLBRDBDelete); if (m_bDBExec) stmt.executeUpdate (strSQLBRDBDelete); } java.lang.String strSQLBRDBInsert = brdb.makeSQLInsert(); if (null != strSQLBRDBInsert) { if (m_bBlog) System.out.println (strSQLBRDBInsert); if (m_bDBExec) stmt.executeUpdate (strSQLBRDBInsert); } } org.drip.product.creator.BondProductBuilder bpb = MakeBPB (astrBondFODATARecord, mpc); if (null != bpb) { if (null != bpb.getFloaterParams()) ++iNumFloaters; java.lang.String strSQLBPBDelete = bpb.makeSQLDelete(); if (null != strSQLBPBDelete) { if (m_bBlog) System.out.println (strSQLBPBDelete); if (m_bDBExec) stmt.executeUpdate (strSQLBPBDelete); } java.lang.String strSQLBPBInsert = bpb.makeSQLInsert(); if (null != strSQLBPBInsert) { if (m_bBlog) System.out.println (strSQLBPBInsert); if (m_bDBExec) stmt.executeUpdate (strSQLBPBInsert); } } if (null == brdb || null == bpb) ++iNumFailedToLoad; } inBondFODATA.close(); System.out.println (iNumFailedToLoad + " out of " + iNumBonds + " failed to load"); System.out.println ("There were " + iNumFloaters + " floaters!"); } }
26.869779
104
0.718544
5a602d52f0beec939a6a0818c2ac6480154c1dc3
196
package br.com.zup.academy.ednelson.proposta.cartao; import org.springframework.data.jpa.repository.JpaRepository; public interface BloqueioRepository extends JpaRepository<Bloqueio, Long> { }
24.5
75
0.831633
865cc31e00b17129be57e1e185c71786caf221d7
4,287
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.vivienda.persistence; import co.edu.uniandes.csw.vivienda.entities.AdministradorEntity; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; /** * * @author da.ramirezv */ @Stateless public class AdministradorPersistence { private static final Logger LOGGER = Logger.getLogger(AdministradorPersistence.class.getName()); @PersistenceContext(unitName = "viviendaPU") protected EntityManager em; /** * * @param entity objeto administrador que se creará en la base de datos * @return devuelve la entidad creada con un id dado por la base de datos. */ public AdministradorEntity create(AdministradorEntity entity) { LOGGER.info("Creando un administrador nuevo"); em.persist(entity); LOGGER.info("Creando un administrador nuevo"); return entity; } /** * Busca si hay algun administrador con el nombre que se envía de argumento * * @param name: Nombre del administrador que se está buscando * @return null si no existe ningun administrador con el nombre del argumento. Si * existe alguna devuelve la primera. */ public AdministradorEntity findByName(String nombre) { LOGGER.log(Level.INFO, "Consultando administrador por nombre", nombre); // Se crea un query para buscar cityes con el nombre que recibe el método como argumento. ":name" es un placeholder que debe ser remplazado TypedQuery query = em.createQuery("Select e From AdministradorEntity e where e.nombre = :nombre", AdministradorEntity.class); // Se remplaza el placeholder ":name" con el valor del argumento query = query.setParameter("nombre", nombre); // Se invoca el query se obtiene la lista resultado List<AdministradorEntity> sameName = query.getResultList(); if (sameName.isEmpty()) { return null; } else { return sameName.get(0); } } /** * actualiza un administrador * @param entity * @return */ public AdministradorEntity update(AdministradorEntity entity) { // Se crea un query para buscar cityes con el nombre que recibe el método como argumento. ":name" es un placeholder que debe ser remplazado AdministradorEntity adminreferencia = em.merge(entity); // Se remplaza el placeholder ":name" con el valor del argumento return adminreferencia; } /** * borra un administrador * @param id */ public void delete(Long id) { AdministradorEntity temp = findByID(id); em.remove(temp); } /** * busca un administrador por id * @param id * @return */ public AdministradorEntity findByID(Long id) { LOGGER.log(Level.INFO, "Consultando administrador por id", id); // Se crea un query para buscar cityes con el nombre que recibe el método como argumento. ":name" es un placeholder que debe ser remplazado //TypedQuery query = em.createQuery("Select e From CityEntity e where e.id = :id", CityEntity.class); AdministradorEntity admin = em.find(AdministradorEntity.class, id); // Se remplaza el placeholder ":name" con el valor del argumento //query = query.setParameter("id", id); // Se invoca el query se obtiene la lista resultado //List<CityEntity> sameID = query.getResultList(); if (admin == null) { return null; } else { return admin; } } /** * devuelve todos los administradores * @return */ public List<AdministradorEntity> findAll() { LOGGER.info("Consultando todos los administradores"); TypedQuery query = em.createQuery("select u from AdministradorEntity u", AdministradorEntity.class); return query.getResultList(); } }
35.429752
147
0.662235
8492882f7c11815667f7ea7eee932c73eec909db
790
package com.kintone.client.model.app.field; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.kintone.client.model.record.FieldType; import lombok.Data; /** An object containing the properties of the Category field for getting the field settings. */ @Data @JsonIgnoreProperties(value = "type", allowGetters = true) public class CategoryFieldProperty implements FieldProperty { /** The field code of the field. */ private String code; /** The field name. */ private String label; /** * Whether the category feature is enabled. * * @return true if the category feature is enabled */ private Boolean enabled; /** {@inheritDoc} */ @Override public FieldType getType() { return FieldType.CATEGORY; } }
25.483871
96
0.701266
1da58e67115c6c3ed9f0b27a512c7736cc1794e7
24,590
package io.github.eddieringle.android.apps.passwordmaker.ui.fragment; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.google.common.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.InjectView; import butterknife.Views; import io.github.eddieringle.android.apps.passwordmaker.R; import io.github.eddieringle.android.apps.passwordmaker.core.PMConstants; import io.github.eddieringle.android.apps.passwordmaker.core.PMProfile; import io.github.eddieringle.android.apps.passwordmaker.ui.activity.BaseActivity; import io.github.eddieringle.android.apps.passwordmaker.util.GsonUtils; public class ProfileEditFragment extends Fragment { private ArrayAdapter<String> mCharacterSetAdapter; private ArrayAdapter<String> mHashesAdapter; private ArrayAdapter<String> mL33tLevelAdapter; private ArrayAdapter<String> mL33tOrderAdapter; private String mOldName; private String[] mCharsets; private String[] mHashes; private String[] mL33tLevels; private String[] mL33tOrders; private PMProfile mProfile; private String mCustomCharsetCache; @InjectView(R.id.use_domain) CheckBox mUseDomain; @InjectView(R.id.use_other) CheckBox mUseOther; @InjectView(R.id.use_protocol) CheckBox mUseProtocol; @InjectView(R.id.use_subdomain) CheckBox mUseSubdomain; @InjectView(R.id.custom_character_set) EditText mCustomCharacterSet; @InjectView(R.id.modifier) EditText mModifier; @InjectView(R.id.password_length) EditText mPasswordLength; @InjectView(R.id.password_prefix) EditText mPasswordPrefix; @InjectView(R.id.password_suffix) EditText mPasswordSuffix; @InjectView(R.id.profile_name) EditText mProfileName; @InjectView(R.id.username) EditText mUsername; @InjectView(R.id.character_set) Spinner mCharacterSet; @InjectView(R.id.hashing_algorithm) Spinner mHashingAlgorithm; @InjectView(R.id.l33t_level) Spinner mL33tLevel; @InjectView(R.id.l33t_order) Spinner mL33tOrder; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle args = getArguments(); mProfile = GsonUtils.fromJson(args.getString("profile", ""), PMProfile.class); getBaseActivity().getSupportActionBar().setSubtitle(mProfile.getProfileName()); if (mProfile.getProfileName() == null || mProfile.getProfileName().isEmpty()) { getBaseActivity().getSupportActionBar().setTitle("New Profile"); getBaseActivity().getSupportActionBar().setSubtitle(null); mProfile.setProfileName(""); } mOldName = mProfile.getProfileName(); mCharsets = getResources().getStringArray(R.array.character_sets); mCharacterSetAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, mCharsets); mCharacterSet.setAdapter(mCharacterSetAdapter); mHashes = getResources().getStringArray(R.array.hash_algorithms); mHashesAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, mHashes); mHashingAlgorithm.setAdapter(mHashesAdapter); mL33tLevels = getResources().getStringArray(R.array.l33t_levels); mL33tLevelAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, mL33tLevels); mL33tLevel.setAdapter(mL33tLevelAdapter); mL33tOrders = getResources().getStringArray(R.array.l33t_orders); mL33tOrderAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, mL33tOrders); mL33tOrder.setAdapter(mL33tOrderAdapter); setFields(mProfile); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_profile_edit, container, false); Views.inject(this, v); return v; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.edit_profile, menu); ActionBar bar = getBaseActivity().getSupportActionBar(); bar.setHomeButtonEnabled(true); bar.setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_save && validateInputs()) { boolean addedEarly = false; ArrayList<PMProfile> profiles = new ArrayList<PMProfile>(); TypeToken<List<PMProfile>> listToken = new TypeToken<List<PMProfile>>(){}; String listJson = getBaseActivity().getPrefs().getString("profiles", ""); List<PMProfile> profileList = GsonUtils.fromJson(listJson, listToken.getType()); for (PMProfile p : profileList) { if (!addedEarly) { if (p.getProfileName().equals(mProfile.getProfileName())) { profiles.add(mProfile); addedEarly = true; continue; } } if (p.getProfileName().equals(mOldName)) { continue; } profiles.add(p); } if (!addedEarly) { profiles.add(mProfile); } getBaseActivity().getPrefsEditor() .putString("profiles", GsonUtils.toJson(profiles)) .commit(); if (getBaseActivity().getPrefs().getString("current_profile", "").equals(mOldName)) { getBaseActivity().getPrefsEditor() .putString("current_profile", mProfile.getProfileName()) .commit(); } Toast.makeText(getBaseActivity(), R.string.toast_profile_save_success, Toast.LENGTH_SHORT).show(); getBaseActivity().setResult(Activity.RESULT_OK); getBaseActivity().finish(); return true; } return super.onOptionsItemSelected(item); } public BaseActivity getBaseActivity() { return (BaseActivity) getActivity(); } public void setFields(final PMProfile profile) { mUseDomain.setChecked(profile.getUseUrlDomain()); mUseOther.setChecked(profile.getUseUrlOther()); mUseProtocol.setChecked(profile.getUseUrlProtocol()); mUseSubdomain.setChecked(profile.getUseUrlSubdomain()); mModifier.setText((profile.getModifier()!=null)?profile.getModifier():""); mPasswordLength.setText((profile.getPasswordLength()!=null)?Integer.toString(profile.getPasswordLength()):""); mPasswordPrefix.setText((profile.getPasswordPrefix()!=null)?profile.getPasswordPrefix():""); mPasswordSuffix.setText((profile.getPasswordSuffix()!=null)?profile.getPasswordSuffix():""); mProfileName.setText((profile.getProfileName()!=null)?profile.getProfileName():""); mUsername.setText((profile.getUsername()!=null)?profile.getUsername():""); final String charsetAlphaName = getString(R.string.charset_alpha_name); final String charsetAlphaNumName = getString(R.string.charset_alphanum_name); final String charsetAlphaNumSymName = getString(R.string.charset_alphanumsym_name); final String charsetHexName = getString(R.string.charset_hex_name); final String charsetNumbersName = getString(R.string.charset_numbers_name); final String charsetSymbolsName = getString(R.string.charset_symbols_name); final String charsetCustomName = getString(R.string.charset_custom_name); final List<String> charsetList = Arrays.asList(mCharsets); final int charsetAlphaIndex = charsetList.indexOf(charsetAlphaName); final int charsetAlphaNumIndex = charsetList.indexOf(charsetAlphaNumName); final int charsetAlphaNumSymIndex = charsetList.indexOf(charsetAlphaNumSymName); final int charsetHexadecimalIndex = charsetList.indexOf(charsetHexName); final int charsetNumbersIndex = charsetList.indexOf(charsetNumbersName); final int charsetSymbolsIndex = charsetList.indexOf(charsetSymbolsName); final int charsetCustomIndex = charsetList.indexOf(charsetCustomName); final String charset = profile.getCharacterSet(); mCustomCharsetCache = null; mCustomCharacterSet.setEnabled(false); if (PMConstants.CHARSET_ALPHA.equals(charset)) { mCharacterSet.setSelection(charsetAlphaIndex); mCharacterSet.setTag(PMConstants.CHARSET_ALPHA); } else if (PMConstants.CHARSET_ALPHANUM.equals(charset)) { mCharacterSet.setSelection(charsetAlphaNumIndex); mCharacterSet.setTag(PMConstants.CHARSET_ALPHANUM); } else if (PMConstants.CHARSET_ALPHANUMSYM.equals(charset)) { mCharacterSet.setSelection(charsetAlphaNumSymIndex); mCharacterSet.setTag(PMConstants.CHARSET_ALPHANUMSYM); } else if (PMConstants.CHARSET_HEX.equals(charset)) { mCharacterSet.setSelection(charsetHexadecimalIndex); mCharacterSet.setTag(PMConstants.CHARSET_HEX); } else if (PMConstants.CHARSET_NUMBERS.equals(charset)) { mCharacterSet.setSelection(charsetNumbersIndex); mCharacterSet.setTag(PMConstants.CHARSET_NUMBERS); } else if (PMConstants.CHARSET_SYMBOLS.equals(charset)) { mCharacterSet.setSelection(charsetSymbolsIndex); mCharacterSet.setTag(PMConstants.CHARSET_SYMBOLS); } else { mCustomCharsetCache = charset; mCharacterSet.setSelection(charsetCustomIndex); mCharacterSet.setTag(PMConstants.CHARSET_CUSTOM); mCustomCharacterSet.setText(charset); mCustomCharacterSet.setEnabled(true); } mCharacterSet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mCustomCharacterSet.setEnabled(false); if (position == charsetAlphaIndex) { mCharacterSet.setTag(PMConstants.CHARSET_ALPHA); mCustomCharacterSet.setText(PMConstants.CHARSET_ALPHA); } else if (position == charsetAlphaNumIndex) { mCharacterSet.setTag(PMConstants.CHARSET_ALPHANUM); mCustomCharacterSet.setText(PMConstants.CHARSET_ALPHANUM); } else if (position == charsetAlphaNumSymIndex) { mCharacterSet.setTag(PMConstants.CHARSET_ALPHANUMSYM); mCustomCharacterSet.setText(PMConstants.CHARSET_ALPHANUMSYM); } else if (position == charsetHexadecimalIndex) { mCharacterSet.setTag(PMConstants.CHARSET_HEX); mCustomCharacterSet.setText(PMConstants.CHARSET_HEX); } else if (position == charsetNumbersIndex) { mCharacterSet.setTag(PMConstants.CHARSET_NUMBERS); mCustomCharacterSet.setText(PMConstants.CHARSET_NUMBERS); } else if (position == charsetSymbolsIndex) { mCharacterSet.setTag(PMConstants.CHARSET_SYMBOLS); mCustomCharacterSet.setText(PMConstants.CHARSET_SYMBOLS); } else if (position == charsetCustomIndex) { mCharacterSet.setTag(PMConstants.CHARSET_CUSTOM); if (mCustomCharsetCache != null && !mCustomCharsetCache.isEmpty()) { mCustomCharacterSet.setText(mCustomCharsetCache); } mCustomCharacterSet.setEnabled(true); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mCustomCharacterSet.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (mCharacterSet.getSelectedItemPosition() == charsetCustomIndex) { mCustomCharsetCache = s.toString(); } } @Override public void afterTextChanged(Editable s) { } }); final String hashMd4Name = getString(R.string.hash_md4); final String hashHmacMd4Name = getString(R.string.hash_hmac_md4); final String hashMd5Name = getString(R.string.hash_md5); final String hashMd5v6Name = getString(R.string.hash_md5_v6); final String hashHmacMd5Name = getString(R.string.hash_hmac_md5); final String hashHmacMd5v6Name = getString(R.string.hash_hmac_md5_v6); final String hashSha1Name = getString(R.string.hash_sha1); final String hashHmacSha1Name = getString(R.string.hash_hmac_sha1); final String hashSha256Name = getString(R.string.hash_sha256); final String hashHmacSha256FixName = getString(R.string.hash_hmac_sha256_fix); final String hashHmacSha256Name = getString(R.string.hash_hmac_sha256); final String hashRmd160Name = getString(R.string.hash_rmd160); final String hashHmacRmd160Name = getString(R.string.hash_hmac_rmd160); final List<String> hashList = Arrays.asList(mHashes); final int hashMd4Index = hashList.indexOf(hashMd4Name); final int hashHmacMd4Index = hashList.indexOf(hashHmacMd4Name); final int hashMd5Index = hashList.indexOf(hashMd5Name); final int hashMd5v6Index = hashList.indexOf(hashMd5v6Name); final int hashHmacMd5Index = hashList.indexOf(hashHmacMd5Name); final int hashHmacMd5v6Index = hashList.indexOf(hashHmacMd5v6Name); final int hashSha1Index = hashList.indexOf(hashSha1Name); final int hashHmacSha1Index = hashList.indexOf(hashHmacSha1Name); final int hashSha256Index = hashList.indexOf(hashSha256Name); final int hashHmacSha256FixIndex = hashList.indexOf(hashHmacSha256FixName); final int hashHmacSha256Index = hashList.indexOf(hashHmacSha256Name); final int hashRmd160Index = hashList.indexOf(hashRmd160Name); final int hashHmacRmd160Index = hashList.indexOf(hashHmacRmd160Name); final String hash = profile.getHashAlgorithm(); if (PMConstants.HASH_MD4.equals(hash)) { mHashingAlgorithm.setSelection(hashMd4Index); mHashingAlgorithm.setTag(PMConstants.HASH_MD4); } else if (PMConstants.HASH_HMAC_MD4.equals(hash)) { mHashingAlgorithm.setSelection(hashHmacMd4Index); mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_MD4); } else if (PMConstants.HASH_MD5.equals(hash)) { mHashingAlgorithm.setSelection(hashMd5Index); mHashingAlgorithm.setTag(PMConstants.HASH_MD5); } else if (PMConstants.HASH_MD5_V6.equals(hash)) { mHashingAlgorithm.setSelection(hashMd5v6Index); mHashingAlgorithm.setTag(PMConstants.HASH_MD5_V6); } else if (PMConstants.HASH_HMAC_MD5.equals(hash)) { mHashingAlgorithm.setSelection(hashHmacMd5Index); mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_MD5); } else if (PMConstants.HASH_HMAC_MD5_V6.equals(hash)) { mHashingAlgorithm.setSelection(hashHmacMd5v6Index); mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_MD5_V6); } else if (PMConstants.HASH_SHA1.equals(hash)) { mHashingAlgorithm.setSelection(hashSha1Index); mHashingAlgorithm.setTag(PMConstants.HASH_SHA1); } else if (PMConstants.HASH_HMAC_SHA1.equals(hash)) { mHashingAlgorithm.setSelection(hashHmacSha1Index); mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_SHA1); } else if (PMConstants.HASH_SHA256.equals(hash)) { mHashingAlgorithm.setSelection(hashSha256Index); mHashingAlgorithm.setTag(PMConstants.HASH_SHA256); } else if (PMConstants.HASH_HMAC_SHA256_FIX.equals(hash)) { mHashingAlgorithm.setSelection(hashHmacSha256FixIndex); mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_SHA256_FIX); } else if (PMConstants.HASH_HMAC_SHA256.equals(hash)) { mHashingAlgorithm.setSelection(hashHmacSha256Index); mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_SHA256); } else if (PMConstants.HASH_RMD160.equals(hash)) { mHashingAlgorithm.setSelection(hashRmd160Index); mHashingAlgorithm.setTag(PMConstants.HASH_RMD160); } else if (PMConstants.HASH_HMAC_RMD160.equals(hash)) { mHashingAlgorithm.setSelection(hashHmacRmd160Index); mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_RMD160); } mHashingAlgorithm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position == hashMd4Index) { mHashingAlgorithm.setTag(PMConstants.HASH_MD4); } else if (position == hashHmacMd4Index) { mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_MD4); } else if (position == hashMd5Index) { mHashingAlgorithm.setTag(PMConstants.HASH_MD5); } else if (position == hashMd5v6Index) { mHashingAlgorithm.setTag(PMConstants.HASH_MD5_V6); } else if (position == hashHmacMd5Index) { mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_MD5); } else if (position == hashHmacMd5v6Index) { mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_MD5_V6); } else if (position == hashSha1Index) { mHashingAlgorithm.setTag(PMConstants.HASH_SHA1); } else if (position == hashHmacSha1Index) { mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_SHA1); } else if (position == hashSha256Index) { mHashingAlgorithm.setTag(PMConstants.HASH_SHA256); } else if (position == hashHmacSha256FixIndex) { mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_SHA256_FIX); } else if (position == hashHmacSha256Index) { mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_SHA256); } else if (position == hashRmd160Index) { mHashingAlgorithm.setTag(PMConstants.HASH_RMD160); } else if (position == hashHmacRmd160Index) { mHashingAlgorithm.setTag(PMConstants.HASH_HMAC_RMD160); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Integer l33tLevel = profile.getL33tLevel(); if (l33tLevel == null || l33tLevel < 0) { l33tLevel = 0; } else if (l33tLevel > 8) { l33tLevel = 8; } mL33tLevel.setSelection(l33tLevel); mL33tLevel.setEnabled(true); final String l33tNeverName = getString(R.string.l33t_use_never); final String l33tBeforeName = getString(R.string.l33t_use_before); final String l33tAfterName = getString(R.string.l33t_use_after); final String l33tBothName = getString(R.string.l33t_use_before_and_after); List<String> l33tOrderList = Arrays.asList(mL33tOrders); final int l33tNeverIndex = l33tOrderList.indexOf(l33tNeverName); final int l33tBeforeIndex = l33tOrderList.indexOf(l33tBeforeName); final int l33tAfterIndex = l33tOrderList.indexOf(l33tAfterName); final int l33tBothIndex = l33tOrderList.indexOf(l33tBothName); final String l33tOrder = profile.getL33tOrder(); if (PMConstants.L33T_NEVER.equals(l33tOrder)) { mL33tOrder.setSelection(l33tNeverIndex); mL33tLevel.setEnabled(false); mL33tOrder.setTag(PMConstants.L33T_NEVER); } else if (PMConstants.L33T_BEFORE.equals(l33tOrder)) { mL33tOrder.setSelection(l33tBeforeIndex); mL33tOrder.setTag(PMConstants.L33T_BEFORE); } else if (PMConstants.L33T_AFTER.equals(l33tOrder)) { mL33tOrder.setSelection(l33tAfterIndex); mL33tOrder.setTag(PMConstants.L33T_AFTER); } else if (PMConstants.L33T_BEFORE_AND_AFTER.equals(l33tOrder)) { mL33tOrder.setSelection(l33tBothIndex); mL33tOrder.setTag(PMConstants.L33T_BEFORE_AND_AFTER); } mL33tOrder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.d("ProfileEditFragment", "Enabled? " + position + " != " + l33tNeverIndex); mL33tLevel.setEnabled(position != l33tNeverIndex); if (position == l33tNeverIndex) { mL33tOrder.setTag(PMConstants.L33T_NEVER); } else if (position == l33tBeforeIndex) { mL33tOrder.setTag(PMConstants.L33T_BEFORE); } else if (position == l33tAfterIndex) { mL33tOrder.setTag(PMConstants.L33T_AFTER); } else if (position == l33tBothIndex) { mL33tOrder.setTag(PMConstants.L33T_BEFORE_AND_AFTER); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } protected boolean validateInputs() { final String profileName = mProfileName.getText().toString(); if (profileName.trim().isEmpty()) { mProfileName.setText(""); mProfileName.setError("Profile name cannot be blank"); return false; } if (mPasswordLength.getText().toString().trim().isEmpty()) { mPasswordLength.setText(""); mPasswordLength.setError("Password length cannot be blank"); return false; } if (PMConstants.CHARSET_CUSTOM.equals((String)mCharacterSet.getTag())) { if (mCustomCharacterSet.getText().toString().length() < 2) { mCustomCharacterSet.setError("Custom character set must contain at least 2 characters"); return false; } } mProfile.setProfileName(mProfileName.getText().toString()); mProfile.setUseUrlProtocol(mUseProtocol.isChecked()); mProfile.setUseUrlSubdomain(mUseSubdomain.isChecked()); mProfile.setUseUrlDomain(mUseDomain.isChecked()); mProfile.setUseUrlOther(mUseOther.isChecked()); mProfile.setUsername(mUsername.getText().toString()); mProfile.setPasswordSuffix(mPasswordSuffix.getText().toString()); mProfile.setPasswordPrefix(mPasswordPrefix.getText().toString()); if (PMConstants.CHARSET_CUSTOM.equals((String)mCharacterSet.getTag())) { mProfile.setCharacterSet(mCustomCharacterSet.getText().toString()); } else { mProfile.setCharacterSet((String)mCharacterSet.getTag()); } mProfile.setHashAlgorithm((String)mHashingAlgorithm.getTag()); mProfile.setL33tLevel(mL33tLevel.getSelectedItemPosition()); mProfile.setL33tOrder((String)mL33tOrder.getTag()); mProfile.setModifier(mModifier.getText().toString()); mProfile.setPasswordLength(Integer.parseInt(mPasswordLength.getText().toString())); return true; } }
46.838095
139
0.669622
21316b46e0ac03a8159a44c335c59a62d92b10cf
2,697
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.spark.node; import com.facebook.presto.Session; import com.facebook.presto.common.type.Type; import com.facebook.presto.execution.scheduler.BucketNodeMap; import com.facebook.presto.execution.scheduler.nodeSelection.NodeSelectionStats; import com.facebook.presto.operator.PartitionFunction; import com.facebook.presto.spi.connector.ConnectorPartitionHandle; import com.facebook.presto.sql.planner.NodePartitionMap; import com.facebook.presto.sql.planner.NodePartitioningManager; import com.facebook.presto.sql.planner.PartitioningHandle; import com.facebook.presto.sql.planner.PartitioningProviderManager; import com.facebook.presto.sql.planner.PartitioningScheme; import javax.inject.Inject; import java.util.List; /** * TODO: Decouple node and partition management in presto-main and remove this hack */ public class PrestoSparkNodePartitioningManager extends NodePartitioningManager { @Inject public PrestoSparkNodePartitioningManager(PartitioningProviderManager partitioningProviderManager) { super(new PrestoSparkNodeScheduler(), partitioningProviderManager, new NodeSelectionStats()); } @Override public PartitionFunction getPartitionFunction(Session session, PartitioningScheme partitioningScheme, List<Type> partitionChannelTypes) { return super.getPartitionFunction(session, partitioningScheme, partitionChannelTypes); } @Override public List<ConnectorPartitionHandle> listPartitionHandles(Session session, PartitioningHandle partitioningHandle) { return super.listPartitionHandles(session, partitioningHandle); } @Override public NodePartitionMap getNodePartitioningMap(Session session, PartitioningHandle partitioningHandle) { throw new UnsupportedOperationException("grouped execution is not supported in presto on spark"); } @Override public BucketNodeMap getBucketNodeMap(Session session, PartitioningHandle partitioningHandle, boolean preferDynamic) { throw new UnsupportedOperationException("grouped execution is not supported in presto on spark"); } }
39.661765
139
0.790879
2a476d70bf622b16a902065d490469d3feacf162
7,000
package com.pesna.entities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.Matrix4; import com.pesna.Main; import com.pesna.objects.ScreenObject; import com.pesna.objects.SimpleLabel; import com.pesna.player.Player; import com.pesna.spriter.LibGdx.SpriterAnimation; import com.pesna.spriter.LibGdx.LibGdxDrawer; import com.pesna.spriter.LibGdx.SpriterAnimationBundle; /** * Created by Zenibryum on 4/4/2017. */ public class EnemyBot implements ScreenObject { private Main reference; public float ATTACK_SPEED,SPEED; public float x ,y; public int HP, CHASE_RANGE, ATTACK_RANGE; public Player target; private SimpleLabel hpLabel ,nameLabel; boolean flip; public com.brashmonkey.spriter.Data spriterData; public com.brashmonkey.spriter.Player spriterPlayer; public LibGdxDrawer spriterDrawer; public SpriterAnimation spriterAnimation; public SpriterAnimation runAnimation, attackAnimation, idleAnimation; public boolean UPDATING = false , DRAWING = false, ANIMATIONS_WORKING = false; public EnemyBot( Main _reference, int posX , int posY, int GraphicsID, int BehaviourID ) { hpLabel = new SimpleLabel(_reference); hpLabel.SetColor(Color.YELLOW); nameLabel = new SimpleLabel(_reference); nameLabel.SetColor(Color.YELLOW); reference = _reference; x = posX; y = posY; BehaviourBundle behaviourBundle = reference.gameRegistry.behaviourBundles[BehaviourID]; HP = behaviourBundle.HP; ATTACK_SPEED = behaviourBundle.ATTACK_SPEED; SPEED = behaviourBundle.SPEED; CHASE_RANGE = behaviourBundle.CHASE_RANGE; ATTACK_RANGE = behaviourBundle.ATTACK_RANGE; SpriterAnimationBundle animationBundles = reference.gameRegistry.animationBundles[GraphicsID]; runAnimation = animationBundles.run; idleAnimation = animationBundles.idle; attackAnimation = animationBundles.attack; target = reference.player; spriterData = reference.gameRegistry.spriterData[GraphicsID]; spriterPlayer = new com.brashmonkey.spriter.Player( spriterData.getEntity(0) ); spriterDrawer = reference.gameRegistry.spriterDrawer[GraphicsID]; //setAnimation(SpriterAnimation.bear_run); setAnimation ( idleAnimation ); //entity 0 running //entity 1 attack_upwards //entity 2 attack_normal //spriterPlayer.setEntity( reference.gameRegistry.werewolfData.getEntity(0 ) ); //spriterPlayer.speed=3; } public void update(Main main) { //This is the main behavioural routine if ( distanceToTarget() <= ATTACK_RANGE ) attack(); else if ( distanceToTarget() <= CHASE_RANGE ) run(); else idle(); UPDATING = true; } public void draw(Main _reference) { if (!IS_Dead()) { drawHealth(); float cameraScale = spriterAnimation.projectionScale; float reverseScale = 1f/cameraScale; spriterPlayer.setPosition(x*reverseScale,(y+spriterAnimation.yOffset)*reverseScale); spriterPlayer.update(); if ( spriterPlayer.flippedX() == 1 && flip) spriterPlayer.flipX(); if ( spriterPlayer.flippedX() == -1 && !flip) spriterPlayer.flipX(); Matrix4 cameracombined = _reference.camera.combined; _reference.batch.setProjectionMatrix( cameracombined.scale(cameraScale,cameraScale,1f) ); _reference.batch.begin(); spriterDrawer.draw(spriterPlayer); _reference.batch.end(); _reference.batch.setProjectionMatrix( cameracombined.scale(reverseScale,reverseScale,1f) ); drawHealth(); } DRAWING = true; } public void setAnimation( SpriterAnimation animation ) { this.spriterAnimation = animation; spriterPlayer.setEntity( spriterData.getEntity(animation.entityID)); com.brashmonkey.spriter.Animation newAnimation = spriterPlayer.getEntity().getAnimation( animation.animationID ); if ( newAnimation != spriterPlayer.getAnimation() ) { //spriterPlayer.setAnimation(spriterPlayer.getEntity().getAnimation(animation.animationID)); spriterPlayer.setTime( 0 ); } //else //spriterPlayer.setAnimation(spriterPlayer.getEntity().getAnimation(animation.animationID)); spriterPlayer.speed = animation.animationSpeed; ANIMATIONS_WORKING = true; } /**Sets the EnemyBot on the attacking routine*/ public void attack() { flipAccordingly(); setAnimation(attackAnimation); System.out.println( spriterPlayer.getTime()+" "+ spriterPlayer.getAnimation().length / 10); if(spriterPlayer.getTime() > spriterPlayer.getAnimation().length / 1.5) { dealDamage();spriterPlayer.setTime(0); } } /**Sets the EnemyBot on the chasing routine*/ public void run() { flipAccordingly(); setAnimation(runAnimation); if ( x < target.x ) { x += Gdx.graphics.getDeltaTime() * SPEED; } else x -= Gdx.graphics.getDeltaTime() * SPEED; } /**Sets the EnemyBot on the sitting routine*/ public void idle() { flipAccordingly(); setAnimation(idleAnimation); } public void dealDamage() { reference.player.TakeDamage(5); } public void flipAccordingly() { if ( target.x < x != ( spriterPlayer.flippedX() == 1 ) ) // if the target is to the left of the EnemyBot { spriterPlayer.flipX(); } } public void TakeDamange(float dmg) { HP -= dmg; } private boolean expAdded = false; public boolean IS_Dead() { if(HP <= 0) { if(!expAdded) { reference.player.Experience += 300; expAdded = true; } return true; } else { return false; } } private void drawHealth() { float procent; procent = (HP * 140)/ 1000; reference.shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); reference.shapeRenderer.setColor(Color.FIREBRICK); reference.shapeRenderer.rect(x - 40, y +400,procent,20); reference.shapeRenderer.end(); hpLabel.SetPosition(x + 15 , y+418); hpLabel.Draw(String.valueOf(HP)); nameLabel.SetPosition(x + 15, y + 460); nameLabel.Draw("Urs"); } public boolean IS_IN_RANGE(Player player, float range) { return Math.abs(Math.abs(player.x) - x) <= ATTACK_RANGE; } public int distanceToTarget() { return Math.abs( (int)( target.x - x ) ); } }
30.042918
121
0.636286
af1f1a62aef210a33037665ffa0f7d0f7f3018cf
559
package de.unipaderborn.visuflow.ui; import org.junit.Assert; import org.junit.Test; public class JimpleEditorTest { @Test public void testIsEditable() { JimpleEditor editor = new JimpleEditor(); Assert.assertFalse(editor.isEditable()); } @Test public void testIsEditorInputReadOnly() { JimpleEditor editor = new JimpleEditor(); Assert.assertTrue(editor.isEditorInputReadOnly()); } @Test public void testIsEditorInputModifiable() { JimpleEditor editor = new JimpleEditor(); Assert.assertFalse(editor.isEditorInputModifiable()); } }
20.703704
55
0.760286
91b0c46ade25a66a6484e8ee9df464a5ac01462e
946
package org.workcraft.plugins.mpsat_verification.utils; import org.workcraft.utils.DialogUtils; import org.workcraft.utils.LogUtils; public class OutcomeUtils { public static final String TITLE = "Verification results"; public static void showOutcome(boolean propertyHolds, String message, boolean interactive) { if (interactive) { showOutcome(propertyHolds, message); } else { logOutcome(propertyHolds, message); } } public static void showOutcome(boolean propertyHolds, String message) { if (propertyHolds) { DialogUtils.showInfo(message, TITLE); } else { DialogUtils.showWarning(message, TITLE); } } public static void logOutcome(boolean propertyHolds, String message) { if (propertyHolds) { LogUtils.logInfo(message); } else { LogUtils.logWarning(message); } } }
27.028571
96
0.643763
86c50508d3ed1f55fc12ec0b9490bca9615fe0fb
3,004
package com.yatsukav.msd.converter; import ncsa.hdf.object.h5.H5File; import java.util.Arrays; public enum Column { ARTIST_NAME, ARTIST_HOTNESS, ARTIST_ID, ARTIST_LOCATION, ARTIST_LATITUDE, ARTIST_LONGITUDE, ARTIST_TERMS, ARTIST_TAGS, YEAR, RELEASE, TITLE, SONG_HOTNESS, DURATION, END_OF_FADE_IN, LOUDNESS, MODE, MODE_CONFIDENCE, START_OF_FADE_OUT, TEMPO, TIME_SIGNATURE, TIME_SIGNATURE_CONFIDENCE; public Object getData(H5File h5, int songIdx) { try { switch (this) { case ARTIST_NAME: return Hdf5Getters.get_artist_name(h5, songIdx); case ARTIST_HOTNESS: return Hdf5Getters.get_artist_hotttnesss(h5, songIdx); case ARTIST_ID: return Hdf5Getters.get_artist_id(h5, songIdx); case ARTIST_LOCATION: return Hdf5Getters.get_artist_location(h5, songIdx); case ARTIST_LATITUDE: return Hdf5Getters.get_artist_latitude(h5, songIdx); case ARTIST_LONGITUDE: return Hdf5Getters.get_artist_longitude(h5, songIdx); case ARTIST_TERMS: return "\"" + Arrays.toString(Hdf5Getters.get_artist_terms(h5, songIdx)) + "\""; case ARTIST_TAGS: return "\"" + Arrays.toString(Hdf5Getters.get_artist_mbtags(h5, songIdx)) + "\""; case YEAR: return Hdf5Getters.get_year(h5, songIdx); case RELEASE: return Hdf5Getters.get_release(h5, songIdx); case TITLE: return Hdf5Getters.get_title(h5, songIdx); case SONG_HOTNESS: return Hdf5Getters.get_song_hotttnesss(h5, songIdx); case DURATION: return Hdf5Getters.get_duration(h5, songIdx); case END_OF_FADE_IN: return Hdf5Getters.get_end_of_fade_in(h5, songIdx); case LOUDNESS: return Hdf5Getters.get_loudness(h5, songIdx); case MODE: return Hdf5Getters.get_mode(h5, songIdx) == 0 ? "major" : "minor"; case MODE_CONFIDENCE: return Hdf5Getters.get_mode_confidence(h5, songIdx); case START_OF_FADE_OUT: return Hdf5Getters.get_start_of_fade_out(h5, songIdx); case TEMPO: return Hdf5Getters.get_tempo(h5, songIdx); case TIME_SIGNATURE: return Hdf5Getters.get_time_signature(h5, songIdx); case TIME_SIGNATURE_CONFIDENCE: return Hdf5Getters.get_time_signature_confidence(h5, songIdx); default: throw new IllegalStateException("There is no implementation for " + this); } } catch (Throwable throwable) { return null; } } }
46.215385
111
0.574567
b5faeb69952a2ca69d8c0da23aa9f5a89e9fa7b4
7,777
package com.example.restreactive.service; import com.example.restreactive.dto.AppointmentDto; import com.example.restreactive.dto.StoreDto; import com.example.restreactive.dto.StoreSlotDto; import com.example.restreactive.dto.UserDto; import com.example.restreactive.mapping.AppointmentException; import com.example.restreactive.model.Appointment; import com.example.restreactive.repository.AppointmentRepository; import com.google.common.collect.ImmutableList; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.time.ZonedDateTime; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class AppointmentServiceTest { public static final ZonedDateTime DATE_TIME_1 = ZonedDateTime .parse("2019-04-01T16:24:11.252Z"); public static final ZonedDateTime DATE_TIME_2 = DATE_TIME_1 .plusMinutes(30); public static final String EMAIL = "[email protected]"; public static final String TEST = "test"; @Autowired private AppointmentService underTest; @Autowired private StoreSlotService storeSlotService; @Autowired private StoreService storeService; @Autowired private UserService userService; @Autowired private AppointmentRepository appointmentRepository; private final EntityDtoCreator creator = new EntityDtoCreator(); private StoreSlotDto storeSlotDto; private StoreDto storeDto; private UserDto userDto; @BeforeEach void setUp() { deleteAll(); // Store slot storeSlotDto = creator .createStoreSlotDto(TEST, TEST, DATE_TIME_1, DATE_TIME_2); storeSlotService.upsertStoreSlot(storeSlotDto); // STORE storeDto = creator.createStoreDto( creator.createStreetAddressDto( creator.createCountryDto())); storeService.upsertStore(storeDto); // USER userDto = creator.createUserDto( creator.createEmailAddressDto(EMAIL)); userService.upsertUser(userDto); } @AfterEach void tearDown() { deleteAll(); } private void deleteAll() { appointmentRepository.deleteAll(); } @Test void whenFindAllSizeThenEmpty() { assertSlotsSize(0); } @Test void whenFindByStartTimeAndEndTimeEmptyThenEmpty() { List<AppointmentDto> expected = ImmutableList.of(); List<AppointmentDto> actual = underTest.findByStartTimeAndEndTime( DATE_TIME_1, DATE_TIME_2); assertEquals(expected, actual); } @Test void whenFindByStartTimeAndEndTime1ApptThen1Appt() { // Check 0 in db, initial conditions assertSlotsSize(0); // Add 1 appointment AppointmentDto appointmentDto = creator.createAppointmentDto( storeSlotDto, storeDto, userDto); appointmentDto = underTest.upsertAppointment(appointmentDto); // Check 0 in db, initial conditions assertSlotsSize(1); // Verify 1 appointment found List<AppointmentDto> expected = ImmutableList.of(appointmentDto); List<AppointmentDto> actual = underTest.findByStartTimeAndEndTime( DATE_TIME_1, DATE_TIME_2); assertEquals(expected, actual); } @Test void whenFindByStartTimeAndEndTimeAndStoreCodeListEmptyThenEmpty() { List<AppointmentDto> expected = ImmutableList.of(); List<AppointmentDto> actual = underTest .findByStartTimeAndEndTimeAndStoreCodeList( DATE_TIME_1, DATE_TIME_2, List.of("non-existent") ); assertEquals(expected, actual); } @Test void whenFindByStartTimeAndEndTimeAndStoreCodeList1ApptThen1Appt() { // Check 0 in db, initial conditions assertSlotsSize(0); // Add 1 appointment AppointmentDto appointmentDto = creator.createAppointmentDto( storeSlotDto, storeDto, userDto); appointmentDto = underTest.upsertAppointment(appointmentDto); // Check 0 in db, initial conditions assertSlotsSize(1); // Verify 1 appointment found List<AppointmentDto> expected = ImmutableList.of(appointmentDto); List<AppointmentDto> actual = underTest .findByStartTimeAndEndTimeAndStoreCodeList( DATE_TIME_1, DATE_TIME_2, List.of(storeDto.getStoreCode()) ); assertEquals(expected, actual); } @Test void whenFindByStoreAndAppointmentEmptyThenEmpty() { List<AppointmentDto> expected = ImmutableList.of(); List<AppointmentDto> actual = underTest .findByStoreAndAppointmentSlot(storeDto, storeSlotDto); assertEquals(expected, actual); } @Test void whenFindByStoreAndAppointmentNullStoreThenException() { Exception ex = assertThrows(AppointmentException.class, () -> underTest .findByStoreAndAppointmentSlot(null, storeSlotDto)); String expected = """ Null value for find appointment,\s store: 'null',\s slot: 'StoreSlotDto(id=null, slotCode=test, storeCode=test, startTime=2019-04-01T16:24:11.252Z[UTC], endTime=2019-04-01T16:54:11.252Z[UTC])'\s users: '[]'"""; assertEquals(expected, ex.getMessage()); } @Test void whenFindByStoreAndAppointmentNullSlotThenException() { Exception ex = assertThrows(AppointmentException.class, () -> underTest .findByStoreAndAppointmentSlot(storeDto, null)); String expected = "Null value for find appointment, \n"; assertTrue(ex.getMessage().startsWith(expected)); } @Test void whenFindByStoreAndAppointmentNullStoreNullSlotThenException() { Exception ex = assertThrows(AppointmentException.class, () -> underTest .findByStoreAndAppointmentSlot(null, null)); String expected = """ Null value for find appointment,\s store: 'null',\s slot: 'null'\s users: '[]'"""; assertEquals(expected, ex.getMessage()); } @Test void whenUpsertAppointmentCreateThenCreate() { // Check 0 in db, initial conditions assertSlotsSize(0); // Step 1 - save AppointmentDto appointmentDto = creator.createAppointmentDto( storeSlotDto, storeDto, userDto ); long actual = underTest.upsertAppointment(appointmentDto).getId(); long expected = 1L; assertTrue(expected <= actual); // Check 1 in db, therefore created assertSlotsSize(1); } @Test void whenUpsertAppointmentExistsThenUpdate() { // Check 0 in db, initial conditions assertSlotsSize(0); // Step 1 - save AppointmentDto appointmentDto = creator.createAppointmentDto( storeSlotDto, storeDto, userDto ); long actual1 = underTest.upsertAppointment(appointmentDto).getId(); long expected = 1L; assertTrue(expected <= actual1); // Check 1 in db, therefore created assertSlotsSize(1); // Step 2 - Update long actual2 = underTest.upsertAppointment(appointmentDto).getId(); assertEquals(actual1, actual2); // Check 1 in db, therefore updated assertSlotsSize(1); } private void assertSlotsSize(int expectedSize) { List<AppointmentDto> slots = underTest.findAllAppointments(); assertEquals(expectedSize, slots.size()); } }
31.108
154
0.664266
9494b30dac05be1f313f76d049a1e7a11265c9e5
11,806
package com.twitter.common.application.modules; import java.util.Set; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import com.google.common.collect.ImmutableSet; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import com.google.inject.servlet.GuiceFilter; import com.google.inject.servlet.GuiceServletContextListener; import org.mortbay.jetty.RequestLog; import com.twitter.common.application.ShutdownRegistry; import com.twitter.common.application.http.DefaultQuitHandler; import com.twitter.common.application.http.GraphViewer; import com.twitter.common.application.http.HttpAssetConfig; import com.twitter.common.application.http.HttpFilterConfig; import com.twitter.common.application.http.HttpServletConfig; import com.twitter.common.application.http.Registration; import com.twitter.common.application.http.Registration.IndexLink; import com.twitter.common.application.modules.LifecycleModule.ServiceRunner; import com.twitter.common.application.modules.LocalServiceRegistry.LocalService; import com.twitter.common.args.Arg; import com.twitter.common.args.CmdLine; import com.twitter.common.args.constraints.NotEmpty; import com.twitter.common.args.constraints.Range; import com.twitter.common.base.Command; import com.twitter.common.base.ExceptionalSupplier; import com.twitter.common.base.Supplier; import com.twitter.common.net.http.HttpServerDispatch; import com.twitter.common.net.http.JettyHttpServerDispatch; import com.twitter.common.net.http.RequestLogger; import com.twitter.common.net.http.handlers.AbortHandler; import com.twitter.common.net.http.handlers.ContentionPrinter; import com.twitter.common.net.http.handlers.HealthHandler; import com.twitter.common.net.http.handlers.LogConfig; import com.twitter.common.net.http.handlers.LogPrinter; import com.twitter.common.net.http.handlers.QuitHandler; import com.twitter.common.net.http.handlers.StringTemplateServlet.CacheTemplates; import com.twitter.common.net.http.handlers.ThreadStackPrinter; import com.twitter.common.net.http.handlers.TimeSeriesDataSource; import com.twitter.common.net.http.handlers.VarsHandler; import com.twitter.common.net.http.handlers.VarsJsonHandler; import com.twitter.common.net.http.handlers.pprof.ContentionProfileHandler; import com.twitter.common.net.http.handlers.pprof.CpuProfileHandler; import com.twitter.common.net.http.handlers.pprof.HeapProfileHandler; import static com.google.common.base.Preconditions.checkNotNull; /** * Binding module for injections related to the HTTP server and the default set of servlets. * * This module uses a single command line argument 'http_port'. If unset, the HTTP server will * be started on an ephemeral port. * * The default HTTP server includes several generic servlets that are useful for debugging. * * This class also offers several convenience methods for other modules to register HTTP servlets * which will be included in the HTTP server configuration. * * Bindings provided by this module: * <ul> * <li>{@code @CacheTemplates boolean} - True if parsed stringtemplates for servlets are cached. * </ul> */ public class HttpModule extends AbstractModule { @Range(lower = 0, upper = 65535) @CmdLine(name = "http_port", help = "The port to start an HTTP server on. Default value will choose a random port.") protected static final Arg<Integer> HTTP_PORT = Arg.create(0); @CmdLine(name = "http_primary_service", help = "True if HTTP is the primary service.") protected static final Arg<Boolean> HTTP_PRIMARY_SERVICE = Arg.create(false); @NotEmpty @CmdLine(name = "http_announce_port_names", help = "Names to identify the HTTP port with when advertising the service.") protected static final Arg<Set<String>> ANNOUNCE_NAMES = Arg.<Set<String>>create(ImmutableSet.of("http")); private static final Logger LOG = Logger.getLogger(HttpModule.class.getName()); // TODO(William Farner): Consider making this configurable if needed. private static final boolean CACHE_TEMPLATES = true; private static class DefaultAbortHandler implements Runnable { @Override public void run() { LOG.info("ABORTING PROCESS IMMEDIATELY!"); System.exit(0); } } private static class DefaultHealthChecker implements Supplier<Boolean> { @Override public Boolean get() { return Boolean.TRUE; } } private final Key<? extends Runnable> abortHandler; private final Key<? extends Runnable> quitHandlerKey; private final Key<? extends ExceptionalSupplier<Boolean, ?>> healthCheckerKey; public HttpModule() { this(builder()); } private HttpModule(Builder builder) { this.abortHandler = checkNotNull(builder.abortHandlerKey); this.quitHandlerKey = checkNotNull(builder.quitHandlerKey); this.healthCheckerKey = checkNotNull(builder.healthCheckerKey); } /** * Creates a builder to override default bindings. * * @return A new builder. */ public static Builder builder() { return new Builder(); } /** * Builder to customize bindings. */ public static class Builder { private Key<? extends Runnable> abortHandlerKey = Key.get(DefaultAbortHandler.class); private Key<? extends Runnable> quitHandlerKey = Key.get(DefaultQuitHandler.class); private Key<? extends ExceptionalSupplier<Boolean, ?>> healthCheckerKey = Key.get(DefaultHealthChecker.class); /** * Specifies a custom abort handler to be invoked when an HTTP abort signal is received. * * @param key Abort callback handler binding key. * @return A reference to this builder. */ public Builder abortHandler(Key<? extends Runnable> key) { this.abortHandlerKey = key; return this; } /** * Specifies a custom quit handler to be invoked when an HTTP quit signal is received. * * @param key Quit callback handler binding key. * @return A reference to this builder. */ public Builder quitHandler(Key<? extends Runnable> key) { this.quitHandlerKey = key; return this; } /** * Specifies a custom health checker to control responses to HTTP health checks. * * @param key Health check callback binding key. * @return A reference to this builder. */ public Builder healthChecker(Key<? extends ExceptionalSupplier<Boolean, ?>> key) { this.healthCheckerKey = key; return this; } /** * Constructs an http module. * * @return An http module constructed from this builder. */ public HttpModule build() { return new HttpModule(this); } } @Override protected void configure() { requireBinding(Injector.class); requireBinding(ShutdownRegistry.class); bind(Runnable.class) .annotatedWith(Names.named(AbortHandler.ABORT_HANDLER_KEY)) .to(abortHandler); bind(abortHandler).in(Singleton.class); bind(Runnable.class).annotatedWith(Names.named(QuitHandler.QUIT_HANDLER_KEY)) .to(quitHandlerKey); bind(quitHandlerKey).in(Singleton.class); bind(new TypeLiteral<ExceptionalSupplier<Boolean, ?>>() { }) .annotatedWith(Names.named(HealthHandler.HEALTH_CHECKER_KEY)) .to(healthCheckerKey); bind(healthCheckerKey).in(Singleton.class); // Allow template reloading in interactive mode for easy debugging of string templates. bindConstant().annotatedWith(CacheTemplates.class).to(CACHE_TEMPLATES); bind(HttpServerDispatch.class).to(JettyHttpServerDispatch.class) .in(Singleton.class); bind(RequestLog.class).to(RequestLogger.class); Registration.registerServlet(binder(), "/abortabortabort", AbortHandler.class, true); Registration.registerServlet(binder(), "/contention", ContentionPrinter.class, false); Registration.registerServlet(binder(), "/graphdata", TimeSeriesDataSource.class, true); Registration.registerServlet(binder(), "/health", HealthHandler.class, true); Registration.registerServlet(binder(), "/healthz", HealthHandler.class, true); Registration.registerServlet(binder(), "/logconfig", LogConfig.class, false); Registration.registerServlet(binder(), "/logs", LogPrinter.class, false); Registration.registerServlet(binder(), "/pprof/heap", HeapProfileHandler.class, false); Registration.registerServlet(binder(), "/pprof/profile", CpuProfileHandler.class, false); Registration.registerServlet( binder(), "/pprof/contention", ContentionProfileHandler.class, false); Registration.registerServlet(binder(), "/quitquitquit", QuitHandler.class, true); Registration.registerServlet(binder(), "/threads", ThreadStackPrinter.class, false); Registration.registerServlet(binder(), "/vars", VarsHandler.class, false); Registration.registerServlet(binder(), "/vars.json", VarsJsonHandler.class, false); GraphViewer.registerResources(binder()); LifecycleModule.bindServiceRunner(binder(), HttpServerLauncher.class); // Ensure at least an empty filter set is bound. Registration.getFilterBinder(binder()); // Ensure at least an empty set of additional links is bound. Registration.getEndpointBinder(binder()); } public static final class HttpServerLauncher implements ServiceRunner { private final HttpServerDispatch httpServer; private final Set<HttpServletConfig> httpServlets; private final Set<HttpAssetConfig> httpAssets; private final Set<HttpFilterConfig> httpFilters; private final Set<String> additionalIndexLinks; private final Injector injector; @Inject HttpServerLauncher( HttpServerDispatch httpServer, Set<HttpServletConfig> httpServlets, Set<HttpAssetConfig> httpAssets, Set<HttpFilterConfig> httpFilters, @IndexLink Set<String> additionalIndexLinks, Injector injector) { this.httpServer = checkNotNull(httpServer); this.httpServlets = checkNotNull(httpServlets); this.httpAssets = checkNotNull(httpAssets); this.httpFilters = checkNotNull(httpFilters); this.additionalIndexLinks = checkNotNull(additionalIndexLinks); this.injector = checkNotNull(injector); } @Override public LocalService launch() { if (!httpServer.listen(HTTP_PORT.get())) { throw new IllegalStateException("Failed to start HTTP server, all servlets disabled."); } httpServer.registerListener(new GuiceServletContextListener() { @Override protected Injector getInjector() { return injector; } }); httpServer.registerFilter(GuiceFilter.class, "/*"); for (HttpServletConfig config : httpServlets) { HttpServlet handler = injector.getInstance(config.handlerClass); httpServer.registerHandler(config.path, handler, config.params, config.silent); } for (HttpAssetConfig config : httpAssets) { httpServer.registerHandler(config.path, config.handler, null, config.silent); } for (HttpFilterConfig filter : httpFilters) { httpServer.registerFilter(filter.filterClass, filter.pathSpec); } for (String indexLink : additionalIndexLinks) { httpServer.registerIndexLink(indexLink); } Command shutdown = new Command() { @Override public void execute() { LOG.info("Shutting down embedded http server"); httpServer.stop(); } }; return HTTP_PRIMARY_SERVICE.get() ? LocalService.primaryService(httpServer.getPort(), shutdown) : LocalService.auxiliaryService(ANNOUNCE_NAMES.get(), httpServer.getPort(), shutdown); } } }
39.48495
99
0.739878
6c2cf73cbfe4f41a697f4aa66e2e6b45a95bb18a
2,014
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Spielfigur here. * * @author (your name) * @version (a version number or a date) */ public class Spielfigur extends Actor { /** * Act - do whatever the Spielfigur wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public Spielfigur(){ this.getImage().scale(40,40); } public void act() { movement(); } // Klasse movement steuert die Figur und prüft Kollision mit Klasse Bloecke public void movement(){ Actor ObenRechts = getOneObjectAtOffset(1, -2, Bloecke.class); Actor ObenLinks = getOneObjectAtOffset(-1, -2, Bloecke.class); Actor UntenRechts = getOneObjectAtOffset(1, 2, Bloecke.class); Actor UntenLinks = getOneObjectAtOffset(-1, 2, Bloecke.class); Actor LinksOben = getOneObjectAtOffset(-2, -1, Bloecke.class); Actor LinksUnten = getOneObjectAtOffset(-2, 1, Bloecke.class); Actor RechtsOben = getOneObjectAtOffset(2, -1, Bloecke.class); Actor RechtsUnten = getOneObjectAtOffset(2, 1, Bloecke.class); if(Greenfoot.isKeyDown("up") && ObenRechts == null && ObenLinks == null) { this.setLocation(this.getX(), this.getY()-1); } if(Greenfoot.isKeyDown("down") && UntenRechts == null && UntenLinks == null) { this.setLocation(this.getX(), this.getY()+1); } if(Greenfoot.isKeyDown("left") && LinksOben == null && LinksUnten == null) { this.setLocation(this.getX()-1, this.getY()); } if(Greenfoot.isKeyDown("right") && RechtsOben == null && RechtsUnten == null) { this.setLocation(this.getX()+1, this.getY()); } if(Greenfoot.isKeyDown("space")){ this.getWorld().addObject(new Bombe(), this.getX(), this.getY()); } } }
37.296296
87
0.602284
1aa676ad976cc04610016f38fea5673b36f97884
6,317
/* * Copyright [2021-2021] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.ahoo.cosky.config.redis; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import lombok.extern.slf4j.Slf4j; import me.ahoo.cosky.config.*; import me.ahoo.cosky.core.listener.MessageListenable; import me.ahoo.cosky.core.listener.MessageListener; import reactor.core.publisher.Mono; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; /** * @author ahoo wang */ @Slf4j public class ConsistencyRedisConfigService implements ConfigService, ConfigListenable { private final ConfigService delegate; private final MessageListenable messageListenable; private final ConfigListener configListener; private final ConcurrentHashMap<NamespacedConfigId, Mono<Config>> configMap; private final ConcurrentHashMap<NamespacedConfigId, CopyOnWriteArraySet<ConfigChangedListener>> configMapListener; public ConsistencyRedisConfigService(ConfigService delegate, MessageListenable messageListenable) { this.configMap = new ConcurrentHashMap<>(); this.configMapListener = new ConcurrentHashMap<>(); this.delegate = delegate; this.messageListenable = messageListenable; this.configListener = new ConfigListener(); } @Override public Mono<Set<String>> getConfigs(String namespace) { return delegate.getConfigs(namespace); } @Override public Mono<Config> getConfig(String namespace, String configId) { Preconditions.checkArgument(!Strings.isNullOrEmpty(namespace), "namespace can not be empty!"); Preconditions.checkArgument(!Strings.isNullOrEmpty(configId), "configId can not be empty!"); return configMap.computeIfAbsent(NamespacedConfigId.of(namespace, configId), (_configId) -> { addListener(namespace, configId); return delegate.getConfig(namespace, configId).cache(); } ); } private void addListener(String namespace, String configId) { String topicStr = ConfigKeyGenerator.getConfigKey(namespace, configId); messageListenable.addChannelListener(topicStr, configListener); } @Override public Mono<Boolean> setConfig(String namespace, String configId, String data) { return delegate.setConfig(namespace, configId, data); } @Override public Mono<Boolean> removeConfig(String configId) { return delegate.removeConfig(configId); } @Override public Mono<Boolean> removeConfig(String namespace, String configId) { return delegate.removeConfig(namespace, configId); } @Override public Mono<Boolean> containsConfig(String namespace, String configId) { return delegate.containsConfig(namespace, configId); } @Override public void addListener(NamespacedConfigId namespacedConfigId, ConfigChangedListener configChangedListener) { configMapListener.compute(namespacedConfigId, (key, val) -> { CopyOnWriteArraySet<ConfigChangedListener> listeners = val; if (Objects.isNull(val)) { addListener(namespacedConfigId.getNamespace(), namespacedConfigId.getConfigId()); listeners = new CopyOnWriteArraySet<>(); } listeners.add(configChangedListener); return listeners; }); } @Override public void removeListener(NamespacedConfigId namespacedConfigId, ConfigChangedListener configChangedListener) { configMapListener.compute(namespacedConfigId, (key, val) -> { if (Objects.isNull(val)) { return null; } val.remove(configChangedListener); if (val.isEmpty()) { return null; } return val; }); } @Override public Mono<Boolean> rollback(String configId, int targetVersion) { return delegate.rollback(configId, targetVersion); } @Override public Mono<Boolean> rollback(String namespace, String configId, int targetVersion) { return delegate.rollback(namespace, configId, targetVersion); } @Override public Mono<List<ConfigVersion>> getConfigVersions(String namespace, String configId) { return delegate.getConfigVersions(namespace, configId); } @Override public Mono<ConfigHistory> getConfigHistory(String namespace, String configId, int version) { return delegate.getConfigHistory(namespace, configId, version); } private class ConfigListener implements MessageListener { @Override public void onMessage(@Nullable String pattern, String channel, String message) { if (log.isInfoEnabled()) { log.info("onMessage@ConfigListener - pattern:[{}] - channel:[{}] - message:[{}]", pattern, channel, message); } final String configkey = channel; NamespacedConfigId namespacedConfigId = ConfigKeyGenerator.getConfigIdOfKey(configkey); configMap.put(namespacedConfigId, delegate.getConfig(namespacedConfigId.getNamespace(), namespacedConfigId.getConfigId()).cache()); CopyOnWriteArraySet<ConfigChangedListener> configChangedListeners = configMapListener.get(namespacedConfigId); if (Objects.isNull(configChangedListeners) || configChangedListeners.isEmpty()) { return; } configChangedListeners.forEach(configChangedListener -> configChangedListener.onChange(namespacedConfigId, message)); } } }
38.993827
143
0.701915
ee4d6d8a0902d31dfe25724594d2d7587393d7c4
726
package com.orion.lang.io; import java.io.OutputStream; /** * 输出流到 /dev/null * * @author Jiahang Li * @version 1.0.0 * @since 2020/10/31 15:48 */ public class IgnoreOutputStream extends OutputStream { public static final IgnoreOutputStream OUT = new IgnoreOutputStream(); /** * write to /dev/null * * @param bs bs * @param off offset * @param len length */ @Override public void write(byte[] bs, int off, int len) { } /** * write to /dev/null * * @param b b */ @Override public void write(int b) { } /** * write to /dev/null * * @param bs bs */ @Override public void write(byte[] bs) { } }
15.782609
74
0.546832
a35ea26ccbaff4267153e4a02c52f8cbb950b6d9
4,499
package appearances; import org.jogamp.java3d.Appearance; import org.jogamp.java3d.ImageComponent2D; import org.jogamp.java3d.Texture; import org.jogamp.java3d.Texture2D; import org.jogamp.java3d.TextureAttributes; import org.jogamp.java3d.Transform3D; import org.jogamp.java3d.utils.image.ImageException; import org.jogamp.java3d.utils.image.TextureLoader; import org.jogamp.vecmath.Color3f; /** * Subclass of appearance that is initialized with a texture * using the given image as the texture image. */ public class TexturedAppearance extends Appearance { /** Texture image to use as a backup */ private static String backupImage = "NoTexture.png"; /** Name of the texture image used */ private String texName; /** Scale of the texture image when applying it */ private float scale; /** Rotation of the texture image when applying it */ private float rotation; /** Default constructor, uses the backup texture image */ public TexturedAppearance () { this("NoTexture.png"); } /** * Overloaded constructor. Defaults scale to 1.0 and rotation to 0.0 * @param textureName Name of texture image to use */ public TexturedAppearance (String textureName) { this(textureName, 1.0f, 0.0f); } /** * Overloaded constructor. Defaults rotation to 0.0 * @param textureName Name of texture image to use * @param scale Multiplier scale of image when projecting */ public TexturedAppearance (String textureName, float scale) { this(textureName, scale, 0.0f); } /** * Full constructor. Creates an appearance initialized * with a texture using the given paramaters. * @param textureName Name of texture image to use * @param scale Multiplier scale of image when projecting * @param rotation Radiand rotation of image when projecting */ public TexturedAppearance (String textureName, float scale, float rotation) { super(); this.texName = textureName; this.scale = scale; this.rotation = rotation; this.setTexture(loadTexture(textureName)); this.setTextureAttributes(newTextureAttributes(scale, rotation)); this.setMaterial(MaterialFactory.createMaterial(new Color3f(0.5f, 0.5f, 0.5f))); } /** * Returns the name of the texture image being used * @return The name of the texture image being used */ public String getName() { return this.texName; } /** * Gets the current image scale being used * @return Scale multiplier of the image */ public float getScale() { return this.scale; } /** * Gets the current image rotation being used * @return Radians rotation of the image */ public float getRotation() { return this.rotation; } /** * Creates a texture attributes object for modifying texture objects * @param scale Multiplier to scale your texture by * @param rotation Radians to rotaate your texture by * @return The newly created TextureAttributes object */ public static TextureAttributes newTextureAttributes (float scale, float rotation) { TextureAttributes ta = new TextureAttributes(); Transform3D trans = new Transform3D(); ta.setTextureMode(TextureAttributes.REPLACE); trans.setScale(scale); trans.rotY(rotation); ta.setTextureTransform(trans); return ta; } /** * Creates a 2D texture object from the given image file name * @param fileName The name, with extension, of the image file to use * @return The newly created Texture2D object */ public static Texture2D loadTexture (String fileName) { String filePath = "assets/images/" + fileName; TextureLoader loader ; try { loader = new TextureLoader(filePath, null); } catch (ImageException e) { if (fileName.equals(backupImage)) { e.printStackTrace(System.err); return null; } else { System.err.println("Failed to open texture image: "+fileName); return loadTexture(backupImage); } } ImageComponent2D image = loader.getImage(); Texture2D texture = new Texture2D( Texture.BASE_LEVEL, Texture.RGBA, image.getWidth(), image.getHeight() ); texture.setImage(0, image); return texture; } }
35.148438
99
0.657479
d282649fc41acd575959ea42ddfda84e07f20f24
618
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package particles; /** * * @author crist */ public class ParticlesTexture { private int textureID; private int numberOfRows; public ParticlesTexture(int textureID, int numberOfRows) { this.textureID = textureID; this.numberOfRows = numberOfRows; } public int getTextureID() { return textureID; } public int getNumberOfRows() { return numberOfRows; } }
19.935484
79
0.661812
afa8665b939d2fcab0743cdc3d90b02a700896fb
5,020
package com.genexus.cloud.serverless.aws; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.ws.rs.core.Application; import com.amazonaws.serverless.proxy.internal.servlet.AwsHttpServletResponse; import com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest; import com.amazonaws.serverless.proxy.internal.servlet.AwsServletContext; import com.genexus.specific.java.LogManager; import com.genexus.webpanels.GXObjectUploadServices; import com.genexus.webpanels.GXWebObjectStub; import org.glassfish.jersey.server.ResourceConfig; import com.amazonaws.serverless.proxy.jersey.JerseyLambdaContainerHandler; import com.amazonaws.serverless.proxy.model.AwsProxyRequest; import com.amazonaws.serverless.proxy.model.AwsProxyResponse; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.genexus.ApplicationContext; import com.genexus.diagnostics.core.ILogger; import com.genexus.util.IniFile; import com.genexus.webpanels.*; import java.util.Enumeration; import java.util.concurrent.CountDownLatch; import com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletResponseWriter; public class LambdaHandler implements RequestHandler<AwsProxyRequest, AwsProxyResponse> { private static ILogger logger = null; public static JerseyLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler = null; private static ResourceConfig jerseyApplication = null; private static final String BASE_REST_PATH = "/rest/"; public LambdaHandler() throws Exception { if (LambdaHandler.jerseyApplication == null) { LambdaHandler.jerseyApplication = ResourceConfig.forApplication(initialize()); if (jerseyApplication.getClasses().size() == 0) { String errMsg = "No endpoints found for this application"; logger.error(errMsg); throw new Exception(errMsg); } LambdaHandler.handler = JerseyLambdaContainerHandler.getAwsProxyHandler(LambdaHandler.jerseyApplication); } } public AwsProxyResponse handleRequest(AwsProxyRequest awsProxyRequest, Context context) { String path = awsProxyRequest.getPath(); if (!path.contains(BASE_REST_PATH)) { return handleServletRequest(awsProxyRequest, context); } else { awsProxyRequest.setPath(path.replace(BASE_REST_PATH, "/")); return this.handler.proxy(awsProxyRequest, context); } } private AwsProxyResponse handleServletRequest(AwsProxyRequest awsProxyRequest, Context context) { try { GXWebObjectStub servlet = resolveServlet(awsProxyRequest); if (servlet != null) { CountDownLatch latch = new CountDownLatch(0); ServletContext servletContext = new AwsServletContext(null);//AwsServletContext.getInstance(lambdaContext, null); AwsProxyHttpServletRequest servletRequest = new AwsProxyHttpServletRequest(awsProxyRequest, context, null); servlet.init(new ServletConfig() { @Override public String getServletName() { return ""; } @Override public ServletContext getServletContext() { return servletContext; } @Override public String getInitParameter(String s) { return ""; } @Override public Enumeration<String> getInitParameterNames() { return null; } }); AwsHttpServletResponse response = new AwsHttpServletResponse(servletRequest, latch); servletRequest.setServletContext(servletContext); servlet.service(servletRequest, response); return new AwsProxyHttpServletResponseWriter().writeResponse(response, context); } else { return new AwsProxyResponse(404); } } catch (Exception e) { logger.error("Error processing servlet request", e); } return new AwsProxyResponse(500); } private GXWebObjectStub resolveServlet(AwsProxyRequest awsProxyRequest) { //TODO: Use web.xml catalog to obtain Handler Class Name to instantiate. GXWebObjectStub handler = null; String path = awsProxyRequest.getPath(); switch (path) { case "/oauth/access_token": handler = new GXOAuthAccessToken(); break; case "/oauth/logout": handler = new GXOAuthLogout(); break; case "/oauth/userinfo": handler = new GXOAuthUserInfo(); break; default: logger.error("Could not handle Servlet Path: " + path); } return handler; } private static Application initialize() throws Exception { logger = LogManager.initialize(".", LambdaHandler.class); IniFile config = com.genexus.ConfigFileFinder.getConfigFile(null, "client.cfg", null); String className = config.getProperty("Client", "PACKAGE", null); Class<?> cls; try { cls = Class.forName(className + ".GXApplication"); Application app = (Application) cls.newInstance(); ApplicationContext appContext = ApplicationContext.getInstance(); appContext.setServletEngine(true); appContext.setServletEngineDefaultPath(""); com.genexus.Application.init(cls); return app; } catch (Exception e) { logger.error("Failed to initialize App", e); throw e; } } }
36.376812
117
0.764741
c5fda88fa3bd7bd0b22ef1beeeb3a8f73f7b4668
454
package scheduling; import process.Process; import java.util.List; public class Priority implements SchedulingAlgorithm { @Override public void schedule(List<Process> processes) { processes.sort((process1, process2) -> { if (process1.getPriority() == process2.getPriority()) return 0; else return (process1.getPriority() < process2.getPriority() ? -1 : 1); }); } }
22.7
82
0.605727
08d642e3f659d34c9cffdd9a1491951ce871c771
1,232
package com.leyou.item.pojo; import lombok.Data; import tk.mybatis.mapper.annotation.KeySql; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; @Data @Table(name = "tb_spu") public class Spu { @Id @KeySql(useGeneratedKeys=true) private Long id; private Long brandId; private Long cid1;// 1级类目 private Long cid2;// 2级类目 private Long cid3;// 3级类目 private String title;// 标题 private String subTitle;// 子标题 private Boolean saleable;// 是否上架 private Boolean valid;// 是否有效,逻辑删除用 private Date createTime;// 创建时间 private Date lastUpdateTime;// 最后修改时间 public Spu() { } public Spu(Long brandId, Long cid1, Long cid2, Long cid3, String title, String subTitle, Boolean saleable, Boolean valid, Date createTime, Date lastUpdateTime) { this.brandId = brandId; this.cid1 = cid1; this.cid2 = cid2; this.cid3 = cid3; this.title = title; this.subTitle = subTitle; this.saleable = saleable; this.valid = valid; this.createTime = createTime; this.lastUpdateTime = lastUpdateTime; } }
26.782609
165
0.67776
7005233f1882e4636e9c1badbf186f532ae9cf00
275
package com.sparta.pages; import org.openqa.selenium.WebDriver; //----------------- incomplete public abstract class SearchPageModelAbstract extends PageModelAbstract { public SearchPageModelAbstract(WebDriver webDriver) { super(webDriver); } }
22.916667
74
0.690909
2ef03fbc1167de9cb7628fc9f17f9d4569965840
2,035
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package scouter.lang.value; import java.io.IOException; import scouter.io.DataInputX; import scouter.io.DataOutputX; public class FloatValue extends NumberValue implements Value, Comparable { public float value; public FloatValue() { } public FloatValue(float value) { this.value = value; } public int compareTo(Object o) { if (o instanceof FloatValue) { return Float.compare(this.value, ((FloatValue) o).value); } return 1; } public boolean equals(Object o) { if (o instanceof FloatValue) { return this.value == ((FloatValue) o).value; } return false; } public int hashCode() { return Float.floatToIntBits(value); } public byte getValueType() { return ValueEnum.FLOAT; } public void write(DataOutputX out) throws IOException { out.writeFloat(value); } public Value read(DataInputX in) throws IOException { this.value = in.readFloat(); return this; } public String toString() { return Float.toString(value); } // //////////////////////////////// public double doubleValue() { return value; } public float floatValue() { return (float) value; } public int intValue() { return (int) value; } public long longValue() { return (long) value; } public Object toJavaObject() { return this.value; } }
21.648936
76
0.667322
8599291e4f627594579206fc0260d23b0c1ca7fc
792
package red.honey.oss.api.constant; import lombok.AllArgsConstructor; import java.io.Serializable; /** * @author yangzhijie * @date 2020/10/12 10:51 */ @AllArgsConstructor public enum CallbackEnum implements Serializable { /** * rest http 回调 */ REST(0, "HTTP REST 回调"); private int code; private String desc; public static CallbackEnum getByCode(int code) { CallbackEnum[] values = CallbackEnum.values(); for (CallbackEnum value : values) { if (value.code == code) { return value; } } throw new IllegalArgumentException("the code of callbackEnum not found"); } public int getCode() { return code; } public String getDesc() { return desc; } }
19.317073
81
0.602273
ba453d5738878b95e0d89919e586e1c26cb998b8
299
package org.ms.api.wrappers; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; @SuperBuilder @Data @NoArgsConstructor public class ApiPaginationRequest { private Integer pageNumber; private Integer pageSize; private Integer totalCount; }
16.611111
40
0.795987
a12012ae58e4ece185723459e572042c92a3a64f
17,108
package com.openshamba.watchdog; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.support.constraint.ConstraintLayout; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.karumi.dexter.Dexter; import com.karumi.dexter.MultiplePermissionsReport; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.DexterError; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.PermissionRequestErrorListener; import com.karumi.dexter.listener.multi.MultiplePermissionsListener; import com.karumi.dexter.listener.single.PermissionListener; import com.openshamba.watchdog.fragments.CallFragment; import com.openshamba.watchdog.fragments.DataFragment; import com.openshamba.watchdog.fragments.FragmentAdapter; import com.openshamba.watchdog.fragments.SMSFragment; import com.openshamba.watchdog.services.CallLoggerService; import com.openshamba.watchdog.services.SmsLoggerService; import com.openshamba.watchdog.utils.Constants; import com.openshamba.watchdog.utils.CustomApplication; import com.openshamba.watchdog.utils.MobileUtils; import com.openshamba.watchdog.utils.SessionManager; import com.openshamba.watchdog.utils.Tools; import java.util.List; public class MainActivity extends BaseActivity { private ActionBarDrawerToggle mDrawerToggle; private Toolbar toolbar; private AppBarLayout appBarLayout; private DrawerLayout drawerLayout; //public FloatingActionButton fab; private Toolbar searchToolbar; private ViewPager viewPager; private View parent_view; private CallFragment f_call; private SMSFragment f_sms; private DataFragment f_data; private TextView email,username; public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469; private boolean isSearch = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); parent_view = findViewById(R.id.main_content); if(!isSystemAlertPermissionGranted(getApplicationContext())){ askSystemAlertPermission(MainActivity.this,ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE); } if(!CustomApplication.isMyServiceRunning(CallLoggerService.class)){ Intent startIntent = new Intent(getApplicationContext(), CallLoggerService.class); startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION); startService(startIntent); } checkAuth(); setupDrawerLayout(); initComponent(); prepareActionBar(toolbar); if (viewPager != null) { setupViewPager(viewPager); } initAction(); // for system bar in lollipop Tools.systemBarLolipop(this); setUpSIM(); } public static void askSystemAlertPermission(Activity context, int requestCode) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return; final String packageName = context == null ? context.getPackageName() : context.getPackageName(); final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + packageName)); if (context != null) context.startActivityForResult(intent, requestCode); else context.startActivityForResult(intent, requestCode); } public void requestSystemAlertPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE); } } } @TargetApi(23) public static boolean isSystemAlertPermissionGranted(Context context) { boolean result; if(Build.VERSION.SDK_INT >= 23) { result = Settings.canDrawOverlays(context); }else{ // another similar method that supports device have API < 23 result = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP; } return result; } private void showSettingsDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Need Permissions"); builder.setMessage("This app needs permission to use this feature. You can grant them in app settings."); builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); openSettings(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } // navigating user to app settings private void openSettings() { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 101); } @TargetApi(Build.VERSION_CODES.M) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) { if (!Settings.canDrawOverlays(this)) { // You don't have permission requestSystemAlertPermission(); //showSettingsDialog(); } else { Snackbar.make(parent_view,"Permission granted!!",Snackbar.LENGTH_LONG).show(); Log.d("NIMZYMAINA","Permission Granted"); } } } private void setUpSIM(){ Dexter.withActivity(this) .withPermission(Manifest.permission.READ_PHONE_STATE) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { CustomApplication.setUp(getApplicationContext()); //Snackbar.make(parent_view,"Setup complete",Snackbar.LENGTH_LONG).show(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { showSettingsDialog(); } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { token.continuePermissionRequest(); } }).check(); } public void setVisibilityAppBar(boolean visible){ CoordinatorLayout.LayoutParams layout_visible = new CoordinatorLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); CoordinatorLayout.LayoutParams layout_invisible = new CoordinatorLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0); if(visible){ appBarLayout.setLayoutParams(layout_visible); //fab.show(); }else{ appBarLayout.setLayoutParams(layout_invisible); //fab.hide(); } } private void settingDrawer() { mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; // Set the drawer toggle as the DrawerListener drawerLayout.setDrawerListener(mDrawerToggle); } private void setupDrawerLayout() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); NavigationView view = (NavigationView) findViewById(R.id.nav_view); View header = view.getHeaderView(0); username = (TextView) header.findViewById(R.id.usernameNav); username.setText(session.getKeyFname()+ " " + session.getKeyLname()); view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { menuItem.setChecked(true); drawerLayout.closeDrawers(); Snackbar.make(parent_view, menuItem.getTitle()+" Clicked ", Snackbar.LENGTH_SHORT).show(); return true; } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (!isSearch) { mDrawerToggle.onConfigurationChanged(newConfig); } } private void initComponent() { toolbar = (Toolbar) findViewById(R.id.toolbar_viewpager); appBarLayout = (AppBarLayout) findViewById(R.id.app_bar_layout); searchToolbar = (Toolbar) findViewById(R.id.toolbar_search); //fab = (FloatingActionButton) findViewById(R.id.fab); viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setOffscreenPageLimit(2); } private void prepareActionBar(Toolbar toolbar) { setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); if (!isSearch) { settingDrawer(); } } private void setupViewPager(ViewPager viewPager) { FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager()); if(f_call == null) f_call = new CallFragment(); if(f_sms == null) f_sms = new SMSFragment(); if(f_data == null) f_data = new DataFragment(); adapter.addFragment(f_sms,getString(R.string.tab_sms)); adapter.addFragment(f_call,getString(R.string.tab_call)); adapter.addFragment(f_data,getString(R.string.tab_data)); viewPager.setAdapter(adapter); } private void initAction() { TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { //closeSearch(); viewPager.setCurrentItem(tab.getPosition()); switch (tab.getPosition()) { case 0: //fab.setImageResource(R.drawable.ic_add_friend); break; case 1: //fab.setImageResource(R.drawable.ic_create); break; case 2: //fab.setImageResource(R.drawable.ic_add_group); break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); viewPager.setCurrentItem(1); } private void closeSearch() { if (isSearch) { isSearch = false; if (viewPager.getCurrentItem() == 0) { f_sms.mAdapter.getFilter().filter(""); } else { f_call.mAdapter.getFilter().filter(""); } prepareActionBar(toolbar); searchToolbar.setVisibility(View.GONE); supportInvalidateOptionsMenu(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(isSearch ? R.menu.menu_search_toolbar : R.menu.menu_main, menu); if (isSearch) { //Toast.makeText(getApplicationContext(), "Search " + isSearch, Toast.LENGTH_SHORT).show(); final SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView(); search.setIconified(false); switch (viewPager.getCurrentItem()) { case 0: search.setQueryHint("Search sms..."); break; case 1: search.setQueryHint("Search calls..."); break; case 2: search.setQueryHint("Search data..."); break; } search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { switch (viewPager.getCurrentItem()) { case 0: f_sms.mAdapter.getFilter().filter(s); break; case 1: f_call.mAdapter.getFilter().filter(s); break; case 2: //f_data.mAdapter.getFilter().filter(s); break; } return true; } }); search.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { closeSearch(); return true; } }); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_search: { isSearch = true; searchToolbar.setVisibility(View.VISIBLE); prepareActionBar(searchToolbar); supportInvalidateOptionsMenu(); return true; } case android.R.id.home: { closeSearch(); return true; } case R.id.action_notif: { Snackbar.make(parent_view, "Notifications Clicked", Snackbar.LENGTH_SHORT).show(); return true; } case R.id.action_logout: { logoutUser(); return true; } default: return super.onOptionsItemSelected(item); } } private long exitTime = 0; public void doExitApp() { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(this, R.string.press_again_exit_app, Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); } } @Override public void onBackPressed() { doExitApp(); } }
37.030303
171
0.625263
a9931748ab265eaf4bea63a625dcb725c93dfde4
7,154
package org.sv.flexobject.hadoop.streaming.parquet; import com.fasterxml.jackson.databind.JsonNode; import org.apache.hadoop.conf.Configuration; import org.apache.parquet.schema.MessageType; import org.junit.Test; import org.sv.flexobject.hadoop.mapreduce.input.parquet.JsonParquetInputFormat; import org.sv.flexobject.hadoop.mapreduce.input.parquet.StreamableParquetInputFormat; import org.sv.flexobject.hadoop.mapreduce.output.parquet.JsonParquetOutputFormat; import org.sv.flexobject.hadoop.mapreduce.output.parquet.StreamableParquetOutputFormat; import org.sv.flexobject.testdata.TestDataWithSubSchema; import org.sv.flexobject.testdata.TestDataWithSubSchemaInCollection; import static org.junit.Assert.*; public class ParquetSchemaConfTest { @Test public void writesToConfigurationClasses() throws Exception { ParquetSchemaConf parquetConf = new ParquetSchemaConf(); assertFalse(parquetConf.hasInputSchema()); assertFalse(parquetConf.hasOutputSchema()); assertFalse(parquetConf.hasFilterPredicate()); assertSame(JsonParquetInputFormat.class, parquetConf.getInputFormat()); assertSame(JsonParquetOutputFormat.class, parquetConf.getOutputFormat()); assertSame(JsonNode.class, parquetConf.getOutputClass()); parquetConf.setInputSchemaClass(TestDataWithSubSchema.class); assertTrue(parquetConf.hasInputSchema()); assertFalse(parquetConf.hasOutputSchema()); parquetConf.setOutputSchemaClass(TestDataWithSubSchemaInCollection.class); assertTrue(parquetConf.hasInputSchema()); assertTrue(parquetConf.hasOutputSchema()); assertSame(StreamableParquetInputFormat.class, parquetConf.getInputFormat()); assertSame(StreamableParquetOutputFormat.class, parquetConf.getOutputFormat()); assertSame(TestDataWithSubSchemaInCollection.class, parquetConf.getOutputClass()); parquetConf.setFilterPredicate("{'eq':{'binary':'text','value':'foobar'}}".replace('\'', '"')); assertTrue(parquetConf.hasFilterPredicate()); assertEquals("eq(text, Binary{\"foobar\"})", parquetConf.getFilterPredicate().toString()); Configuration conf = new Configuration(false); parquetConf.update(conf); conf.writeXml(System.out); assertEquals(TestDataWithSubSchema.class.getName(), conf.get("sv.parquet.input.schema.class")); assertEquals(TestDataWithSubSchemaInCollection.class.getName(), conf.get("sv.parquet.output.schema.class")); assertNull(conf.get("sv.parquet.input.schema.json")); assertNull(conf.get("sv.parquet.output.schema.json")); assertEquals("{\"eq\":{\"binary\":\"text\",\"value\":\"foobar\"}}", conf.get("sv.parquet.filter.predicate.json")); ParquetSchemaConf parquetConf2 = new ParquetSchemaConf().from(conf); MessageType inputSchema = ParquetSchema.forClass(TestDataWithSubSchema.class); MessageType outputSchema = ParquetSchema.forClass(TestDataWithSubSchemaInCollection.class); assertEquals(inputSchema, parquetConf2.getInputSchema()); assertEquals(outputSchema, parquetConf2.getOutputSchema()); assertTrue(parquetConf2.hasInputSchema()); assertTrue(parquetConf2.hasOutputSchema()); assertSame(StreamableParquetInputFormat.class, parquetConf2.getInputFormat()); assertSame(StreamableParquetOutputFormat.class, parquetConf2.getOutputFormat()); assertSame(TestDataWithSubSchemaInCollection.class, parquetConf2.getOutputClass()); assertEquals("eq(text, Binary{\"foobar\"})", parquetConf2.getFilterPredicate().toString()); } @Test public void writesToConfigurationJson() throws Exception { ParquetSchemaConf parquetConf = new ParquetSchemaConf(); MessageType inputSchema = ParquetSchema.forClass(TestDataWithSubSchema.class); JsonNode inputSchemaJson = ParquetSchema.toJson(inputSchema); MessageType outputSchema = ParquetSchema.forClass(TestDataWithSubSchemaInCollection.class); JsonNode outputSchemaJson = ParquetSchema.toJson(outputSchema); assertFalse(parquetConf.hasInputSchema()); assertFalse(parquetConf.hasOutputSchema()); parquetConf.setInputSchemaJson(inputSchemaJson); assertTrue(parquetConf.hasInputSchema()); assertFalse(parquetConf.hasOutputSchema()); parquetConf.setOutputSchemaJson(outputSchemaJson); assertTrue(parquetConf.hasInputSchema()); assertTrue(parquetConf.hasOutputSchema()); assertSame(JsonParquetInputFormat.class, parquetConf.getInputFormat()); assertSame(JsonParquetOutputFormat.class, parquetConf.getOutputFormat()); assertSame(JsonNode.class, parquetConf.getOutputClass()); Configuration conf = new Configuration(false); parquetConf.update(conf); conf.writeXml(System.out); assertNull(conf.get("sv.parquet.input.schema.class")); assertNull(conf.get("sv.parquet.output.schema.class")); assertEquals(inputSchemaJson.toString(), conf.get("sv.parquet.input.schema.json")); assertEquals(outputSchemaJson.toString(), conf.get("sv.parquet.output.schema.json")); ParquetSchemaConf parquetConf2 = new ParquetSchemaConf().from(conf); assertEquals(inputSchema, parquetConf2.getInputSchema()); assertEquals(outputSchema, parquetConf2.getOutputSchema()); assertSame(JsonParquetInputFormat.class, parquetConf.getInputFormat()); assertSame(JsonParquetOutputFormat.class, parquetConf.getOutputFormat()); assertSame(JsonNode.class, parquetConf.getOutputClass()); } @Test public void overwritesToConfigurationJson() throws Exception { ParquetSchemaConf parquetConf = new ParquetSchemaConf(); MessageType inputSchema = ParquetSchema.forClass(TestDataWithSubSchema.class); JsonNode inputSchemaJson = ParquetSchema.toJson(inputSchema); MessageType outputSchema = ParquetSchema.forClass(TestDataWithSubSchemaInCollection.class); JsonNode outputSchemaJson = ParquetSchema.toJson(outputSchema); parquetConf.setInputSchemaJson(inputSchemaJson); parquetConf.setOutputSchemaJson(outputSchemaJson); Configuration conf = new Configuration(false); conf.set("dont.touch.that", "foobar"); parquetConf.update(conf); assertEquals("foobar", conf.get("dont.touch.that")); ParquetSchemaConf parquetConf2 = new ParquetSchemaConf(); parquetConf2.setInputSchemaClass(TestDataWithSubSchema.class); parquetConf2.setOutputSchemaClass(TestDataWithSubSchemaInCollection.class); parquetConf2.update(conf); conf.writeXml(System.out); assertEquals(TestDataWithSubSchema.class.getName(), conf.get("sv.parquet.input.schema.class")); assertEquals(TestDataWithSubSchemaInCollection.class.getName(), conf.get("sv.parquet.output.schema.class")); assertNull(conf.get("sv.parquet.input.schema.json")); assertNull(conf.get("sv.parquet.output.schema.json")); assertEquals("foobar", conf.get("dont.touch.that")); } }
45.566879
122
0.740984
e1a2e49620d08f0fa2633363995554d42ec165ad
7,733
package tonePkg; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.*; import javax.swing.JTextField; import javax.sound.sampled.*;; public class board { public static void launchMainWindow() throws IOException { tone usrTone = new tone(); JFrame frame = new JFrame(); final int FRAME_WIDTH = 800; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("ToneMonkey"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); panel.setBackground(Color.darkGray); BufferedImage testImage = ImageIO.read(new File("./testImage.png")); Image resizeTest = testImage.getScaledInstance(400, 150, Image.SCALE_SMOOTH); JLabel label = new JLabel(new ImageIcon(resizeTest)); c.gridx = 1; c.gridy = 0; panel.add(label, c); JButton enterFreq = new JButton("Enter Frequency"); enterFreq.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e1) { board.launchFreqWindow(usrTone); } }); c.gridx = 0; c.gridy = 1; panel.add(enterFreq, c); JButton plotAmp = new JButton("Plot Amplitude"); plotAmp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e1) { board.launchAmpWindow(usrTone); } }); c.gridx = 0; c.gridy = 2; panel.add(plotAmp, c); JButton selectWav = new JButton("Select .wav File"); selectWav.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e1) { board.launchSelectWindow(usrTone); } }); c.gridx = 2; c.gridy = 1; panel.add(selectWav, c); JButton plotFreq = new JButton("Plot Frequency"); plotFreq.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e1) { try { board.launchPlotWindow(usrTone); } catch (IOException e) { e.printStackTrace(); } } }); c.gridx = 2; c.gridy = 2; panel.add(plotFreq, c); JButton playTone = new JButton("Play Audio Tone"); playTone.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e1) { if(usrTone.getFileStatus()) { try { usrTone.playSound(); usrTone.setFileInactive(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if(usrTone.getFreqStatus()) { try { usrTone.playFreq(); } catch (LineUnavailableException e) { e.printStackTrace(); } } } }); c.gridx = 1; c.gridy = 3; panel.add(playTone, c); frame.add(panel); frame.setVisible(true); } public static void launchFreqWindow(tone usrTone) { JFrame freqFrame = new JFrame(); freqFrame.setSize(450, 250); freqFrame.setTitle("Frequency Input"); freqFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel freqPane = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); JTextField freqInput = new JTextField(5); JLabel freqLabel = new JLabel("Please enter the desired frequency in Hertz: ",JLabel.LEFT); c.weightx = 0.1; c.gridx = 0; c.gridy = 0; freqPane.add(freqLabel,c); c.gridx = 2; freqPane.add(freqInput, c); JButton enterBtn = new JButton("Enter"); enterBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e1) { String freqTextBox = freqInput.getText(); try { double freqCast = Double.parseDouble(freqTextBox); usrTone.setFreq(freqCast); //System.out.println(usrTone.getFreq()); usrTone.setFreqActive(); freqFrame.setVisible(false); } catch (Exception e) { Object[] options = { "OK" }; JOptionPane.showOptionDialog(null, "Only digits can be entered in this field", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); } } }); c.gridy = 1; c.gridx = 1; freqPane.add(enterBtn, c); freqPane.setBackground(Color.lightGray); freqFrame.add(freqPane); freqFrame.setVisible(true); } public static void launchAmpWindow(tone usrTone) { if(usrTone.getFileStatus() && usrTone.getFreqStatus()) { Object[] options = {"Use Frequency" , "Use File" }; int selection = JOptionPane.showOptionDialog(null, "Both a file and frequency have been input, select which to plot:", "Plot Selection", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if(selection == 0) { usrTone.plotAmpFreq(); } if(selection == 1) { try { usrTone.plotAmpFile(); } catch (IOException e) { e.printStackTrace(); } } } else if (usrTone.getFileStatus() && !usrTone.getFreqStatus()) { try { usrTone.plotAmpFile(); } catch (IOException e) { e.printStackTrace(); } } else if (!usrTone.getFileStatus() && usrTone.getFreqStatus()) { usrTone.plotAmpFreq(); } else { Object[] options = { "OK" }; JOptionPane.showOptionDialog(null, "Neither frequency or file has been activated.", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); } } public static void launchPlotWindow(tone usrTone) throws IOException { if(usrTone.getFileStatus() && usrTone.getFreqStatus()) { Object[] options = {"Use Frequency" , "Use File" }; int selection = JOptionPane.showOptionDialog(null, "Both a file and frequency have been input, select which to plot:", "Plot Selection", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if(selection == 0) { usrTone.plotUsrFreq(); } if(selection == 1) { usrTone.plotFileFreq(); } } else if (usrTone.getFileStatus() && !usrTone.getFreqStatus()) { try { usrTone.plotFileFreq(); //System.out.println("got to usrtone.plotFF"); } catch (IOException e) { e.printStackTrace(); } } else if (!usrTone.getFileStatus() && usrTone.getFreqStatus()) { usrTone.plotUsrFreq(); } else { Object[] options = { "OK" }; JOptionPane.showOptionDialog(null, "Neither frequency or file has been activated.", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); } } public static void launchSelectWindow(tone usrTone) { JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); FileNameExtensionFilter filter = new FileNameExtensionFilter("wave", "wav"); j.setFileFilter(filter); int returnValue = j.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File usrFile = j.getSelectedFile(); usrTone.setFile(usrFile); usrTone.setFileActive(); //System.out.println(usrFile.getAbsolutePath()); } } }
29.857143
122
0.65408
12df6c95d844fc4011ebbc0d0df7ad5900b8a04c
1,512
package com.ruoyi.project.duties.taskNotification.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.framework.web.domain.BaseEntity; /** * 消息表 tb_task_notification * * @author admin * @date 2019-04-29 */ public class TaskNotification extends BaseEntity { private static final long serialVersionUID = 1L; /** */ private Long id; /** 消息内容 */ private String msg; /** 通知id */ private Long notifyId; private String sqlWhere; private String msgtype; public String getMsgtype() { return msgtype; } public void setMsgtype(String msgtype) { this.msgtype = msgtype; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setMsg(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setNotifyId(Long notifyId) { this.notifyId = notifyId; } public Long getNotifyId() { return notifyId; } public String getSqlWhere() { return sqlWhere; } public void setSqlWhere(String sqlWhere) { this.sqlWhere = sqlWhere; } public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("msg", getMsg()) .append("notifyId", getNotifyId()) .append("createTime", getCreateTime()) .toString(); } }
19.139241
72
0.636243
c5b357eac3a656f37d3104339e2a9d11d6be6abe
554
package com.soccer.ws.service; import org.assertj.core.util.Lists; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class CSVServiceImplTest { private final CSVService csvService = new CSVServiceImpl(); @BeforeMethod public void setUp() { } @Test public void testWrite() { assertEquals("test,test\ntest1,test2", csvService.write(Lists.newArrayList(Lists.newArrayList("test", "test"), Lists.newArrayList("test1", "test2")))); } }
26.380952
159
0.729242
719a6a8423eb03c8de3753ec9297a2e0c519d535
806
package com.miya.pay; import com.miya.annotation.EnableMiyaLettuceRedis; import com.miya.annotation.MiyaCloudApplication; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; /** * @author Caixiaowei-zy */ @SpringBootApplication @EnableFeignClients @EnableMiyaLettuceRedis @MiyaCloudApplication public class MiyaPayApplication { public static void main(String[] args) { SpringApplication.run(MiyaPayApplication.class, args); } }
31
102
0.834988
34195785668522780f65ac967c58ee2fa9a9ac43
613
package org.jessenpan.leetcode.dp; import org.junit.Assert; import org.junit.Test; /** * @author jessenpan */ public class S746MinCostClimbingStairsTest { private S746MinCostClimbingStairs minCostClimbingStairs = new S746MinCostClimbingStairs(); @Test public void test1() { int c = minCostClimbingStairs.minCostClimbingStairs(new int[] { 10, 15, 20 }); Assert.assertEquals(15, c); } @Test public void test2() { int c = minCostClimbingStairs.minCostClimbingStairs(new int[] { 1, 100, 1, 1, 1, 100, 1, 1, 100, 1 }); Assert.assertEquals(6, c); } }
23.576923
110
0.665579
ba7ff0859c3af391dc1e11f110f0aaf257c5289f
3,542
package org.jbpm.process.migration.test; import java.util.ArrayList; import java.util.List; import org.assertj.core.api.Assertions; import org.jbpm.process.migration.RemoteTestBase; import org.junit.Test; import org.kie.api.runtime.manager.audit.ProcessInstanceLog; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.task.model.Task; public class AddTaskAfterActiveTest extends RemoteTestBase { private static final String PROCESS_ID_V1 = "process-migration-testv1.AddTaskAfterActive"; private static final String PROCESS_ID_V2 = "process-migration-testv2.AddTaskAfterActive"; @Test public void testSingleMigration() { ProcessInstance piv1 = testv1.startProcess(PROCESS_ID_V1); long pid = piv1.getId(); Assertions.assertThat(piv1.getProcessId()).isEqualTo(PROCESS_ID_V1); Task activeTask = testv1.getActiveTask(pid); Assertions.assertThat(activeTask).isNotNull(); Assertions.assertThat(activeTask.getName()).isEqualTo("Active Task"); migrateSingleProcessInstance(DEPID_TESTV1, DEPID_TESTV2, pid, PROCESS_ID_V2); ProcessInstance piv2 = testv2.getProcessInstance(pid); Assertions.assertThat(piv2).isNotNull(); Assertions.assertThat(piv2.getProcessId()).isEqualTo(PROCESS_ID_V2); activeTask = testv2.getActiveTask(pid); Assertions.assertThat(activeTask).isNotNull(); Assertions.assertThat(activeTask.getName()).isEqualTo("Active Task"); testv2.completeTask(activeTask); activeTask = testv2.getActiveTask(pid); Assertions.assertThat(activeTask).isNotNull(); Assertions.assertThat(activeTask.getName()).isEqualTo("Added Task"); testv2.completeTask(activeTask); ProcessInstanceLog pil = testv2.getProcessInstanceLog(pid); Assertions.assertThat(pil).isNotNull(); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_COMPLETED); } @Test public void testMultiMigration() { List<Long> pids = new ArrayList<Long>(); for (int i=0; i<10; ++i) { ProcessInstance piv1 = testv1.startProcess(PROCESS_ID_V1); long pid = piv1.getId(); Assertions.assertThat(piv1.getProcessId()).isEqualTo(PROCESS_ID_V1); pids.add(pid); } migrateMultiProcessInstances(DEPID_TESTV1, DEPID_TESTV2, PROCESS_ID_V1, PROCESS_ID_V2); for (Long pid : pids) { ProcessInstance piv2 = testv2.getProcessInstance(pid); Assertions.assertThat(piv2).isNotNull(); Assertions.assertThat(piv2.getProcessId()).isEqualTo(PROCESS_ID_V2); Task activeTask = testv2.getActiveTask(pid); Assertions.assertThat(activeTask).isNotNull(); Assertions.assertThat(activeTask.getName()).isEqualTo("Active Task"); testv2.completeTask(activeTask); activeTask = testv2.getActiveTask(pid); Assertions.assertThat(activeTask).isNotNull(); Assertions.assertThat(activeTask.getName()).isEqualTo("Added Task"); testv2.completeTask(activeTask); ProcessInstanceLog pil = testv2.getProcessInstanceLog(pid); Assertions.assertThat(pil).isNotNull(); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_COMPLETED); } } }
39.797753
95
0.666008
44710a42d725989555e1222cadd910e290a1636c
5,838
package nl.knokko.customitems.editor.menu.edit.item; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Scanner; import nl.knokko.customitems.editor.menu.commandhelp.CommandBlockHelpOverview; import nl.knokko.customitems.editor.menu.edit.EditProps; import nl.knokko.customitems.editor.menu.edit.item.EditCustomModel.ByteArrayFileConverter; import nl.knokko.customitems.editor.util.HelpButtons; import nl.knokko.gui.color.GuiColor; import nl.knokko.gui.component.GuiComponent; import nl.knokko.gui.component.menu.FileChooserMenu; import nl.knokko.gui.component.menu.GuiMenu; import nl.knokko.gui.component.text.ConditionalTextButton; import nl.knokko.gui.component.text.TextEditField; import nl.knokko.gui.component.text.dynamic.DynamicTextButton; import nl.knokko.gui.component.text.dynamic.DynamicTextComponent; public class EditCustomModel extends GuiMenu { private final GuiComponent returnMenu; private final ByteArrayListener receiver; private final String[] exampleContent; private final byte[] currentContent; private TextEditField parent = new TextEditField("handheld", EditProps.EDIT_BASE, EditProps.EDIT_ACTIVE); public EditCustomModel(String[] exampleContent, GuiComponent returnMenu, ByteArrayListener receiver, byte[] currentContent) { this.returnMenu = returnMenu; this.receiver = receiver; this.exampleContent = exampleContent; this.currentContent = currentContent; } @Override protected void addComponents() { addComponent(new DynamicTextButton("Cancel", EditProps.CANCEL_BASE, EditProps.CANCEL_HOVER, () -> { state.getWindow().setMainComponent(returnMenu); }), 0.025f, 0.8f, 0.175f, 0.9f); addComponent(new ConditionalTextButton("Change to default model with given parent", EditProps.SAVE_BASE, EditProps.SAVE_HOVER, () -> { String output = ""; for (String content: exampleContent) { output += content + "\n"; } String result = output.replaceFirst("handheld", parent.getText()); byte[] array = result.getBytes(); receiver.readArray(array); state.getWindow().setMainComponent(returnMenu); }, () -> { return exampleContent != null && !parent.getText().equals("handheld"); }), 0.65f, 0.025f, 0.995f, 0.125f); addComponent(new DynamicTextComponent("The editor will simply put the model you choose in the resourcepack", EditProps.LABEL), 0.1f, 0.7f, 0.9f, 0.8f); addComponent(new DynamicTextComponent("upon exporting, no attempt will be made to read the model json.", EditProps.LABEL), 0.1f, 0.6f, 0.85f, 0.7f); if (exampleContent != null && currentContent == null) { addComponent(new DynamicTextComponent("The default model for this item would be:", EditProps.LABEL), 0.1f, 0.5f, 0.6f, 0.6f); int index = 0; for (String content : exampleContent) { addComponent(new DynamicTextComponent(content, EditProps.LABEL), 0.025f, 0.40f - 0.05f * index, 0.025f + content.length() * 0.01f, 0.45f - 0.05f * index); index++; } } else if (currentContent != null) { try { String asString = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(currentContent)).toString(); Scanner lineByLine = new Scanner(asString); addComponent(new DynamicTextComponent("The current custom model for this item is:", EditProps.LABEL), 0.1f, 0.5f, 0.6f, 0.6f); int index = 0; while (lineByLine.hasNextLine()) { String content = lineByLine.nextLine(); addComponent(new DynamicTextComponent(content, EditProps.LABEL), 0.025f, 0.40f - 0.05f * index, 0.025f + content.length() * 0.01f, 0.45f - 0.05f * index); index++; } lineByLine.close(); } catch (CharacterCodingException e) { addComponent(new DynamicTextComponent("The current custom model for this item seems to be invalid", EditProps.LABEL), 0.1f, 0.5f, 0.6f, 0.6f); } } addComponent(new DynamicTextButton("Select file...", EditProps.CHOOSE_BASE, EditProps.CHOOSE_HOVER, () -> { state.getWindow().setMainComponent(new FileChooserMenu(returnMenu, (File file) -> { receiver.readArray(new ByteArrayFileListener().convertFile(file)); return returnMenu; }, (File file) -> { return file.getName().endsWith(".json"); }, EditProps.CANCEL_BASE, EditProps.CANCEL_HOVER, EditProps.CHOOSE_BASE, EditProps.CHOOSE_HOVER, EditProps.BACKGROUND, EditProps.BACKGROUND2)); }), 0.2f, 0.8f, 0.375f, 0.9f); if (exampleContent != null) { addComponent(new DynamicTextButton("Copy Default Model", EditProps.BUTTON, EditProps.HOVER, () -> { String result = ""; for (String content: exampleContent) { result += content + "\n"; } CommandBlockHelpOverview.setClipboard(result); }), 0.4f, 0.8f, 0.675f, 0.9f); addComponent(new DynamicTextComponent("Default Parent:", EditProps.LABEL), 0.8f, 0.325f, 0.975f, 0.425f); addComponent(parent, 0.8f, 0.2f, 0.975f, 0.3f); } HelpButtons.addHelpLink(this, "edit%20menu/items/edit/model.html"); } @Override public GuiColor getBackgroundColor() { return EditProps.BACKGROUND; } public static interface ByteArrayFileConverter{ byte[] convertFile(File file); } public static interface ByteArrayListener { void readArray(byte[] array); } } class ByteArrayFileListener implements ByteArrayFileConverter{ public byte[] convertFile (File file) { try { if (file.length() > 500000000) { return new byte[0]; } byte[] result = new byte[(int) file.length()]; InputStream in = Files.newInputStream(file.toPath()); DataInputStream dataIn = new DataInputStream(in); dataIn.readFully(result); in.close(); return result; } catch (IOException ioex) { return new byte[0]; } } }
40.541667
159
0.728845
97c38e3797fac44f7b5cedf70d5900f9044933d1
8,890
package com.wonderfulenchantments.enchantments; import com.mlib.Random; import com.mlib.config.ConfigGroup; import com.mlib.config.DoubleConfig; import com.mlib.config.DurationConfig; import com.mlib.config.StringListConfig; import com.mlib.effects.EffectHelper; import com.wonderfulenchantments.Instances; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnchantmentType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.ListNBT; import net.minecraft.potion.Effect; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.EffectType; import net.minecraft.potion.Effects; import net.minecraft.util.DamageSource; import net.minecraft.util.text.IFormattableTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.living.PotionEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; /** Enchantment that gives Absorption and Mithridatism Protection after any negative effect is applied to the player. */ public class MithridatismEnchantment extends WonderfulEnchantment { public MithridatismEnchantment() { super( "mithridatism", Rarity.VERY_RARE, EnchantmentType.ARMOR_CHEST, EquipmentSlotType.CHEST, "Mithridatism" ); setMaximumEnchantmentLevel( 4 ); setDifferenceBetweenMinimumAndMaximum( 30 ); setMinimumEnchantabilityCalculator( level->( 15 + 100 * ( level - 1 ) ) ); } /** Adds config group from to enchantment group. */ public void addConfigGroup( ConfigGroup group ) { this.enchantmentGroup.addGroup( group ); } /** Returns current Mithridatism enchantment level. */ public int getEnchantmentLevel( LivingEntity entity ) { return EnchantmentHelper.getEnchantmentLevel( this, entity.getItemStackFromSlot( EquipmentSlotType.CHEST ) ); } /** Effect that decreases damage from certain negative effects. */ @Mod.EventBusSubscriber public static class MithridatismProtectionEffect extends Effect { protected final ConfigGroup effectGroup; protected final StringListConfig damageSourceList; protected final DoubleConfig absorptionPerLevel, baseDamageReduction, damageReductionPerLevel, levelUpChance; protected final DurationConfig duration; public MithridatismProtectionEffect( MithridatismEnchantment mithridatism ) { super( EffectType.BENEFICIAL, 0xff76db4c ); String listComment = "Damage sources that will deal less damage when effect is active."; String absorptionComment = "Level of Absorption applied to the player per enchantment level rounded down. (minimum. 1lvl)"; String baseReductionComment = "Base amount of damage decreased from negative effects."; String levelReductionComment = "Amount of damage decreased from negative effects per enchantment level."; String durationComment = "Duration of both the Absorption and Mithridatism Protection. (in seconds)"; String levelUpComment = "Chance for Mithridatism to increase its level."; this.effectGroup = new ConfigGroup( "MithridatismProtection", "" ); this.damageSourceList = new StringListConfig( "damage_source_list", listComment, false, "magic", "wither", "bleeding" ); this.absorptionPerLevel = new DoubleConfig( "absorption_per_level", absorptionComment, false, 0.5, 0, 3 ); this.baseDamageReduction = new DoubleConfig( "base_reduction", baseReductionComment, false, 0.2, 0.0, 1.0 ); this.damageReductionPerLevel = new DoubleConfig( "reduction_per_level", levelReductionComment, false, 0.1, 0.0, 1.0 ); this.levelUpChance = new DoubleConfig( "level_up_chance", levelUpComment, false, 0.025, 0.0, 1.0 ); this.duration = new DurationConfig( "duration", durationComment, false, 60.0, 2.0, 600.0 ); this.effectGroup.addConfigs( this.damageSourceList, this.absorptionPerLevel, this.baseDamageReduction, this.damageReductionPerLevel, this.levelUpChance, this.duration ); mithridatism.addConfigGroup( this.effectGroup ); } @SubscribeEvent public static void whenEffectApplied( PotionEvent.PotionAddedEvent event ) { EffectInstance effectInstance = event.getPotionEffect(); Effect effect = effectInstance.getPotion(); LivingEntity entity = event.getEntityLiving(); MithridatismEnchantment mithridatism = Instances.MITHRIDATISM; MithridatismEnchantment.MithridatismProtectionEffect mithridatismEffect = Instances.MITHRIDATISM_PROTECTION; int mithridatismLevel = mithridatism.getEnchantmentLevel( entity ); if( !effect.isBeneficial() && mithridatismLevel > 0 && !entity.isPotionActive( mithridatismEffect ) ) { int duration = mithridatismEffect.getDuration(); EffectHelper.applyEffectIfPossible( entity, mithridatismEffect, duration, mithridatismLevel - 1 ); int absorptionAmplifier = Math.max( 0, mithridatismEffect.getAbsorptionLevel( entity ) - 1 ); EffectHelper.applyEffectIfPossible( entity, Effects.ABSORPTION, duration, absorptionAmplifier ); } } @SubscribeEvent public static void whenEffectRemoved( PotionEvent.PotionExpiryEvent event ) { EffectInstance effectInstance = event.getPotionEffect(); if( effectInstance == null ) return; Effect effect = effectInstance.getPotion(); LivingEntity entity = event.getEntityLiving(); MithridatismEnchantment mithridatism = Instances.MITHRIDATISM; MithridatismEnchantment.MithridatismProtectionEffect mithridatismEffect = Instances.MITHRIDATISM_PROTECTION; int mithridatismLevel = mithridatism.getEnchantmentLevel( entity ); if( mithridatismLevel >= mithridatism.getMaxLevel() || mithridatismLevel == 0 || mithridatism.isDisabled() ) return; if( effect.isBeneficial() || !Random.tryChance( mithridatismEffect.levelUpChance.get() ) ) return; mithridatismEffect.increaseLevel( entity ); } @SubscribeEvent public static void whenDamaged( LivingHurtEvent event ) { MithridatismProtectionEffect mithridatismEffect = Instances.MITHRIDATISM_PROTECTION; DamageSource damageSource = event.getSource(); if( !mithridatismEffect.isDamageAffected( damageSource ) ) return; double damageReduction = mithridatismEffect.getDamageReduction( event.getEntityLiving() ); if( damageReduction == 0.0 ) return; event.setAmount( ( float )( event.getAmount() * ( 1.0 - damageReduction ) ) ); } /** Returns current damage reduction depending on enchantment level. */ protected double getDamageReduction( LivingEntity entity ) { EffectInstance effectInstance = entity.getActivePotionEffect( this ); int mithridatismLevel = effectInstance != null ? effectInstance.getAmplifier() : 0; return mithridatismLevel == 0 ? 0.0 : Math.min( 1, mithridatismLevel * this.damageReductionPerLevel.get() + this.baseDamageReduction.get() ); } /** Returns current Absorption level depending on enchantment level. */ protected int getAbsorptionLevel( LivingEntity entity ) { int mithridatismLevel = Instances.MITHRIDATISM.getEnchantmentLevel( entity ); return mithridatismLevel == 0 ? 0 : ( int )( Math.max( 0, mithridatismLevel * this.absorptionPerLevel.get() ) ); } /** Returns Mithridatism effect duration. */ protected int getDuration() { return this.duration.getDuration(); } /** Checks whether given damage source is one from the effect list. */ protected boolean isDamageAffected( DamageSource damageSource ) { return this.damageSourceList.contains( damageSource.getDamageType() ); } /** Increases Mithridatism level for given player. */ protected void increaseLevel( LivingEntity entity ) { ItemStack chestplate = entity.getItemStackFromSlot( EquipmentSlotType.CHEST ); MithridatismEnchantment mithridatism = Instances.MITHRIDATISM; ListNBT listNBT = chestplate.getEnchantmentTagList(); for( int i = 0; i < listNBT.size(); ++i ) { CompoundNBT compoundNBT = listNBT.getCompound( i ); String enchantmentID = compoundNBT.getString( "id" ); if( enchantmentID.contains( "mithridatism" ) ) { compoundNBT.putInt( "lvl", mithridatism.getEnchantmentLevel( entity ) + 1 ); break; } } chestplate.setTagInfo( "Enchantments", listNBT ); notifyAboutLevelUp( entity ); } /** Notifies player when the Mithridatism level was increased. */ protected void notifyAboutLevelUp( LivingEntity entity ) { if( !( entity instanceof PlayerEntity ) ) return; IFormattableTextComponent message = new TranslationTextComponent( "wonderful_enchantments.mithridatism_level_up" ); message.mergeStyle( TextFormatting.BOLD ); PlayerEntity player = ( PlayerEntity )entity; player.sendStatusMessage( message, true ); } } }
45.357143
135
0.774803
4028e63501b58c6b22a02797c9fdd910913784e0
2,462
/* * Copyright 2013 Anton Karmanov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.antkar.syn.sample.script.ide; import java.io.IOException; import java.io.OutputStream; import javax.swing.SwingUtilities; /** * Output stream that redirects output to a {@link ScriptWindow}'s console box. */ abstract class WindowOutputStream extends OutputStream { private final ScriptWindow window; private final StringBuilder bld; private OutputStream otherOut; WindowOutputStream(ScriptWindow window) { this.window = window; bld = new StringBuilder(); } /** * Sets the paired output. A paired output stream is flushed when a byte is written into this * stream. This is necessary to avoid mixing of standard output and standard error fragments. */ final void setPairedOut(OutputStream otherOut) { this.otherOut = otherOut; } @Override public final void write(int b) throws IOException { synchronized (window) { if (otherOut != null) { otherOut.flush(); } bld.append((char)b); if (b == '\n' || bld.length() >= 100) { //Automatically flush on a new line or if the length of the buffer is big enough. flush(); } } } @Override public final void flush() { synchronized (window) { if (bld.length() > 0) { final String str = bld.toString(); bld.setLength(0); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { append(window, str); } }); } } } /** * Append the specified string to a {@link ScriptWindow}'s standard output or standard error. */ abstract void append(ScriptWindow win, String str); }
30.395062
97
0.610885
93d0c11b6084e3559f71f7946283ba199d12cf12
3,946
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.analysis.opennlp; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.opennlp.tools.NLPChunkerOp; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.FlagsAttribute; import org.apache.lucene.analysis.tokenattributes.TypeAttribute; import org.apache.lucene.util.AttributeSource; /** * Run OpenNLP chunker. Prerequisite: the OpenNLPTokenizer and OpenNLPPOSFilter must precede this * filter. Tags terms in the TypeAttribute, replacing the POS tags previously put there by * OpenNLPPOSFilter. */ public final class OpenNLPChunkerFilter extends TokenFilter { private List<AttributeSource> sentenceTokenAttrs = new ArrayList<>(); private int tokenNum = 0; private boolean moreTokensAvailable = true; private String[] sentenceTerms = null; private String[] sentenceTermPOSTags = null; private final NLPChunkerOp chunkerOp; private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class); private final FlagsAttribute flagsAtt = addAttribute(FlagsAttribute.class); private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); public OpenNLPChunkerFilter(TokenStream input, NLPChunkerOp chunkerOp) { super(input); this.chunkerOp = chunkerOp; } @Override public final boolean incrementToken() throws IOException { if (!moreTokensAvailable) { clear(); return false; } if (tokenNum == sentenceTokenAttrs.size()) { nextSentence(); if (sentenceTerms == null) { clear(); return false; } assignTokenTypes(chunkerOp.getChunks(sentenceTerms, sentenceTermPOSTags, null)); tokenNum = 0; } clearAttributes(); sentenceTokenAttrs.get(tokenNum++).copyTo(this); return true; } private void nextSentence() throws IOException { List<String> termList = new ArrayList<>(); List<String> posTagList = new ArrayList<>(); sentenceTokenAttrs.clear(); boolean endOfSentence = false; while (!endOfSentence && (moreTokensAvailable = input.incrementToken())) { termList.add(termAtt.toString()); posTagList.add(typeAtt.type()); endOfSentence = 0 != (flagsAtt.getFlags() & OpenNLPTokenizer.EOS_FLAG_BIT); sentenceTokenAttrs.add(input.cloneAttributes()); } sentenceTerms = termList.size() > 0 ? termList.toArray(new String[termList.size()]) : null; sentenceTermPOSTags = posTagList.size() > 0 ? posTagList.toArray(new String[posTagList.size()]) : null; } private void assignTokenTypes(String[] tags) { for (int i = 0; i < tags.length; ++i) { sentenceTokenAttrs.get(i).getAttribute(TypeAttribute.class).setType(tags[i]); } } @Override public void reset() throws IOException { super.reset(); moreTokensAvailable = true; clear(); } private void clear() { sentenceTokenAttrs.clear(); sentenceTerms = null; sentenceTermPOSTags = null; tokenNum = 0; } }
35.872727
97
0.731374
0d270dd74c8b8cde9b3a852a3b486997a01c5eb4
11,320
package org.springframework.roo.addon.ws.addon.jaxb; import java.lang.reflect.Modifier; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.roo.addon.ws.annotations.jaxb.RooJaxbEntity; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.DeclaredMethodAnnotationDetails; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.MethodMetadataBuilder; import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder; import org.springframework.roo.classpath.details.comments.CommentStructure; import org.springframework.roo.classpath.details.comments.CommentStructure.CommentLocation; import org.springframework.roo.classpath.details.comments.JavadocComment; import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.model.JavaPackage; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.project.LogicalPath; import org.springframework.roo.support.logging.HandlerUtils; /** * Metadata for {@link RooJaxbEntity}. * * @author Juan Carlos García * @since 2.0 */ public class JaxbEntityMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { protected final static Logger LOGGER = HandlerUtils.getLogger(JaxbEntityMetadata.class); private static final String PROVIDES_TYPE_STRING = JaxbEntityMetadata.class.getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils .create(PROVIDES_TYPE_STRING); private final JavaPackage projectTopLevelPackage; private final JavaType entity; private final String pluralEntityName; private final MethodMetadata identifierAccessor; private final List<MethodMetadata> oneToManyGetters; private final List<MethodMetadata> manyToOneGetters; private MethodMetadata xmlIdentityInfoMethod; public static String createIdentifier(final JavaType javaType, final LogicalPath path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path); } public static String createIdentifier(ClassOrInterfaceTypeDetails details) { final LogicalPath logicalPath = PhysicalTypeIdentifier.getPath(details.getDeclaredByMetadataId()); return createIdentifier(details.getType(), logicalPath); } public static JavaType getJavaType(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static LogicalPath getPath(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(final String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } /** * Constructor * * @param identifier * the identifier for this item of metadata (required) * @param aspectName * the Java type of the ITD (required) * @param governorPhysicalTypeMetadata * the governor, which is expected to contain a * {@link ClassOrInterfaceTypeDetails} (required) * @param projectTopLevelPackage the topLevelPackage * of the generated project. * @param entity the annotated entity * @param pluralEntityName the plural name of the entity * @param identifierAccessor the identifier accessor method * @param oneToManyGetters accessor methods of all oneToMany relation fields * @param manyToOneGetters accessor methods of all manyToOne relation fields */ public JaxbEntityMetadata(final String identifier, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final JavaPackage projectTopLevelPackage, final JavaType entity, final String pluralEntityName, final MethodMetadata identifierAccessor, final List<MethodMetadata> oneToManyGetters, final List<MethodMetadata> manyToOneGetters, Map<String, String> entityNames) { super(identifier, aspectName, governorPhysicalTypeMetadata); this.projectTopLevelPackage = projectTopLevelPackage; this.entity = entity; this.pluralEntityName = pluralEntityName; this.identifierAccessor = identifierAccessor; this.oneToManyGetters = oneToManyGetters; this.manyToOneGetters = manyToOneGetters; // Declare precendence builder.setDeclarePrecedence(aspectName); // Include @XmlRootElement annotation AnnotationMetadataBuilder xmlRootElementAnnotation = new AnnotationMetadataBuilder(JavaType.XML_ROOT_ELEMENT); xmlRootElementAnnotation.addStringAttribute("name", entity.getSimpleTypeName().toLowerCase()); xmlRootElementAnnotation.addStringAttribute( "namespace", String.format("http://ws.%s/", StringUtils.reverseDelimited( projectTopLevelPackage.getFullyQualifiedPackageName(), '.'))); ensureGovernorIsAnnotated(xmlRootElementAnnotation); // Include annotations on @OneToMany getters for (MethodMetadata getter : oneToManyGetters) { // Getting the getter type name String getterTypeName = getter.getReturnType().getBaseType().getSimpleTypeName().toLowerCase(); // Define @XmlIDREF annotation DeclaredMethodAnnotationDetails xmlIdRefAnnotationInGetterMethod = new DeclaredMethodAnnotationDetails(getter, new AnnotationMetadataBuilder( JavaType.XML_ID_REF).build()); // Define @XmlElement annotation AnnotationMetadataBuilder xmlElementAnnotation = new AnnotationMetadataBuilder(JavaType.XML_ELEMENT); xmlElementAnnotation.addStringAttribute("name", getterTypeName); DeclaredMethodAnnotationDetails xmlElementAnnotationInGetterMethod = new DeclaredMethodAnnotationDetails(getter, xmlElementAnnotation.build()); // Define @XmlElementWrapper annotation AnnotationMetadataBuilder xmlElementWrapperAnnotation = new AnnotationMetadataBuilder(JavaType.XML_ELEMENT_WRAPPER); xmlElementWrapperAnnotation.addStringAttribute("name", entityNames.get(getterTypeName)); DeclaredMethodAnnotationDetails xmlElementWrapperAnnotationInGetterMethod = new DeclaredMethodAnnotationDetails(getter, xmlElementWrapperAnnotation.build()); builder.addMethodAnnotation(xmlIdRefAnnotationInGetterMethod); builder.addMethodAnnotation(xmlElementAnnotationInGetterMethod); builder.addMethodAnnotation(xmlElementWrapperAnnotationInGetterMethod); } // Include annotations on @ManyToOne getters for (MethodMetadata getter : manyToOneGetters) { // Getting the getter type name String getterTypeName = getter.getReturnType().getSimpleTypeName().toLowerCase(); // Define @XmlIDREF annotation DeclaredMethodAnnotationDetails xmlIdRefAnnotationInGetterMethod = new DeclaredMethodAnnotationDetails(getter, new AnnotationMetadataBuilder( JavaType.XML_ID_REF).build()); // Define @XmlElement annotation AnnotationMetadataBuilder xmlElementAnnotation = new AnnotationMetadataBuilder(JavaType.XML_ELEMENT); xmlElementAnnotation.addStringAttribute("name", getterTypeName); DeclaredMethodAnnotationDetails xmlElementAnnotationInGetterMethod = new DeclaredMethodAnnotationDetails(getter, xmlElementAnnotation.build()); builder.addMethodAnnotation(xmlIdRefAnnotationInGetterMethod); builder.addMethodAnnotation(xmlElementAnnotationInGetterMethod); } // Annotate the identifier accessor method and generate new one if (identifierAccessor != null) { // Define @XmlTransient annotation DeclaredMethodAnnotationDetails xmlTransientAnnotationInGetterMethod = new DeclaredMethodAnnotationDetails(identifierAccessor, new AnnotationMetadataBuilder( JavaType.XML_TRANSIENT).build()); builder.addMethodAnnotation(xmlTransientAnnotationInGetterMethod); // Include getXmlIdentityInfo() method ensureGovernorHasMethod(new MethodMetadataBuilder(getXmlIdentityInfoMethod())); } // Build the ITD itdTypeDetails = builder.build(); } /** * This method returns the getXmlIdentityInfo() method. * * @return MethodMetadata that contains the getXmlIdentityInfoMethod */ public MethodMetadata getXmlIdentityInfoMethod() { // Check if already exists if (xmlIdentityInfoMethod != null) { return xmlIdentityInfoMethod; } // If not, generate a new one InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // return getClass().getName() + ":" + getId(); bodyBuilder.appendFormalLine(String.format("return getClass().getName() + \":\" + %s();", identifierAccessor.getMethodName())); MethodMetadataBuilder method = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, new JavaSymbolName("getXmlIdentityInfo"), JavaType.STRING, bodyBuilder); method.addAnnotation(new AnnotationMetadataBuilder(JavaType.XML_ID)); AnnotationMetadataBuilder xmlAttributeAnnotation = new AnnotationMetadataBuilder(JavaType.XML_ATTRIBUTE); xmlAttributeAnnotation.addStringAttribute("name", "id"); method.addAnnotation(xmlAttributeAnnotation); CommentStructure comment = new CommentStructure(); comment.addComment(new JavadocComment("Must return an unique ID across all entities"), CommentLocation.BEGINNING); method.setCommentStructure(comment); xmlIdentityInfoMethod = method.build(); return xmlIdentityInfoMethod; } @Override public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("identifier", getId()); builder.append("valid", valid); builder.append("aspectName", aspectName); builder.append("destinationType", destination); builder.append("governor", governorPhysicalTypeMetadata.getId()); builder.append("itdTypeDetails", itdTypeDetails); return builder.toString(); } public JavaPackage getProjectTopLevelPackage() { return projectTopLevelPackage; } public JavaType getEntity() { return entity; } public List<MethodMetadata> getOneToManyGetters() { return oneToManyGetters; } public List<MethodMetadata> getManyToOneGetters() { return manyToOneGetters; } public String getPluralEntityName() { return pluralEntityName; } public MethodMetadata getIdentifierAccessor() { return identifierAccessor; } }
41.163636
100
0.776413
59fb7b8403a98cc2ec77e00e29e133644e791532
2,315
package ecommerce.firstproduct.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.jms.core.JmsTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import ecommerce.productservice.entity.Product; import ecommerce.productservice.repository.ProductRepository; @RestController @RequestMapping("/first/product") public class ProductFirstController { @Autowired private ProductRepository repo; @Autowired private JmsTemplate jmsTemplate; @Value("${product.jms.destination}") private String jmsQueue; @PostMapping("/addOne") public Product addProduct(@RequestBody Product product ) { return repo.save(product); } @PostMapping("/addList") public List<Product> addProductList (@RequestBody List<Product> products) { return repo.saveAll(products); } @GetMapping("/getAll") public List<Product> getAllProduct() { return repo.findAll(); } @GetMapping("/sendToCart/{id}") public ResponseEntity<Product> sendToCart(@PathVariable long id) { Optional<Product> product = repo.findById(id); if (!product.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } ObjectMapper mapper = new ObjectMapper(); try { String jsonString = mapper.writeValueAsString(product.get()); jmsTemplate.convertAndSend(jmsQueue, jsonString); return new ResponseEntity<>(product.get(), HttpStatus.OK); } catch (JsonProcessingException e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } }
30.866667
80
0.739957
b54c92af3e94e6b6b1dfdf3bb14a6a9df8a2dd92
147
package com.nkasenides.athlos.model; /** * Abstracts the functionality of grid-based worlds. */ public interface IGridWorld extends IWorld { }
16.333333
52
0.755102
46126bf21ab62e1fa4ccf7292fe85558cb2c86a7
20,453
package com.stephenwranger.compgeo.algorithms.trapezoids; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import com.stephenwranger.compgeo.algorithms.Algorithm; import com.stephenwranger.graphics.collections.Pair; import com.stephenwranger.graphics.math.Tuple2d; import com.stephenwranger.graphics.math.intersection.IntersectionUtils; import com.stephenwranger.graphics.math.intersection.LineSegment; import com.stephenwranger.graphics.math.intersection.Trapezoid; public class TrapezoidalMapAlgorithm implements Algorithm<LineSegment, String[]> { private final Rectangle2D bounds; private TrapezoidalMapNode root; private String[][] matrix = null; private final LinkedHashMap<Tuple2d, Pair<String, Integer>> xNodes = new LinkedHashMap<Tuple2d, Pair<String, Integer>>(); private final LinkedHashMap<LineSegment, Pair<String, Integer>> yNodes = new LinkedHashMap<LineSegment, Pair<String, Integer>>(); private final LinkedHashMap<Trapezoid, Pair<String, Integer>> leafNodes = new LinkedHashMap<Trapezoid, Pair<String, Integer>>(); public final List<Trapezoid> trapezoids = new ArrayList<Trapezoid>(); private List<String[]> output = null; private int pNodeIndex = 0; private int qNodeIndex = 0; private int yNodeIndex = 0; private int leafNodeIndex = 0; public TrapezoidalMapAlgorithm(final Rectangle2D bounds) { this.bounds = bounds; } public void printQuery(final Tuple2d queryPoint) { this.printQuery(this.root, queryPoint); } private void printQuery(final TrapezoidalMapNode n, final Tuple2d queryPoint) { System.out.print(n.getLabel() + " "); if (n instanceof XNode) { final XNode node = (XNode) n; if (IntersectionUtils.isLessOrEqual(queryPoint.x, node.segmentEndpoint.x)) { this.printQuery(node.getLeftAbove(), queryPoint); } else { this.printQuery(node.getRightBelow(), queryPoint); } } else if (n instanceof YNode) { final YNode node = (YNode) n; if (IntersectionUtils.isGreaterThan(queryPoint.y, node.segment.a * queryPoint.x + node.segment.b)) { this.printQuery(node.getLeftAbove(), queryPoint); } else { this.printQuery(node.getRightBelow(), queryPoint); } } } @Override public boolean compute(final List<LineSegment> input, final List<String[]> output, final long timeout) { this.output = output; final long startTime = System.nanoTime(); // initialize the root with the bounding box as a trapezoid this.root = new LeafNode(this.getTrapezoidalBounds(), new LeafNode[0]); List<LeafNode> intersected; LeafNode leaf; Trapezoid trapezoid; // loop over all input segments and insert them one at a time for (final LineSegment segment : input) { if ((System.nanoTime() - startTime) / 1000000l > timeout) { return false; } // traverse tree and adjacent trapezoids to get list of intersected leaf nodes intersected = this.getIntersectedNodes(segment); // if size is 1, the the segment is completely inside the node; split into 4 pieces if (intersected.size() == 1) { leaf = intersected.get(0); trapezoid = leaf.getTrapezoid(); // segment is completely inside leaf node final LineSegment leftEdge = trapezoid.getLeft(); final LineSegment rightEdge = trapezoid.getRight(); final LineSegment topEdge = trapezoid.getTop(); final LineSegment bottomEdge = trapezoid.getBottom(); final LineSegment pMax = new LineSegment(segment.min, new Tuple2d(segment.min.x, segment.min.y + this.bounds.getHeight())); final LineSegment pMin = new LineSegment(segment.min, new Tuple2d(segment.min.x, segment.min.y - this.bounds.getHeight())); final LineSegment qMax = new LineSegment(segment.max, new Tuple2d(segment.max.x, segment.max.y + this.bounds.getHeight())); final LineSegment qMin = new LineSegment(segment.max, new Tuple2d(segment.max.x, segment.max.y - this.bounds.getHeight())); final Tuple2d topLeft = topEdge.intersect(pMax); final Tuple2d topRight = topEdge.intersect(qMax); final Tuple2d bottomLeft = bottomEdge.intersect(pMin); final Tuple2d bottomRight = bottomEdge.intersect(qMin); final Trapezoid u = new Trapezoid(leftEdge.min, leftEdge.max, topLeft, bottomLeft); final Trapezoid x = new Trapezoid(rightEdge.min, rightEdge.max, topRight, bottomRight); final Trapezoid y = new Trapezoid(segment.min, topLeft, topRight, segment.max); final Trapezoid z = new Trapezoid(segment.min, bottomLeft, bottomRight, segment.max); final LeafNode a = this.getLeafNode(u); final LeafNode d = this.getLeafNode(x); final LeafNode b = this.getLeafNode(y); b.addNeighbors(new LeafNode[] { a, d }); final LeafNode c = this.getLeafNode(z); c.addNeighbors(new LeafNode[] { a, d }); a.addNeighbors(leaf.getNeighborsLeft()); a.addNeighbor(b); a.addNeighbor(c); d.addNeighbors(leaf.getNeighborsRight()); d.addNeighbor(b); d.addNeighbor(c); final YNode s1 = this.getYNode(segment, b, c); final XNode p1 = this.getXNode(segment.min, "P", a, null); final XNode q1 = this.getXNode(segment.max, "Q", s1, d); p1.setRightBelow(q1); if (leaf == this.root) { this.root = p1; } else { for(final TrapezoidalMapNode p : leaf.getParentNodes()) { p.replaceChild(leaf, p1); } leaf.removeAsNeighbor(); } } else { // each endpoint is inside a different trapezoid and potentially bisects intermediaries final List<LeafNode> newNodes = new ArrayList<LeafNode>(); LeafNode node; Trapezoid[] splitTrapezoids; // loop left-to-right and deal with each node for (int i = 0; i < intersected.size(); i++) { node = intersected.get(i); try { splitTrapezoids = node.getTrapezoid().split(segment); } catch (final Exception e) { System.out.println(node.getTrapezoid()); System.out.println(segment); throw e; } if (i == 0) { // split into three on left end final LeafNode a = this.getLeafNode(splitTrapezoids[0]); a.addNeighbors(node.getNeighborsLeft()); final LeafNode b = this.getLeafNode(splitTrapezoids[1]); b.addNeighbors(node.getNeighborsRight()); b.addNeighbor(a); final LeafNode c = this.getLeafNode(splitTrapezoids[2]); c.addNeighbors(node.getNeighborsRight()); c.addNeighbor(a); a.addNeighbor(b); a.addNeighbor(c); newNodes.add(a); newNodes.add(b); newNodes.add(c); final YNode s = this.getYNode(segment, b, c); final XNode p1 = this.getXNode(segment.min, "P", a, s); for (final TrapezoidalMapNode p : node.getParentNodes()) { p.replaceChild(node, p1); } } else if (i == intersected.size() - 1 && splitTrapezoids.length > 2) { // split into three on right end final LeafNode c = this.getLeafNode(splitTrapezoids[2]); c.addNeighbors(node.getNeighborsRight()); final LeafNode b = this.getLeafNode(splitTrapezoids[1]); b.addNeighbors(node.getNeighborsLeft()); b.addNeighbor(c); final LeafNode a = this.getLeafNode(splitTrapezoids[0]); a.addNeighbors(node.getNeighborsLeft()); a.addNeighbor(c); c.addNeighbor(b); c.addNeighbor(a); newNodes.add(a); newNodes.add(b); newNodes.add(c); final YNode s = this.getYNode(segment, a, b); final XNode q = this.getXNode(segment.max, "Q", s, c); for (final TrapezoidalMapNode p : node.getParentNodes()) { p.replaceChild(node, q); } } else { // bisect final LeafNode top = this.getLeafNode(splitTrapezoids[0]); final LeafNode bottom = this.getLeafNode(splitTrapezoids[1]); top.addNeighbors(node.getNeighborsLeft()); top.addNeighbors(node.getNeighborsRight()); bottom.addNeighbors(node.getNeighborsLeft()); bottom.addNeighbors(node.getNeighborsRight()); newNodes.add(top); newNodes.add(bottom); final YNode s = this.getYNode(segment, top, bottom); for (final TrapezoidalMapNode p : node.getParentNodes()) { p.replaceChild(node, s); } } node.removeAsNeighbor(); } // check for any merges within set of new nodes final List<Pair<LeafNode, LeafNode>> toMerge = new ArrayList<>(); LeafNode n, m; LineSegment left, right; // TODO: last node to get merged didn't get added to graph? (T27) do { // for any pair of nodes that contained an identical edge, merge them for (final Pair<LeafNode, LeafNode> pair : toMerge) { left = pair.left.getTrapezoid().getLeft(); right = pair.right.getTrapezoid().getRight(); // make sure we didn't merge it in a previous step if (newNodes.contains(pair.left) && newNodes.contains(pair.right)) { final Trapezoid merged = new Trapezoid(left.min, left.max, right.max, right.min); n = this.getLeafNode(merged); n.addNeighbors(pair.left.getNeighborsLeft()); n.addNeighbors(pair.right.getNeighborsRight()); n.addParentNode(pair.left.getParentNodes(), pair.left); n.addParentNode(pair.right.getParentNodes(), pair.right); newNodes.remove(pair.left); newNodes.remove(pair.right); newNodes.add(n); pair.left.removeAsNeighbor(); pair.right.removeAsNeighbor(); if (pair.left == this.root || pair.right == this.root) { this.root = n; } } } toMerge.clear(); // loop through list of new leaf nodes and look for merge-able leaves for (int i = 0; i < newNodes.size() - 1; i++) { n = newNodes.get(i); for (int j = i + 1; j < newNodes.size(); j++) { m = newNodes.get(j); Pair<LeafNode, LeafNode> pair = null; if (n.getTrapezoid().getRight().equals(m.getTrapezoid().getLeft())) { pair = Pair.getInstance(n, m); } else if (n.getTrapezoid().getLeft().equals(m.getTrapezoid().getRight())) { pair = Pair.getInstance(m, n); } if (pair != null && !toMerge.contains(pair)) { toMerge.add(pair); } } } } while (!toMerge.isEmpty()); } // update output matrix (so even if it crashes we get something) this.updateMatrix(); } // update output matrix this.updateMatrix(); return true; } /** * Returns a new LeafNode for the given Trapezoid or, if one has already been created, the cached node. * * @param trapezoid * @return */ private LeafNode getLeafNode(final Trapezoid trapezoid) { Pair<String, Integer> label = null; if (this.leafNodes.containsKey(trapezoid)) { label = this.leafNodes.get(trapezoid); } else { label = Pair.getInstance("T" + this.leafNodeIndex, this.leafNodeIndex); this.leafNodeIndex++; this.leafNodes.put(trapezoid, label); } final LeafNode node = new LeafNode(trapezoid, null); node.setLabel(label.left); node.setIndex(label.right); return node; } /** * Returns a new XNode for the given point and the given left and right nodes or, if one has already been created, the cached one. * * @param point * @param left * @param right * @return */ private XNode getXNode(final Tuple2d point, final String labelPrefix, final TrapezoidalMapNode left, final TrapezoidalMapNode right) { Pair<String, Integer> label = null; if (this.xNodes.containsKey(point)) { label = this.xNodes.get(point); } else { int index = -1; if (labelPrefix.equals("P")) { index = this.pNodeIndex; this.pNodeIndex++; } else { index = this.qNodeIndex; this.qNodeIndex++; } label = Pair.getInstance(labelPrefix + index, index); this.xNodes.put(point, label); } final XNode node = new XNode(point, left, right); node.setLabel(label.left); node.setIndex(label.right); return node; } /** * Returns a new YNode for the given segment and the given above and below nodes or, if one has already been created, the cached one. * * @param segment * @param above * @param below * @return */ private YNode getYNode(final LineSegment segment, final TrapezoidalMapNode above, final TrapezoidalMapNode below) { Pair<String, Integer> label = null; if (this.yNodes.containsKey(segment)) { label = this.yNodes.get(segment); } else { label = Pair.getInstance("S" + this.yNodeIndex, this.yNodeIndex); this.yNodeIndex++; this.yNodes.put(segment, label); } final YNode node = new YNode(segment, above, below); node.setLabel(label.left); node.setIndex(label.right); return node; } private void updateNode(final TrapezoidalMapNode node) { if (node == null || (!(node instanceof LeafNode) && node.getLeftAbove() == null && node.getRightBelow() == null)) { return; } int parentIndex = 0, childIndex = node.getIndex(); if (node instanceof XNode) { childIndex += ((node.getLabel().startsWith("P")) ? 0 : this.pNodeIndex); } else if (node instanceof YNode) { childIndex += this.xNodes.size(); } else { ((LeafNode) node).getTrapezoid().setLabel(node.getLabel()); this.trapezoids.add(((LeafNode) node).getTrapezoid()); childIndex += this.xNodes.size() + this.yNodes.size(); } this.matrix[childIndex + 1][0] = node.getLabel(); this.matrix[0][childIndex + 1] = node.getLabel(); for (final TrapezoidalMapNode parent : node.getParentNodes()) { parentIndex = parent.getIndex(); if (parent instanceof XNode) { parentIndex += ((parent.getLabel().startsWith("P")) ? 0 : this.pNodeIndex); } else if (parent instanceof YNode) { parentIndex += this.xNodes.size(); } else { parentIndex += this.xNodes.size() + this.yNodes.size(); } this.matrix[childIndex + 1][parentIndex + 1] = "1"; } this.updateNode(node.getLeftAbove()); this.updateNode(node.getRightBelow()); } /** * Updates the trapezoidal map matrix. */ private void updateMatrix() { // TODO: Normalize labels for nodes so there's no jumps in numbering this.output.clear(); this.trapezoids.clear(); this.matrix = new String[this.xNodes.size() + this.yNodes.size() + this.leafNodes.size() + 2][this.xNodes.size() + this.yNodes.size() + this.leafNodes.size() + 2]; String[] row; for (int i = 0; i < this.matrix.length; i++) { row = this.matrix[i]; if (i == 0 || i == this.matrix.length - 1) { Arrays.fill(row, ""); } else { Arrays.fill(row, 1, row.length - 1, "0"); row[0] = ""; row[row.length - 1] = ""; } } this.updateNode(this.root); this.matrix[0][this.matrix.length - 1] = "Total"; this.matrix[this.matrix.length - 1][0] = "Total"; int totalRow = 0, totalCol = 0; for (int i = 1; i < this.matrix.length - 1; i++) { totalRow = 0; totalCol = 0; for (int j = 1; j < this.matrix.length - 1; j++) { totalRow += Integer.parseInt(this.matrix[i][j]); totalCol += Integer.parseInt(this.matrix[j][i]); } this.matrix[i][this.matrix.length - 1] = Integer.toString(totalRow); this.matrix[this.matrix.length - 1][i] = Integer.toString(totalCol); } final List<Integer> validRows = new ArrayList<Integer>(); final List<Integer> validCols = new ArrayList<Integer>(); for (int i = 1; i < this.matrix.length - 1; i++) { if (!this.matrix[0][i].equals("")) { validCols.add(i); } if (!this.matrix[i][0].equals("")) { validRows.add(i); } } int colIndex; for (int i = 0; i < this.matrix.length; i++) { if (i == 0 || i == this.matrix.length - 1 || validRows.contains(i)) { colIndex = 0; row = new String[validCols.size() + 2]; for (int j = 0; j < this.matrix.length; j++) { if (j == 0 || j == this.matrix.length - 1 || validCols.contains(j)) { row[colIndex] = this.matrix[i][j]; colIndex++; } } this.output.add(row); } } // this.output.addAll(Arrays.asList(this.matrix)); } /** * Uses the Trapezoid Map Query to determine which nodes a given line segment has intersected. * * @param segment * @return */ private List<LeafNode> getIntersectedNodes(final LineSegment segment) { final List<LeafNode> intersected = new ArrayList<LeafNode>(); final LeafNode leftNode = this.root.queryMap(segment.min); final LeafNode rightNode = this.root.queryMap(segment.max); LeafNode temp = leftNode; if (leftNode != rightNode) { do { intersected.add(temp); temp = temp.getNeighbor(segment); } while (IntersectionUtils.isLessOrEqual(temp.getTrapezoid().getRight().x, rightNode.getTrapezoid().getLeft().x)); intersected.add(temp); } else { intersected.add(leftNode); } return intersected; } /** * Returns the bounds of this algorithm as a Trapezoid. * * @return */ private Trapezoid getTrapezoidalBounds() { final double x = this.bounds.getX(); final double y = this.bounds.getY(); final double w = this.bounds.getWidth(); final double h = this.bounds.getHeight(); final Tuple2d c0 = new Tuple2d(x, y); final Tuple2d c1 = new Tuple2d(x, y + h); final Tuple2d c2 = new Tuple2d(x + w, y + h); final Tuple2d c3 = new Tuple2d(x + w, y); return new Trapezoid(c0, c1, c2, c3); } }
37.597426
169
0.556104
ad2df8971b2e55ee3a3966c01250b06f4b3c5d50
7,108
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package session; import Connnection.DBConnection; import entity.Customer; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.ejb.LocalBean; /** * * @author thain */ @Stateless @LocalBean public class Customer_s { public List<Customer> getAll(){ DBConnection db=new DBConnection(); Connection conn=db.getConnect(); List<Customer> list_cus=new ArrayList<Customer>(); String sql="select * from tmdt.customer"; try { ResultSet rs=conn.createStatement().executeQuery(sql); while(rs.next()){ int idCustomer=rs.getInt("idcustomer"); String customerName=rs.getString("customername"); String gender=rs.getString("gender"); Date dateBirth=rs.getDate("datebirth"); String address=rs.getString("address"); String phoneNumber=rs.getString("phonenumber"); String transport=rs.getString("transport"); String userName=rs.getString("username"); String passWord=rs.getString("password"); Customer cus=new Customer(idCustomer, customerName, gender, dateBirth, address, phoneNumber, transport, userName, passWord); list_cus.add(cus); } } catch (SQLException ex) { Logger.getLogger(Customer_s.class.getName()).log(Level.SEVERE, null, ex); } return list_cus; } public Customer getByUserPass(String user, String pass){ DBConnection db=new DBConnection(); Connection conn=db.getConnect(); Customer cus=null; String sql="select * from tmdt.customer where username='"+user+"' and password='"+pass+"'"; try { ResultSet rs=conn.createStatement().executeQuery(sql); while(rs.next()){ int idCustomer=rs.getInt("idcustomer"); String customerName=rs.getString("customername"); String gender=rs.getString("gender"); Date dateBirth=rs.getDate("datebirth"); String address=rs.getString("address"); String phoneNumber=rs.getString("phonenumber"); String transport=rs.getString("transport"); String userName=rs.getString("username"); String passWord=rs.getString("password"); cus=new Customer(idCustomer, customerName, gender, dateBirth, address, phoneNumber, transport, userName, passWord); } } catch (SQLException ex) { Logger.getLogger(Customer_s.class.getName()).log(Level.SEVERE, null, ex); } return cus; } public int delete(int id){ DBConnection db=new DBConnection(); Connection conn=db.getConnect(); int n=0; String sql="delete from tmdt.customer where idcustomer='"+id+"'"; try { n=conn.createStatement().executeUpdate(sql); } catch (SQLException ex) { Logger.getLogger(Customer_s.class.getName()).log(Level.SEVERE, null, ex); } return n; } public Customer getCustomerByID(int idCus){ DBConnection db=new DBConnection(); Connection conn=db.getConnect(); Customer cus=null; String sql="select * from tmdt.customer where idcustomer='"+idCus+"'"; try { PreparedStatement pre=conn.prepareStatement(sql); pre.setInt(1, idCus); ResultSet rs=pre.executeQuery(); if(rs.next()){ int idCustomer=rs.getInt("idcustomer"); String customerName=rs.getString("customername"); String gender=rs.getString("gender"); Date dateBirth=rs.getDate("datebirth"); String address=rs.getString("address"); String phoneNumber=rs.getString("phonenumber"); String transport=rs.getString("transport"); String userName=rs.getString("username"); String passWord=rs.getString("password"); cus=new Customer(idCustomer, customerName, gender, dateBirth, address, phoneNumber, transport, userName, passWord); } } catch (SQLException ex) { Logger.getLogger(Customer_s.class.getName()).log(Level.SEVERE, null, ex); } return cus; } public Customer selectByUsername(String username){ DBConnection db=new DBConnection(); Connection conn=db.getConnect(); Customer cus=null; String sql="select * from tmdt.customer where username=?"; try { PreparedStatement pre=conn.prepareStatement(sql); pre.setString(1, username); ResultSet rs=pre.executeQuery(); if(rs.next()){ int idCustomer=rs.getInt("idcustomer"); String customerName=rs.getString("customername"); String gender=rs.getString("gender"); Date dateBirth=rs.getDate("datebirth"); String address=rs.getString("address"); String phoneNumber=rs.getString("phonenumber"); String transport=rs.getString("transport"); String userName=rs.getString("username"); String passWord=rs.getString("password"); cus=new Customer(idCustomer, customerName, gender, dateBirth, address, phoneNumber, transport, userName, passWord); } } catch (SQLException ex) { Logger.getLogger(Customer_s.class.getName()).log(Level.SEVERE, null, ex); } return cus; } public int insert(Customer cus){ DBConnection db=new DBConnection(); Connection conn=db.getConnect(); int n=0; String sql="insert into tmdt.customer(customername, gender, datebirth, address, phonenumber, transport, username, password)" + " values(?, ?, ?, ?, ?, ?, ?, ?)"; try { PreparedStatement pre=conn.prepareStatement(sql); pre.setString(1, cus.getCustomername()); pre.setString(2, cus.getGender()); pre.setDate(3, (java.sql.Date) cus.getDatebirth()); pre.setString(4, cus.getAddress()); pre.setString(5, cus.getPhonenumber()); pre.setString(6, cus.getTransport()); pre.setString(7, cus.getUsername()); pre.setString(8, cus.getPassword()); n=pre.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Customer_s.class.getName()).log(Level.SEVERE, null, ex); } return n; } }
39.709497
140
0.596933
99b0c3496ef2d28b7de1b70d8e9e377f2c01a7f4
624
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) { String data="Patika 102 Dersleri!"; ByteArrayOutputStream output=new ByteArrayOutputStream(); byte[] dataByteArray=data.getBytes(); try { output.write(dataByteArray); String newData=output.toString(); System.out.println("Çıkış Akışı\t: "+newData); }catch (IOException e){ e.printStackTrace(); } } }
29.714286
66
0.636218
a4fc8b5a1e423a19ca3317279464b9749c37f919
852
package com.example.commontask.model; import java.io.Serializable; /** * Created by Αρης on 27/2/2018. */ public class Privacy implements Serializable{ private String name = ""; private boolean checked = false; public Privacy() { } public Privacy(String name) { this.name = name; } public Privacy(String name, boolean checked) { this.name = name; this.checked = checked; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public String toString() { return name; } public void toggleChecked() { checked = !checked; } }
16.705882
50
0.584507
79b136db3d0660e09e4b5428f54dab4ec245a8d9
718
package com.tekwill.learning.datatypes.operators; import java.util.Scanner; public class PopulationOfNation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the current world's population: "); long currentWorldPopulation = scanner.nextLong(); System.out.println("Enter the population of the Romanian: "); long countryPopulation = scanner.nextLong(); double percentage = (countryPopulation * 100.0) / currentWorldPopulation; System.out.printf("The population of Romanian is %.5f %% of the world population. ", percentage); } }
44.875
113
0.63649
cab4a85ad5868833f776171c6f8fd9642a974f3d
3,244
package ya.boilerplate.thebasic.controller; import java.util.Map; import java.util.Optional; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import ya.boilerplate.thebasic.model.request.LoginRequest; import ya.boilerplate.thebasic.model.request.SignUpRequest; import ya.boilerplate.thebasic.model.response.ApiResponse; import ya.boilerplate.thebasic.model.response.JwtAuthenticationResponse; import ya.boilerplate.thebasic.service.UserAuthService; import ya.boilerplate.thebasic.service.UserService; /** * Auth Controller */ @RestController @RequestMapping("/api/account") public class AuthController { private static final Logger logger = LoggerFactory.getLogger(AuthController.class); public static final String LOGIN_ROUTE = "/login"; public static final String REGISTER_ROUTE = "/register"; public static final String TOKEN_REFRESH_ROUTE = "/token/refresh"; public static final String LOGOUT_ROUTE = "/logout"; @Autowired UserService userService; @Autowired UserAuthService userAuthService; @PostMapping(LOGIN_ROUTE) public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { logger.info("AuthenticateUser with Username Or Email: " + loginRequest.getUsernameOrEmail()); JwtAuthenticationResponse response = userAuthService.createToken(loginRequest.getUsernameOrEmail(), loginRequest.getPassword()); logger.info("JWT Generated for Username Or Email: " + loginRequest.getUsernameOrEmail()); return ResponseEntity.ok(response); } @PostMapping(REGISTER_ROUTE) public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) { logger.info("Register User with Email: " + signUpRequest.getEmail()); try { return userService.registerUser(signUpRequest); } catch (Exception e) { return ResponseEntity.ok(new ApiResponse(false, "Failed to register user: " + e.getMessage())); } } @PostMapping(TOKEN_REFRESH_ROUTE) public ResponseEntity<?> refreshAccessToken(@RequestBody Map<String, String> payload) { String refreshToken = payload.get("refresh_token"); Optional<JwtAuthenticationResponse> response = userAuthService.refreshAccessToken(refreshToken); if (response.isPresent()) { return ResponseEntity.ok(response); } else { return new ResponseEntity<>("Please login first :D", HttpStatus.UNAUTHORIZED); } } @DeleteMapping(LOGOUT_ROUTE) public ResponseEntity<?> logoutUser(@RequestBody Map<String, String> payload) { try { String refreshToken = payload.get("refresh_token"); userService.logoutUser(refreshToken); return ResponseEntity.ok(new ApiResponse(true, "Yay!")); } catch (Exception e) { return ResponseEntity.ok(new ApiResponse(false, "Failed to logout" + e.getMessage())); } } }
33.443299
101
0.790074
1c84f0da2c15badca66995d640b24cda2ed8f0b9
162
package ru.metrovagonmash.service; public interface RoomServiceCRUD<T,ID> extends RoomService<T,ID> { T update(T model, ID id); T deleteById(ID id); }
18
66
0.716049
bb3d33b490a86b3388120b959fb87a073ba81e5d
1,197
package plodsoft.slingshot; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import plodsoft.slingshot.proxy.CommonProxy; @Mod(modid = Slingshot.MODID, name = Slingshot.NAME, version = Slingshot.VERSION, acceptedMinecraftVersions = "[1.10.2]") public class Slingshot { public static final String MODID = "slingshot"; public static final String VERSION = "1.0"; public static final String NAME = "Slingshot"; @SidedProxy(serverSide = "plodsoft.slingshot.proxy.CommonProxy", clientSide = "plodsoft.slingshot.proxy.ClientProxy") public static CommonProxy proxy; @Mod.Instance(MODID) public static Slingshot instance; public static Logger log = LogManager.getLogger(NAME); @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { Config.init(e); ModItems.init(); proxy.preInit(); } @Mod.EventHandler public void init(FMLInitializationEvent e) { ModItems.registerRecipe(); proxy.init(); } }
28.5
69
0.781955
a22190d4f838f394f61dd665baf97d696111669a
2,117
package mx.uach.smp.models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import mx.uach.smp.models.genericos.BaseModel; /** * * @author Erik David Zubia Hernández */ @Entity @Table(name = "clientes") public class Cliente extends BaseModel{ private String nombre; @Column(name = "apellido_paterno") private String apellidoPaterno; @Column(name = "apellido_materno") private String apellidoMaterno; private String direccion; private String telefono; public Cliente() { } public Cliente(String nombre, String apellidoPaterno, String apellidoMaterno, String direccion, String telefono) { this.nombre = nombre; this.apellidoPaterno = apellidoPaterno; this.apellidoMaterno = apellidoMaterno; this.direccion = direccion; this.telefono = telefono; } public Cliente(String nombre, String apellidoPaterno, String apellidoMaterno, String direccion, String telefono, Long id) { super(id); this.nombre = nombre; this.apellidoPaterno = apellidoPaterno; this.apellidoMaterno = apellidoMaterno; this.direccion = direccion; this.telefono = telefono; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidoPaterno() { return apellidoPaterno; } public void setApellidoPaterno(String apellidoPaterno) { this.apellidoPaterno = apellidoPaterno; } public String getApellidoMaterno() { return apellidoMaterno; } public void setApellidoMaterno(String apellidoMaterno) { this.apellidoMaterno = apellidoMaterno; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } }
23.522222
127
0.665092
95c637c12dd885ddcf1675a11052d76907c025fe
1,251
package com.example.test; /** * Class stores main constants * Created by Evgeniy Bezkorovayniy * [email protected] * * 30.04.2020 */ public class ApplicationConfig { public enum SystemType { SOURCE_SYSTEM, MODIFIED_SYSTEM } public static final String HAAR_CLASSIFIER_FILE_PATH = "C:\\IntellijIDEAProjects\\BiometricTests\\files\\cascade\\haarcascade_frontalface_alt.xml"; public static final String LBPH_RECOGNIZER_FILE_PATH = "C:\\IntellijIDEAProjects\\BiometricTests\\files\\recognizers\\lbph.xml"; public static final String EIGENFACE_RECOGNIZER_FILE_PATH = "C:\\IntellijIDEAProjects\\BiometricTests\\files\\recognizers\\eigenface.xml"; public static final String FISHERFACE_RECOGNIZER_FILE_PATH = "C:\\IntellijIDEAProjects\\BiometricTests\\files\\recognizers\\fisherface.xml"; public static final String SOURCE_FACE_DATASET_PATH = "C:\\IntellijIDEAProjects\\BiometricTests\\files\\faces_source\\"; public static final String MODOFIED_FACE_DATASET_PATH = "C:\\IntellijIDEAProjects\\BiometricTests\\files\\faces_modified\\"; public static final String CONTROL_FACE_DATASET_PATH = "C:\\IntellijIDEAProjects\\BiometricTests\\files\\faces_control\\"; }
50.04
152
0.763389
bc16c88cb9b5cdaebe5330a1a2ac20e57291f652
10,898
package gui; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import tech_demo.ScrollingText; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import launchpad_s_plus.Colors; /** * Implements the GUI for the Scrolling Text demo * * @author Helion * * @version $Revision: 1.0 $ */ public class TextScrollGUI { private static boolean firstTimeRunning = true; private static boolean ready = false; static ScrollingText scr = new ScrollingText(); private static final JFrame ScrollingTextDialog = new JFrame(); private static final JPanel ScrollingTextContainer = new JPanel(); private static final JButton startButton = new JButton("Start"); private static final JButton stopButton = new JButton("Stop"); private static final JPanel startStopPanel = new JPanel(); private static final JLabel textLabel = new JLabel(); private static final JTextField textField = new JTextField(); private static final JPanel textPanel = new JPanel(); private static final JPanel colorPanel = new JPanel(); private static final JLabel colorLabel = new JLabel(); private static final JComboBox<String> color = new JComboBox<String>(); private static final JPanel intensityPanel = new JPanel(); private static final JLabel intensityLabel = new JLabel(); private static final JComboBox<Integer> intensity = new JComboBox<Integer>(); private static final JPanel loopingPanel = new JPanel(); private static final JLabel loopingText = new JLabel(); private static final JCheckBox loopingCheck = new JCheckBox(); private static final JPanel speedPanel = new JPanel(); private static final JLabel speedLabel = new JLabel(); private static final JComboBox<Integer> speed = new JComboBox<Integer>(); private static final JPanel settingsPanel = new JPanel(); static String defaultMessage = "Launchpad S+"; static String defaultColor = "green"; static int defaultIntensity = 3; static int defaultSpeed = 4; static boolean defaultLoop = true; private static int mainWindowX; private static int mainWindowY; private static int mainWindowW; private static int mainWindowH; private static int windowX; private static int windowY; private static int windowW; private static int windowH; /** * Constructor for the GUI * * @param start * true if the GUI should be displayed, false otherwise */ TextScrollGUI(boolean start) { if (start) { initialize(); if (firstTimeRunning) createAndShowGUI(); setInteractions(); firstTimeRunning = false; ScrollingTextDialog.setVisible(true); askSettings(); Main.delay(500); while (!ready) { Main.delay(1); } firstTimeRunning = false; new Thread() { @Override public void run() { try { scr = new ScrollingText(); scr.begin(); } catch (Exception ex) { Thread.currentThread().interrupt(); } } }.start(); } else { quit(); } } /** * Sets the window position and dimenstions */ private static void initialize() { Main.setClosing(false); Main.setCardIcon(Main.textScrollCard, "textScroll", "selected"); ScrollingText.setText(defaultMessage); ScrollingText.setColor(defaultColor); ScrollingText.setIntensity(defaultIntensity); ScrollingText.setSpeed(defaultSpeed); mainWindowX = Main.getWindowPositionX(); mainWindowY = Main.getWindowPositionY(); mainWindowW = Main.getWindowDimensionsW(); mainWindowH = Main.getWindowDimensionsH(); windowW = 450; windowH = 200; windowX = (mainWindowX + mainWindowW + 20); windowY = ((mainWindowY + mainWindowH + windowH) / 3); } /** * Creates the GUI and places GUI elements */ private static void createAndShowGUI() { ScrollingTextDialog.setIconImage(Toolkit.getDefaultToolkit().getImage( Main.class.getResource("/Images/icon.png"))); ScrollingTextDialog.setTitle("Scrolling Text Demo"); ScrollingTextDialog.setResizable(false); ScrollingTextDialog.setBounds(windowX, windowY, windowW, windowH); if (firstTimeRunning) { speed.addItem(1); speed.addItem(2); speed.addItem(3); speed.addItem(4); speed.addItem(5); color.addItem("green"); color.addItem("yellow"); color.addItem("red"); color.addItem("lime"); color.addItem("orange"); intensity.addItem(1); intensity.addItem(2); intensity.addItem(3); } speedLabel.setText("Speed"); color.setSelectedIndex(0); colorLabel.setText("Color"); speed.setSelectedIndex(defaultSpeed); intensity.setSelectedIndex(defaultIntensity - 1); intensityLabel.setText("Intensity"); loopingCheck.setSelected(true); loopingText.setText("Looping"); textLabel.setText("Message"); textField.setPreferredSize(new Dimension(200, 25)); textField.setDocument(new JTextFieldLimit(31)); speedPanel.add(speedLabel); speedPanel.add(speed); colorPanel.add(colorLabel); colorPanel.add(color); intensityPanel.add(intensityLabel); intensityPanel.add(intensity); loopingPanel.add(loopingText); loopingPanel.add(loopingCheck); settingsPanel.add(speedPanel); settingsPanel.add(colorPanel); settingsPanel.add(intensityPanel); settingsPanel.add(loopingPanel); settingsPanel.setVisible(true); ScrollingText.setText(defaultMessage); ScrollingText.setColor(defaultColor); ScrollingText.setSpeed(defaultSpeed); ScrollingText.setIntensity(defaultIntensity); ScrollingText.setLoop(defaultLoop); if (firstTimeRunning) setText(defaultMessage); textPanel.add(textLabel); textPanel.add(textField); textPanel.setVisible(true); startStopPanel.add(startButton); startStopPanel.add(stopButton); startStopPanel.setVisible(true); ScrollingTextContainer.setBounds(0, 0, windowW, windowH); ScrollingTextContainer.setLayout(new BoxLayout(ScrollingTextContainer, BoxLayout.Y_AXIS)); ScrollingTextContainer.add(textPanel); ScrollingTextContainer.add(startStopPanel); ScrollingTextContainer.add(settingsPanel); ScrollingTextDialog.getContentPane().add(ScrollingTextContainer); } /** * Defines and implements all the interactions for the Scrolling Text GUI */ private static void setInteractions() { ScrollingTextDialog .addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { quitScrollingText(); } }); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ScrollingText.forceQuit(); defaultMessage = textField.getText(); ScrollingText.setText(textField.getText()); resetScrolling(); } }); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ScrollingText.forceQuit(); } }); speed.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { defaultSpeed = speed.getSelectedIndex() + 1; ScrollingText.setSpeed(speed.getSelectedIndex() + 1); } }); color.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { defaultColor = Colors.stringFromValue(color.getSelectedIndex()); ScrollingText.setColor(Colors.stringFromValue(color .getSelectedIndex())); } }); intensity.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { defaultIntensity = intensity.getSelectedIndex() + 1; ScrollingText.setIntensity(intensity.getSelectedIndex() + 1); } }); loopingCheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { defaultLoop = loopingCheck.isSelected(); ScrollingText.setLoop(loopingCheck.isSelected()); } }); textField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ScrollingText.forceQuit(); defaultMessage = textField.getText(); ScrollingText.setText(textField.getText()); resetScrolling(); } }); } /** * Stops text that might be already scrolling and displays new text */ private static void resetScrolling() { ScrollingText.forceQuit(); delay(10); new Thread() { @Override public void run() { try { new ScrollingText(); ScrollingText.restartScroll(); } catch (Exception ex) { Thread.currentThread().interrupt(); } } }.start(); } /** * Delays for a certain duration * * @param duration * Time in MS to delay for */ private static void delay(int duration) { try { Thread.sleep(duration); } catch (Exception e) { e.printStackTrace(); } } /** * Sets the new text to scroll on the Launchpad * * @param newText * New text to display */ private static void setText(String newText) { textField.setText(newText); ScrollingText.setText(newText); } /** * Gets the text in the Message field * * * @return Text from the message field */ public static String getText() { return textField.getText(); } /** * Gets the color selected on the GUI * * * @return Color selected on the GUI */ public static String getColor() { return Colors.stringFromValue(color.getSelectedIndex()); } /** * Gets the speed selected on the GUI * * * @return Speed selected on the GUI */ public static int getSpeed() { return speed.getSelectedIndex() + 1; } /** * Gets the intensity selected on the GUI * * * @return Intensity selected on the GUI */ public static int getIntensity() { return intensity.getSelectedIndex() + 1; } /** * Returns whether the Looping checkbox is selected on the GUI * * * @return True if it is checked, False otherwise */ public static boolean getLooping() { return loopingCheck.isSelected(); } /** * Asks for user input before initiating the sub program */ private static void askSettings() { ready = true; } /** * Method called to close the GUI from the ScrollingText class */ public static void quit() { System.out.println("Quitting\n"); Main.setClosing(true); Main.textScrollRunning = false; Main.nothingRunning(); Main.resetCards(); ScrollingTextDialog.dispose(); Main.setCardIcon(Main.textScrollCard, "textScroll", "default"); scr = null; Main.textScrollRunning = false; } /** * Method called to close the GUI and demo. <br> * Should not be called from within ScrollingText class. * * @return 1 */ public static int quitScrollingText() { System.out.println("Force Quitting\n"); ScrollingText.forceQuit(); scr = null; Main.setClosing(true); Main.textScrollRunning = false; Main.nothingRunning(); Main.resetCards(); ScrollingTextDialog.dispose(); return 1; } }
26.134293
78
0.716737
ff2b48f38e49237eae13668354fb6fbe2584911d
952
package com.example.as_frasesdodia; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.Random; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void gerarNovaFrase(View view){ String [] frases = { "frase1", "frase2", "frase3", "frase4" // nao precisa virgula no ultimo item }; int numero = new Random().nextInt(4); // gera numeros aleatorios de 0 a 4 TextView texto = findViewById(R.id.textResultado); // atribui resultado ao TextView id 'textResultado' texto.setText(frases[numero]); // indice aleatorio do array 'frases[]' exibido no TextView } }
26.444444
110
0.659664
e48216fc019fae86645bf98b581f424e4b5538f3
836
package com.huhx0015.builditbigger.backend; /** ----------------------------------------------------------------------------------------------- * [MyBean] CLASS * DESCRIPTION: The object model for the data we are sending through endpoints. * ----------------------------------------------------------------------------------------------- */ public class MyBean { /** CLASS VARIABLES ________________________________________________________________________ **/ private String myData; /** GET METHODS ____________________________________________________________________________ **/ public String getData() { return myData; } /** SET METHODS ____________________________________________________________________________ **/ public void setData(String data) { myData = data; } }
32.153846
100
0.566986
6df27be9031974b1396cd01dc54bbd489d1c7705
7,591
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.maintenance; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.questionnaire.question.Question; import org.kuali.kra.questionnaire.question.QuestionService; import org.kuali.rice.kns.document.MaintenanceDocument; import org.kuali.rice.kns.document.MaintenanceDocumentBase; import org.kuali.rice.kns.maintenance.Maintainable; import org.kuali.rice.kns.service.KNSServiceLocator; import org.kuali.rice.kns.util.KNSGlobalVariables; import org.kuali.rice.kns.web.struts.form.KualiMaintenanceForm; import org.kuali.rice.kns.web.ui.Section; import org.kuali.rice.krad.bo.DocumentHeader; import org.kuali.rice.krad.service.SequenceAccessorService; import org.kuali.rice.krad.util.GlobalVariables; import java.util.ArrayList; import java.util.List; /** * This class customizes the maintainable class for the question maintenance document. */ public class QuestionMaintainableImpl extends KraMaintainableImpl { private static final long serialVersionUID = 713068582185818373L; private static final String SEQUENCE_STATUS_ARCHIVED = "A"; /** * * @see org.kuali.core.maintenance.Maintainable#prepareForSave() */ @Override public void prepareForSave() { super.prepareForSave(); if ((businessObject != null) && (businessObject instanceof KcPersistableBusinessObjectBase)) { // This is a solution to enable the lookreturn have a proper dropdown list if (businessObject instanceof Question) { Question question = (Question)businessObject; question.setDocumentNumber(getDocumentNumber()); if (StringUtils.isNotBlank(((Question) businessObject).getLookupClass())) { GlobalVariables.getUserSession().addObject(Constants.LOOKUP_CLASS_NAME, (Object) question.getLookupClass()); } // In order for the questionId to be displayed after a submission of a new question we need to manually create it. if (question.getQuestionId() == null) { Long newQuestionId = KcServiceLocator.getService(SequenceAccessorService.class) .getNextAvailableSequenceNumber("SEQ_QUESTION_ID", question.getClass()); question.setQuestionIdFromInteger(newQuestionId.intValue()); } } } } /** * Normally the parent method builds the maintenance sections from the data dictionary. But since * we want full control over the screen layout we disable the automatic build by overriding the * method and returning an empty list of sections. * * @see org.kuali.kra.maintenance.KraMaintainableImpl#getSections(org.kuali.rice.kns.document.MaintenanceDocument, org.kuali.rice.kns.maintenance.Maintainable) */ @Override public List<Section> getSections(MaintenanceDocument document, Maintainable oldMaintainable) { // This is a solution to enable the lookreturn have a proper dropdown list if (KNSGlobalVariables.getKualiForm() != null && KNSGlobalVariables.getKualiForm() instanceof KualiMaintenanceForm) { Question question = (Question)((MaintenanceDocumentBase)((KualiMaintenanceForm)KNSGlobalVariables.getKualiForm()).getDocument()).getDocumentBusinessObject(); if (StringUtils.isNotBlank(question.getLookupClass())) { if (StringUtils.isBlank((String)GlobalVariables.getUserSession().retrieveObject(Constants.LOOKUP_CLASS_NAME)) && ((((List)GlobalVariables.getUserSession().retrieveObject(Constants.LOOKUP_RETURN_FIELDS))) == null || ((List)GlobalVariables.getUserSession().retrieveObject(Constants.LOOKUP_RETURN_FIELDS)).size() == 0)) { GlobalVariables.getUserSession().addObject(Constants.LOOKUP_CLASS_NAME, (Object)question.getLookupClass()); } } } return new ArrayList<Section>(); } @Override public void doRouteStatusChange(DocumentHeader documentHeader) { clearUnusedFieldValues(); } /** * This method sets the unused fields of the question response type to null. */ private void clearUnusedFieldValues() { Question question = (Question) businessObject; if (question.getQuestionType() != null) { switch (question.getQuestionTypeId()) { case Constants.QUESTION_RESPONSE_TYPE_YES_NO: question.setLookupClass(null); question.setLookupReturn(null); question.setDisplayedAnswers(null); question.setMaxAnswers(null); question.setAnswerMaxLength(null); break; case Constants.QUESTION_RESPONSE_TYPE_YES_NO_NA: question.setLookupClass(null); question.setLookupReturn(null); question.setDisplayedAnswers(null); question.setMaxAnswers(null); question.setAnswerMaxLength(null); break; case Constants.QUESTION_RESPONSE_TYPE_NUMBER: question.setLookupClass(null); question.setLookupReturn(null); break; case Constants.QUESTION_RESPONSE_TYPE_DATE: question.setLookupClass(null); question.setLookupReturn(null); question.setAnswerMaxLength(null); break; case Constants.QUESTION_RESPONSE_TYPE_TEXT: question.setLookupClass(null); question.setLookupReturn(null); break; case Constants.QUESTION_RESPONSE_TYPE_LOOKUP: question.setDisplayedAnswers(null); question.setAnswerMaxLength(null); break; } } } /** * * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#saveBusinessObject() * * This method will set the sequence status of the original question from current to * archived before the revision for the question is saved. */ public void saveBusinessObject() { Question newQuestion = (Question) businessObject; QuestionService questionService = KcServiceLocator.getService(QuestionService.class); Question oldQuestion = questionService.getQuestionById(newQuestion.getQuestionId()); if (oldQuestion != null) { oldQuestion.setSequenceStatus(SEQUENCE_STATUS_ARCHIVED); KNSServiceLocator.getBusinessObjectService().save(oldQuestion); } super.saveBusinessObject(); } }
46.286585
334
0.670531
28b39393c5f87ef2ddcd263228d685029eb96e1e
235
package com.joypupil.study.design_pattern._03abstract_factory; public abstract class AbstractCreator { //创建A产品家族 public abstract AbstractProductA createProductA(); //创建B产品家族 public abstract AbstractProductB createProductB(); }
21.363636
62
0.817021
fa0cff3e3de3f01fff2a4a3438881cfbbcdae0d2
13,395
import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.ArrayDeque; import java.io.File; import java.io.IOException; /** Copyright (C) Jan 2019, Oct 2019 Ettore Merlo - All rights reserved */ public class buzzUnparsePrettyPrintVisCl implements defsInt { buzzParseTableCl astTable = null; private int curColumn = 0; private int curLine = 1; private int curTab = 0; final private int TAB_SIZE = 4; public void initParams(buzzParseTableCl parAstTable) { astTable = parAstTable; return; } // // Printing methods // private void printString(String str) { if (curColumn == 0) { for(int i = 0; i < curTab * TAB_SIZE; i++) { System.out.print(" "); curColumn += 1; } } System.out.print(str); curColumn += str.length(); } private void newLine(){ curLine += 1; curColumn = 0; System.out.println(); } // // AST utils // private void visitChildren(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if (children != null) { for (Integer childId: children) { visit(childId, depth); } } return; } // // Node visitors // private void visit_GENERIC(Integer astNodeId, int depth) { visitChildren(astNodeId, (depth + 1)); return; } private void visit_token(Integer astNodeId, int depth) { String curLiteral = astTable.getTkLiteral(astNodeId); String curImg = astTable.getTkImage(astNodeId); int curNodeLineBeg = astTable.lineBeginTable.get(astNodeId); int curNodeColumnBeg = astTable.columnBeginTable.get(astNodeId); if (curLiteral != null && !curLiteral.equals("UNDEFINED")) { printString(curLiteral); } else { if (!curImg.equals("UNDEFINED")) { printString(curImg); } } visitChildren(astNodeId, (depth + 1)); return; } private void visit_BLOCK(Integer astNodeId, int depth) { // BLOCK // token <{> // STATLIST // token <}> List<Integer> children = astTable.succTable.get(astNodeId); if (children != null && children.size() > 1) { for (int i = 0; i < children.size() - 1; i++) { if(i == 1) { newLine(); curTab += 1; } visit(children.get(i), depth + 1); } curTab -= 1; visit(children.get(children.size() - 1), depth + 1); printString(" "); // newLine(); } else { visitChildren(astNodeId, depth + 1); } return; } private void visit_BLOCKSTAT(Integer astNodeId, int depth) { // BLOCKSTAT // STAT // BLOCKSTAT // BLOCK List<Integer> children = astTable.succTable.get(astNodeId); if (children != null && children.size() == 1 && astTable.getType(children.get(0)).equals("STAT")) { newLine(); curTab += 1; visit(children.get(0), depth + 1); curTab -= 1; } else { visitChildren(astNodeId, (depth + 1)); } return; } private void visit_CALL(Integer astNodeId, int depth) { printString("("); visitChildren(astNodeId, (depth + 1)); return; } private void visit_COMMAND(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if (children.size() != 2) { visitChildren(astNodeId, (depth + 1)); } else { visit(children.get(0), depth + 1); printString(" = "); visit(children.get(1), depth + 1); } printString(";"); // newLine(); return; } private void visit_COMPARISON(Integer astNodeId, int depth) { // COMPARISON // EXPRESSION // REL_OP // token <!=> // EXPRESSION List<Integer> children = astTable.succTable.get(astNodeId); if (children != null && children.size() > 1) { for (int i = 0; i < children.size(); i++) { if (i == 2 || i == 3) { printString(" "); } visit(children.get(i), depth + 1); } } else { visitChildren(astNodeId, (depth + 1)); } return; } private void visit_EQUATION(Integer astNodeId, int depth) { // EXPRESSION || PRODUCT || MODULO || CONDITION // PRODUCT // PRODUCT // BINARY_ARITHM_OP // token <+> // [PRODUCT // BINARY_ARITHM_OP // token <+>]* List<Integer> children = astTable.succTable.get(astNodeId); if (children.size() >= 4) { visit(children.get(0), depth + 1); printString(" "); visit(children.get(3), depth + 1); printString(" "); visit(children.get(1), depth + 1); for (int i = 4; i < children.size(); i += 3) { printString(" "); visit(children.get(i + 2), depth + 1); printString(" "); visit(children.get(i), depth + 1); } } else if (children.size() == 3 && astTable.getType(children.get(1)).equals("UNARY_LOGIC_OP")){ visit(children.get(2), depth + 1); printString(" "); visit(children.get(0), depth + 1); } else { visitChildren(astNodeId, depth + 1); } return; } private void visit_FUNCTION(Integer astNodeId, int depth) { // FUNCTION // token <function> // token <check_rc_wp> <identifier> // token <(> // FORMAL_PARAMETER_LIST // token <)> // BLOCK List<Integer> children = astTable.succTable.get(astNodeId); if (children != null) { for (int i = 0; i < children.size(); i++) { if (i == 1 || i == 5) { printString(" "); } visit(children.get(i), depth + 1); } } else { visitChildren(astNodeId, (depth + 1)); } return; } private void visit_IDREF(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if (children != null) { boolean previousIsToken = false; for (int i = 0; i < children.size(); i++) { if (astTable.getType(children.get(i)).equals("token")) { if (!previousIsToken){ previousIsToken = true; } else { printString("."); } } else { previousIsToken = false; } if (astTable.getType(children.get(i)).equals("EXPRESSION")) { printString("["); } visit(children.get(i), depth + 1); } } return; } private void visit_IF(Integer astNodeId, int depth) { // IF // token <if> // token <(> // CONDITION // token <)> // BLOCKSTAT // ... List<Integer> children = astTable.succTable.get(astNodeId); int i = 0; while(!astTable.getType(children.get(i)).equals("BLOCKSTAT")) { if (i == 1) { printString(" "); } visit(children.get(i), depth + 1); i++; } printString(" "); visit(children.get(i), depth + 1); i++; for(; i < children.size(); i++) { printString("else "); visit(children.get(i), depth + 1); } return; } private void visit_OPERAND(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if(children.size() == 2 && astTable.getType(children.get(1)).equals("token") && astTable.getTkImage(children.get(1)).equals(")")) { printString("("); } visitChildren(astNodeId, (depth + 1)); return; } private void visit_PARAMETER_LIST(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if (children != null) { visit(children.get(0), depth + 1); for (int i = 1; i < children.size(); i++) { printString(", "); visit(children.get(i), depth + 1); } } return; } private void visit_LAMBDA(Integer astNodeId, int depth) { // LAMBDA // token <function> // token <(> // FORMAL_PARAMETER_LIST // token <)> // BLOCK List<Integer> children = astTable.succTable.get(astNodeId); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { if (astTable.getType(children.get(i)).equals("BLOCK")) { printString(" "); } visit(children.get(i), depth + 1); } } else { visitChildren(astNodeId, depth + 1); } return; } private void visit_LIST(Integer astNodeId, int depth) { printString("{"); List<Integer> children = astTable.succTable.get(astNodeId); if (children != null) { visit(children.get(0), depth + 1); int i = 1; while (i < children.size() && astTable.getType(children.get(i)).equals("LIST_STATEMENT")) { printString(", "); visit(children.get(i), depth + 1); i++; } for (; i < children.size(); i++) { visit(children.get(i), depth + 1); } } return; } private void visit_POWERREST(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if(children != null && children.size() == 3) { visit(children.get(2), depth + 1); visit(children.get(0), depth + 1); } else { visitChildren(astNodeId, (depth + 1)); } return; } private void visit_RETURN(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if (children != null && children.size() > 0) { printString("return "); visitChildren(astNodeId, (depth + 1)); printString(";"); } else { printString("return;"); } // newLine(); return; } private void visit_STAT(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if (children != null) {// && children.size() > 0){ for (int i = 0; i < children.size(); i++) { visit(children.get(i), depth + 1); if (curColumn > 0) { newLine(); } } } else { visitChildren(astNodeId, depth + 1); } return; } private void visit_STATLIST(Integer astNodeId, int depth) { List<Integer> children = astTable.succTable.get(astNodeId); if (children != null){ for (int i = 0; i < children.size(); i++) { visit(children.get(i), depth + 1); } } return; } private void visit_VAR(Integer astNodeId, int depth) { // VAR // token <var> <variable> // token <ls> <identifier> // [EXPRESSION] List<Integer> children = astTable.succTable.get(astNodeId); if (children.size() == 3) { visit(children.get(0), depth + 1); printString(" "); visit(children.get(1), depth + 1); printString(" = "); visit(children.get(2), depth + 1); } else if (children.size() == 2) { visit(children.get(0), depth + 1); printString(" "); visit(children.get(1), depth + 1); } else { visitChildren(astNodeId, (depth + 1)); } printString(";"); // newLine(); return; } private void visit_WHILE(Integer astNodeId, int depth) { // WHILE // token <while> // token <(> // COMPARISON // token <)> // BLOCK List<Integer> children = astTable.succTable.get(astNodeId); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { if (i == 1|| i == 4) { printString(" "); } visit(children.get(i), depth + 1); } } else { visitChildren(astNodeId, depth + 1); } return; } public Integer visit(Integer astNodeId, int depth) { Integer retVal = null; String curType = astTable.getType(astNodeId); if (curType == null) { System.err.println("ERROR: missing type for node " + astNodeId); System.exit(1); } switch (curType) { case "BINARY_ARITHM_OP": case "BINARY_LOGIC_OP": case "BITSHIFT": case "BITWISEANDOR": case "BITWISENOT": case "CONDITION_LIST": case "IDLIST": case "LIST_STATEMENT": case "PARSE": case "POWER": case "REL_OP": case "SCRIPT": case "UNARY_ARITHM_OP": case "UNARY_LOGIC_OP": visit_GENERIC(astNodeId, depth); break; case "BLOCK": visit_BLOCK(astNodeId, depth); break; case "BLOCKSTAT": visit_BLOCKSTAT(astNodeId, depth); break; case "CALL": visit_CALL(astNodeId, depth); break; case "COMMAND": visit_COMMAND(astNodeId, depth); break; case "COMPARISON": visit_COMPARISON(astNodeId, depth); break; case "CONDITION": case "EXPRESSION": case "MODULO": case "PRODUCT": visit_EQUATION(astNodeId, depth); break; case "FUNCTION": visit_FUNCTION(astNodeId, depth); break; case "IDREF": visit_IDREF(astNodeId, depth); break; case "IF": visit_IF(astNodeId, depth); break; case "ACTUAL_PARAMETER_LIST": case "FORMAL_PARAMETER_LIST": visit_PARAMETER_LIST(astNodeId, depth); break; case "LAMBDA": visit_LAMBDA(astNodeId, depth); break; case "LIST": visit_LIST(astNodeId, depth); break; case "OPERAND": visit_OPERAND(astNodeId, depth); break; case "POWERREST": visit_POWERREST(astNodeId, depth); break; case "RETURN": visit_RETURN(astNodeId, depth); break; case "STAT": visit_STAT(astNodeId, depth); break; case "STATLIST": visit_STATLIST(astNodeId, depth); break; case "token": visit_token(astNodeId, depth); break; case "VAR": visit_VAR(astNodeId, depth); break; case "WHILE": visit_WHILE(astNodeId, depth); break; default: System.err.println("ERROR: invalid type " + curType + " for node " + astNodeId); System.exit(1); } return(retVal); } }
21.061321
101
0.587906
315ce88d5e205fd43720d2a48edf20c6e4c87dd8
4,534
package com.portfolio.usermaster.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.portfolio.securingweb.domain.User; import com.portfolio.securingweb.service.UserService; import com.portfolio.usermaster.validation.sub.UserCreateForm; import com.portfolio.usermaster.validation.sub.UserUpdateForm; /** * ユーザーマスタ画面のコントローラークラス.<br/> * クラスで@RequestMappingを利用すると、<br/> * リクエストURLが「クラスの@RequestMappingで指定したパス + メソッドで指定したパス」になります。 */ @Controller @RequestMapping("/usermaster") public class UserMasterController { /** * UserEntityクラスを操作するServiceクラス. */ @Autowired private UserService userService; /** * Redirect用一覧画面パス. */ private final String REDIRECT_INDEX_URL = "redirect:/usermaster/index"; /** * 新規登録画面のTemplateHTMLのパス. */ private final String NEW_TEMPLATE_PATH = "usermaster/usermaster/new"; /** * 編集画面のTemplateHTMLのパス. */ private final String EDIT_TEMPLATE_PATH = "usermaster/usermaster/edit"; /** * 詳細画面のTemplateHTMLのパス. */ private final String SHOW_TEMPLATE_PATH = "usermaster/usermaster/show"; /** * ユーザーマスタ一覧画面表示. * @param model * @return HOME画面のテンプレートパス */ @RequestMapping("index") public String index(Model model){ List<User> users = userService.findAll(); model.addAttribute("users", users); return "usermaster/usermaster/index"; } /** * ユーザー新規登録画面表示. * @param userCreateForm * @param model * @return ユーザー新規登録画面のテンプレートパス */ @GetMapping("new") public String newUser(@ModelAttribute UserCreateForm userCreateForm, Model model) { return NEW_TEMPLATE_PATH; } /** * ユーザー編集画面表示. * @param id ユーザーID * @param model * @return ユーザー編集画面のテンプレートパス */ @GetMapping("edit/{id}") public String edit(@PathVariable String id, Model model) { User user = userService.findOne(id); model.addAttribute("userUpdateForm", new UserUpdateForm(user)); return EDIT_TEMPLATE_PATH; } /** * ユーザー詳細画面表示. * @param id ユーザーID * @param model * @return ユーザー詳細画面のテンプレートパス */ @GetMapping("show/{id}") public String show(@PathVariable String id, Model model) { // ユーザー情報を取得 User user = userService.findOne(id); model.addAttribute("user", user); return SHOW_TEMPLATE_PATH; } /** * ユーザーの新規登録処理. * @param userCreateForm 新規登録画面の入力情報 * @param model * @return 遷移先パス(エラーの場合、新規登録画面のテンプレートパス。成功の場合、Topページ) */ @PostMapping("create") public String create(@Validated @ModelAttribute UserCreateForm userCreateForm, final BindingResult bindingResult, Model model) { // 入力チェック if (bindingResult.hasErrors()) { // 入力チェックエラー時の処理 return NEW_TEMPLATE_PATH; } User user = userCreateForm.toEntity(); // ユーザー情報を保存 userService.save(user); return REDIRECT_INDEX_URL; } /** * ユーザーの更新処理. * @param id ユーザーID * @param userUpdateForm 編集画面の入力情報 * @param bindingResult 入力チェック結果 * @param model * @return 遷移先パス(エラーの場合、編集画面のテンプレートパス。成功の場合、Topページ) */ @PostMapping("update/{id}") public String update(@PathVariable String id, @Validated @ModelAttribute UserUpdateForm userUpdateForm, final BindingResult bindingResult, Model model) { // 入力チェック if (bindingResult.hasErrors()) { // 入力チェックエラー時の処理 return EDIT_TEMPLATE_PATH; } User user = userUpdateForm.toEntity(); // ユーザー情報を保存 userService.save(user); return REDIRECT_INDEX_URL; } /** * ユーザーの削除処理. * @param id ユーザーID * @param model * @return TopページのURL */ @PostMapping("delete/{id}") public String destroy(@PathVariable String id) { userService.delete(id); return REDIRECT_INDEX_URL; } }
26.51462
107
0.664535
886949893c681c0e1d2ce8b4520bee703a09b700
5,615
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2017. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // ColumnChartFillFragment.java is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** package com.scichart.examples.fragments; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.Spinner; import android.widget.ToggleButton; import com.scichart.charting.model.dataSeries.XyDataSeries; import com.scichart.charting.visuals.SciChartSurface; import com.scichart.charting.visuals.axes.AxisAlignment; import com.scichart.charting.visuals.axes.IAxis; import com.scichart.charting.visuals.renderableSeries.FastColumnRenderableSeries; import com.scichart.data.model.DoubleRange; import com.scichart.drawing.common.BrushStyle; import com.scichart.drawing.common.LinearGradientBrushStyle; import com.scichart.drawing.common.RadialGradientBrushStyle; import com.scichart.drawing.common.SolidBrushStyle; import com.scichart.drawing.common.TextureBrushStyle; import com.scichart.drawing.common.TextureMappingMode; import com.scichart.drawing.utility.ColorUtil; import com.scichart.examples.R; import com.scichart.examples.components.SpinnerStringAdapter; import com.scichart.examples.fragments.base.ExampleBaseFragment; import java.util.Collections; import butterknife.BindView; import butterknife.OnClick; import butterknife.OnItemSelected; public class ColumnChartFillFragment extends ExampleBaseFragment { @BindView(R.id.chart) SciChartSurface surface; @BindView(R.id.fillList) Spinner fillSpinner; @BindView(R.id.textureMappingModesList) Spinner textureMappingModesSpinner; @BindView(R.id.rotate) ToggleButton rotateChartButton; private FastColumnRenderableSeries rs; private Bitmap texture; private IAxis xAxis, yAxis; @Override protected int getLayoutId() { return R.layout.example_column_chart_fill_fragment; } @Override protected void initExample() { texture = BitmapFactory.decodeResource(getResources(), R.drawable.example_scichartlogo); final SpinnerStringAdapter seriesTypeAdapter = new SpinnerStringAdapter(getActivity(), R.array.fill_list); fillSpinner.setAdapter(seriesTypeAdapter); fillSpinner.setSelection(0); final SpinnerStringAdapter seriesMappingAdapter = new SpinnerStringAdapter(getActivity(), R.array.texture_mapping_mode_list); textureMappingModesSpinner.setAdapter(seriesMappingAdapter); textureMappingModesSpinner.setSelection(0); xAxis = sciChartBuilder.newNumericAxis().withGrowBy(new DoubleRange(0.1d, 0.1d)).build(); yAxis = sciChartBuilder.newNumericAxis().withGrowBy(new DoubleRange(0.1d, 0.1d)).build(); final XyDataSeries<Double, Double> dataSeries = new XyDataSeries<>(Double.class, Double.class); dataSeries.append(new Double[]{0d, 2d, 4d, 6d, 8d, 10d}, new Double[]{1d, 5d, -5d, -10d, 10d, 3d}); rs = sciChartBuilder.newColumnSeries().withDataSeries(dataSeries).withStrokeStyle(ColorUtil.White, 3f, false).build(); surface.getChartModifiers().add(sciChartBuilder.newModifierGroupWithDefaultModifiers().build()); Collections.addAll(surface.getXAxes(), xAxis); Collections.addAll(surface.getYAxes(), yAxis); Collections.addAll(surface.getRenderableSeries(), rs); surface.zoomExtents(); } @OnItemSelected(R.id.textureMappingModesList) public void onTextureMappingModeSelected(int position) { switch (position){ case 0: rs.setFillBrushMappingMode(TextureMappingMode.PerScreen); break; case 1: rs.setFillBrushMappingMode(TextureMappingMode.PerPrimitive); break; } } @OnItemSelected(R.id.fillList) public void onFillStyleSelected(int position) { BrushStyle brushStyle = null; switch (position) { case 0: brushStyle = new SolidBrushStyle(ColorUtil.argb(0xEE, 0xFF, 0xC9, 0xA8)); break; case 1: brushStyle = new LinearGradientBrushStyle(0.25f, 0.25f, 0.75f, 0.75f, ColorUtil.argb(0xEE, 0xFF, 0xC9, 0xA8), ColorUtil.argb(0xEE, 0x13, 0x24, 0xA5)); break; case 2: brushStyle = new RadialGradientBrushStyle(0.5f, 0.5f, 0.25f, 0.5f, ColorUtil.argb(0xEE, 0xFF, 0xC9, 0xA8), ColorUtil.argb(0xEE, 0x13, 0x24, 0xA5)); break; case 3: brushStyle = new TextureBrushStyle(texture); break; } rs.setFillBrushStyle(brushStyle); } @OnClick(R.id.rotate) public void onRotateButtonClicked(ToggleButton button){ if(button.isChecked()){ xAxis.setAxisAlignment(AxisAlignment.Right); yAxis.setAxisAlignment(AxisAlignment.Bottom); } else{ xAxis.setAxisAlignment(AxisAlignment.Bottom); yAxis.setAxisAlignment(AxisAlignment.Right); } } }
37.684564
166
0.694746
b0b250a6d39d4aff6d6e8bed4bbc09f8d55c9e73
2,964
package unl.cse.counting; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; public class Combination<T> implements Iterable<List<T>> { private final List<T> underlyingSet; private final Integer r; public Combination(Collection<T> collection, Integer r) { if(collection == null || collection.size() == 0) { throw new IllegalArgumentException("Combination expects a non-null, non-empty collection"); } if(r < 0 || r > collection.size()) { throw new IllegalArgumentException("Invalid r-value: "+r); } this.underlyingSet = Collections.unmodifiableList(new ArrayList<T>(collection)); this.r = r; } private List<T> getOrderedList(List<Integer> indices) { List<T> result = new ArrayList<T>(indices.size()); for(Integer index : indices) { result.add(this.underlyingSet.get(index-1)); } return result; } @Override public Iterator<List<T>> iterator() { return new Iterator<List<T>>() { private List<T> curr = underlyingSet.subList(0, r); private final List<Integer> a = new ArrayList<Integer>(underlyingSet.size()); private final List<Integer> c; { for(int i=1; i<=underlyingSet.size(); i++) { a.add(i); } c = a.subList(0, r); } @Override public boolean hasNext() { return (curr != null); } @Override public List<T> next() { List<T> result = curr; int i = r; while(i > 0 && c.get(i-1).intValue() == (underlyingSet.size()-r+i)) { i--; } if(i == 0) { curr = null; } else { c.set(i-1, c.get(i-1)+1); for(int j=(i+1); j<=r; j++) { c.set(j-1, c.get(i-1)+j-i); } this.curr = getOrderedList(c); } return result; } @Override public void remove() { throw new UnsupportedOperationException("remove is not allowed"); } }; } public List<List<T>> getCombinations() { List<List<T>> result = new ArrayList<List<T>>(); int n = this.underlyingSet.size(); List<Integer> a = new ArrayList<Integer>(n); for(int i=1; i<=n; i++) { a.add(i); } List<Integer> c = a.subList(0, r); result.add(getOrderedList(c)); while(true) { int i = r; while(i > 0 && c.get(i-1).intValue() == (n-r+i)) { i--; } if(i == 0) { break; } c.set(i-1, c.get(i-1)+1); for(int j=(i+1); j<=r; j++) { c.set(j-1, c.get(i-1)+j-i); } result.add(getOrderedList(c)); } return result; } public static void main(String args[]) { List<Character> c = Arrays.asList('a', 'b', 'c', 'd', 'e'); Combination<Character> comb = new Combination<Character>(c, 3); System.out.println("gettin' all: "); int count = 1; for(List<Character> list : comb) { System.out.println(count +": " +list); count++; } } }
24.097561
95
0.575911
b623fb0b35765438f5618789ab1c2a7359ce64b9
3,663
package com.lakeel.altla.sample.wifibatterydrain; import android.Manifest; import android.content.Context; import android.content.Intent; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.view.View; import android.widget.Button; import android.widget.EditText; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnTextChanged; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE_REQUEST_PERMISSIONS = 1; @BindView(R.id.view_top) View mViewTop; @BindView(R.id.text_input_layout) TextInputLayout mTextInputLayout; @BindView(R.id.edit_text_interval) EditText mEditTextInterval; @BindView(R.id.button_start) Button mButtonStart; @BindView(R.id.button_stop) Button mButtonStop; private WifiManager mWifiManager; private PermissionManager mPermissionManager; public static Intent createStartIntent(@NonNull Context context) { return new Intent(context, MainActivity.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); mPermissionManager = new PermissionManager.Builder(this) .addPermission(Manifest.permission.ACCESS_WIFI_STATE) .addPermission(Manifest.permission.CHANGE_WIFI_STATE) .build(); if (!mPermissionManager.isPermissionsGranted()) { mPermissionManager.requestPermissions(REQUEST_CODE_REQUEST_PERMISSIONS); } mEditTextInterval.setText(String.valueOf(MainService.DEFAULT_INTERVAL)); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_CODE_REQUEST_PERMISSIONS) { if (mPermissionManager.isRequestedPermissionsGranted(grantResults)) { mButtonStart.setEnabled(true); } else { // rationale Snackbar.make(mViewTop, R.string.permission_error, Snackbar.LENGTH_LONG).show(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @OnTextChanged(value = R.id.edit_text_interval, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED) void onTextChanged(Editable editable) { if (editable.length() == 0) { mTextInputLayout.setError(getString(R.string.error_required)); mButtonStart.setEnabled(false); } else { mTextInputLayout.setError(null); mButtonStart.setEnabled(true); } } @OnClick(R.id.button_start) void onClickButtonStart() { mWifiManager.setWifiEnabled(true); String intervalString = mEditTextInterval.getText().toString(); int interval = Integer.parseInt(intervalString); Intent intent = MainService.createIntent(getApplicationContext(), interval); startService(intent); } @OnClick(R.id.button_stop) void onClickButtonStop() { Intent intent = MainService.createIntent(getApplicationContext()); stopService(intent); } }
32.415929
105
0.701884
11f13bf621c09759432c00523baaba267a115480
12,113
/*- * ============LICENSE_START========================================== * OPENECOMP - DCAE * =================================================================== * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ */ /** */ package org.openecomp.ncomp.openstack.neutron.impl; import org.openecomp.ncomp.openstack.neutron.CreateRouterRequest; import org.openecomp.ncomp.openstack.neutron.NeutronPackage; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EDataTypeEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Create Router Request</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.openecomp.ncomp.openstack.neutron.impl.CreateRouterRequestImpl#getName <em>Name</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.neutron.impl.CreateRouterRequestImpl#getAdmin_state_up <em>Admin state up</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.neutron.impl.CreateRouterRequestImpl#getShared <em>Shared</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.neutron.impl.CreateRouterRequestImpl#getExternalNetwork <em>External Network</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.neutron.impl.CreateRouterRequestImpl#getPorts <em>Ports</em>}</li> * <li>{@link org.openecomp.ncomp.openstack.neutron.impl.CreateRouterRequestImpl#getSubnets <em>Subnets</em>}</li> * </ul> * * @generated */ public class CreateRouterRequestImpl extends NeutronRequestImpl implements CreateRouterRequest { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getAdmin_state_up() <em>Admin state up</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAdmin_state_up() * @generated * @ordered */ protected static final Boolean ADMIN_STATE_UP_EDEFAULT = null; /** * The cached value of the '{@link #getAdmin_state_up() <em>Admin state up</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAdmin_state_up() * @generated * @ordered */ protected Boolean admin_state_up = ADMIN_STATE_UP_EDEFAULT; /** * The default value of the '{@link #getShared() <em>Shared</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShared() * @generated * @ordered */ protected static final Boolean SHARED_EDEFAULT = null; /** * The cached value of the '{@link #getShared() <em>Shared</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getShared() * @generated * @ordered */ protected Boolean shared = SHARED_EDEFAULT; /** * The default value of the '{@link #getExternalNetwork() <em>External Network</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExternalNetwork() * @generated * @ordered */ protected static final String EXTERNAL_NETWORK_EDEFAULT = null; /** * The cached value of the '{@link #getExternalNetwork() <em>External Network</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExternalNetwork() * @generated * @ordered */ protected String externalNetwork = EXTERNAL_NETWORK_EDEFAULT; /** * The cached value of the '{@link #getPorts() <em>Ports</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPorts() * @generated * @ordered */ protected EList<String> ports; /** * The cached value of the '{@link #getSubnets() <em>Subnets</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSubnets() * @generated * @ordered */ protected EList<String> subnets; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CreateRouterRequestImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return NeutronPackage.Literals.CREATE_ROUTER_REQUEST; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, NeutronPackage.CREATE_ROUTER_REQUEST__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Boolean getAdmin_state_up() { return admin_state_up; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAdmin_state_up(Boolean newAdmin_state_up) { Boolean oldAdmin_state_up = admin_state_up; admin_state_up = newAdmin_state_up; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, NeutronPackage.CREATE_ROUTER_REQUEST__ADMIN_STATE_UP, oldAdmin_state_up, admin_state_up)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Boolean getShared() { return shared; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setShared(Boolean newShared) { Boolean oldShared = shared; shared = newShared; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, NeutronPackage.CREATE_ROUTER_REQUEST__SHARED, oldShared, shared)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getExternalNetwork() { return externalNetwork; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExternalNetwork(String newExternalNetwork) { String oldExternalNetwork = externalNetwork; externalNetwork = newExternalNetwork; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, NeutronPackage.CREATE_ROUTER_REQUEST__EXTERNAL_NETWORK, oldExternalNetwork, externalNetwork)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getPorts() { if (ports == null) { ports = new EDataTypeEList<String>(String.class, this, NeutronPackage.CREATE_ROUTER_REQUEST__PORTS); } return ports; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getSubnets() { if (subnets == null) { subnets = new EDataTypeEList<String>(String.class, this, NeutronPackage.CREATE_ROUTER_REQUEST__SUBNETS); } return subnets; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case NeutronPackage.CREATE_ROUTER_REQUEST__NAME: return getName(); case NeutronPackage.CREATE_ROUTER_REQUEST__ADMIN_STATE_UP: return getAdmin_state_up(); case NeutronPackage.CREATE_ROUTER_REQUEST__SHARED: return getShared(); case NeutronPackage.CREATE_ROUTER_REQUEST__EXTERNAL_NETWORK: return getExternalNetwork(); case NeutronPackage.CREATE_ROUTER_REQUEST__PORTS: return getPorts(); case NeutronPackage.CREATE_ROUTER_REQUEST__SUBNETS: return getSubnets(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case NeutronPackage.CREATE_ROUTER_REQUEST__NAME: setName((String)newValue); return; case NeutronPackage.CREATE_ROUTER_REQUEST__ADMIN_STATE_UP: setAdmin_state_up((Boolean)newValue); return; case NeutronPackage.CREATE_ROUTER_REQUEST__SHARED: setShared((Boolean)newValue); return; case NeutronPackage.CREATE_ROUTER_REQUEST__EXTERNAL_NETWORK: setExternalNetwork((String)newValue); return; case NeutronPackage.CREATE_ROUTER_REQUEST__PORTS: getPorts().clear(); getPorts().addAll((Collection<? extends String>)newValue); return; case NeutronPackage.CREATE_ROUTER_REQUEST__SUBNETS: getSubnets().clear(); getSubnets().addAll((Collection<? extends String>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case NeutronPackage.CREATE_ROUTER_REQUEST__NAME: setName(NAME_EDEFAULT); return; case NeutronPackage.CREATE_ROUTER_REQUEST__ADMIN_STATE_UP: setAdmin_state_up(ADMIN_STATE_UP_EDEFAULT); return; case NeutronPackage.CREATE_ROUTER_REQUEST__SHARED: setShared(SHARED_EDEFAULT); return; case NeutronPackage.CREATE_ROUTER_REQUEST__EXTERNAL_NETWORK: setExternalNetwork(EXTERNAL_NETWORK_EDEFAULT); return; case NeutronPackage.CREATE_ROUTER_REQUEST__PORTS: getPorts().clear(); return; case NeutronPackage.CREATE_ROUTER_REQUEST__SUBNETS: getSubnets().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case NeutronPackage.CREATE_ROUTER_REQUEST__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case NeutronPackage.CREATE_ROUTER_REQUEST__ADMIN_STATE_UP: return ADMIN_STATE_UP_EDEFAULT == null ? admin_state_up != null : !ADMIN_STATE_UP_EDEFAULT.equals(admin_state_up); case NeutronPackage.CREATE_ROUTER_REQUEST__SHARED: return SHARED_EDEFAULT == null ? shared != null : !SHARED_EDEFAULT.equals(shared); case NeutronPackage.CREATE_ROUTER_REQUEST__EXTERNAL_NETWORK: return EXTERNAL_NETWORK_EDEFAULT == null ? externalNetwork != null : !EXTERNAL_NETWORK_EDEFAULT.equals(externalNetwork); case NeutronPackage.CREATE_ROUTER_REQUEST__PORTS: return ports != null && !ports.isEmpty(); case NeutronPackage.CREATE_ROUTER_REQUEST__SUBNETS: return subnets != null && !subnets.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(", admin_state_up: "); result.append(admin_state_up); result.append(", shared: "); result.append(shared); result.append(", externalNetwork: "); result.append(externalNetwork); result.append(", ports: "); result.append(ports); result.append(", subnets: "); result.append(subnets); result.append(')'); return result.toString(); } } //CreateRouterRequestImpl
28.703791
151
0.669033
bd13e31198aa11745c80e33dca5ffad75832780a
226
package pl.ether.models; public enum ValidationLevel { ALL(0), BODY(1), BODY_TEXT(3); int choice; ValidationLevel(int lvl) { // TODO Auto-generated constructor stub choice = lvl; } }
20.545455
48
0.597345
cc4aebf3dff336eed039168f635ded37e9fc8832
1,379
package org.comroid.dreadpool.future; import java.time.Instant; import java.util.concurrent.CompletableFuture; import java.util.function.BooleanSupplier; public final class ScheduledCompletableFuture<T> extends CompletableFuture<T> implements ExecutionFuture<T> { private final Instant targetTime; private final BooleanSupplier cancellation; private final BooleanSupplier isCancelled; @Override public boolean isCancelled() { return isCancelled.getAsBoolean() || super.isCancelled(); } @Override public Instant getTargetTime() { return targetTime; } public ScheduledCompletableFuture(long targetTime, BooleanSupplier cancellation, BooleanSupplier isCancelled) { this.targetTime = Instant.ofEpochMilli(targetTime); this.cancellation = cancellation; this.isCancelled = isCancelled; } @Override public void pushValue(T value) { validateUndone(); complete(value); } @Override public void pushException(Exception ex) { validateUndone(); completeExceptionally(ex); } private void validateUndone() { if (isDone()) throw new IllegalStateException("Task has already been executed!"); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return cancellation.getAsBoolean(); } }
27.58
115
0.700508
bc7ac32d29d2ffb355525310e51606f6b971fe0a
2,071
package com.survey.controller; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import static org.hamcrest.CoreMatchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @Transactional public class RegistrationControllerTest { @Autowired private MockMvc mockMvc; @Test public void registrationPageTest() throws Exception { mockMvc.perform(get("/registration")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("Зарегистрироваться"))); } @Test @Ignore public void handleRegistrationForm() { } @Test public void deniedActivateUser() throws Exception { mockMvc.perform(get("/activate/ ")) .andDo(print()) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/login")); } @Test @Ignore public void activateUser() throws Exception { } @Test public void getRestorePasswordPage() throws Exception { mockMvc.perform(get("/restore_password")).andDo(print()).andExpect(status().isOk()); } @Test public void emailUsedTest() throws Exception { mockMvc.perform(get("/search_used_mail").param("enteredEmail", "[email protected]")) .andDo(print()) .andExpect(status().isOk()); } }
32.873016
92
0.712216
15e0baa04c57c70f66c240781f67ddfac20f680a
170
package cn.ervin; public final class Constants { public static final String MP4_FULL_PATH = "G:\\第三方\\youtube\\Getting Started with Spring Boot-sbPSjI4tt10.mp4"; }
24.285714
116
0.752941
99acddabaf383e556b9da66dd57f9d8280f4cf82
929
package viko.eif.lt.dfultinavcius.freeflight; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class FreeflightApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(FreeflightApplication.class, args); } @GetMapping("/") @ResponseBody public String hello() { return "Hello to the FreeFlight REST API !"; } }
32.034483
81
0.805167
e21842f0043e686986a91c30cd889912bdd9f490
2,501
package pl.java.scalatech.exercise.n1; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.test.context.jdbc.Sql; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Sql( statements = { "INSERT INTO JobCandidate (id, version, fullName) VALUES (1, 0,'przodownik')", "INSERT INTO JobCandidate (id, version, fullName) VALUES (2, 0,'kowalksi')", "INSERT INTO JobCandidate (id, version, fullName) VALUES (3, 0,'nowak')", "INSERT INTO JobCandidate (id, version, fullName) VALUES (4, 0,'lis')", "INSERT INTO JobCandidate (id, version, fullName) VALUES (5, 0,'wilk')", "INSERT INTO JobCandidate (id, version, fullName) VALUES (6, 0,'sarna')", "INSERT INTO JobCandidate (id, version, fullName) VALUES (7, 0,'borsuk')", "INSERT INTO Skill (id, version, name,candidateId) VALUES (1, 0,'java',1)", //przodownik "INSERT INTO Skill (id, version, name,candidateId) VALUES (2, 0,'hibernate',1)",//przodownik "INSERT INTO Skill (id, version, name,candidateId) VALUES (3, 0,'groovy',1)",//przodownik "INSERT INTO Skill (id, version, name,candidateId) VALUES (4, 0,'gradle',1)",//przodownik "INSERT INTO Skill (id, version, name,candidateId) VALUES (5, 0,'c#',2)", //kowalksi "INSERT INTO Skill (id, version, name,candidateId) VALUES (6, 0,'java',2)",//kowalksi "INSERT INTO Skill (id, version, name,candidateId) VALUES (7, 0,'maven',3)",//nowak "INSERT INTO Skill (id, version, name,candidateId) VALUES (8, 0,'c#',4)", //list "INSERT INTO Skill (id, version, name,candidateId) VALUES (9, 0,'c#',5)", //wilk "INSERT INTO Skill (id, version, name,candidateId) VALUES (10, 0,'c#',6)", //sarna "INSERT INTO Skill (id, version, name,candidateId) VALUES (11, 0,'eclipse',6)", //sarna "INSERT INTO Skill (id, version, name,candidateId) VALUES (12, 0,'uml',7)", //borsku }, executionPhase = BEFORE_TEST_METHOD ) public @interface SqlDataN1 { }
55.577778
108
0.597361
2eda3aeebded1af655fef4d048f1c0e1791f8516
2,558
package com.omertron.imdbapi.model; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract class to handle any unknown properties by outputting a log message * * @author stuart.boston */ public abstract class AbstractJsonMapping implements Serializable, IStatusMessage { private static final transient Logger LOG = LoggerFactory.getLogger(AbstractJsonMapping.class); @JsonProperty("error") private ImdbStatusMessage statusMessage = null; private boolean error = Boolean.FALSE; /** * Get the status message * * @return */ @Override public ImdbStatusMessage getStatusMessage() { return statusMessage; } /** * Set the detailed status message for the error * * @param statusMessage */ @Override public void setStatusMessage(ImdbStatusMessage statusMessage) { this.statusMessage = statusMessage; // Set the error flag this.error = Boolean.TRUE; } /** * Set the status message for the error * * @param message */ @Override public void setStatusMessageMsg(String message) { setStatusMessage(new ImdbStatusMessage(message)); } /** * Set the status message and exception for the error * * @param message * @param error */ @Override public void setStatusMessage(String message, Throwable error) { ImdbStatusMessage sm = new ImdbStatusMessage(message); sm.setThrownError(error); setStatusMessage(sm); } /** * Does the result have an error? * * @return */ @Override public boolean isError() { return error; } /** * Handle unknown properties and print a message * * @param key * @param value */ @JsonAnySetter protected void handleUnknown(String key, Object value) { StringBuilder unknown = new StringBuilder(this.getClass().getSimpleName()); unknown.append(": Unknown property='").append(key); unknown.append("' value='").append(value).append("'"); LOG.trace(unknown.toString()); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE, Boolean.FALSE); } }
25.838384
105
0.662627
d3bf95d6f812e518346defab070e51a232b903a8
779
package dev.abarmin.home.is.backend.readings.repository; import dev.abarmin.home.is.backend.readings.domain.DeviceReadingEntity; import java.time.LocalDate; import java.util.Optional; import org.springframework.data.repository.CrudRepository; /** * @author Aleksandr Barmin */ public interface DeviceReadingJdbcRepository extends CrudRepository<DeviceReadingEntity, Integer> { Iterable<DeviceReadingEntity> findDeviceReadingByYearAndFlat(int year, int flat); Iterable<DeviceReadingEntity> findDeviceReadingByFlat(int flat); Optional<DeviceReadingEntity> findDeviceReadingByFlatAndDeviceAndDate(int flat, int device, LocalDate date); }
38.95
99
0.693196
3b0b955fbb03ad2369261033c6102b10ef8b9ff1
2,344
import org.apache.pdfbox.util.Splitter; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.exceptions.COSVisitorException; import java.io.IOException; import java.util.List; import java.util.Iterator; /** * * @author Stephen H * Created 21 June 2014 * Revised 25 June 2014 * Email [email protected] * * An example showing how to split a PDF file. * Here is how it works * 1. Load a PDF file. Make provisions to catch or throw IOException. * 2. Create an object of Splitter * 3. Use the split method to split the document * NOTE: This will create a PDF document out of each page and return them as a list * 4. The split method returns the PDFs as a list * 5. Create an iterator to iterate through them * 6. Do whatever you want with each file but catch COSVisitorException * In my case I am naming them according to the page number which I assume to start with 1 and saving them. * 7. If you get a COSVisitorException error display it with the number of the page where it occurred. */ public class SplitDemo { public static void main(String[] args) throws IOException { // Load the PDF. The PDDocument throws IOException PDDocument document = new PDDocument(); document = PDDocument.load("C:\\Main.pdf"); // Create a Splitter object Splitter splitter = new Splitter(); // We need this as split method returns a list List<PDDocument> listOfSplitPages; // We are receiving the split pages as a list of PDFs listOfSplitPages = splitter.split(document); // We need an iterator to iterate through them Iterator<PDDocument> iterator = listOfSplitPages.listIterator(); // I am using variable i to denote page numbers. int i = 1; while(iterator.hasNext()){ PDDocument pd = iterator.next(); try{ // Saving each page with its assumed page no. pd.save("C:\\Page " + i++ + ".pdf"); } catch (COSVisitorException anException){ // Something went wrong with a PDF object System.out.println("Something went wrong with page " + (i-1) + "\n Here is the error message" + anException); } } } }
39.728814
141
0.642491
36a21dfaac1df527debefb8721af80a1d50fd321
28,853
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.user.rebind.rpc; import com.google.gwt.core.client.UnsafeNativeLong; import com.google.gwt.core.client.impl.WeakMapping; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.typeinfo.JArrayType; import com.google.gwt.core.ext.typeinfo.JClassType; import com.google.gwt.core.ext.typeinfo.JConstructor; import com.google.gwt.core.ext.typeinfo.JEnumType; import com.google.gwt.core.ext.typeinfo.JField; import com.google.gwt.core.ext.typeinfo.JMethod; import com.google.gwt.core.ext.typeinfo.JPrimitiveType; import com.google.gwt.core.ext.typeinfo.JType; import com.google.gwt.core.ext.typeinfo.JTypeParameter; import com.google.gwt.core.ext.typeinfo.TypeOracle; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.lang.Object_Array_CustomFieldSerializer; import com.google.gwt.user.client.rpc.impl.ReflectionHelper; import com.google.gwt.user.client.rpc.impl.TypeHandler; import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; import com.google.gwt.user.rebind.SourceWriter; import java.io.PrintWriter; /** * Creates a field serializer for a class that implements * {@link com.google.gwt.user.client.rpc.IsSerializable IsSerializable} or * {@link java.io.Serializable Serializable}. The field serializer is emitted * into the same package as the class that it serializes. * * TODO(mmendez): Need to make the generated field serializers final * TODO(mmendez): Would be nice to be able to have imports, rather than using * fully qualified type names everywhere */ public class FieldSerializerCreator { /* * NB: FieldSerializerCreator generates two different sets of code for DevMode * and ProdMode. In ProdMode, the generated code uses the JSNI violator * pattern to access private class members. In DevMode, the generated code * uses ReflectionHelper instead of JSNI to avoid the many JSNI * boundary-crossings which are slow in DevMode. */ private static final String WEAK_MAPPING_CLASS_NAME = WeakMapping.class.getName(); private final TreeLogger logger; private final GeneratorContext context; private final JClassType customFieldSerializer; private final boolean customFieldSerializerHasInstantiate; private final String fieldSerializerName; private final boolean isJRE; private final boolean isProd; private final String methodEnd; private final String methodStart; private final JClassType serializableClass; private final JField[] serializableFields; private SourceWriter sourceWriter; private final SerializableTypeOracle typesSentFromBrowser; private final SerializableTypeOracle typesSentToBrowser; private final TypeOracle typeOracle; /** * Constructs a field serializer for the class. */ public FieldSerializerCreator(TreeLogger logger, GeneratorContext context, SerializableTypeOracle typesSentFromBrowser, SerializableTypeOracle typesSentToBrowser, JClassType requestedClass, JClassType customFieldSerializer) { this.logger = logger; this.context = context; this.isProd = context.isProdMode(); methodStart = isProd ? "/*-{" : "{"; methodEnd = isProd ? "}-*/;" : "}"; this.customFieldSerializer = customFieldSerializer; assert (requestedClass != null); assert (requestedClass.isClass() != null || requestedClass.isArray() != null); this.typeOracle = context.getTypeOracle(); this.typesSentFromBrowser = typesSentFromBrowser; this.typesSentToBrowser = typesSentToBrowser; serializableClass = requestedClass; serializableFields = SerializationUtils.getSerializableFields(context, requestedClass); this.fieldSerializerName = SerializationUtils.getStandardSerializerName(serializableClass); this.isJRE = SerializableTypeOracleBuilder.isInStandardJavaPackage(serializableClass .getQualifiedSourceName()); this.customFieldSerializerHasInstantiate = (customFieldSerializer != null && CustomFieldSerializerValidator.hasInstantiationMethod( customFieldSerializer, serializableClass)); } public String realize(TreeLogger logger, GeneratorContext ctx) { assert (ctx != null); assert (typesSentFromBrowser.isSerializable(serializableClass) || typesSentToBrowser .isSerializable(serializableClass)); logger = logger.branch(TreeLogger.DEBUG, "Generating a field serializer for type '" + serializableClass.getQualifiedSourceName() + "'", null); sourceWriter = getSourceWriter(logger, ctx); if (sourceWriter == null) { return fieldSerializerName; } assert sourceWriter != null; writeFieldAccessors(); writeDeserializeMethod(); maybeWriteInstatiateMethod(); writeSerializeMethod(); maybeWriteTypeHandlerImpl(); sourceWriter.commit(logger); return fieldSerializerName; } private boolean classIsAccessible() { JClassType testClass = serializableClass; while (testClass != null) { if (testClass.isPrivate() || (isJRE && !testClass.isPublic())) { return false; } testClass = testClass.getEnclosingType(); } return true; } private String createArrayInstantiationExpression(JArrayType array) { StringBuilder sb = new StringBuilder(); sb.append("new "); sb.append(array.getLeafType().getQualifiedSourceName()); sb.append("[size]"); for (int i = 0; i < array.getRank() - 1; ++i) { sb.append("[]"); } return sb.toString(); } private boolean ctorIsAccessible() { JConstructor ctor = serializableClass.findConstructor(new JType[0]); if (ctor.isPrivate() || (isJRE && !ctor.isPublic())) { return false; } return true; } /** * Returns the depth of the given class in the class hierarchy (where the * depth of java.lang.Object == 0). */ private int getDepth(JClassType clazz) { int depth = 0; while ((clazz = clazz.getSuperclass()) != null) { depth++; } return depth; } private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext ctx) { int packageNameEnd = fieldSerializerName.lastIndexOf('.'); String className; String packageName; if (packageNameEnd != -1) { className = fieldSerializerName.substring(packageNameEnd + 1); packageName = fieldSerializerName.substring(0, packageNameEnd); } else { className = fieldSerializerName; packageName = ""; } PrintWriter printWriter = ctx.tryCreate(logger, packageName, className); if (printWriter == null) { return null; } ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className); composerFactory.addImport(SerializationException.class.getCanonicalName()); composerFactory.addImport(SerializationStreamReader.class.getCanonicalName()); composerFactory.addImport(SerializationStreamWriter.class.getCanonicalName()); composerFactory.addImport(ReflectionHelper.class.getCanonicalName()); composerFactory.addAnnotationDeclaration("@SuppressWarnings(\"deprecation\")"); if (needsTypeHandler()) { composerFactory.addImplementedInterface(TypeHandler.class.getCanonicalName()); } return composerFactory.createSourceWriter(ctx, printWriter); } private String getTypeSig(JMethod deserializationMethod) { JTypeParameter[] typeParameters = deserializationMethod.getTypeParameters(); String typeSig = ""; if (typeParameters.length > 0) { StringBuilder sb = new StringBuilder(); sb.append('<'); for (JTypeParameter typeParameter : typeParameters) { sb.append(typeParameter.getFirstBound().getQualifiedSourceName()); sb.append(','); } sb.setCharAt(sb.length() - 1, '>'); typeSig = sb.toString(); } return typeSig; } private void maybeSuppressLongWarnings(JType fieldType) { if (fieldType == JPrimitiveType.LONG) { /** * Accessing long from JSNI causes a error, but field serializers need to * be able to do just that in order to bypass java accessibility * restrictions. */ sourceWriter.println("@" + UnsafeNativeLong.class.getName()); } } /** * Writes an instantiate method. Examples: * * <h2>Class</h2> * * <pre> * public static com.google.gwt.sample.client.Student instantiate( * SerializationStreamReader streamReader) throws SerializationException { * return new com.google.gwt.sample.client.Student(); * } * </pre> * * <h2>Class with private ctor</h2> * * <pre> * public static native com.google.gwt.sample.client.Student instantiate( * SerializationStreamReader streamReader) throws SerializationException /*-{ * return @com.google.gwt.sample.client.Student::new()(); * }-&#42;/; * </pre> * * <h2>Array</h2> * * <pre> * public static com.google.gwt.sample.client.Student[] instantiate( * SerializationStreamReader streamReader) throws SerializationException { * int size = streamReader.readInt(); * return new com.google.gwt.sample.client.Student[size]; * } * </pre> * * <h2>Enum</h2> * * <pre> * public static com.google.gwt.sample.client.Role instantiate( * SerializationStreamReader streamReader) throws SerializationException { * int ordinal = streamReader.readInt(); * com.google.gwt.sample.client.Role[] values = com.google.gwt.sample.client.Role.values(); * assert (ordinal &gt;= 0 &amp;&amp; ordinal &lt; values.length); * return values[ordinal]; * } * </pre> */ private void maybeWriteInstatiateMethod() { if (serializableClass.isEnum() == null && (serializableClass.isAbstract() || !serializableClass.isDefaultInstantiable())) { /* * Field serializers are shared by all of the RemoteService proxies in a * compilation. Therefore, we have to generate an instantiate method even * if the type is not instantiable relative to the RemoteService which * caused this field serializer to be created. If the type is not * instantiable relative to any of the RemoteService proxies, dead code * optimizations will cause the method to be removed from the compiled * output. * * Enumerated types require an instantiate method even if they are * abstract. You will have an abstract enum in cases where the enum type * is sub-classed. Non-default instantiable classes cannot have * instantiate methods. */ return; } if (customFieldSerializerHasInstantiate) { // The custom field serializer already defined it. return; } JArrayType isArray = serializableClass.isArray(); JEnumType isEnum = serializableClass.isEnum(); JClassType isClass = serializableClass.isClass(); boolean useViolator = false; boolean isAccessible = true; if (isEnum == null && isClass != null) { isAccessible = classIsAccessible() && ctorIsAccessible(); useViolator = !isAccessible && isProd; } sourceWriter.print("public static" + (useViolator ? " native " : " ")); String qualifiedSourceName = serializableClass.getQualifiedSourceName(); sourceWriter.print(qualifiedSourceName); sourceWriter .println(" instantiate(SerializationStreamReader streamReader) throws SerializationException " + (useViolator ? "/*-{" : "{")); sourceWriter.indent(); if (isArray != null) { sourceWriter.println("int size = streamReader.readInt();"); sourceWriter.println("return " + createArrayInstantiationExpression(isArray) + ";"); } else if (isEnum != null) { sourceWriter.println("int ordinal = streamReader.readInt();"); sourceWriter.println(qualifiedSourceName + "[] values = " + qualifiedSourceName + ".values();"); sourceWriter.println("assert (ordinal >= 0 && ordinal < values.length);"); sourceWriter.println("return values[ordinal];"); } else if (!isAccessible) { if (isProd) { sourceWriter.println("return @" + qualifiedSourceName + "::new()();"); } else { sourceWriter.println("return ReflectionHelper.newInstance(" + qualifiedSourceName + ".class);"); } } else { sourceWriter.println("return new " + qualifiedSourceName + "();"); } sourceWriter.outdent(); sourceWriter.println(useViolator ? "}-*/;" : "}"); sourceWriter.println(); } /** * Implement {@link TypeHandler} for the class, used by Java. * * <pre> * public void deserial(SerializationStreamReader reader, Object object) * throws SerializationException { * com.google.gwt.sample.client.Student_FieldSerializer.deserialize( * reader, (com.google.gwt.sample.client.Student) object); * } * * public Object create(SerializationStreamReader reader) * throws SerializationException { * return com.google.gwt.sample.client.Student_FieldSerializer.instantiate(reader); * } * * public void serial(SerializationStreamWriter writer, Object object) * throws SerializationException { * com.google.gwt.sample.client.Student_FieldSerializer.serialize( * writer, (com.google.gwt.sample.client.Student) object); * } * </pre> */ private void maybeWriteTypeHandlerImpl() { if (!needsTypeHandler()) { return; } // Create method sourceWriter .println("public Object create(SerializationStreamReader reader) throws SerializationException {"); sourceWriter.indent(); if (serializableClass.isEnum() != null || serializableClass.isDefaultInstantiable() || customFieldSerializerHasInstantiate) { sourceWriter.print("return "); String typeSig; if (customFieldSerializer != null && customFieldSerializerHasInstantiate) { sourceWriter.print(customFieldSerializer.getQualifiedSourceName()); JMethod instantiationMethod = CustomFieldSerializerValidator.getInstantiationMethod(customFieldSerializer, serializableClass); typeSig = getTypeSig(instantiationMethod); } else { sourceWriter.print(fieldSerializerName); typeSig = ""; } sourceWriter.print("." + typeSig + "instantiate"); sourceWriter.println("(reader);"); } else { sourceWriter.println("return null;"); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); // Deserial method sourceWriter .println("public void deserial(SerializationStreamReader reader, Object object) throws SerializationException {"); if (customFieldSerializer != null) { JMethod deserializationMethod = CustomFieldSerializerValidator.getDeserializationMethod(customFieldSerializer, serializableClass); JType castType = deserializationMethod.getParameters()[1].getType(); String typeSig = getTypeSig(deserializationMethod); sourceWriter.indentln(customFieldSerializer.getQualifiedSourceName() + "." + typeSig + "deserialize(reader, (" + castType.getQualifiedSourceName() + ")object);"); } else { sourceWriter.indentln(fieldSerializerName + ".deserialize(reader, (" + serializableClass.getQualifiedSourceName() + ")object);"); } sourceWriter.println("}"); sourceWriter.println(); // Serial method sourceWriter .println("public void serial(SerializationStreamWriter writer, Object object) throws SerializationException {"); if (customFieldSerializer != null) { JMethod serializationMethod = CustomFieldSerializerValidator.getSerializationMethod(customFieldSerializer, serializableClass); JType castType = serializationMethod.getParameters()[1].getType(); String typeSig = getTypeSig(serializationMethod); sourceWriter.indentln(customFieldSerializer.getQualifiedSourceName() + "." + typeSig + "serialize(writer, (" + castType.getQualifiedSourceName() + ")object);"); } else { sourceWriter.indentln(fieldSerializerName + ".serialize(writer, (" + serializableClass.getQualifiedSourceName() + ")object);"); } sourceWriter.println("}"); sourceWriter.println(); } /** * Returns true if we will need a get/set method pair for a field. * * @return true if the field requires accessor methods */ private boolean needsAccessorMethods(JField field) { /* * Field serializers are always emitted into the same package as the * class that they serialize. This enables the serializer class to access * all fields except those that are private or final. * * Java Access Levels: default - package private - class only protected - * package and all subclasses public - all */ if (Shared.shouldSerializeFinalFields(logger, context)) { return field.isPrivate() || field.isFinal(); } else { return field.isPrivate(); } } /** * Enumerated types can be instantiated even if they are abstract. You will * have an abstract enum in cases where the enum type is sub-classed. * Non-default instantiable classes cannot have instantiate methods. */ private boolean needsTypeHandler() { return serializableClass.isEnum() != null || !serializableClass.isAbstract(); } private void writeArrayDeserializationStatements(JArrayType isArray) { JType componentType = isArray.getComponentType(); String readMethodName = Shared.getStreamReadMethodNameFor(componentType); if ("readObject".equals(readMethodName)) { // Optimize and use the default object custom serializer... sourceWriter.println(Object_Array_CustomFieldSerializer.class.getName() + ".deserialize(streamReader, instance);"); } else { sourceWriter.println("for (int i = 0, n = instance.length; i < n; ++i) {"); sourceWriter.indent(); sourceWriter.print("instance[i] = streamReader."); sourceWriter.println(readMethodName + "();"); sourceWriter.outdent(); sourceWriter.println("}"); } } private void writeArraySerializationStatements(JArrayType isArray) { JType componentType = isArray.getComponentType(); String writeMethodName = Shared.getStreamWriteMethodNameFor(componentType); if ("writeObject".equals(writeMethodName)) { // Optimize and use the default object custom serializer... sourceWriter.println(Object_Array_CustomFieldSerializer.class.getName() + ".serialize(streamWriter, instance);"); } else { sourceWriter.println("streamWriter.writeInt(instance.length);"); sourceWriter.println(); sourceWriter.println("for (int i = 0, n = instance.length; i < n; ++i) {"); sourceWriter.indent(); sourceWriter.print("streamWriter."); sourceWriter.print(writeMethodName); sourceWriter.println("(instance[i]);"); sourceWriter.outdent(); sourceWriter.println("}"); } } private void writeClassDeserializationStatements() { /** * If the type is capable of making a round trip between the client and * server, store additional server-only field data using {@link WeakMapping} * . */ if (serializableClass.isEnhanced()) { sourceWriter.println(WEAK_MAPPING_CLASS_NAME + ".set(instance, " + "\"server-enhanced-data-" + getDepth(serializableClass) + "\", streamReader.readString());"); } for (JField serializableField : serializableFields) { JType fieldType = serializableField.getType(); String readMethodName = Shared.getStreamReadMethodNameFor(fieldType); String streamReadExpression = "streamReader." + readMethodName + "()"; if (Shared.typeNeedsCast(fieldType)) { streamReadExpression = "(" + fieldType.getQualifiedSourceName() + ") " + streamReadExpression; } if (needsAccessorMethods(serializableField)) { sourceWriter.print("set"); sourceWriter.print(Shared.capitalize(serializableField.getName())); sourceWriter.print("(instance, "); sourceWriter.print(streamReadExpression); sourceWriter.println(");"); } else { sourceWriter.print("instance."); sourceWriter.print(serializableField.getName()); sourceWriter.print(" = "); sourceWriter.print(streamReadExpression); sourceWriter.println(";"); } } sourceWriter.println(); JClassType superClass = serializableClass.getSuperclass(); if (superClass != null && (typesSentFromBrowser.isSerializable(superClass) || typesSentToBrowser .isSerializable(superClass))) { String superFieldSerializer = SerializationUtils.getFieldSerializerName(typeOracle, superClass); sourceWriter.print(superFieldSerializer); sourceWriter.println(".deserialize(streamReader, instance);"); } } private void writeClassSerializationStatements() { /** * If the type is capable of making a round trip between the client and * server, retrieve the additional server-only field data from * {@link WeakMapping}. */ if (serializableClass.isEnhanced()) { sourceWriter.println("streamWriter.writeString((String) " + WEAK_MAPPING_CLASS_NAME + ".get(instance, \"server-enhanced-data-" + getDepth(serializableClass) + "\"));"); } for (JField serializableField : serializableFields) { JType fieldType = serializableField.getType(); String writeMethodName = Shared.getStreamWriteMethodNameFor(fieldType); sourceWriter.print("streamWriter."); sourceWriter.print(writeMethodName); sourceWriter.print("("); if (needsAccessorMethods(serializableField)) { sourceWriter.print("get"); sourceWriter.print(Shared.capitalize(serializableField.getName())); sourceWriter.println("(instance));"); } else { sourceWriter.print("instance."); sourceWriter.print(serializableField.getName()); sourceWriter.println(");"); } } sourceWriter.println(); JClassType superClass = serializableClass.getSuperclass(); if (superClass != null && (typesSentFromBrowser.isSerializable(superClass) || typesSentToBrowser .isSerializable(superClass))) { String superFieldSerializer = SerializationUtils.getFieldSerializerName(typeOracle, superClass); sourceWriter.print(superFieldSerializer); sourceWriter.println(".serialize(streamWriter, instance);"); } } private void writeDeserializeMethod() { if (customFieldSerializer != null) { return; } sourceWriter.print("public static void deserialize(SerializationStreamReader streamReader, "); sourceWriter.print(serializableClass.getQualifiedSourceName()); sourceWriter.println(" instance) throws SerializationException {"); sourceWriter.indent(); JArrayType isArray = serializableClass.isArray(); if (isArray != null) { writeArrayDeserializationStatements(isArray); } else if (serializableClass.isEnum() != null) { writeEnumDeserializationStatements(); } else { writeClassDeserializationStatements(); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); } private void writeEnumDeserializationStatements() { sourceWriter.println("// Enum deserialization is handled via the instantiate method"); } private void writeEnumSerializationStatements() { sourceWriter.println("assert (instance != null);"); sourceWriter.println("streamWriter.writeInt(instance.ordinal());"); } /** * This method will generate a native JSNI accessor method for every field * that is protected, private using the "Violator" pattern to allow an * external class to access the field's value. */ private void writeFieldAccessors() { if (customFieldSerializer != null) { return; } for (JField serializableField : serializableFields) { if (!needsAccessorMethods(serializableField)) { continue; } writeFieldGet(serializableField); writeFieldSet(serializableField); } } /** * Write a getter method for an instance field. */ private void writeFieldGet(JField serializableField) { JType fieldType = serializableField.getType(); String fieldTypeQualifiedSourceName = fieldType.getQualifiedSourceName(); String serializableClassQualifedName = serializableClass.getQualifiedSourceName(); String fieldName = serializableField.getName(); maybeSuppressLongWarnings(fieldType); sourceWriter.print("private static " + (isProd ? "native " : "")); sourceWriter.print(fieldTypeQualifiedSourceName); sourceWriter.print(" get"); sourceWriter.print(Shared.capitalize(fieldName)); sourceWriter.print("("); sourceWriter.print(serializableClassQualifedName); sourceWriter.print(" instance) "); sourceWriter.println(methodStart); sourceWriter.indent(); if (context.isProdMode()) { sourceWriter.print("return instance.@"); sourceWriter.print(SerializationUtils.getRpcTypeName(serializableClass)); sourceWriter.print("::"); sourceWriter.print(fieldName); sourceWriter.println(";"); } else { sourceWriter.print("return "); JPrimitiveType primType = fieldType.isPrimitive(); if (primType != null) { sourceWriter.print("(" + primType.getQualifiedBoxedSourceName() + ") "); } else { sourceWriter.print("(" + fieldTypeQualifiedSourceName + ") "); } sourceWriter.println("ReflectionHelper.getField(" + serializableClassQualifedName + ".class, instance, \"" + fieldName + "\");"); } sourceWriter.outdent(); sourceWriter.println(methodEnd); sourceWriter.println(); } /** * Write a setter method for an instance field. */ private void writeFieldSet(JField serializableField) { JType fieldType = serializableField.getType(); String fieldTypeQualifiedSourceName = fieldType.getQualifiedSourceName(); String serializableClassQualifedName = serializableClass.getQualifiedSourceName(); String fieldName = serializableField.getName(); maybeSuppressLongWarnings(fieldType); sourceWriter.print("private static " + (isProd ? "native " : "") + "void"); sourceWriter.print(" set"); sourceWriter.print(Shared.capitalize(fieldName)); sourceWriter.print("("); sourceWriter.print(serializableClassQualifedName); sourceWriter.print(" instance, "); sourceWriter.print(fieldTypeQualifiedSourceName); sourceWriter.println(" value) "); sourceWriter.println(methodStart); sourceWriter.indent(); if (context.isProdMode()) { sourceWriter.print("instance.@"); sourceWriter.print(SerializationUtils.getRpcTypeName(serializableClass)); sourceWriter.print("::"); sourceWriter.print(fieldName); sourceWriter.println(" = value;"); } else { sourceWriter.println("ReflectionHelper.setField(" + serializableClassQualifedName + ".class, instance, \"" + fieldName + "\", value);"); } sourceWriter.outdent(); sourceWriter.println(methodEnd); sourceWriter.println(); } private void writeSerializeMethod() { if (customFieldSerializer != null) { return; } sourceWriter.print("public static void serialize(SerializationStreamWriter streamWriter, "); sourceWriter.print(serializableClass.getQualifiedSourceName()); sourceWriter.println(" instance) throws SerializationException {"); sourceWriter.indent(); JArrayType isArray = serializableClass.isArray(); if (isArray != null) { writeArraySerializationStatements(isArray); } else if (serializableClass.isEnum() != null) { writeEnumSerializationStatements(); } else { writeClassSerializationStatements(); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); } }
37.133848
122
0.697397
d84fd56f73f7213df2563399fa6a03981b956ad2
7,958
/** */ package analysismetamodel.impl; import analysismetamodel.AnalysismetamodelPackage; import analysismetamodel.NumericKnowledge; import analysismetamodel.ProcessInvocableByEQSet; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Process Invocable By EQ Set</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link analysismetamodel.impl.ProcessInvocableByEQSetImpl#getInputKnowledges <em>Input Knowledges</em>}</li> * <li>{@link analysismetamodel.impl.ProcessInvocableByEQSetImpl#getOutputKnowledge <em>Output Knowledge</em>}</li> * <li>{@link analysismetamodel.impl.ProcessInvocableByEQSetImpl#isDoCartesianProduct <em>Do Cartesian Product</em>}</li> * </ul> * </p> * * @generated */ public class ProcessInvocableByEQSetImpl extends MinimalEObjectImpl.Container implements ProcessInvocableByEQSet { /** * The cached value of the '{@link #getInputKnowledges() <em>Input Knowledges</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInputKnowledges() * @generated * @ordered */ protected EList<NumericKnowledge> inputKnowledges; /** * The cached value of the '{@link #getOutputKnowledge() <em>Output Knowledge</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOutputKnowledge() * @generated * @ordered */ protected NumericKnowledge outputKnowledge; /** * The default value of the '{@link #isDoCartesianProduct() <em>Do Cartesian Product</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDoCartesianProduct() * @generated * @ordered */ protected static final boolean DO_CARTESIAN_PRODUCT_EDEFAULT = false; /** * The cached value of the '{@link #isDoCartesianProduct() <em>Do Cartesian Product</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDoCartesianProduct() * @generated * @ordered */ protected boolean doCartesianProduct = DO_CARTESIAN_PRODUCT_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ProcessInvocableByEQSetImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AnalysismetamodelPackage.Literals.PROCESS_INVOCABLE_BY_EQ_SET; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<NumericKnowledge> getInputKnowledges() { if (inputKnowledges == null) { inputKnowledges = new EObjectResolvingEList<NumericKnowledge>(NumericKnowledge.class, this, AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__INPUT_KNOWLEDGES); } return inputKnowledges; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NumericKnowledge getOutputKnowledge() { if (outputKnowledge != null && outputKnowledge.eIsProxy()) { InternalEObject oldOutputKnowledge = (InternalEObject)outputKnowledge; outputKnowledge = (NumericKnowledge)eResolveProxy(oldOutputKnowledge); if (outputKnowledge != oldOutputKnowledge) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__OUTPUT_KNOWLEDGE, oldOutputKnowledge, outputKnowledge)); } } return outputKnowledge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NumericKnowledge basicGetOutputKnowledge() { return outputKnowledge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOutputKnowledge(NumericKnowledge newOutputKnowledge) { NumericKnowledge oldOutputKnowledge = outputKnowledge; outputKnowledge = newOutputKnowledge; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__OUTPUT_KNOWLEDGE, oldOutputKnowledge, outputKnowledge)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isDoCartesianProduct() { return doCartesianProduct; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDoCartesianProduct(boolean newDoCartesianProduct) { boolean oldDoCartesianProduct = doCartesianProduct; doCartesianProduct = newDoCartesianProduct; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__DO_CARTESIAN_PRODUCT, oldDoCartesianProduct, doCartesianProduct)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__INPUT_KNOWLEDGES: return getInputKnowledges(); case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__OUTPUT_KNOWLEDGE: if (resolve) return getOutputKnowledge(); return basicGetOutputKnowledge(); case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__DO_CARTESIAN_PRODUCT: return isDoCartesianProduct(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__INPUT_KNOWLEDGES: getInputKnowledges().clear(); getInputKnowledges().addAll((Collection<? extends NumericKnowledge>)newValue); return; case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__OUTPUT_KNOWLEDGE: setOutputKnowledge((NumericKnowledge)newValue); return; case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__DO_CARTESIAN_PRODUCT: setDoCartesianProduct((Boolean)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__INPUT_KNOWLEDGES: getInputKnowledges().clear(); return; case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__OUTPUT_KNOWLEDGE: setOutputKnowledge((NumericKnowledge)null); return; case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__DO_CARTESIAN_PRODUCT: setDoCartesianProduct(DO_CARTESIAN_PRODUCT_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__INPUT_KNOWLEDGES: return inputKnowledges != null && !inputKnowledges.isEmpty(); case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__OUTPUT_KNOWLEDGE: return outputKnowledge != null; case AnalysismetamodelPackage.PROCESS_INVOCABLE_BY_EQ_SET__DO_CARTESIAN_PRODUCT: return doCartesianProduct != DO_CARTESIAN_PRODUCT_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (DoCartesianProduct: "); result.append(doCartesianProduct); result.append(')'); return result.toString(); } } //ProcessInvocableByEQSetImpl
29.805243
177
0.724051